Search in sources :

Example 16 with Duration

use of org.joda.time.Duration in project druid by druid-io.

the class LookupCoordinatorManagerTest method testDeleteAllTierMissing.

@Test
public void testDeleteAllTierMissing() throws Exception {
    final HttpResponseHandler<InputStream, InputStream> responseHandler = EasyMock.createStrictMock(HttpResponseHandler.class);
    final LookupCoordinatorManager manager = new LookupCoordinatorManager(client, discoverer, mapper, configManager, lookupCoordinatorManagerConfig) {

        @Override
        HttpResponseHandler<InputStream, InputStream> makeResponseHandler(final AtomicInteger returnCode, final AtomicReference<String> reasonString) {
            returnCode.set(404);
            reasonString.set("");
            return responseHandler;
        }
    };
    final HostAndPort hostAndPort = HostAndPort.fromParts("someHost", 8080);
    final Collection<String> drop = ImmutableList.of("lookup1");
    EasyMock.expect(discoverer.getNodes(LookupModule.getTierListenerPath(LOOKUP_TIER))).andReturn(ImmutableList.of(hostAndPort)).once();
    final SettableFuture<InputStream> future = SettableFuture.create();
    future.set(new ByteArrayInputStream(new byte[0]));
    EasyMock.expect(client.go(EasyMock.<Request>anyObject(), EasyMock.<SequenceInputStreamResponseHandler>anyObject(), EasyMock.<Duration>anyObject())).andReturn(future).once();
    EasyMock.replay(client, discoverer, responseHandler);
    manager.deleteAllOnTier(LOOKUP_TIER, drop);
    EasyMock.verify(client, discoverer, responseHandler);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Request(com.metamx.http.client.Request) AtomicReference(java.util.concurrent.atomic.AtomicReference) Duration(org.joda.time.Duration) SequenceInputStreamResponseHandler(com.metamx.http.client.response.SequenceInputStreamResponseHandler) HostAndPort(com.google.common.net.HostAndPort) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ByteArrayInputStream(java.io.ByteArrayInputStream) Test(org.junit.Test)

Example 17 with Duration

use of org.joda.time.Duration in project druid by druid-io.

the class LookupCoordinatorManagerTest method testDeleteAllTierContinuesOnMissing.

@Test
public void testDeleteAllTierContinuesOnMissing() throws Exception {
    final HttpResponseHandler<InputStream, InputStream> responseHandler = EasyMock.createStrictMock(HttpResponseHandler.class);
    final AtomicInteger responseHandlerCalls = new AtomicInteger(0);
    final LookupCoordinatorManager manager = new LookupCoordinatorManager(client, discoverer, mapper, configManager, lookupCoordinatorManagerConfig) {

        @Override
        HttpResponseHandler<InputStream, InputStream> makeResponseHandler(final AtomicInteger returnCode, final AtomicReference<String> reasonString) {
            if (responseHandlerCalls.getAndIncrement() == 0) {
                returnCode.set(404);
                reasonString.set("Not Found");
            } else {
                returnCode.set(202);
                reasonString.set("");
            }
            return responseHandler;
        }
    };
    final HostAndPort hostAndPort = HostAndPort.fromParts("someHost", 8080);
    final Collection<String> drop = ImmutableList.of("lookup1");
    EasyMock.expect(discoverer.getNodes(LookupModule.getTierListenerPath(LOOKUP_TIER))).andReturn(ImmutableList.of(hostAndPort, hostAndPort)).once();
    final SettableFuture<InputStream> future = SettableFuture.create();
    future.set(new ByteArrayInputStream(new byte[0]));
    EasyMock.expect(client.go(EasyMock.<Request>anyObject(), EasyMock.<SequenceInputStreamResponseHandler>anyObject(), EasyMock.<Duration>anyObject())).andReturn(future).times(2);
    EasyMock.replay(client, discoverer, responseHandler);
    manager.deleteAllOnTier(LOOKUP_TIER, drop);
    EasyMock.verify(client, discoverer, responseHandler);
    Assert.assertEquals(2, responseHandlerCalls.get());
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Request(com.metamx.http.client.Request) AtomicReference(java.util.concurrent.atomic.AtomicReference) Duration(org.joda.time.Duration) SequenceInputStreamResponseHandler(com.metamx.http.client.response.SequenceInputStreamResponseHandler) HostAndPort(com.google.common.net.HostAndPort) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ByteArrayInputStream(java.io.ByteArrayInputStream) Test(org.junit.Test)

Example 18 with Duration

use of org.joda.time.Duration in project druid by druid-io.

the class KafkaIndexTaskClient method submitRequest.

private FullResponseHolder submitRequest(String id, HttpMethod method, String pathSuffix, String query, byte[] content, boolean retry) {
    final RetryPolicy retryPolicy = retryPolicyFactory.makeRetryPolicy();
    while (true) {
        FullResponseHolder response = null;
        Request request = null;
        TaskLocation location = TaskLocation.unknown();
        String path = String.format("%s/%s/%s", BASE_PATH, id, pathSuffix);
        Optional<TaskStatus> status = taskInfoProvider.getTaskStatus(id);
        if (!status.isPresent() || !status.get().isRunnable()) {
            throw new TaskNotRunnableException(String.format("Aborting request because task [%s] is not runnable", id));
        }
        try {
            location = taskInfoProvider.getTaskLocation(id);
            if (location.equals(TaskLocation.unknown())) {
                throw new NoTaskLocationException(String.format("No TaskLocation available for task [%s]", id));
            }
            // Netty throws some annoying exceptions if a connection can't be opened, which happens relatively frequently
            // for tasks that happen to still be starting up, so test the connection first to keep the logs clean.
            checkConnection(location.getHost(), location.getPort());
            try {
                URI serviceUri = new URI("http", null, location.getHost(), location.getPort(), path, query, null);
                request = new Request(method, serviceUri.toURL());
                // used to validate that we are talking to the correct worker
                request.addHeader(ChatHandlerResource.TASK_ID_HEADER, id);
                if (content.length > 0) {
                    request.setContent(MediaType.APPLICATION_JSON, content);
                }
                log.debug("HTTP %s: %s", method.getName(), serviceUri.toString());
                response = httpClient.go(request, new FullResponseHandler(Charsets.UTF_8), httpTimeout).get();
            } catch (Exception e) {
                Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);
                Throwables.propagateIfInstanceOf(e.getCause(), ChannelException.class);
                throw Throwables.propagate(e);
            }
            int responseCode = response.getStatus().getCode();
            if (responseCode / 100 == 2) {
                return response;
            } else if (responseCode == 400) {
                // don't bother retrying if it's a bad request
                throw new IAE("Received 400 Bad Request with body: %s", response.getContent());
            } else {
                throw new IOException(String.format("Received status [%d]", responseCode));
            }
        } catch (IOException | ChannelException e) {
            // Since workers are free to move tasks around to different ports, there is a chance that a task may have been
            // moved but our view of its location has not been updated yet from ZK. To detect this case, we send a header
            // identifying our expected recipient in the request; if this doesn't correspond to the worker we messaged, the
            // worker will return an HTTP 404 with its ID in the response header. If we get a mismatching task ID, then
            // we will wait for a short period then retry the request indefinitely, expecting the task's location to
            // eventually be updated.
            final Duration delay;
            if (response != null && response.getStatus().equals(HttpResponseStatus.NOT_FOUND)) {
                String headerId = response.getResponse().headers().get(ChatHandlerResource.TASK_ID_HEADER);
                if (headerId != null && !headerId.equals(id)) {
                    log.warn("Expected worker to have taskId [%s] but has taskId [%s], will retry in [%d]s", id, headerId, TASK_MISMATCH_RETRY_DELAY_SECONDS);
                    delay = Duration.standardSeconds(TASK_MISMATCH_RETRY_DELAY_SECONDS);
                } else {
                    delay = retryPolicy.getAndIncrementRetryDelay();
                }
            } else {
                delay = retryPolicy.getAndIncrementRetryDelay();
            }
            String urlForLog = (request != null ? request.getUrl().toString() : String.format("http://%s:%d%s", location.getHost(), location.getPort(), path));
            if (!retry) {
                // if retry=false, we probably aren't too concerned if the operation doesn't succeed (i.e. the request was
                // for informational purposes only) so don't log a scary stack trace
                log.info("submitRequest failed for [%s], with message [%s]", urlForLog, e.getMessage());
                Throwables.propagate(e);
            } else if (delay == null) {
                log.warn(e, "Retries exhausted for [%s], last exception:", urlForLog);
                Throwables.propagate(e);
            } else {
                try {
                    final long sleepTime = delay.getMillis();
                    log.debug("Bad response HTTP [%s] from [%s]; will try again in [%s] (body/exception: [%s])", (response != null ? response.getStatus().getCode() : "no response"), urlForLog, new Duration(sleepTime).toString(), (response != null ? response.getContent() : e.getMessage()));
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e2) {
                    Throwables.propagate(e2);
                }
            }
        } catch (NoTaskLocationException e) {
            log.info("No TaskLocation available for task [%s], this task may not have been assigned to a worker yet or " + "may have already completed", id);
            throw e;
        } catch (Exception e) {
            log.warn(e, "Exception while sending request");
            throw e;
        }
    }
}
Also used : Request(com.metamx.http.client.Request) Duration(org.joda.time.Duration) IOException(java.io.IOException) TaskStatus(io.druid.indexing.common.TaskStatus) IAE(io.druid.java.util.common.IAE) URI(java.net.URI) TaskLocation(io.druid.indexing.common.TaskLocation) ChannelException(org.jboss.netty.channel.ChannelException) IOException(java.io.IOException) FullResponseHandler(com.metamx.http.client.response.FullResponseHandler) FullResponseHolder(com.metamx.http.client.response.FullResponseHolder) RetryPolicy(io.druid.indexing.common.RetryPolicy) ChannelException(org.jboss.netty.channel.ChannelException)

Example 19 with Duration

use of org.joda.time.Duration in project druid by druid-io.

the class SQLMetadataSegmentManager method start.

@LifecycleStart
public void start() {
    synchronized (lock) {
        if (started) {
            return;
        }
        exec = MoreExecutors.listeningDecorator(Execs.scheduledSingleThreaded("DatabaseSegmentManager-Exec--%d"));
        final Duration delay = config.get().getPollDuration().toStandardDuration();
        future = exec.scheduleWithFixedDelay(new Runnable() {

            @Override
            public void run() {
                try {
                    poll();
                } catch (Exception e) {
                    log.makeAlert(e, "uncaught exception in segment manager polling thread").emit();
                }
            }
        }, 0, delay.getMillis(), TimeUnit.MILLISECONDS);
        started = true;
    }
}
Also used : Duration(org.joda.time.Duration) SQLException(java.sql.SQLException) IOException(java.io.IOException) LifecycleStart(io.druid.java.util.common.lifecycle.LifecycleStart)

Example 20 with Duration

use of org.joda.time.Duration in project druid by druid-io.

the class AppenderatorPlumber method startPersistThread.

private void startPersistThread() {
    final Granularity segmentGranularity = schema.getGranularitySpec().getSegmentGranularity();
    final Period windowPeriod = config.getWindowPeriod();
    final DateTime truncatedNow = segmentGranularity.bucketStart(new DateTime());
    final long windowMillis = windowPeriod.toStandardDuration().getMillis();
    log.info("Expect to run at [%s]", new DateTime().plus(new Duration(System.currentTimeMillis(), segmentGranularity.increment(truncatedNow).getMillis() + windowMillis)));
    ScheduledExecutors.scheduleAtFixedRate(scheduledExecutor, new Duration(System.currentTimeMillis(), segmentGranularity.increment(truncatedNow).getMillis() + windowMillis), new Duration(truncatedNow, segmentGranularity.increment(truncatedNow)), new ThreadRenamingCallable<ScheduledExecutors.Signal>(String.format("%s-overseer-%d", schema.getDataSource(), config.getShardSpec().getPartitionNum())) {

        @Override
        public ScheduledExecutors.Signal doCall() {
            if (stopped) {
                log.info("Stopping merge-n-push overseer thread");
                return ScheduledExecutors.Signal.STOP;
            }
            mergeAndPush();
            if (stopped) {
                log.info("Stopping merge-n-push overseer thread");
                return ScheduledExecutors.Signal.STOP;
            } else {
                return ScheduledExecutors.Signal.REPEAT;
            }
        }
    });
}
Also used : Period(org.joda.time.Period) Duration(org.joda.time.Duration) Granularity(io.druid.java.util.common.granularity.Granularity) DateTime(org.joda.time.DateTime)

Aggregations

Duration (org.joda.time.Duration)272 Test (org.junit.Test)148 Instant (org.joda.time.Instant)66 DateTime (org.joda.time.DateTime)32 Period (org.joda.time.Period)27 IntervalWindow (org.apache.beam.sdk.transforms.windowing.IntervalWindow)24 TestDruidCoordinatorConfig (org.apache.druid.server.coordinator.TestDruidCoordinatorConfig)22 HashMap (java.util.HashMap)18 IOException (java.io.IOException)17 Category (org.junit.experimental.categories.Category)16 ArrayList (java.util.ArrayList)15 Map (java.util.Map)15 KV (org.apache.beam.sdk.values.KV)15 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 IndexSpec (org.apache.druid.segment.IndexSpec)12 Set (java.util.Set)10 GlobalWindows (org.apache.beam.sdk.transforms.windowing.GlobalWindows)10 DynamicPartitionsSpec (org.apache.druid.indexer.partitions.DynamicPartitionsSpec)10 Interval (org.joda.time.Interval)10 Request (com.metamx.http.client.Request)9