Search in sources :

Example 11 with ISE

use of org.apache.druid.java.util.common.ISE in project druid by druid-io.

the class MetricHolder method fromByteBuffer.

public static MetricHolder fromByteBuffer(ByteBuffer buf) {
    final byte ver = buf.get();
    if (VERSION[0] != ver) {
        throw new ISE("Unknown version[%s] of MetricHolder", ver);
    }
    final String metricName = SERIALIZER_UTILS.readString(buf);
    final String typeName = SERIALIZER_UTILS.readString(buf);
    MetricHolder holder = new MetricHolder(metricName, typeName);
    switch(holder.type) {
        case FLOAT:
            holder.floatType = CompressedColumnarFloatsSupplier.fromByteBuffer(buf, ByteOrder.nativeOrder());
            break;
        case COMPLEX:
            final ComplexMetricSerde serdeForType = ComplexMetrics.getSerdeForType(holder.getTypeName());
            if (serdeForType == null) {
                throw new ISE("Unknown type[%s], cannot load.", holder.getTypeName());
            }
            holder.complexType = read(buf, serdeForType);
            break;
        case LONG:
        case DOUBLE:
            throw new ISE("Unsupported type[%s]", holder.type);
    }
    return holder;
}
Also used : ComplexMetricSerde(org.apache.druid.segment.serde.ComplexMetricSerde) ISE(org.apache.druid.java.util.common.ISE)

Example 12 with ISE

use of org.apache.druid.java.util.common.ISE in project druid by druid-io.

the class TopNQueryRunnerTest method testTopNBySegment.

@Test
public void testTopNBySegment() {
    final HashMap<String, Object> specialContext = new HashMap<String, Object>();
    specialContext.put(QueryContexts.BY_SEGMENT_KEY, "true");
    TopNQuery query = new TopNQueryBuilder().dataSource(QueryRunnerTestHelper.DATA_SOURCE).granularity(QueryRunnerTestHelper.ALL_GRAN).dimension(QueryRunnerTestHelper.MARKET_DIMENSION).metric(QueryRunnerTestHelper.INDEX_METRIC).threshold(4).intervals(QueryRunnerTestHelper.FIRST_TO_THIRD).aggregators(commonAggregators).postAggregators(QueryRunnerTestHelper.ADD_ROWS_INDEX_CONSTANT).context(specialContext).build();
    List<Result<TopNResultValue>> expectedResults = Collections.singletonList(new Result<>(DateTimes.of("2011-04-01T00:00:00.000Z"), new TopNResultValue(Arrays.<Map<String, Object>>asList(ImmutableMap.of("addRowsIndexConstant", 5356.814783D, "index", 5351.814783D, QueryRunnerTestHelper.MARKET_DIMENSION, "total_market", "uniques", QueryRunnerTestHelper.UNIQUES_2, "rows", 4L), ImmutableMap.of("addRowsIndexConstant", 4880.669692D, "index", 4875.669692D, QueryRunnerTestHelper.MARKET_DIMENSION, "upfront", "uniques", QueryRunnerTestHelper.UNIQUES_2, "rows", 4L), ImmutableMap.of("addRowsIndexConstant", 2250.876812D, "index", 2231.876812D, QueryRunnerTestHelper.MARKET_DIMENSION, "spot", "uniques", QueryRunnerTestHelper.UNIQUES_9, "rows", 18L)))));
    Sequence<Result<TopNResultValue>> results = runWithMerge(query);
    List<Result<BySegmentTopNResultValue>> resultList = results.map((Result<TopNResultValue> input) -> {
        // Stupid type erasure
        Object val = input.getValue();
        if (val instanceof BySegmentResultValue) {
            BySegmentResultValue bySegVal = (BySegmentResultValue) val;
            return new Result<>(input.getTimestamp(), new BySegmentTopNResultValue(Lists.transform(bySegVal.getResults(), res -> {
                if (Preconditions.checkNotNull(res) instanceof Result) {
                    Result theResult = (Result) res;
                    Object resVal = theResult.getValue();
                    if (resVal instanceof TopNResultValue) {
                        return new Result<>(theResult.getTimestamp(), (TopNResultValue) resVal);
                    }
                }
                throw new IAE("Bad input: [%s]", res);
            }), bySegVal.getSegmentId(), bySegVal.getInterval()));
        }
        throw new ISE("Bad type");
    }).toList();
    Result<BySegmentTopNResultValue> result = resultList.get(0);
    TestHelper.assertExpectedResults(expectedResults, result.getValue().getResults());
}
Also used : QueryPlus(org.apache.druid.query.QueryPlus) Arrays(java.util.Arrays) ExtractionFn(org.apache.druid.query.extraction.ExtractionFn) ByteBuffer(java.nio.ByteBuffer) Pair(org.apache.druid.java.util.common.Pair) DefaultDimensionSpec(org.apache.druid.query.dimension.DefaultDimensionSpec) DimExtractionFn(org.apache.druid.query.extraction.DimExtractionFn) LongSumAggregatorFactory(org.apache.druid.query.aggregation.LongSumAggregatorFactory) SelectorDimFilter(org.apache.druid.query.filter.SelectorDimFilter) Map(java.util.Map) QueryRunner(org.apache.druid.query.QueryRunner) IAE(org.apache.druid.java.util.common.IAE) ExtractionDimensionSpec(org.apache.druid.query.dimension.ExtractionDimensionSpec) Parameterized(org.junit.runners.Parameterized) AndDimFilter(org.apache.druid.query.filter.AndDimFilter) DateTimes(org.apache.druid.java.util.common.DateTimes) Sequence(org.apache.druid.java.util.common.guava.Sequence) FinalizeResultsQueryRunner(org.apache.druid.query.FinalizeResultsQueryRunner) Longs(com.google.common.primitives.Longs) HyperUniquesAggregatorFactory(org.apache.druid.query.aggregation.hyperloglog.HyperUniquesAggregatorFactory) AfterClass(org.junit.AfterClass) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Closer(org.apache.druid.java.util.common.io.Closer) AggregatorFactory(org.apache.druid.query.aggregation.AggregatorFactory) FloatMaxAggregatorFactory(org.apache.druid.query.aggregation.FloatMaxAggregatorFactory) ISE(org.apache.druid.java.util.common.ISE) TestExprMacroTable(org.apache.druid.query.expression.TestExprMacroTable) HyperUniqueFinalizingPostAggregator(org.apache.druid.query.aggregation.hyperloglog.HyperUniqueFinalizingPostAggregator) FloatLastAggregatorFactory(org.apache.druid.query.aggregation.last.FloatLastAggregatorFactory) RegexDimExtractionFn(org.apache.druid.query.extraction.RegexDimExtractionFn) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) QueryContexts(org.apache.druid.query.QueryContexts) ExprMacroTable(org.apache.druid.math.expr.ExprMacroTable) BySegmentResultValue(org.apache.druid.query.BySegmentResultValue) BySegmentResultValueClass(org.apache.druid.query.BySegmentResultValueClass) List(java.util.List) StringFormatExtractionFn(org.apache.druid.query.extraction.StringFormatExtractionFn) CloseableStupidPool(org.apache.druid.collections.CloseableStupidPool) ExpressionPostAggregator(org.apache.druid.query.aggregation.post.ExpressionPostAggregator) DimFilter(org.apache.druid.query.filter.DimFilter) QueryRunnerTestHelper(org.apache.druid.query.QueryRunnerTestHelper) DimensionSpec(org.apache.druid.query.dimension.DimensionSpec) Doubles(com.google.common.primitives.Doubles) DoubleFirstAggregatorFactory(org.apache.druid.query.aggregation.first.DoubleFirstAggregatorFactory) Iterables(com.google.common.collect.Iterables) DoubleSumAggregatorFactory(org.apache.druid.query.aggregation.DoubleSumAggregatorFactory) Intervals(org.apache.druid.java.util.common.Intervals) JavaScriptExtractionFn(org.apache.druid.query.extraction.JavaScriptExtractionFn) FilteredAggregatorFactory(org.apache.druid.query.aggregation.FilteredAggregatorFactory) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) JavaScriptConfig(org.apache.druid.js.JavaScriptConfig) ArrayList(java.util.ArrayList) MapLookupExtractor(org.apache.druid.query.extraction.MapLookupExtractor) Lists(com.google.common.collect.Lists) ColumnHolder(org.apache.druid.segment.column.ColumnHolder) ImmutableList(com.google.common.collect.ImmutableList) LookupExtractionFn(org.apache.druid.query.lookup.LookupExtractionFn) DoubleMinAggregatorFactory(org.apache.druid.query.aggregation.DoubleMinAggregatorFactory) TestQueryRunners(org.apache.druid.query.TestQueryRunners) LongLastAggregatorFactory(org.apache.druid.query.aggregation.last.LongLastAggregatorFactory) StringComparators(org.apache.druid.query.ordering.StringComparators) LongFirstAggregatorFactory(org.apache.druid.query.aggregation.first.LongFirstAggregatorFactory) MultipleIntervalSegmentSpec(org.apache.druid.query.spec.MultipleIntervalSegmentSpec) FloatMinAggregatorFactory(org.apache.druid.query.aggregation.FloatMinAggregatorFactory) ListFilteredDimensionSpec(org.apache.druid.query.dimension.ListFilteredDimensionSpec) BoundDimFilter(org.apache.druid.query.filter.BoundDimFilter) ExpressionVirtualColumn(org.apache.druid.segment.virtual.ExpressionVirtualColumn) ExpectedException(org.junit.rules.ExpectedException) CountAggregatorFactory(org.apache.druid.query.aggregation.CountAggregatorFactory) FloatFirstAggregatorFactory(org.apache.druid.query.aggregation.first.FloatFirstAggregatorFactory) Nullable(javax.annotation.Nullable) DoubleMaxAggregatorFactory(org.apache.druid.query.aggregation.DoubleMaxAggregatorFactory) CardinalityAggregatorFactory(org.apache.druid.query.aggregation.cardinality.CardinalityAggregatorFactory) ExpressionLambdaAggregatorFactory(org.apache.druid.query.aggregation.ExpressionLambdaAggregatorFactory) ResponseContext(org.apache.druid.query.context.ResponseContext) TimeFormatExtractionFn(org.apache.druid.query.extraction.TimeFormatExtractionFn) InitializedNullHandlingTest(org.apache.druid.testing.InitializedNullHandlingTest) Test(org.junit.Test) IOException(java.io.IOException) ExtractionDimFilter(org.apache.druid.query.filter.ExtractionDimFilter) StrlenExtractionFn(org.apache.druid.query.extraction.StrlenExtractionFn) Granularities(org.apache.druid.java.util.common.granularity.Granularities) Result(org.apache.druid.query.Result) TestHelper(org.apache.druid.segment.TestHelper) Rule(org.junit.Rule) NullHandling(org.apache.druid.common.config.NullHandling) ColumnType(org.apache.druid.segment.column.ColumnType) Preconditions(com.google.common.base.Preconditions) Assert(org.junit.Assert) Collections(java.util.Collections) BySegmentResultValue(org.apache.druid.query.BySegmentResultValue) HashMap(java.util.HashMap) IAE(org.apache.druid.java.util.common.IAE) Result(org.apache.druid.query.Result) ISE(org.apache.druid.java.util.common.ISE) InitializedNullHandlingTest(org.apache.druid.testing.InitializedNullHandlingTest) Test(org.junit.Test)

Example 13 with ISE

use of org.apache.druid.java.util.common.ISE in project druid by druid-io.

the class JettyServerModule method makeAndInitializeServer.

static Server makeAndInitializeServer(Injector injector, Lifecycle lifecycle, DruidNode node, ServerConfig config, TLSServerConfig tlsServerConfig, Binding<SslContextFactory.Server> sslContextFactoryBinding, TLSCertificateChecker certificateChecker) {
    // adjusting to make config.getNumThreads() mean, "number of threads
    // that concurrently handle the requests".
    int numServerThreads = config.getNumThreads() + getMaxJettyAcceptorsSelectorsNum(node);
    final QueuedThreadPool threadPool;
    if (config.getQueueSize() == Integer.MAX_VALUE) {
        threadPool = new QueuedThreadPool();
        threadPool.setMinThreads(numServerThreads);
        threadPool.setMaxThreads(numServerThreads);
    } else {
        threadPool = new QueuedThreadPool(numServerThreads, numServerThreads, // same default is used in other case when threadPool = new QueuedThreadPool()
        60000, new LinkedBlockingQueue<>(config.getQueueSize()));
    }
    threadPool.setDaemon(true);
    jettyServerThreadPool = threadPool;
    final Server server = new Server(threadPool);
    // Without this bean set, the default ScheduledExecutorScheduler runs as non-daemon, causing lifecycle hooks to fail
    // to fire on main exit. Related bug: https://github.com/apache/druid/pull/1627
    server.addBean(new ScheduledExecutorScheduler("JettyScheduler", true), true);
    final List<ServerConnector> serverConnectors = new ArrayList<>();
    if (node.isEnablePlaintextPort()) {
        log.info("Creating http connector with port [%d]", node.getPlaintextPort());
        HttpConfiguration httpConfiguration = new HttpConfiguration();
        if (config.isEnableForwardedRequestCustomizer()) {
            httpConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }
        httpConfiguration.setRequestHeaderSize(config.getMaxRequestHeaderSize());
        httpConfiguration.setSendServerVersion(false);
        final ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfiguration));
        if (node.isBindOnHost()) {
            connector.setHost(node.getHost());
        }
        connector.setPort(node.getPlaintextPort());
        serverConnectors.add(connector);
    }
    final SslContextFactory.Server sslContextFactory;
    if (node.isEnableTlsPort()) {
        log.info("Creating https connector with port [%d]", node.getTlsPort());
        if (sslContextFactoryBinding == null) {
            // Never trust all certificates by default
            sslContextFactory = new IdentityCheckOverrideSslContextFactory(tlsServerConfig, certificateChecker);
            sslContextFactory.setKeyStorePath(tlsServerConfig.getKeyStorePath());
            sslContextFactory.setKeyStoreType(tlsServerConfig.getKeyStoreType());
            sslContextFactory.setKeyStorePassword(tlsServerConfig.getKeyStorePasswordProvider().getPassword());
            sslContextFactory.setCertAlias(tlsServerConfig.getCertAlias());
            sslContextFactory.setKeyManagerFactoryAlgorithm(tlsServerConfig.getKeyManagerFactoryAlgorithm() == null ? KeyManagerFactory.getDefaultAlgorithm() : tlsServerConfig.getKeyManagerFactoryAlgorithm());
            sslContextFactory.setKeyManagerPassword(tlsServerConfig.getKeyManagerPasswordProvider() == null ? null : tlsServerConfig.getKeyManagerPasswordProvider().getPassword());
            if (tlsServerConfig.getIncludeCipherSuites() != null) {
                sslContextFactory.setIncludeCipherSuites(tlsServerConfig.getIncludeCipherSuites().toArray(new String[0]));
            }
            if (tlsServerConfig.getExcludeCipherSuites() != null) {
                sslContextFactory.setExcludeCipherSuites(tlsServerConfig.getExcludeCipherSuites().toArray(new String[0]));
            }
            if (tlsServerConfig.getIncludeProtocols() != null) {
                sslContextFactory.setIncludeProtocols(tlsServerConfig.getIncludeProtocols().toArray(new String[0]));
            }
            if (tlsServerConfig.getExcludeProtocols() != null) {
                sslContextFactory.setExcludeProtocols(tlsServerConfig.getExcludeProtocols().toArray(new String[0]));
            }
            sslContextFactory.setNeedClientAuth(tlsServerConfig.isRequireClientCertificate());
            sslContextFactory.setWantClientAuth(tlsServerConfig.isRequestClientCertificate());
            if (tlsServerConfig.isRequireClientCertificate() || tlsServerConfig.isRequestClientCertificate()) {
                if (tlsServerConfig.getCrlPath() != null) {
                    // setValidatePeerCerts is used just to enable revocation checking using a static CRL file.
                    // Certificate validation is always performed when client certificates are required.
                    sslContextFactory.setValidatePeerCerts(true);
                    sslContextFactory.setCrlPath(tlsServerConfig.getCrlPath());
                }
                if (tlsServerConfig.isValidateHostnames()) {
                    sslContextFactory.setEndpointIdentificationAlgorithm("HTTPS");
                }
                if (tlsServerConfig.getTrustStorePath() != null) {
                    sslContextFactory.setTrustStorePath(tlsServerConfig.getTrustStorePath());
                    sslContextFactory.setTrustStoreType(tlsServerConfig.getTrustStoreType() == null ? KeyStore.getDefaultType() : tlsServerConfig.getTrustStoreType());
                    sslContextFactory.setTrustManagerFactoryAlgorithm(tlsServerConfig.getTrustStoreAlgorithm() == null ? TrustManagerFactory.getDefaultAlgorithm() : tlsServerConfig.getTrustStoreAlgorithm());
                    sslContextFactory.setTrustStorePassword(tlsServerConfig.getTrustStorePasswordProvider() == null ? null : tlsServerConfig.getTrustStorePasswordProvider().getPassword());
                }
            }
        } else {
            sslContextFactory = sslContextFactoryBinding.getProvider().get();
        }
        final HttpConfiguration httpsConfiguration = new HttpConfiguration();
        if (config.isEnableForwardedRequestCustomizer()) {
            httpsConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }
        httpsConfiguration.setSecureScheme("https");
        httpsConfiguration.setSecurePort(node.getTlsPort());
        httpsConfiguration.addCustomizer(new SecureRequestCustomizer());
        httpsConfiguration.setRequestHeaderSize(config.getMaxRequestHeaderSize());
        httpsConfiguration.setSendServerVersion(false);
        final ServerConnector connector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HTTP_1_1_STRING), new HttpConnectionFactory(httpsConfiguration));
        if (node.isBindOnHost()) {
            connector.setHost(node.getHost());
        }
        connector.setPort(node.getTlsPort());
        serverConnectors.add(connector);
    } else {
        sslContextFactory = null;
    }
    final ServerConnector[] connectors = new ServerConnector[serverConnectors.size()];
    int index = 0;
    for (ServerConnector connector : serverConnectors) {
        connectors[index++] = connector;
        connector.setIdleTimeout(Ints.checkedCast(config.getMaxIdleTime().toStandardDuration().getMillis()));
        // workaround suggested in -
        // https://bugs.eclipse.org/bugs/show_bug.cgi?id=435322#c66 for jetty half open connection issues during failovers
        connector.setAcceptorPriorityDelta(-1);
        List<ConnectionFactory> monitoredConnFactories = new ArrayList<>();
        for (ConnectionFactory cf : connector.getConnectionFactories()) {
            // connection factories (in this case HTTP/1.1 after the connection is unencrypted for SSL)
            if (cf.getProtocol().equals(connector.getDefaultProtocol())) {
                monitoredConnFactories.add(new JettyMonitoringConnectionFactory(cf, ACTIVE_CONNECTIONS));
            } else {
                monitoredConnFactories.add(cf);
            }
        }
        connector.setConnectionFactories(monitoredConnFactories);
    }
    server.setConnectors(connectors);
    final long gracefulStop = config.getGracefulShutdownTimeout().toStandardDuration().getMillis();
    if (gracefulStop > 0) {
        server.setStopTimeout(gracefulStop);
    }
    server.addLifeCycleListener(new LifeCycle.Listener() {

        @Override
        public void lifeCycleStarting(LifeCycle event) {
            log.debug("Jetty lifecycle starting [%s]", event.getClass());
        }

        @Override
        public void lifeCycleStarted(LifeCycle event) {
            log.debug("Jetty lifeycle started [%s]", event.getClass());
        }

        @Override
        public void lifeCycleFailure(LifeCycle event, Throwable cause) {
            log.error(cause, "Jetty lifecycle event failed [%s]", event.getClass());
        }

        @Override
        public void lifeCycleStopping(LifeCycle event) {
            log.debug("Jetty lifecycle stopping [%s]", event.getClass());
        }

        @Override
        public void lifeCycleStopped(LifeCycle event) {
            log.debug("Jetty lifecycle stopped [%s]", event.getClass());
        }
    });
    // initialize server
    JettyServerInitializer initializer = injector.getInstance(JettyServerInitializer.class);
    try {
        initializer.initialize(server, injector);
    } catch (Exception e) {
        throw new RE(e, "server initialization exception");
    }
    lifecycle.addHandler(new Lifecycle.Handler() {

        @Override
        public void start() throws Exception {
            log.debug("Starting Jetty Server...");
            server.start();
            if (node.isEnableTlsPort()) {
                // Perform validation
                Preconditions.checkNotNull(sslContextFactory);
                final SSLEngine sslEngine = sslContextFactory.newSSLEngine();
                if (sslEngine.getEnabledCipherSuites() == null || sslEngine.getEnabledCipherSuites().length == 0) {
                    throw new ISE("No supported cipher suites found, supported suites [%s], configured suites include list: [%s] exclude list: [%s]", Arrays.toString(sslEngine.getSupportedCipherSuites()), tlsServerConfig.getIncludeCipherSuites(), tlsServerConfig.getExcludeCipherSuites());
                }
                if (sslEngine.getEnabledProtocols() == null || sslEngine.getEnabledProtocols().length == 0) {
                    throw new ISE("No supported protocols found, supported protocols [%s], configured protocols include list: [%s] exclude list: [%s]", Arrays.toString(sslEngine.getSupportedProtocols()), tlsServerConfig.getIncludeProtocols(), tlsServerConfig.getExcludeProtocols());
                }
            }
        }

        @Override
        public void stop() {
            try {
                final long unannounceDelay = config.getUnannouncePropagationDelay().toStandardDuration().getMillis();
                if (unannounceDelay > 0) {
                    log.info("Sleeping %s ms for unannouncement to propagate.", unannounceDelay);
                    Thread.sleep(unannounceDelay);
                } else {
                    log.debug("Skipping unannounce wait.");
                }
                log.debug("Stopping Jetty Server...");
                server.stop();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RE(e, "Interrupted waiting for jetty shutdown.");
            } catch (Exception e) {
                log.warn(e, "Unable to stop Jetty server.");
            }
        }
    }, Lifecycle.Stage.SERVER);
    if (!config.isShowDetailedJettyErrors()) {
        server.setErrorHandler(new ErrorHandler() {

            @Override
            public boolean isShowServlet() {
                return false;
            }

            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, null);
                super.handle(target, baseRequest, request, response);
            }
        });
    }
    return server;
}
Also used : LifeCycle(org.eclipse.jetty.util.component.LifeCycle) Server(org.eclipse.jetty.server.Server) SSLEngine(javax.net.ssl.SSLEngine) ScheduledExecutorScheduler(org.eclipse.jetty.util.thread.ScheduledExecutorScheduler) ArrayList(java.util.ArrayList) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ConnectionFactory(org.eclipse.jetty.server.ConnectionFactory) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ISE(org.apache.druid.java.util.common.ISE) ErrorHandler(org.eclipse.jetty.server.handler.ErrorHandler) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) Lifecycle(org.apache.druid.java.util.common.lifecycle.Lifecycle) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) ForwardedRequestCustomizer(org.eclipse.jetty.server.ForwardedRequestCustomizer) RE(org.apache.druid.java.util.common.RE)

Example 14 with ISE

use of org.apache.druid.java.util.common.ISE in project druid by druid-io.

the class LookupCoordinatorManager method start.

// start() and stop() are synchronized so that they never run in parallel in case of ZK acting funny or druid bug and
// coordinator becomes leader and drops leadership in quick succession.
public void start() {
    synchronized (lifecycleLock) {
        if (!lifecycleLock.canStart()) {
            throw new ISE("LookupCoordinatorManager can't start.");
        }
        try {
            LOG.debug("Starting.");
            if (lookupNodeDiscovery == null) {
                lookupNodeDiscovery = new LookupNodeDiscovery(druidNodeDiscoveryProvider);
            }
            // so that we don't have multiple live executorService instances lying around doing lookup management.
            if (executorService != null && !executorService.awaitTermination(lookupCoordinatorManagerConfig.getHostTimeout().getMillis() * 10, TimeUnit.MILLISECONDS)) {
                throw new ISE("LookupCoordinatorManager executor from last start() hasn't finished. Failed to Start.");
            }
            executorService = MoreExecutors.listeningDecorator(Executors.newScheduledThreadPool(lookupCoordinatorManagerConfig.getThreadPoolSize(), Execs.makeThreadFactory("LookupCoordinatorManager--%s")));
            initializeLookupsConfigWatcher();
            this.backgroundManagerExitedLatch = new CountDownLatch(1);
            this.backgroundManagerFuture = executorService.scheduleWithFixedDelay(this::lookupManagementLoop, lookupCoordinatorManagerConfig.getInitialDelay(), lookupCoordinatorManagerConfig.getPeriod(), TimeUnit.MILLISECONDS);
            Futures.addCallback(backgroundManagerFuture, new FutureCallback<Object>() {

                @Override
                public void onSuccess(@Nullable Object result) {
                    backgroundManagerExitedLatch.countDown();
                    LOG.debug("Exited background lookup manager");
                }

                @Override
                public void onFailure(Throwable t) {
                    backgroundManagerExitedLatch.countDown();
                    if (backgroundManagerFuture.isCancelled()) {
                        LOG.debug("Exited background lookup manager due to cancellation.");
                    } else {
                        LOG.makeAlert(t, "Background lookup manager exited with error!").emit();
                    }
                }
            });
            LOG.debug("Started");
        } catch (Exception ex) {
            LOG.makeAlert(ex, "Got Exception while start()").emit();
        } finally {
            // so that subsequent stop() would happen, even if start() failed with exception
            lifecycleLock.started();
            lifecycleLock.exitStart();
        }
    }
}
Also used : ISE(org.apache.druid.java.util.common.ISE) CountDownLatch(java.util.concurrent.CountDownLatch) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Example 15 with ISE

use of org.apache.druid.java.util.common.ISE in project druid by druid-io.

the class JoinableFactoryWrapper method convertJoinsToFilters.

/**
 * Converts any join clauses to filters that can be converted, and returns the rest as-is.
 *
 * See {@link #convertJoinToFilter} for details on the logic.
 */
@VisibleForTesting
static Pair<List<Filter>, List<JoinableClause>> convertJoinsToFilters(final List<JoinableClause> clauses, final Set<String> requiredColumns, final int maxNumFilterValues) {
    final List<Filter> filterList = new ArrayList<>();
    final List<JoinableClause> clausesToUse = new ArrayList<>();
    // Join clauses may depend on other, earlier join clauses.
    // We track that using a Multiset, because we'll need to remove required columns one by one as we convert clauses,
    // and multiple clauses may refer to the same column.
    final Multiset<String> columnsRequiredByJoinClauses = HashMultiset.create();
    for (JoinableClause clause : clauses) {
        for (String column : clause.getCondition().getRequiredColumns()) {
            columnsRequiredByJoinClauses.add(column, 1);
        }
    }
    // Walk through the list of clauses, picking off any from the start of the list that can be converted to filters.
    boolean atStart = true;
    for (JoinableClause clause : clauses) {
        if (atStart) {
            // Remove this clause from columnsRequiredByJoinClauses. It's ok if it relies on itself.
            for (String column : clause.getCondition().getRequiredColumns()) {
                columnsRequiredByJoinClauses.remove(column, 1);
            }
            final Optional<Filter> filter = convertJoinToFilter(clause, Sets.union(requiredColumns, columnsRequiredByJoinClauses.elementSet()), maxNumFilterValues);
            if (filter.isPresent()) {
                filterList.add(filter.get());
            } else {
                clausesToUse.add(clause);
                atStart = false;
            }
        } else {
            clausesToUse.add(clause);
        }
    }
    // Sanity check. If this exception is ever thrown, it's a bug.
    if (filterList.size() + clausesToUse.size() != clauses.size()) {
        throw new ISE("Lost a join clause during planning");
    }
    return Pair.of(filterList, clausesToUse);
}
Also used : InDimFilter(org.apache.druid.query.filter.InDimFilter) Filter(org.apache.druid.query.filter.Filter) ArrayList(java.util.ArrayList) ISE(org.apache.druid.java.util.common.ISE) PreJoinableClause(org.apache.druid.query.planning.PreJoinableClause) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

ISE (org.apache.druid.java.util.common.ISE)354 IOException (java.io.IOException)95 ArrayList (java.util.ArrayList)90 Map (java.util.Map)68 List (java.util.List)60 File (java.io.File)48 Interval (org.joda.time.Interval)48 DataSegment (org.apache.druid.timeline.DataSegment)44 HashMap (java.util.HashMap)43 Nullable (javax.annotation.Nullable)43 URL (java.net.URL)36 StatusResponseHolder (org.apache.druid.java.util.http.client.response.StatusResponseHolder)33 Request (org.apache.druid.java.util.http.client.Request)30 ExecutionException (java.util.concurrent.ExecutionException)29 ImmutableMap (com.google.common.collect.ImmutableMap)28 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)28 VisibleForTesting (com.google.common.annotations.VisibleForTesting)27 Collectors (java.util.stream.Collectors)27 IAE (org.apache.druid.java.util.common.IAE)27 ImmutableList (com.google.common.collect.ImmutableList)26