Search in sources :

Example 1 with Pair

use of io.datarouter.util.tuple.Pair in project datarouter by hotpads.

the class LatencyMonitoringService method getClientChecks.

public List<LatencyCheck> getClientChecks() {
    List<LatencyCheck> checks = new ArrayList<>();
    if (MAKE_GET_CHECK) {
        for (ClientId clientId : clientInitializationTracker.getInitializedClients()) {
            Collection<PhysicalNode<?, ?, ?>> nodesForClient = nodes.getPhysicalNodesForClient(clientId.getName());
            Optional<PhysicalNode<?, ?, ?>> findFirst = nodesForClient.stream().findFirst();
            if (findFirst.isPresent()) {
                PhysicalNode<?, ?, ?> node = findFirst.get();
                if (node instanceof PhysicalMapStorageNode) {
                    PhysicalMapStorageNode<?, ?, ?> ms = (PhysicalMapStorageNode<?, ?, ?>) node;
                    checks.add(new DatarouterClientLatencyCheck(LatencyMonitoringService.DR_CLIENT_PREFIX + clientId + LatencyMonitoringService.MS_CHECK_SUFIX, makeGet(ms), clientId));
                }
            }
        }
    }
    Function<ClientId, Stream<Pair<ClientId, SortedStorage<?, ?>>>> mapClientIdToFirstSortedStorageNode = clientId -> nodes.getPhysicalNodesForClient(clientId.getName()).stream().filter(node -> node instanceof SortedStorage).limit(1).map(SortedStorage.class::cast).peek(sortedStorage -> logger.info("selected SortedStorage {}", sortedStorage)).map(sortedStorage -> new Pair<>(clientId, sortedStorage));
    checks.addAll(clientInitializationTracker.getInitializedClients().stream().filter(clientId -> clients.getClientManager(clientId).monitorLatency()).flatMap(mapClientIdToFirstSortedStorageNode).map(pair -> new DatarouterClientLatencyCheck(getCheckNameForDatarouterClient(pair.getLeft()), () -> pair.getRight().scanKeys(ONLY_FIRST).findFirst(), pair.getLeft())).collect(Collectors.toList()));
    return checks;
}
Also used : SortedStorage(io.datarouter.storage.node.op.raw.SortedStorage) OptionalDouble(java.util.OptionalDouble) LoggerFactory(org.slf4j.LoggerFactory) PhysicalNode(io.datarouter.storage.node.type.physical.PhysicalNode) PhysicalDatabeanFieldInfo(io.datarouter.storage.serialize.fieldcache.PhysicalDatabeanFieldInfo) PhysicalMapStorageNode(io.datarouter.storage.node.op.raw.MapStorage.PhysicalMapStorageNode) Deque(java.util.Deque) Singleton(javax.inject.Singleton) ServerName(io.datarouter.storage.config.properties.ServerName) Function(java.util.function.Function) ServiceName(io.datarouter.web.config.service.ServiceName) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) Map(java.util.Map) ClientId(io.datarouter.storage.client.ClientId) StreamTool(io.datarouter.util.StreamTool) Config(io.datarouter.storage.config.Config) DatarouterNodes(io.datarouter.storage.node.DatarouterNodes) DatarouterClients(io.datarouter.storage.client.DatarouterClients) DatarouterWebSettingRoot(io.datarouter.web.config.DatarouterWebSettingRoot) Logger(org.slf4j.Logger) DatarouterClientAvailabilitySwitchThresholdSettingsProvider(io.datarouter.storage.config.setting.impl.DatarouterClientAvailabilitySwitchThresholdSettingsProvider) Gauges(io.datarouter.storage.metric.Gauges) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Counters(io.datarouter.instrumentation.count.Counters) SortedStorage(io.datarouter.storage.node.op.raw.SortedStorage) DatarouterDuration(io.datarouter.util.duration.DatarouterDuration) Collectors(java.util.stream.Collectors) ConcurrentLinkedDeque(java.util.concurrent.ConcurrentLinkedDeque) PrimaryKey(io.datarouter.model.key.primary.PrimaryKey) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ClientInitializationTracker(io.datarouter.storage.client.ClientInitializationTracker) Stream(java.util.stream.Stream) TreeMap(java.util.TreeMap) Entry(java.util.Map.Entry) Optional(java.util.Optional) Pair(io.datarouter.util.tuple.Pair) Collections(java.util.Collections) PhysicalMapStorageNode(io.datarouter.storage.node.op.raw.MapStorage.PhysicalMapStorageNode) ArrayList(java.util.ArrayList) ClientId(io.datarouter.storage.client.ClientId) Stream(java.util.stream.Stream) PhysicalNode(io.datarouter.storage.node.type.physical.PhysicalNode)

Example 2 with Pair

use of io.datarouter.util.tuple.Pair in project datarouter by hotpads.

the class BaseCacheRateLimiter method internalAllow.

@Override
protected Pair<Boolean, Instant> internalAllow(String key, boolean increment) {
    Instant now = Instant.now();
    Map<String, Long> results = readCounts(buildKeysToRead(key, now));
    String currentMapKey = makeMapKey(key, getTimeStr(now));
    int total = 0;
    for (Entry<String, Long> entry : results.entrySet()) {
        Long numRequests = entry.getValue() == null ? 0L : entry.getValue();
        if (entry.getKey().equals(currentMapKey)) {
            numRequests++;
        }
        // exceeded maxSpikeRequests
        if (numRequests > config.maxSpikeRequests) {
            Instant exceededInstant = getDateFromKey(entry.getKey());
            Counters.inc(HIT_COUNTER_NAME);
            return new Pair<>(false, exceededInstant.plusMillis(config.bucketIntervalMs * (config.numIntervals - 1)));
        }
        total += numRequests;
    }
    double avgRequests = total / (double) config.numIntervals;
    // exceeded maxAvgRequests
    if (avgRequests > config.maxAverageRequests) {
        List<Instant> instants = Scanner.of(results.keySet()).map(this::getDateFromKey).list();
        Instant lastTime = Instant.MIN;
        for (Instant instant : instants) {
            if (instant.isAfter(lastTime)) {
                lastTime = instant;
            }
        }
        Objects.requireNonNull(lastTime);
        // add to get next available time
        Counters.inc(HIT_COUNTER_NAME);
        return new Pair<>(false, lastTime.plusMillis(config.bucketIntervalMs));
    }
    if (increment) {
        increment(currentMapKey);
    }
    return new Pair<>(true, null);
}
Also used : Instant(java.time.Instant) Pair(io.datarouter.util.tuple.Pair)

Example 3 with Pair

use of io.datarouter.util.tuple.Pair in project datarouter by hotpads.

the class AwsMemcachedWebInspector method getDetails.

@Override
protected Pair<Integer, DivTag> getDetails(ClientId clientId) {
    MemcachedClientMode mode = options.getClientMode(clientId.getName());
    Pair<Integer, DivTag> nodeCountByNodeTag = new Pair<>();
    if (mode == MemcachedClientMode.DYNAMIC) {
        List<AwsMemcachedNodeEndpointDto> nodeEndpointDtos = Scanner.of(getSpyClient(clientId).getAllNodeEndPoints()).map(nodeEndPoint -> new AwsMemcachedNodeEndpointDto(nodeEndPoint.getHostName(), nodeEndPoint.getIpAddress(), nodeEndPoint.getPort())).list();
        var table = new J2HtmlTable<AwsMemcachedNodeEndpointDto>().withClasses("sortable table table-sm table-striped my-4 border").withColumn("HostName", dto -> dto.hostName).withColumn("IpAddress", dto -> dto.ipAddress).withColumn("Port", dto -> dto.port).build(nodeEndpointDtos);
        DivTag divTable = div(table).withClass("container-fluid my-4").withStyle("padding-left: 0px");
        nodeCountByNodeTag.setLeft(nodeEndpointDtos.size());
        nodeCountByNodeTag.setRight(divTable);
    } else {
        List<LiTag> socketAddresses = Scanner.of(getSpyClient(clientId).getAvailableServers()).map(Object::toString).map(TagCreator::li).list();
        DivTag div = div(ul(socketAddresses.toArray(new ContainerTag[0])));
        nodeCountByNodeTag.setLeft(socketAddresses.size());
        nodeCountByNodeTag.setRight(div);
    }
    return nodeCountByNodeTag;
}
Also used : Scanner(io.datarouter.scanner.Scanner) MemcachedClientMode(io.datarouter.aws.memcached.client.MemcachedClientMode) DivTag(j2html.tags.specialized.DivTag) LiTag(j2html.tags.specialized.LiTag) MemcachedWebInspector(io.datarouter.client.memcached.web.MemcachedWebInspector) ContainerTag(j2html.tags.ContainerTag) Inject(javax.inject.Inject) List(java.util.List) ClientId(io.datarouter.storage.client.ClientId) Pair(io.datarouter.util.tuple.Pair) TagCreator.div(j2html.TagCreator.div) AwsMemcachedOptions(io.datarouter.aws.memcached.client.options.AwsMemcachedOptions) J2HtmlTable(io.datarouter.web.html.j2html.J2HtmlTable) TagCreator(j2html.TagCreator) TagCreator.ul(j2html.TagCreator.ul) DivTag(j2html.tags.specialized.DivTag) LiTag(j2html.tags.specialized.LiTag) MemcachedClientMode(io.datarouter.aws.memcached.client.MemcachedClientMode) Pair(io.datarouter.util.tuple.Pair)

Example 4 with Pair

use of io.datarouter.util.tuple.Pair in project datarouter by hotpads.

the class BaseDatarouterServletContextListener method processListeners.

private void processListeners(OnAction onAction, boolean executeAllListenersSynchronously) {
    ThreadFactory factory = new NamedThreadFactory("datarouterListenerExecutor", false);
    ExecutorService executor = Executors.newFixedThreadPool(allListeners.size(), factory);
    var timer = new PhaseTimer();
    long shutdownStartMillis = System.currentTimeMillis();
    for (Pair<ExecutionMode, List<DatarouterAppListener>> listenersByShutdownMode : listenersByExecutionMods) {
        List<DatarouterAppListener> listeners = listenersByShutdownMode.getRight();
        ExecutionMode executionMode = executeAllListenersSynchronously ? ExecutionMode.SYNCHRONOUS : listenersByShutdownMode.getLeft();
        logger.warn("{} {}: [{}", onAction.display, executionMode.display, listeners.stream().map(listener -> listener.getClass().getSimpleName()).collect(Collectors.joining(", ")) + "]");
        if (executionMode == ExecutionMode.SYNCHRONOUS) {
            Scanner.of(listeners).map(executeOnAction(onAction)).forEach(timer::add);
        } else if (executionMode == ExecutionMode.PARALLEL) {
            long shutdownParallelStartMillis = System.currentTimeMillis();
            Scanner.of(listeners).parallel(new ParallelScannerContext(executor, listeners.size(), true)).map(executeOnAction(onAction)).forEach(timer::add);
            logger.info("Parallel {} total={}", onAction.display, System.currentTimeMillis() - shutdownParallelStartMillis);
        }
    }
    logger.warn(String.format("%s [total=%d][%s]", onAction, System.currentTimeMillis() - shutdownStartMillis, timer.getPhaseNamesAndTimes().stream().map(pair -> pair.getLeft() + "=" + pair.getRight()).collect(Collectors.joining("]["))));
    ExecutorServiceTool.shutdown(executor, Duration.ofSeconds(2));
}
Also used : DatarouterInjector(io.datarouter.inject.DatarouterInjector) Scanner(io.datarouter.scanner.Scanner) Logger(org.slf4j.Logger) ParallelScannerContext(io.datarouter.scanner.ParallelScannerContext) LoggerFactory(org.slf4j.LoggerFactory) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) ArrayList(java.util.ArrayList) NamedThreadFactory(io.datarouter.util.concurrent.NamedThreadFactory) List(java.util.List) ServletContextEvent(javax.servlet.ServletContextEvent) ExecutorServiceTool(io.datarouter.util.concurrent.ExecutorServiceTool) InjectorRetriever(io.datarouter.web.inject.InjectorRetriever) Duration(java.time.Duration) ThreadFactory(java.util.concurrent.ThreadFactory) Pair(io.datarouter.util.tuple.Pair) Collections(java.util.Collections) ServletContextListener(javax.servlet.ServletContextListener) ExecutorService(java.util.concurrent.ExecutorService) PhaseTimer(io.datarouter.util.timer.PhaseTimer) NamedThreadFactory(io.datarouter.util.concurrent.NamedThreadFactory) ThreadFactory(java.util.concurrent.ThreadFactory) PhaseTimer(io.datarouter.util.timer.PhaseTimer) NamedThreadFactory(io.datarouter.util.concurrent.NamedThreadFactory) ParallelScannerContext(io.datarouter.scanner.ParallelScannerContext) ExecutorService(java.util.concurrent.ExecutorService) ArrayList(java.util.ArrayList) List(java.util.List)

Example 5 with Pair

use of io.datarouter.util.tuple.Pair in project datarouter by hotpads.

the class BaseDatarouterServletContextListener method buildExecuteOnActionsLists.

private void buildExecuteOnActionsLists(ServletContextEvent event) {
    DatarouterInjector injector = getInjector(event.getServletContext());
    Scanner.of(listenerClasses).map(injector::getInstance).forEach(allListeners::add);
    Scanner.of(webListenerClasses).map(injector::getInstance).each(listener -> listener.setServletContext(event.getServletContext())).forEach(allListeners::add);
    Scanner.of(allListeners).splitBy(DatarouterAppListener::safeToExecuteInParallel).map(Scanner::list).map(listeners -> new Pair<>(listeners.get(0).safeToExecuteInParallel() ? ExecutionMode.PARALLEL : ExecutionMode.SYNCHRONOUS, listeners)).forEach(listenersByExecutionMods::add);
}
Also used : DatarouterInjector(io.datarouter.inject.DatarouterInjector) Scanner(io.datarouter.scanner.Scanner) Logger(org.slf4j.Logger) ParallelScannerContext(io.datarouter.scanner.ParallelScannerContext) LoggerFactory(org.slf4j.LoggerFactory) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) ArrayList(java.util.ArrayList) NamedThreadFactory(io.datarouter.util.concurrent.NamedThreadFactory) List(java.util.List) ServletContextEvent(javax.servlet.ServletContextEvent) ExecutorServiceTool(io.datarouter.util.concurrent.ExecutorServiceTool) InjectorRetriever(io.datarouter.web.inject.InjectorRetriever) Duration(java.time.Duration) ThreadFactory(java.util.concurrent.ThreadFactory) Pair(io.datarouter.util.tuple.Pair) Collections(java.util.Collections) ServletContextListener(javax.servlet.ServletContextListener) ExecutorService(java.util.concurrent.ExecutorService) PhaseTimer(io.datarouter.util.timer.PhaseTimer) Scanner(io.datarouter.scanner.Scanner) DatarouterInjector(io.datarouter.inject.DatarouterInjector) Pair(io.datarouter.util.tuple.Pair)

Aggregations

Pair (io.datarouter.util.tuple.Pair)16 List (java.util.List)9 Inject (javax.inject.Inject)8 Scanner (io.datarouter.scanner.Scanner)7 ArrayList (java.util.ArrayList)6 Collectors (java.util.stream.Collectors)6 Optional (java.util.Optional)5 Logger (org.slf4j.Logger)5 LoggerFactory (org.slf4j.LoggerFactory)5 DatarouterInjector (io.datarouter.inject.DatarouterInjector)4 ClientId (io.datarouter.storage.client.ClientId)3 StringTool (io.datarouter.util.string.StringTool)3 BaseHandler (io.datarouter.web.handler.BaseHandler)3 Mav (io.datarouter.web.handler.mav.Mav)3 CurrentUserSessionInfoService (io.datarouter.web.user.session.CurrentUserSessionInfoService)3 TagCreator.div (j2html.TagCreator.div)3 ZoneId (java.time.ZoneId)3 Collections (java.util.Collections)3 Date (java.util.Date)3 Function (java.util.function.Function)3