Search in sources :

Example 46 with Duration

use of io.airlift.units.Duration in project presto by prestodb.

the class TaskResource method getResults.

@GET
@Path("{taskId}/results/{bufferId}/{token}")
@Produces(PRESTO_PAGES)
public void getResults(@PathParam("taskId") TaskId taskId, @PathParam("bufferId") OutputBufferId bufferId, @PathParam("token") final long token, @HeaderParam(PRESTO_MAX_SIZE) DataSize maxSize, @Suspended AsyncResponse asyncResponse) throws InterruptedException {
    requireNonNull(taskId, "taskId is null");
    requireNonNull(bufferId, "bufferId is null");
    long start = System.nanoTime();
    ListenableFuture<BufferResult> bufferResultFuture = taskManager.getTaskResults(taskId, bufferId, token, maxSize);
    Duration waitTime = randomizeWaitTime(DEFAULT_MAX_WAIT_TIME);
    bufferResultFuture = addTimeout(bufferResultFuture, () -> BufferResult.emptyResults(taskManager.getTaskInstanceId(taskId), token, false), waitTime, timeoutExecutor);
    ListenableFuture<Response> responseFuture = Futures.transform(bufferResultFuture, result -> {
        List<SerializedPage> serializedPages = result.getSerializedPages();
        GenericEntity<?> entity = null;
        Status status;
        if (serializedPages.isEmpty()) {
            status = Status.NO_CONTENT;
        } else {
            entity = new GenericEntity<>(serializedPages, new TypeToken<List<Page>>() {
            }.getType());
            status = Status.OK;
        }
        return Response.status(status).entity(entity).header(PRESTO_TASK_INSTANCE_ID, result.getTaskInstanceId()).header(PRESTO_PAGE_TOKEN, result.getToken()).header(PRESTO_PAGE_NEXT_TOKEN, result.getNextToken()).header(PRESTO_BUFFER_COMPLETE, result.isBufferComplete()).build();
    });
    // For hard timeout, add an additional 5 seconds to max wait for thread scheduling contention and GC
    Duration timeout = new Duration(waitTime.toMillis() + 5000, MILLISECONDS);
    bindAsyncResponse(asyncResponse, responseFuture, responseExecutor).withTimeout(timeout, Response.status(Status.NO_CONTENT).header(PRESTO_TASK_INSTANCE_ID, taskManager.getTaskInstanceId(taskId)).header(PRESTO_PAGE_TOKEN, token).header(PRESTO_PAGE_NEXT_TOKEN, token).header(PRESTO_BUFFER_COMPLETE, false).build());
    responseFuture.addListener(() -> readFromOutputBufferTime.add(Duration.nanosSince(start)), directExecutor());
    asyncResponse.register((CompletionCallback) throwable -> resultsRequestTime.add(Duration.nanosSince(start)));
}
Also used : TaskStatus(com.facebook.presto.execution.TaskStatus) Status(javax.ws.rs.core.Response.Status) Page(com.facebook.presto.spi.Page) Produces(javax.ws.rs.Produces) Iterables.transform(com.google.common.collect.Iterables.transform) TaskStatus(com.facebook.presto.execution.TaskStatus) Path(javax.ws.rs.Path) AsyncResponseHandler.bindAsyncResponse(io.airlift.http.server.AsyncResponseHandler.bindAsyncResponse) TaskState(com.facebook.presto.execution.TaskState) Duration(io.airlift.units.Duration) OutputBufferId(com.facebook.presto.OutputBuffers.OutputBufferId) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) BoundedExecutor(io.airlift.concurrent.BoundedExecutor) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) BufferResult(com.facebook.presto.execution.buffer.BufferResult) DELETE(javax.ws.rs.DELETE) PRESTO_PAGE_TOKEN(com.facebook.presto.client.PrestoHeaders.PRESTO_PAGE_TOKEN) Context(javax.ws.rs.core.Context) AsyncResponse(javax.ws.rs.container.AsyncResponse) GenericEntity(javax.ws.rs.core.GenericEntity) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Suspended(javax.ws.rs.container.Suspended) MoreExecutors.directExecutor(com.google.common.util.concurrent.MoreExecutors.directExecutor) DataSize(io.airlift.units.DataSize) List(java.util.List) Response(javax.ws.rs.core.Response) CompletionCallback(javax.ws.rs.container.CompletionCallback) PRESTO_BUFFER_COMPLETE(com.facebook.presto.client.PrestoHeaders.PRESTO_BUFFER_COMPLETE) SerializedPage(com.facebook.presto.execution.buffer.SerializedPage) UriInfo(javax.ws.rs.core.UriInfo) PRESTO_CURRENT_STATE(com.facebook.presto.client.PrestoHeaders.PRESTO_CURRENT_STATE) Nested(org.weakref.jmx.Nested) PathParam(javax.ws.rs.PathParam) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) GET(javax.ws.rs.GET) TypeToken(com.google.common.reflect.TypeToken) Inject(javax.inject.Inject) PRESTO_TASK_INSTANCE_ID(com.facebook.presto.client.PrestoHeaders.PRESTO_TASK_INSTANCE_ID) ImmutableList(com.google.common.collect.ImmutableList) Managed(org.weakref.jmx.Managed) PRESTO_MAX_SIZE(com.facebook.presto.client.PrestoHeaders.PRESTO_MAX_SIZE) TaskManager(com.facebook.presto.execution.TaskManager) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Objects.requireNonNull(java.util.Objects.requireNonNull) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) MoreFutures.addTimeout(io.airlift.concurrent.MoreFutures.addTimeout) PRESTO_PAGE_NEXT_TOKEN(com.facebook.presto.client.PrestoHeaders.PRESTO_PAGE_NEXT_TOKEN) SessionPropertyManager(com.facebook.presto.metadata.SessionPropertyManager) TimeStat(io.airlift.stats.TimeStat) Status(javax.ws.rs.core.Response.Status) POST(javax.ws.rs.POST) Executor(java.util.concurrent.Executor) Session(com.facebook.presto.Session) PRESTO_MAX_WAIT(com.facebook.presto.client.PrestoHeaders.PRESTO_MAX_WAIT) Futures(com.google.common.util.concurrent.Futures) PRESTO_PAGES(com.facebook.presto.PrestoMediaTypes.PRESTO_PAGES) TaskId(com.facebook.presto.execution.TaskId) TaskInfo(com.facebook.presto.execution.TaskInfo) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Duration(io.airlift.units.Duration) AsyncResponseHandler.bindAsyncResponse(io.airlift.http.server.AsyncResponseHandler.bindAsyncResponse) AsyncResponse(javax.ws.rs.container.AsyncResponse) Response(javax.ws.rs.core.Response) BufferResult(com.facebook.presto.execution.buffer.BufferResult) SerializedPage(com.facebook.presto.execution.buffer.SerializedPage) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 47 with Duration

use of io.airlift.units.Duration in project presto by prestodb.

the class AssignmentLimiter method checkAssignFrom.

public synchronized void checkAssignFrom(String nodeIdentifier) {
    if (offlineNodes.contains(nodeIdentifier)) {
        return;
    }
    long now = ticker.read();
    long start = delayedNodes.computeIfAbsent(nodeIdentifier, key -> now);
    Duration delay = new Duration(now - start, NANOSECONDS);
    if (delay.compareTo(reassignmentDelay) < 0) {
        throw new PrestoException(RAPTOR_REASSIGNMENT_DELAY, format("Reassignment delay is in effect for node %s (elapsed: %s)", nodeIdentifier, delay.convertToMostSuccinctTimeUnit()));
    }
    if (lastOfflined.isPresent()) {
        delay = new Duration(now - lastOfflined.getAsLong(), NANOSECONDS);
        if (delay.compareTo(reassignmentInterval) < 0) {
            throw new PrestoException(RAPTOR_REASSIGNMENT_THROTTLE, format("Reassignment throttle is in effect for node %s (elapsed: %s)", nodeIdentifier, delay.convertToMostSuccinctTimeUnit()));
        }
    }
    delayedNodes.remove(nodeIdentifier);
    offlineNodes.add(nodeIdentifier);
    lastOfflined = OptionalLong.of(now);
}
Also used : Duration(io.airlift.units.Duration) PrestoException(com.facebook.presto.spi.PrestoException)

Example 48 with Duration

use of io.airlift.units.Duration in project presto by prestodb.

the class ShardRecoveryManager method restoreFromBackup.

@VisibleForTesting
void restoreFromBackup(UUID shardUuid, OptionalLong shardSize) {
    File storageFile = storageService.getStorageFile(shardUuid);
    if (!backupStore.get().shardExists(shardUuid)) {
        stats.incrementShardRecoveryBackupNotFound();
        throw new PrestoException(RAPTOR_RECOVERY_ERROR, "No backup file found for shard: " + shardUuid);
    }
    if (storageFile.exists()) {
        if (!shardSize.isPresent() || (storageFile.length() == shardSize.getAsLong())) {
            return;
        }
        log.warn("Local shard file is corrupt. Deleting local file: %s", storageFile);
        storageFile.delete();
    }
    // create a temporary file in the staging directory
    File stagingFile = temporarySuffix(storageService.getStagingFile(shardUuid));
    storageService.createParents(stagingFile);
    // copy to temporary file
    log.info("Copying shard %s from backup...", shardUuid);
    long start = System.nanoTime();
    try {
        backupStore.get().restoreShard(shardUuid, stagingFile);
    } catch (PrestoException e) {
        stats.incrementShardRecoveryFailure();
        stagingFile.delete();
        throw e;
    }
    Duration duration = nanosSince(start);
    DataSize size = succinctBytes(stagingFile.length());
    DataSize rate = dataRate(size, duration).convertToMostSuccinctDataSize();
    stats.addShardRecoveryDataRate(rate, size, duration);
    log.info("Copied shard %s from backup in %s (%s at %s/s)", shardUuid, duration, size, rate);
    // move to final location
    storageService.createParents(storageFile);
    try {
        Files.move(stagingFile.toPath(), storageFile.toPath(), ATOMIC_MOVE);
    } catch (FileAlreadyExistsException e) {
    // someone else already created it (should not happen, but safe to ignore)
    } catch (IOException e) {
        stats.incrementShardRecoveryFailure();
        throw new PrestoException(RAPTOR_RECOVERY_ERROR, "Failed to move shard: " + shardUuid, e);
    } finally {
        stagingFile.delete();
    }
    if (!storageFile.exists() || (shardSize.isPresent() && (storageFile.length() != shardSize.getAsLong()))) {
        stats.incrementShardRecoveryFailure();
        log.info("Files do not match after recovery. Deleting local file: " + shardUuid);
        storageFile.delete();
        throw new PrestoException(RAPTOR_RECOVERY_ERROR, "File not recovered correctly: " + shardUuid);
    }
    stats.incrementShardRecoverySuccess();
}
Also used : FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) DataSize.succinctDataSize(io.airlift.units.DataSize.succinctDataSize) DataSize(io.airlift.units.DataSize) PrestoException(com.facebook.presto.spi.PrestoException) Duration(io.airlift.units.Duration) IOException(java.io.IOException) File(java.io.File) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 49 with Duration

use of io.airlift.units.Duration in project presto by prestodb.

the class TestStorageManagerConfig method testExplicitPropertyMappings.

@Test
public void testExplicitPropertyMappings() {
    Map<String, String> properties = new ImmutableMap.Builder<String, String>().put("storage.data-directory", "/data").put("storage.min-available-space", "123GB").put("storage.orc.max-merge-distance", "16kB").put("storage.orc.max-read-size", "16kB").put("storage.orc.stream-buffer-size", "16kB").put("storage.max-deletion-threads", "999").put("storage.shard-recovery-timeout", "1m").put("storage.missing-shard-discovery-interval", "4m").put("storage.compaction-enabled", "false").put("storage.compaction-interval", "4h").put("storage.organization-enabled", "false").put("storage.organization-interval", "4h").put("storage.ejector-interval", "9h").put("storage.max-recovery-threads", "12").put("storage.max-organization-threads", "12").put("storage.max-shard-rows", "10000").put("storage.max-shard-size", "10MB").put("storage.max-buffer-size", "512MB").put("storage.one-split-per-bucket-threshold", "4").build();
    StorageManagerConfig expected = new StorageManagerConfig().setDataDirectory(new File("/data")).setMinAvailableSpace(new DataSize(123, GIGABYTE)).setOrcMaxMergeDistance(new DataSize(16, KILOBYTE)).setOrcMaxReadSize(new DataSize(16, KILOBYTE)).setOrcStreamBufferSize(new DataSize(16, KILOBYTE)).setDeletionThreads(999).setShardRecoveryTimeout(new Duration(1, MINUTES)).setMissingShardDiscoveryInterval(new Duration(4, MINUTES)).setCompactionEnabled(false).setCompactionInterval(new Duration(4, HOURS)).setOrganizationEnabled(false).setOrganizationInterval(new Duration(4, HOURS)).setShardEjectorInterval(new Duration(9, HOURS)).setRecoveryThreads(12).setOrganizationThreads(12).setMaxShardRows(10_000).setMaxShardSize(new DataSize(10, MEGABYTE)).setMaxBufferSize(new DataSize(512, MEGABYTE)).setOneSplitPerBucketThreshold(4);
    assertFullMapping(properties, expected);
}
Also used : DataSize(io.airlift.units.DataSize) Duration(io.airlift.units.Duration) File(java.io.File) Test(org.testng.annotations.Test)

Example 50 with Duration

use of io.airlift.units.Duration in project presto by prestodb.

the class TestMetadataConfig method testExplicitPropertyMappings.

@Test
public void testExplicitPropertyMappings() {
    Map<String, String> properties = new ImmutableMap.Builder<String, String>().put("raptor.startup-grace-period", "42m").put("raptor.reassignment-delay", "6m").put("raptor.reassignment-interval", "7m").build();
    MetadataConfig expected = new MetadataConfig().setStartupGracePeriod(new Duration(42, MINUTES)).setReassignmentDelay(new Duration(6, MINUTES)).setReassignmentInterval(new Duration(7, MINUTES));
    assertFullMapping(properties, expected);
}
Also used : Duration(io.airlift.units.Duration) Test(org.testng.annotations.Test)

Aggregations

Duration (io.airlift.units.Duration)124 Test (org.testng.annotations.Test)66 DataSize (io.airlift.units.DataSize)35 URI (java.net.URI)12 TestingHttpClient (io.airlift.http.client.testing.TestingHttpClient)11 Session (com.facebook.presto.Session)9 DateTime (org.joda.time.DateTime)9 ImmutableMap (com.google.common.collect.ImmutableMap)8 ImmutableSet (com.google.common.collect.ImmutableSet)8 TestingTicker (io.airlift.testing.TestingTicker)8 List (java.util.List)8 PrestoException (com.facebook.presto.spi.PrestoException)7 ImmutableList (com.google.common.collect.ImmutableList)7 File (java.io.File)6 PlanNodeId (com.facebook.presto.sql.planner.plan.PlanNodeId)5 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)5 CyclicBarrier (java.util.concurrent.CyclicBarrier)5 Produces (javax.ws.rs.Produces)5 Type (com.facebook.presto.spi.type.Type)4 IOException (java.io.IOException)4