Search in sources :

Example 1 with ServiceDescriptor

use of com.facebook.airlift.discovery.client.ServiceDescriptor in project presto by prestodb.

the class DiscoveryNodeManager method refreshNodesInternal.

private synchronized void refreshNodesInternal() {
    // This is currently a blacklist.
    // TODO: make it a whitelist (a failure-detecting service selector) and maybe build in support for injecting this in airlift
    Set<ServiceDescriptor> services = serviceSelector.selectAllServices().stream().filter(service -> !failureDetector.getFailed().contains(service)).filter(service -> !nodeStatusService.isPresent() || nodeStatusService.get().isAllowed(service.getLocation()) || isCoordinator(service) || isResourceManager(service)).collect(toImmutableSet());
    ImmutableSet.Builder<InternalNode> activeNodesBuilder = ImmutableSortedSet.orderedBy(comparing(InternalNode::getNodeIdentifier));
    ImmutableSet.Builder<InternalNode> inactiveNodesBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<InternalNode> shuttingDownNodesBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<InternalNode> coordinatorsBuilder = ImmutableSet.builder();
    ImmutableSet.Builder<InternalNode> resourceManagersBuilder = ImmutableSet.builder();
    ImmutableSetMultimap.Builder<ConnectorId, InternalNode> byConnectorIdBuilder = ImmutableSetMultimap.builder();
    Map<String, InternalNode> nodes = new HashMap<>();
    SetMultimap<String, ConnectorId> connectorIdsByNodeId = HashMultimap.create();
    // For a given connectorId, sort the nodes based on their nodeIdentifier
    byConnectorIdBuilder.orderValuesBy(comparing(InternalNode::getNodeIdentifier));
    if (isMemoizeDeadNodesEnabled && this.nodes != null) {
        nodes.putAll(this.nodes);
    }
    if (isMemoizeDeadNodesEnabled && this.connectorIdsByNodeId != null) {
        connectorIdsByNodeId.putAll(this.connectorIdsByNodeId);
    }
    for (ServiceDescriptor service : services) {
        URI uri = getHttpUri(service, httpsRequired);
        OptionalInt thriftPort = getThriftServerPort(service);
        NodeVersion nodeVersion = getNodeVersion(service);
        // Currently, a node may have the roles of both a coordinator and a worker.  In the future, a resource manager may also
        // take the form of a coordinator, hence these flags are not exclusive.
        boolean coordinator = isCoordinator(service);
        boolean resourceManager = isResourceManager(service);
        if (uri != null && nodeVersion != null) {
            InternalNode node = new InternalNode(service.getNodeId(), uri, thriftPort, nodeVersion, coordinator, resourceManager, ALIVE);
            NodeState nodeState = getNodeState(node);
            switch(nodeState) {
                case ACTIVE:
                    activeNodesBuilder.add(node);
                    if (coordinator) {
                        coordinatorsBuilder.add(node);
                    }
                    if (resourceManager) {
                        resourceManagersBuilder.add(node);
                    }
                    nodes.put(node.getNodeIdentifier(), node);
                    // record available active nodes organized by connector id
                    String connectorIds = service.getProperties().get("connectorIds");
                    if (connectorIds != null) {
                        connectorIds = connectorIds.toLowerCase(ENGLISH);
                        for (String id : CONNECTOR_ID_SPLITTER.split(connectorIds)) {
                            ConnectorId connectorId = new ConnectorId(id);
                            byConnectorIdBuilder.put(connectorId, node);
                            connectorIdsByNodeId.put(node.getNodeIdentifier(), connectorId);
                        }
                    }
                    // always add system connector
                    byConnectorIdBuilder.put(new ConnectorId(GlobalSystemConnector.NAME), node);
                    break;
                case INACTIVE:
                    inactiveNodesBuilder.add(node);
                    break;
                case SHUTTING_DOWN:
                    shuttingDownNodesBuilder.add(node);
                    break;
                default:
                    log.error("Unknown state %s for node %s", nodeState, node);
            }
        }
    }
    if (allNodes != null) {
        // log node that are no longer active (but not shutting down)
        SetView<InternalNode> missingNodes = difference(allNodes.getActiveNodes(), Sets.union(activeNodesBuilder.build(), shuttingDownNodesBuilder.build()));
        for (InternalNode missingNode : missingNodes) {
            log.info("Previously active node is missing: %s (last seen at %s)", missingNode.getNodeIdentifier(), missingNode.getHost());
        }
    }
    // nodes by connector id changes anytime a node adds or removes a connector (note: this is not part of the listener system)
    activeNodesByConnectorId = byConnectorIdBuilder.build();
    if (isMemoizeDeadNodesEnabled) {
        SetView<String> deadNodeIds = difference(nodes.keySet(), activeNodesBuilder.build().stream().map(InternalNode::getNodeIdentifier).collect(toImmutableSet()));
        for (String nodeId : deadNodeIds) {
            InternalNode deadNode = nodes.get(nodeId);
            Set<ConnectorId> deadNodeConnectorIds = connectorIdsByNodeId.get(nodeId);
            for (ConnectorId id : deadNodeConnectorIds) {
                byConnectorIdBuilder.put(id, new InternalNode(deadNode.getNodeIdentifier(), deadNode.getInternalUri(), deadNode.getThriftPort(), deadNode.getNodeVersion(), deadNode.isCoordinator(), deadNode.isResourceManager(), DEAD));
            }
        }
    }
    this.nodes = ImmutableMap.copyOf(nodes);
    this.nodesByConnectorId = byConnectorIdBuilder.build();
    this.connectorIdsByNodeId = ImmutableSetMultimap.copyOf(connectorIdsByNodeId);
    AllNodes allNodes = new AllNodes(activeNodesBuilder.build(), inactiveNodesBuilder.build(), shuttingDownNodesBuilder.build(), coordinatorsBuilder.build(), resourceManagersBuilder.build());
    // only update if all nodes actually changed (note: this does not include the connectors registered with the nodes)
    if (!allNodes.equals(this.allNodes)) {
        // assign allNodes to a local variable for use in the callback below
        this.allNodes = allNodes;
        coordinators = coordinatorsBuilder.build();
        resourceManagers = resourceManagersBuilder.build();
        // notify listeners
        List<Consumer<AllNodes>> listeners = ImmutableList.copyOf(this.listeners);
        nodeStateEventExecutor.submit(() -> listeners.forEach(listener -> listener.accept(allNodes)));
    }
}
Also used : ServiceType(com.facebook.airlift.discovery.client.ServiceType) URISyntaxException(java.net.URISyntaxException) DEAD(com.facebook.presto.metadata.InternalNode.NodeStatus.DEAD) NodeVersion(com.facebook.presto.client.NodeVersion) ACTIVE(com.facebook.presto.spi.NodeState.ACTIVE) PreDestroy(javax.annotation.PreDestroy) Sets.difference(com.google.common.collect.Sets.difference) Executors.newSingleThreadScheduledExecutor(java.util.concurrent.Executors.newSingleThreadScheduledExecutor) HashMultimap(com.google.common.collect.HashMultimap) GlobalSystemConnector(com.facebook.presto.connector.system.GlobalSystemConnector) Map(java.util.Map) ServiceSelector(com.facebook.airlift.discovery.client.ServiceSelector) URI(java.net.URI) Splitter(com.google.common.base.Splitter) ENGLISH(java.util.Locale.ENGLISH) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) CommunicationProtocol(com.facebook.presto.server.InternalCommunicationConfig.CommunicationProtocol) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) ThreadSafe(javax.annotation.concurrent.ThreadSafe) GuardedBy(javax.annotation.concurrent.GuardedBy) NodeState(com.facebook.presto.spi.NodeState) Sets(com.google.common.collect.Sets) Preconditions.checkState(com.google.common.base.Preconditions.checkState) List(java.util.List) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) ConnectorId(com.facebook.presto.spi.ConnectorId) INACTIVE(com.facebook.presto.spi.NodeState.INACTIVE) NodeStatusService(com.facebook.presto.statusservice.NodeStatusService) ServiceDescriptor(com.facebook.airlift.discovery.client.ServiceDescriptor) Logger(com.facebook.airlift.log.Logger) NodeInfo(com.facebook.airlift.node.NodeInfo) HashMap(java.util.HashMap) OptionalInt(java.util.OptionalInt) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) ImmutableList(com.google.common.collect.ImmutableList) Managed(org.weakref.jmx.Managed) Objects.requireNonNull(java.util.Objects.requireNonNull) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) Comparator.comparing(java.util.Comparator.comparing) ExecutorService(java.util.concurrent.ExecutorService) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) Threads.threadsNamed(com.facebook.airlift.concurrent.Threads.threadsNamed) SHUTTING_DOWN(com.facebook.presto.spi.NodeState.SHUTTING_DOWN) InternalCommunicationConfig(com.facebook.presto.server.InternalCommunicationConfig) ALIVE(com.facebook.presto.metadata.InternalNode.NodeStatus.ALIVE) SetView(com.google.common.collect.Sets.SetView) DriftClient(com.facebook.drift.client.DriftClient) HttpClient(com.facebook.airlift.http.client.HttpClient) SetMultimap(com.google.common.collect.SetMultimap) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) HttpUriBuilder.uriBuilderFrom(com.facebook.airlift.http.client.HttpUriBuilder.uriBuilderFrom) Executors.newCachedThreadPool(java.util.concurrent.Executors.newCachedThreadPool) FailureDetector(com.facebook.presto.failureDetector.FailureDetector) ThriftServerInfoClient(com.facebook.presto.server.thrift.ThriftServerInfoClient) NodeState(com.facebook.presto.spi.NodeState) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) OptionalInt(java.util.OptionalInt) URI(java.net.URI) NodeVersion(com.facebook.presto.client.NodeVersion) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) Consumer(java.util.function.Consumer) ServiceDescriptor(com.facebook.airlift.discovery.client.ServiceDescriptor) ConnectorId(com.facebook.presto.spi.ConnectorId)

Example 2 with ServiceDescriptor

use of com.facebook.airlift.discovery.client.ServiceDescriptor in project presto by prestodb.

the class HeartbeatFailureDetector method updateMonitoredServices.

@VisibleForTesting
void updateMonitoredServices() {
    Set<ServiceDescriptor> online = selector.selectAllServices().stream().filter(descriptor -> !nodeInfo.getNodeId().equals(descriptor.getNodeId())).collect(toImmutableSet());
    Set<UUID> onlineIds = online.stream().map(ServiceDescriptor::getId).collect(toImmutableSet());
    // make sure only one thread is updating the registrations
    synchronized (tasks) {
        // 1. remove expired tasks
        List<UUID> expiredIds = tasks.values().stream().filter(MonitoringTask::isExpired).map(MonitoringTask::getService).map(ServiceDescriptor::getId).collect(toImmutableList());
        tasks.keySet().removeAll(expiredIds);
        // 2. disable offline services
        tasks.values().stream().filter(task -> !onlineIds.contains(task.getService().getId())).forEach(MonitoringTask::disable);
        // 3. create tasks for new services
        Set<ServiceDescriptor> newServices = online.stream().filter(service -> !tasks.keySet().contains(service.getId())).collect(toImmutableSet());
        for (ServiceDescriptor service : newServices) {
            URI uri = getHttpUri(service);
            if (uri != null) {
                URI pingURI = uriBuilderFrom(uri).appendPath("/v1/status").build();
                tasks.put(service.getId(), new MonitoringTask(service, pingURI));
            }
        }
        // 4. enable all online tasks (existing plus newly created)
        tasks.values().stream().filter(task -> onlineIds.contains(task.getService().getId())).forEach(MonitoringTask::enable);
    }
}
Also used : ServiceType(com.facebook.airlift.discovery.client.ServiceType) ExponentialDecay(com.facebook.airlift.stats.ExponentialDecay) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) ScheduledFuture(java.util.concurrent.ScheduledFuture) URISyntaxException(java.net.URISyntaxException) Duration(io.airlift.units.Duration) PreDestroy(javax.annotation.PreDestroy) ALIVE(com.facebook.presto.failureDetector.FailureDetector.State.ALIVE) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Response(com.facebook.airlift.http.client.Response) Map(java.util.Map) ServiceSelector(com.facebook.airlift.discovery.client.ServiceSelector) URI(java.net.URI) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HostAddress(com.facebook.presto.spi.HostAddress) Set(java.util.Set) ThreadSafe(javax.annotation.concurrent.ThreadSafe) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) DecayCounter(com.facebook.airlift.stats.DecayCounter) UUID(java.util.UUID) GuardedBy(javax.annotation.concurrent.GuardedBy) UNRESPONSIVE(com.facebook.presto.failureDetector.FailureDetector.State.UNRESPONSIVE) HostAddress.fromUri(com.facebook.presto.spi.HostAddress.fromUri) ResponseHandler(com.facebook.airlift.http.client.ResponseHandler) Threads.daemonThreadsNamed(com.facebook.airlift.concurrent.Threads.daemonThreadsNamed) List(java.util.List) PostConstruct(javax.annotation.PostConstruct) Nested(org.weakref.jmx.Nested) ServiceDescriptor(com.facebook.airlift.discovery.client.ServiceDescriptor) Logger(com.facebook.airlift.log.Logger) ThreadPoolExecutorMBean(com.facebook.airlift.concurrent.ThreadPoolExecutorMBean) NodeInfo(com.facebook.airlift.node.NodeInfo) UNKNOWN(com.facebook.presto.failureDetector.FailureDetector.State.UNKNOWN) Failures(com.facebook.presto.util.Failures) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConcurrentMap(java.util.concurrent.ConcurrentMap) Inject(javax.inject.Inject) Managed(org.weakref.jmx.Managed) FailureInfo(com.facebook.presto.client.FailureInfo) SocketTimeoutException(java.net.SocketTimeoutException) Objects.requireNonNull(java.util.Objects.requireNonNull) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) ConnectException(java.net.ConnectException) Nullable(javax.annotation.Nullable) InternalCommunicationConfig(com.facebook.presto.server.InternalCommunicationConfig) DateTime(org.joda.time.DateTime) HttpClient(com.facebook.airlift.http.client.HttpClient) TimeUnit(java.util.concurrent.TimeUnit) HttpUriBuilder.uriBuilderFrom(com.facebook.airlift.http.client.HttpUriBuilder.uriBuilderFrom) Request(com.facebook.airlift.http.client.Request) Builder.prepareHead(com.facebook.airlift.http.client.Request.Builder.prepareHead) VisibleForTesting(com.google.common.annotations.VisibleForTesting) GONE(com.facebook.presto.failureDetector.FailureDetector.State.GONE) ServiceDescriptor(com.facebook.airlift.discovery.client.ServiceDescriptor) UUID(java.util.UUID) URI(java.net.URI) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 3 with ServiceDescriptor

use of com.facebook.airlift.discovery.client.ServiceDescriptor in project presto by prestodb.

the class BenchmarkQueryRunner method getAllNodes.

private List<URI> getAllNodes(URI server) {
    Request request = prepareGet().setUri(uriBuilderFrom(server).replacePath("/v1/service/presto").build()).build();
    JsonResponseHandler<ServiceDescriptorsRepresentation> responseHandler = createJsonResponseHandler(jsonCodec(ServiceDescriptorsRepresentation.class));
    ServiceDescriptorsRepresentation serviceDescriptors = httpClient.execute(request, responseHandler);
    ImmutableList.Builder<URI> addresses = ImmutableList.builder();
    for (ServiceDescriptor serviceDescriptor : serviceDescriptors.getServiceDescriptors()) {
        String httpUri = serviceDescriptor.getProperties().get("http");
        if (httpUri != null) {
            addresses.add(URI.create(httpUri));
        }
    }
    return addresses.build();
}
Also used : ServiceDescriptorsRepresentation(com.facebook.airlift.discovery.client.ServiceDescriptorsRepresentation) ServiceDescriptor(com.facebook.airlift.discovery.client.ServiceDescriptor) ImmutableList(com.google.common.collect.ImmutableList) Request(com.facebook.airlift.http.client.Request) URI(java.net.URI)

Example 4 with ServiceDescriptor

use of com.facebook.airlift.discovery.client.ServiceDescriptor in project presto by prestodb.

the class DiscoveryNodeManager method findCurrentNode.

private static InternalNode findCurrentNode(List<ServiceDescriptor> allServices, String currentNodeId, NodeVersion expectedNodeVersion, boolean httpsRequired) {
    for (ServiceDescriptor service : allServices) {
        URI uri = getHttpUri(service, httpsRequired);
        OptionalInt thriftPort = getThriftServerPort(service);
        NodeVersion nodeVersion = getNodeVersion(service);
        if (uri != null && nodeVersion != null) {
            InternalNode node = new InternalNode(service.getNodeId(), uri, thriftPort, nodeVersion, isCoordinator(service), isResourceManager(service), ALIVE);
            if (node.getNodeIdentifier().equals(currentNodeId)) {
                checkState(node.getNodeVersion().equals(expectedNodeVersion), "INVARIANT: current node version (%s) should be equal to %s", node.getNodeVersion(), expectedNodeVersion);
                return node;
            }
        }
    }
    throw new IllegalStateException("INVARIANT: current node not returned from service selector");
}
Also used : NodeVersion(com.facebook.presto.client.NodeVersion) ServiceDescriptor(com.facebook.airlift.discovery.client.ServiceDescriptor) OptionalInt(java.util.OptionalInt) URI(java.net.URI)

Aggregations

ServiceDescriptor (com.facebook.airlift.discovery.client.ServiceDescriptor)4 URI (java.net.URI)4 ServiceSelector (com.facebook.airlift.discovery.client.ServiceSelector)2 ServiceType (com.facebook.airlift.discovery.client.ServiceType)2 HttpClient (com.facebook.airlift.http.client.HttpClient)2 HttpUriBuilder.uriBuilderFrom (com.facebook.airlift.http.client.HttpUriBuilder.uriBuilderFrom)2 Request (com.facebook.airlift.http.client.Request)2 Logger (com.facebook.airlift.log.Logger)2 NodeInfo (com.facebook.airlift.node.NodeInfo)2 NodeVersion (com.facebook.presto.client.NodeVersion)2 InternalCommunicationConfig (com.facebook.presto.server.InternalCommunicationConfig)2 ImmutableMap (com.google.common.collect.ImmutableMap)2 ImmutableSet.toImmutableSet (com.google.common.collect.ImmutableSet.toImmutableSet)2 URISyntaxException (java.net.URISyntaxException)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 Objects.requireNonNull (java.util.Objects.requireNonNull)2 Set (java.util.Set)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2