Search in sources :

Example 6 with ElasticsearchTimeoutException

use of org.elasticsearch.ElasticsearchTimeoutException in project nifi by apache.

the class FetchElasticsearch method onTrigger.

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }
    final String index = context.getProperty(INDEX).evaluateAttributeExpressions(flowFile).getValue();
    final String docId = context.getProperty(DOC_ID).evaluateAttributeExpressions(flowFile).getValue();
    final String docType = context.getProperty(TYPE).evaluateAttributeExpressions(flowFile).getValue();
    final Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
    final ComponentLog logger = getLogger();
    try {
        logger.debug("Fetching {}/{}/{} from Elasticsearch", new Object[] { index, docType, docId });
        final long startNanos = System.nanoTime();
        GetRequestBuilder getRequestBuilder = esClient.get().prepareGet(index, docType, docId);
        if (authToken != null) {
            getRequestBuilder.putHeader("Authorization", authToken);
        }
        final GetResponse getResponse = getRequestBuilder.execute().actionGet();
        if (getResponse == null || !getResponse.isExists()) {
            logger.debug("Failed to read {}/{}/{} from Elasticsearch: Document not found", new Object[] { index, docType, docId });
            // We couldn't find the document, so penalize it and send it to "not found"
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_NOT_FOUND);
        } else {
            flowFile = session.putAttribute(flowFile, "filename", docId);
            flowFile = session.putAttribute(flowFile, "es.index", index);
            flowFile = session.putAttribute(flowFile, "es.type", docType);
            flowFile = session.write(flowFile, new OutputStreamCallback() {

                @Override
                public void process(OutputStream out) throws IOException {
                    out.write(getResponse.getSourceAsString().getBytes(charset));
                }
            });
            logger.debug("Elasticsearch document " + docId + " fetched, routing to success");
            final long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
            final String uri = context.getProperty(HOSTS).evaluateAttributeExpressions().getValue() + "/" + index + "/" + docType + "/" + docId;
            session.getProvenanceReporter().fetch(flowFile, uri, millis);
            session.transfer(flowFile, REL_SUCCESS);
        }
    } catch (NoNodeAvailableException | ElasticsearchTimeoutException | ReceiveTimeoutTransportException | NodeClosedException exceptionToRetry) {
        logger.error("Failed to read into Elasticsearch due to {}, this may indicate an error in configuration " + "(hosts, username/password, etc.). Routing to retry", new Object[] { exceptionToRetry.getLocalizedMessage() }, exceptionToRetry);
        session.transfer(flowFile, REL_RETRY);
        context.yield();
    } catch (Exception e) {
        logger.error("Failed to read {} from Elasticsearch due to {}", new Object[] { flowFile, e.getLocalizedMessage() }, e);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    }
}
Also used : FlowFile(org.apache.nifi.flowfile.FlowFile) OutputStream(java.io.OutputStream) Charset(java.nio.charset.Charset) NoNodeAvailableException(org.elasticsearch.client.transport.NoNodeAvailableException) ComponentLog(org.apache.nifi.logging.ComponentLog) GetResponse(org.elasticsearch.action.get.GetResponse) NodeClosedException(org.elasticsearch.node.NodeClosedException) ProcessException(org.apache.nifi.processor.exception.ProcessException) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) ReceiveTimeoutTransportException(org.elasticsearch.transport.ReceiveTimeoutTransportException) NoNodeAvailableException(org.elasticsearch.client.transport.NoNodeAvailableException) IOException(java.io.IOException) ReceiveTimeoutTransportException(org.elasticsearch.transport.ReceiveTimeoutTransportException) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) NodeClosedException(org.elasticsearch.node.NodeClosedException) OutputStreamCallback(org.apache.nifi.processor.io.OutputStreamCallback) GetRequestBuilder(org.elasticsearch.action.get.GetRequestBuilder)

Example 7 with ElasticsearchTimeoutException

use of org.elasticsearch.ElasticsearchTimeoutException in project nifi by apache.

the class PutElasticsearch method onTrigger.

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final ComponentLog logger = getLogger();
    final String id_attribute = context.getProperty(ID_ATTRIBUTE).getValue();
    final int batchSize = context.getProperty(BATCH_SIZE).evaluateAttributeExpressions().asInteger();
    final List<FlowFile> flowFiles = session.get(batchSize);
    if (flowFiles.isEmpty()) {
        return;
    }
    // Keep track of the list of flow files that need to be transferred. As they are transferred, remove them from the list.
    List<FlowFile> flowFilesToTransfer = new LinkedList<>(flowFiles);
    try {
        final BulkRequestBuilder bulk = esClient.get().prepareBulk();
        if (authToken != null) {
            bulk.putHeader("Authorization", authToken);
        }
        for (FlowFile file : flowFiles) {
            final String index = context.getProperty(INDEX).evaluateAttributeExpressions(file).getValue();
            final String docType = context.getProperty(TYPE).evaluateAttributeExpressions(file).getValue();
            final String indexOp = context.getProperty(INDEX_OP).evaluateAttributeExpressions(file).getValue();
            final Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(file).getValue());
            final String id = file.getAttribute(id_attribute);
            if (id == null) {
                logger.error("No value in identifier attribute {} for {}, transferring to failure", new Object[] { id_attribute, file });
                flowFilesToTransfer.remove(file);
                session.transfer(file, REL_FAILURE);
            } else {
                session.read(file, new InputStreamCallback() {

                    @Override
                    public void process(final InputStream in) throws IOException {
                        String json = IOUtils.toString(in, charset).replace("\r\n", " ").replace('\n', ' ').replace('\r', ' ');
                        if (indexOp.equalsIgnoreCase("index")) {
                            bulk.add(esClient.get().prepareIndex(index, docType, id).setSource(json.getBytes(charset)));
                        } else if (indexOp.equalsIgnoreCase("upsert")) {
                            bulk.add(esClient.get().prepareUpdate(index, docType, id).setDoc(json.getBytes(charset)).setDocAsUpsert(true));
                        } else if (indexOp.equalsIgnoreCase("update")) {
                            bulk.add(esClient.get().prepareUpdate(index, docType, id).setDoc(json.getBytes(charset)));
                        } else {
                            throw new IOException("Index operation: " + indexOp + " not supported.");
                        }
                    }
                });
            }
        }
        final BulkResponse response = bulk.execute().actionGet();
        if (response.hasFailures()) {
            // Responses are guaranteed to be in order, remove them in reverse order
            BulkItemResponse[] responses = response.getItems();
            if (responses != null && responses.length > 0) {
                for (int i = responses.length - 1; i >= 0; i--) {
                    final FlowFile flowFile = flowFilesToTransfer.get(i);
                    if (responses[i].isFailed()) {
                        logger.error("Failed to insert {} into Elasticsearch due to {}, transferring to failure", new Object[] { flowFile, responses[i].getFailure().getMessage() });
                        session.transfer(flowFile, REL_FAILURE);
                    } else {
                        session.getProvenanceReporter().send(flowFile, context.getProperty(HOSTS).evaluateAttributeExpressions().getValue() + "/" + responses[i].getIndex());
                        session.transfer(flowFile, REL_SUCCESS);
                    }
                    flowFilesToTransfer.remove(flowFile);
                }
            }
        }
        // Transfer any remaining flowfiles to success
        flowFilesToTransfer.forEach(file -> {
            session.transfer(file, REL_SUCCESS);
            // Record provenance event
            session.getProvenanceReporter().send(file, context.getProperty(HOSTS).evaluateAttributeExpressions().getValue() + "/" + context.getProperty(INDEX).evaluateAttributeExpressions(file).getValue());
        });
    } catch (NoNodeAvailableException | ElasticsearchTimeoutException | ReceiveTimeoutTransportException | NodeClosedException exceptionToRetry) {
        // Authorization errors and other problems are often returned as NoNodeAvailableExceptions without a
        // traceable cause. However the cause seems to be logged, just not available to this caught exception.
        // Since the error message will show up as a bulletin, we make specific mention to check the logs for
        // more details.
        logger.error("Failed to insert into Elasticsearch due to {}. More detailed information may be available in " + "the NiFi logs.", new Object[] { exceptionToRetry.getLocalizedMessage() }, exceptionToRetry);
        session.transfer(flowFilesToTransfer, REL_RETRY);
        context.yield();
    } catch (Exception exceptionToFail) {
        logger.error("Failed to insert into Elasticsearch due to {}, transferring to failure", new Object[] { exceptionToFail.getLocalizedMessage() }, exceptionToFail);
        session.transfer(flowFilesToTransfer, REL_FAILURE);
        context.yield();
    }
}
Also used : FlowFile(org.apache.nifi.flowfile.FlowFile) InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) BulkItemResponse(org.elasticsearch.action.bulk.BulkItemResponse) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) IOException(java.io.IOException) NoNodeAvailableException(org.elasticsearch.client.transport.NoNodeAvailableException) ComponentLog(org.apache.nifi.logging.ComponentLog) LinkedList(java.util.LinkedList) NodeClosedException(org.elasticsearch.node.NodeClosedException) ProcessException(org.apache.nifi.processor.exception.ProcessException) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) ReceiveTimeoutTransportException(org.elasticsearch.transport.ReceiveTimeoutTransportException) NoNodeAvailableException(org.elasticsearch.client.transport.NoNodeAvailableException) IOException(java.io.IOException) ReceiveTimeoutTransportException(org.elasticsearch.transport.ReceiveTimeoutTransportException) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) InputStreamCallback(org.apache.nifi.processor.io.InputStreamCallback) NodeClosedException(org.elasticsearch.node.NodeClosedException) BulkRequestBuilder(org.elasticsearch.action.bulk.BulkRequestBuilder)

Example 8 with ElasticsearchTimeoutException

use of org.elasticsearch.ElasticsearchTimeoutException in project crate by crate.

the class TransportClearVotingConfigExclusionsAction method masterOperation.

@Override
protected void masterOperation(ClearVotingConfigExclusionsRequest request, ClusterState initialState, ActionListener<ClearVotingConfigExclusionsResponse> listener) throws Exception {
    final long startTimeMillis = threadPool.relativeTimeInMillis();
    final Predicate<ClusterState> allExclusionsRemoved = newState -> {
        for (VotingConfigExclusion tombstone : initialState.getVotingConfigExclusions()) {
            // NB checking for the existence of any node with this persistent ID, because persistent IDs are how votes are counted.
            if (newState.nodes().nodeExists(tombstone.getNodeId())) {
                return false;
            }
        }
        return true;
    };
    if (request.getWaitForRemoval() && allExclusionsRemoved.test(initialState) == false) {
        final ClusterStateObserver clusterStateObserver = new ClusterStateObserver(initialState, clusterService, request.getTimeout(), logger);
        clusterStateObserver.waitForNextChange(new Listener() {

            @Override
            public void onNewClusterState(ClusterState state) {
                submitClearVotingConfigExclusionsTask(request, startTimeMillis, listener);
            }

            @Override
            public void onClusterServiceClose() {
                listener.onFailure(new ElasticsearchException("cluster service closed while waiting for removal of nodes " + initialState.getVotingConfigExclusions()));
            }

            @Override
            public void onTimeout(TimeValue timeout) {
                listener.onFailure(new ElasticsearchTimeoutException("timed out waiting for removal of nodes; if nodes should not be removed, set waitForRemoval to false. " + initialState.getVotingConfigExclusions()));
            }
        }, allExclusionsRemoved);
    } else {
        submitClearVotingConfigExclusionsTask(request, startTimeMillis, listener);
    }
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) Priority(org.elasticsearch.common.Priority) Listener(org.elasticsearch.cluster.ClusterStateObserver.Listener) Predicate(java.util.function.Predicate) ClusterService(org.elasticsearch.cluster.service.ClusterService) IOException(java.io.IOException) CoordinationMetadata(org.elasticsearch.cluster.coordination.CoordinationMetadata) Names(org.elasticsearch.threadpool.ThreadPool.Names) Inject(org.elasticsearch.common.inject.Inject) TransportMasterNodeAction(org.elasticsearch.action.support.master.TransportMasterNodeAction) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) ClusterState(org.elasticsearch.cluster.ClusterState) Metadata(org.elasticsearch.cluster.metadata.Metadata) ClusterStateUpdateTask(org.elasticsearch.cluster.ClusterStateUpdateTask) VotingConfigExclusion(org.elasticsearch.cluster.coordination.CoordinationMetadata.VotingConfigExclusion) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) StreamInput(org.elasticsearch.common.io.stream.StreamInput) TimeValue(io.crate.common.unit.TimeValue) ThreadPool(org.elasticsearch.threadpool.ThreadPool) TransportService(org.elasticsearch.transport.TransportService) ClusterStateObserver(org.elasticsearch.cluster.ClusterStateObserver) ClusterBlockLevel(org.elasticsearch.cluster.block.ClusterBlockLevel) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) ActionListener(org.elasticsearch.action.ActionListener) VotingConfigExclusion(org.elasticsearch.cluster.coordination.CoordinationMetadata.VotingConfigExclusion) ClusterState(org.elasticsearch.cluster.ClusterState) ClusterStateObserver(org.elasticsearch.cluster.ClusterStateObserver) Listener(org.elasticsearch.cluster.ClusterStateObserver.Listener) ActionListener(org.elasticsearch.action.ActionListener) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) ElasticsearchException(org.elasticsearch.ElasticsearchException) TimeValue(io.crate.common.unit.TimeValue)

Example 9 with ElasticsearchTimeoutException

use of org.elasticsearch.ElasticsearchTimeoutException in project crate by crate.

the class Node method start.

/**
 * Start the node. If the node is already started, this method is no-op.
 */
public Node start() throws NodeValidationException {
    if (!lifecycle.moveToStarted()) {
        return this;
    }
    logger.info("starting ...");
    pluginLifecycleComponents.forEach(LifecycleComponent::start);
    injector.getInstance(BlobService.class).start();
    injector.getInstance(DecommissioningService.class).start();
    injector.getInstance(NodeDisconnectJobMonitorService.class).start();
    injector.getInstance(JobsLogService.class).start();
    injector.getInstance(PostgresNetty.class).start();
    injector.getInstance(TasksService.class).start();
    injector.getInstance(Schemas.class).start();
    injector.getInstance(ArrayMapperService.class).start();
    injector.getInstance(DanglingArtifactsService.class).start();
    injector.getInstance(SslContextProviderService.class).start();
    injector.getInstance(MappingUpdatedAction.class).setClient(client);
    injector.getInstance(IndicesService.class).start();
    injector.getInstance(IndicesClusterStateService.class).start();
    injector.getInstance(SnapshotsService.class).start();
    injector.getInstance(SnapshotShardsService.class).start();
    nodeService.getMonitorService().start();
    final ClusterService clusterService = injector.getInstance(ClusterService.class);
    final NodeConnectionsService nodeConnectionsService = injector.getInstance(NodeConnectionsService.class);
    nodeConnectionsService.start();
    clusterService.setNodeConnectionsService(nodeConnectionsService);
    injector.getInstance(GatewayService.class).start();
    Discovery discovery = injector.getInstance(Discovery.class);
    clusterService.getMasterService().setClusterStatePublisher(discovery::publish);
    HttpServerTransport httpServerTransport = injector.getInstance(HttpServerTransport.class);
    httpServerTransport.start();
    // CRATE_PATCH: add http publish address to the discovery node
    TransportAddress publishAddress = httpServerTransport.info().address().publishAddress();
    localNodeFactory.httpPublishAddress = publishAddress.getAddress() + ':' + publishAddress.getPort();
    // Start the transport service now so the publish address will be added to the local disco node in ClusterService
    TransportService transportService = injector.getInstance(TransportService.class);
    transportService.start();
    assert localNodeFactory.getNode() != null;
    assert transportService.getLocalNode().equals(localNodeFactory.getNode()) : "transportService has a different local node than the factory provided";
    injector.getInstance(PeerRecoverySourceService.class).start();
    // Load (and maybe upgrade) the metadata stored on disk
    final GatewayMetaState gatewayMetaState = injector.getInstance(GatewayMetaState.class);
    gatewayMetaState.start(settings(), transportService, clusterService, injector.getInstance(MetaStateService.class), injector.getInstance(MetadataIndexUpgradeService.class), injector.getInstance(MetadataUpgrader.class), injector.getInstance(PersistedClusterStateService.class));
    if (Assertions.ENABLED) {
        try {
            assert injector.getInstance(MetaStateService.class).loadFullState().v1().isEmpty();
            final NodeMetadata nodeMetaData = NodeMetadata.FORMAT.loadLatestState(logger, NamedXContentRegistry.EMPTY, nodeEnvironment.nodeDataPaths());
            assert nodeMetaData != null;
            assert nodeMetaData.nodeVersion().equals(Version.CURRENT);
            assert nodeMetaData.nodeId().equals(localNodeFactory.getNode().getId());
        } catch (IOException e) {
            assert false : e;
        }
    }
    // we load the global state here (the persistent part of the cluster state stored on disk) to
    // pass it to the bootstrap checks to allow plugins to enforce certain preconditions based on the recovered state.
    final Metadata onDiskMetadata = gatewayMetaState.getPersistedState().getLastAcceptedState().metadata();
    // this is never null
    assert onDiskMetadata != null : "metadata is null but shouldn't";
    validateNodeBeforeAcceptingRequests(transportService.boundAddress(), pluginsService.filterPlugins(Plugin.class).stream().flatMap(p -> p.getBootstrapChecks().stream()).collect(Collectors.toList()));
    // start after transport service so the local disco is known
    // start before cluster service so that it can set initial state on ClusterApplierService
    discovery.start();
    clusterService.start();
    assert clusterService.localNode().equals(localNodeFactory.getNode()) : "clusterService has a different local node than the factory provided";
    transportService.acceptIncomingRequests();
    discovery.startInitialJoin();
    final TimeValue initialStateTimeout = INITIAL_STATE_TIMEOUT_SETTING.get(settings);
    configureNodeAndClusterIdStateListener(clusterService);
    if (initialStateTimeout.millis() > 0) {
        final ThreadPool thread = injector.getInstance(ThreadPool.class);
        ClusterState clusterState = clusterService.state();
        ClusterStateObserver observer = new ClusterStateObserver(clusterState, clusterService, null, logger);
        if (clusterState.nodes().getMasterNodeId() == null) {
            logger.debug("waiting to join the cluster. timeout [{}]", initialStateTimeout);
            final CountDownLatch latch = new CountDownLatch(1);
            observer.waitForNextChange(new ClusterStateObserver.Listener() {

                @Override
                public void onNewClusterState(ClusterState state) {
                    latch.countDown();
                }

                @Override
                public void onClusterServiceClose() {
                    latch.countDown();
                }

                @Override
                public void onTimeout(TimeValue timeout) {
                    logger.warn("timed out while waiting for initial discovery state - timeout: {}", initialStateTimeout);
                    latch.countDown();
                }
            }, state -> state.nodes().getMasterNodeId() != null, initialStateTimeout);
            try {
                latch.await();
            } catch (InterruptedException e) {
                throw new ElasticsearchTimeoutException("Interrupted while waiting for initial discovery state");
            }
        }
    }
    if (WRITE_PORTS_FILE_SETTING.get(settings)) {
        TransportService transport = injector.getInstance(TransportService.class);
        writePortsFile("transport", transport.boundAddress());
        HttpServerTransport http = injector.getInstance(HttpServerTransport.class);
        writePortsFile("http", http.boundAddress());
    }
    logger.info("started");
    pluginsService.filterPlugins(ClusterPlugin.class).forEach(ClusterPlugin::onNodeStarted);
    return this;
}
Also used : SnapshotsService(org.elasticsearch.snapshots.SnapshotsService) SnapshotShardsService(org.elasticsearch.snapshots.SnapshotShardsService) NodeConnectionsService(org.elasticsearch.cluster.NodeConnectionsService) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) TransportAddress(org.elasticsearch.common.transport.TransportAddress) SslContextProviderService(io.crate.protocols.ssl.SslContextProviderService) IndexMetadata(org.elasticsearch.cluster.metadata.IndexMetadata) Metadata(org.elasticsearch.cluster.metadata.Metadata) IndexTemplateMetadata(org.elasticsearch.cluster.metadata.IndexTemplateMetadata) NodeMetadata(org.elasticsearch.env.NodeMetadata) ThreadPool(org.elasticsearch.threadpool.ThreadPool) MetadataUpgrader(org.elasticsearch.plugins.MetadataUpgrader) TasksService(io.crate.execution.jobs.TasksService) HttpServerTransport(org.elasticsearch.http.HttpServerTransport) DecommissioningService(io.crate.cluster.gracefulstop.DecommissioningService) GatewayMetaState(org.elasticsearch.gateway.GatewayMetaState) PostgresNetty(io.crate.protocols.postgres.PostgresNetty) MetaStateService(org.elasticsearch.gateway.MetaStateService) IndicesClusterStateService(org.elasticsearch.indices.cluster.IndicesClusterStateService) LifecycleComponent(org.elasticsearch.common.component.LifecycleComponent) PeerRecoverySourceService(org.elasticsearch.indices.recovery.PeerRecoverySourceService) DanglingArtifactsService(io.crate.metadata.DanglingArtifactsService) TimeValue(io.crate.common.unit.TimeValue) JobsLogService(io.crate.execution.engine.collect.stats.JobsLogService) ClusterState(org.elasticsearch.cluster.ClusterState) ClusterStateObserver(org.elasticsearch.cluster.ClusterStateObserver) ClusterPlugin(org.elasticsearch.plugins.ClusterPlugin) Discovery(org.elasticsearch.discovery.Discovery) IndicesService(org.elasticsearch.indices.IndicesService) MetadataIndexUpgradeService(org.elasticsearch.cluster.metadata.MetadataIndexUpgradeService) IOException(java.io.IOException) Schemas(io.crate.metadata.Schemas) CountDownLatch(java.util.concurrent.CountDownLatch) GatewayService(org.elasticsearch.gateway.GatewayService) NodeMetadata(org.elasticsearch.env.NodeMetadata) ClusterService(org.elasticsearch.cluster.service.ClusterService) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) BlobService(io.crate.blob.BlobService) NodeDisconnectJobMonitorService(io.crate.execution.jobs.transport.NodeDisconnectJobMonitorService) TransportService(org.elasticsearch.transport.TransportService) MappingUpdatedAction(org.elasticsearch.cluster.action.index.MappingUpdatedAction) PersistedClusterStateService(org.elasticsearch.gateway.PersistedClusterStateService) ArrayMapperService(io.crate.lucene.ArrayMapperService)

Example 10 with ElasticsearchTimeoutException

use of org.elasticsearch.ElasticsearchTimeoutException in project elasticsearch by elastic.

the class Node method start.

/**
     * Start the node. If the node is already started, this method is no-op.
     */
public Node start() throws NodeValidationException {
    if (!lifecycle.moveToStarted()) {
        return this;
    }
    Logger logger = Loggers.getLogger(Node.class, NODE_NAME_SETTING.get(settings));
    logger.info("starting ...");
    // hack around dependency injection problem (for now...)
    injector.getInstance(Discovery.class).setAllocationService(injector.getInstance(AllocationService.class));
    pluginLifecycleComponents.forEach(LifecycleComponent::start);
    injector.getInstance(MappingUpdatedAction.class).setClient(client);
    injector.getInstance(IndicesService.class).start();
    injector.getInstance(IndicesClusterStateService.class).start();
    injector.getInstance(SnapshotsService.class).start();
    injector.getInstance(SnapshotShardsService.class).start();
    injector.getInstance(RoutingService.class).start();
    injector.getInstance(SearchService.class).start();
    injector.getInstance(MonitorService.class).start();
    final ClusterService clusterService = injector.getInstance(ClusterService.class);
    final NodeConnectionsService nodeConnectionsService = injector.getInstance(NodeConnectionsService.class);
    nodeConnectionsService.start();
    clusterService.setNodeConnectionsService(nodeConnectionsService);
    // TODO hack around circular dependencies problems
    injector.getInstance(GatewayAllocator.class).setReallocation(clusterService, injector.getInstance(RoutingService.class));
    injector.getInstance(ResourceWatcherService.class).start();
    injector.getInstance(GatewayService.class).start();
    Discovery discovery = injector.getInstance(Discovery.class);
    clusterService.setDiscoverySettings(discovery.getDiscoverySettings());
    clusterService.addInitialStateBlock(discovery.getDiscoverySettings().getNoMasterBlock());
    clusterService.setClusterStatePublisher(discovery::publish);
    // start before the cluster service since it adds/removes initial Cluster state blocks
    final TribeService tribeService = injector.getInstance(TribeService.class);
    tribeService.start();
    // Start the transport service now so the publish address will be added to the local disco node in ClusterService
    TransportService transportService = injector.getInstance(TransportService.class);
    transportService.getTaskManager().setTaskResultsService(injector.getInstance(TaskResultsService.class));
    transportService.start();
    validateNodeBeforeAcceptingRequests(settings, transportService.boundAddress(), pluginsService.filterPlugins(Plugin.class).stream().flatMap(p -> p.getBootstrapChecks().stream()).collect(Collectors.toList()));
    clusterService.addStateApplier(transportService.getTaskManager());
    clusterService.start();
    assert localNodeFactory.getNode() != null;
    assert transportService.getLocalNode().equals(localNodeFactory.getNode()) : "transportService has a different local node than the factory provided";
    assert clusterService.localNode().equals(localNodeFactory.getNode()) : "clusterService has a different local node than the factory provided";
    // start after cluster service so the local disco is known
    discovery.start();
    transportService.acceptIncomingRequests();
    discovery.startInitialJoin();
    // tribe nodes don't have a master so we shouldn't register an observer         s
    final TimeValue initialStateTimeout = DiscoverySettings.INITIAL_STATE_TIMEOUT_SETTING.get(settings);
    if (initialStateTimeout.millis() > 0) {
        final ThreadPool thread = injector.getInstance(ThreadPool.class);
        ClusterState clusterState = clusterService.state();
        ClusterStateObserver observer = new ClusterStateObserver(clusterState, clusterService, null, logger, thread.getThreadContext());
        if (clusterState.nodes().getMasterNodeId() == null) {
            logger.debug("waiting to join the cluster. timeout [{}]", initialStateTimeout);
            final CountDownLatch latch = new CountDownLatch(1);
            observer.waitForNextChange(new ClusterStateObserver.Listener() {

                @Override
                public void onNewClusterState(ClusterState state) {
                    latch.countDown();
                }

                @Override
                public void onClusterServiceClose() {
                    latch.countDown();
                }

                @Override
                public void onTimeout(TimeValue timeout) {
                    logger.warn("timed out while waiting for initial discovery state - timeout: {}", initialStateTimeout);
                    latch.countDown();
                }
            }, state -> state.nodes().getMasterNodeId() != null, initialStateTimeout);
            try {
                latch.await();
            } catch (InterruptedException e) {
                throw new ElasticsearchTimeoutException("Interrupted while waiting for initial discovery state");
            }
        }
    }
    if (NetworkModule.HTTP_ENABLED.get(settings)) {
        injector.getInstance(HttpServerTransport.class).start();
    }
    // start nodes now, after the http server, because it may take some time
    tribeService.startNodes();
    // starts connecting to remote clusters if any cluster is configured
    SearchTransportService searchTransportService = injector.getInstance(SearchTransportService.class);
    searchTransportService.start();
    if (WRITE_PORTS_FIELD_SETTING.get(settings)) {
        if (NetworkModule.HTTP_ENABLED.get(settings)) {
            HttpServerTransport http = injector.getInstance(HttpServerTransport.class);
            writePortsFile("http", http.boundAddress());
        }
        TransportService transport = injector.getInstance(TransportService.class);
        writePortsFile("transport", transport.boundAddress());
    }
    logger.info("started");
    return this;
}
Also used : TribeService(org.elasticsearch.tribe.TribeService) GatewayAllocator(org.elasticsearch.gateway.GatewayAllocator) SnapshotsService(org.elasticsearch.snapshots.SnapshotsService) SnapshotShardsService(org.elasticsearch.snapshots.SnapshotShardsService) NodeConnectionsService(org.elasticsearch.cluster.NodeConnectionsService) MonitorService(org.elasticsearch.monitor.MonitorService) ThreadPool(org.elasticsearch.threadpool.ThreadPool) Logger(org.apache.logging.log4j.Logger) DeprecationLogger(org.elasticsearch.common.logging.DeprecationLogger) TaskResultsService(org.elasticsearch.tasks.TaskResultsService) HttpServerTransport(org.elasticsearch.http.HttpServerTransport) IndicesClusterStateService(org.elasticsearch.indices.cluster.IndicesClusterStateService) LifecycleComponent(org.elasticsearch.common.component.LifecycleComponent) SearchService(org.elasticsearch.search.SearchService) SearchTransportService(org.elasticsearch.action.search.SearchTransportService) AllocationService(org.elasticsearch.cluster.routing.allocation.AllocationService) TimeValue(org.elasticsearch.common.unit.TimeValue) ClusterState(org.elasticsearch.cluster.ClusterState) ClusterStateObserver(org.elasticsearch.cluster.ClusterStateObserver) RoutingService(org.elasticsearch.cluster.routing.RoutingService) Discovery(org.elasticsearch.discovery.Discovery) IndicesService(org.elasticsearch.indices.IndicesService) CountDownLatch(java.util.concurrent.CountDownLatch) GatewayService(org.elasticsearch.gateway.GatewayService) ClusterService(org.elasticsearch.cluster.service.ClusterService) ElasticsearchTimeoutException(org.elasticsearch.ElasticsearchTimeoutException) SearchTransportService(org.elasticsearch.action.search.SearchTransportService) TransportService(org.elasticsearch.transport.TransportService) MappingUpdatedAction(org.elasticsearch.cluster.action.index.MappingUpdatedAction) ResourceWatcherService(org.elasticsearch.watcher.ResourceWatcherService)

Aggregations

ElasticsearchTimeoutException (org.elasticsearch.ElasticsearchTimeoutException)22 ReceiveTimeoutTransportException (org.elasticsearch.transport.ReceiveTimeoutTransportException)11 IOException (java.io.IOException)10 NoNodeAvailableException (org.elasticsearch.client.transport.NoNodeAvailableException)10 NodeClosedException (org.elasticsearch.node.NodeClosedException)8 FlowFile (org.apache.nifi.flowfile.FlowFile)5 ComponentLog (org.apache.nifi.logging.ComponentLog)5 ProcessException (org.apache.nifi.processor.exception.ProcessException)5 Test (org.junit.Test)5 TimeValue (io.crate.common.unit.TimeValue)4 Charset (java.nio.charset.Charset)4 ClusterState (org.elasticsearch.cluster.ClusterState)4 ClusterStateObserver (org.elasticsearch.cluster.ClusterStateObserver)4 HashMap (java.util.HashMap)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 ElasticsearchParseException (org.elasticsearch.ElasticsearchParseException)3 BulkResponse (org.elasticsearch.action.bulk.BulkResponse)3 Matchers.anyString (org.mockito.Matchers.anyString)3 InputStream (java.io.InputStream)2 OutputStream (java.io.OutputStream)2