Search in sources :

Example 26 with Duration

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

the class RemoteNodeState method asyncRefresh.

public synchronized void asyncRefresh() {
    Duration sinceUpdate = nanosSince(lastUpdateNanos.get());
    if (nanosSince(lastWarningLogged.get()).toMillis() > 1_000 && sinceUpdate.toMillis() > 10_000 && future.get() != null) {
        log.warn("Node state update request to %s has not returned in %s", stateInfoUri, sinceUpdate.toString(SECONDS));
        lastWarningLogged.set(System.nanoTime());
    }
    if (sinceUpdate.toMillis() > 1_000 && future.get() == null) {
        Request request = prepareGet().setUri(stateInfoUri).setHeader(CONTENT_TYPE, JSON_UTF_8.toString()).build();
        HttpResponseFuture<JsonResponse<NodeState>> responseFuture = httpClient.executeAsync(request, createFullJsonResponseHandler(jsonCodec(NodeState.class)));
        future.compareAndSet(null, responseFuture);
        Futures.addCallback(responseFuture, new FutureCallback<JsonResponse<NodeState>>() {

            @Override
            public void onSuccess(@Nullable JsonResponse<NodeState> result) {
                lastUpdateNanos.set(System.nanoTime());
                future.compareAndSet(responseFuture, null);
                if (result != null) {
                    if (result.hasValue()) {
                        nodeState.set(ofNullable(result.getValue()));
                    }
                    if (result.getStatusCode() != OK.code()) {
                        log.warn("Error fetching node state from %s returned status %d: %s", stateInfoUri, result.getStatusCode(), result.getStatusMessage());
                        return;
                    }
                }
            }

            @Override
            public void onFailure(Throwable t) {
                log.warn("Error fetching node state from %s: %s", stateInfoUri, t.getMessage());
                lastUpdateNanos.set(System.nanoTime());
                future.compareAndSet(responseFuture, null);
            }
        });
    }
}
Also used : NodeState(com.facebook.presto.spi.NodeState) Request(io.airlift.http.client.Request) Duration(io.airlift.units.Duration) JsonResponse(io.airlift.http.client.FullJsonResponseHandler.JsonResponse)

Example 27 with Duration

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

the class StatementResource method createQuery.

@POST
@Produces(MediaType.APPLICATION_JSON)
public Response createQuery(String statement, @Context HttpServletRequest servletRequest, @Context UriInfo uriInfo) throws InterruptedException {
    if (isNullOrEmpty(statement)) {
        throw new WebApplicationException(Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity("SQL statement is empty").build());
    }
    SessionSupplier sessionSupplier = new HttpRequestSessionFactory(servletRequest);
    ExchangeClient exchangeClient = exchangeClientSupplier.get(deltaMemoryInBytes -> {
    });
    Query query = new Query(sessionSupplier, statement, queryManager, sessionPropertyManager, exchangeClient, blockEncodingSerde);
    queries.put(query.getQueryId(), query);
    return getQueryResults(query, Optional.empty(), uriInfo, new Duration(1, MILLISECONDS));
}
Also used : ExchangeClient(com.facebook.presto.operator.ExchangeClient) WebApplicationException(javax.ws.rs.WebApplicationException) Duration(io.airlift.units.Duration) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 28 with Duration

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

the class StatementResource method getQueryResults.

@GET
@Path("{queryId}/{token}")
@Produces(MediaType.APPLICATION_JSON)
public Response getQueryResults(@PathParam("queryId") QueryId queryId, @PathParam("token") long token, @QueryParam("maxWait") Duration maxWait, @Context UriInfo uriInfo) throws InterruptedException {
    Query query = queries.get(queryId);
    if (query == null) {
        return Response.status(Status.NOT_FOUND).build();
    }
    Duration wait = WAIT_ORDERING.min(MAX_WAIT_TIME, maxWait);
    return getQueryResults(query, Optional.of(token), uriInfo, wait);
}
Also used : Duration(io.airlift.units.Duration) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 29 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 30 with Duration

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

the class TestDbResourceGroupConfigurationManager method testConfiguration.

@Test
public void testConfiguration() {
    H2DaoProvider daoProvider = setup("test_configuration");
    H2ResourceGroupsDao dao = daoProvider.get();
    dao.createResourceGroupsGlobalPropertiesTable();
    dao.createResourceGroupsTable();
    dao.createSelectorsTable();
    dao.insertResourceGroupsGlobalProperties("cpu_quota_period", "1h");
    dao.insertResourceGroup(1, "global", "1MB", 1000, 100, "weighted", null, true, "1h", "1d", null);
    dao.insertResourceGroup(2, "sub", "2MB", 4, 3, null, 5, null, null, null, 1L);
    dao.insertSelector(2, null, null);
    DbResourceGroupConfigurationManager manager = new DbResourceGroupConfigurationManager((poolId, listener) -> {
    }, daoProvider.get());
    AtomicBoolean exported = new AtomicBoolean();
    InternalResourceGroup global = new InternalResourceGroup.RootInternalResourceGroup("global", (group, export) -> exported.set(export), directExecutor());
    manager.configure(global, new SelectionContext(true, "user", Optional.empty(), 1));
    assertEqualsResourceGroup(global, "1MB", 1000, 100, WEIGHTED, DEFAULT_WEIGHT, true, new Duration(1, HOURS), new Duration(1, DAYS));
    exported.set(false);
    InternalResourceGroup sub = global.getOrCreateSubGroup("sub");
    manager.configure(sub, new SelectionContext(true, "user", Optional.empty(), 1));
    assertEqualsResourceGroup(sub, "2MB", 4, 3, FAIR, 5, false, new Duration(Long.MAX_VALUE, MILLISECONDS), new Duration(Long.MAX_VALUE, MILLISECONDS));
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) InternalResourceGroup(com.facebook.presto.execution.resourceGroups.InternalResourceGroup) Duration(io.airlift.units.Duration) SelectionContext(com.facebook.presto.spi.resourceGroups.SelectionContext) Test(org.testng.annotations.Test)

Aggregations

Duration (io.airlift.units.Duration)323 Test (org.testng.annotations.Test)203 DataSize (io.airlift.units.DataSize)66 ImmutableMap (com.google.common.collect.ImmutableMap)42 URI (java.net.URI)40 Map (java.util.Map)22 List (java.util.List)21 ImmutableList (com.google.common.collect.ImmutableList)18 TestingTicker (com.facebook.airlift.testing.TestingTicker)17 Optional (java.util.Optional)17 MILLISECONDS (java.util.concurrent.TimeUnit.MILLISECONDS)16 Assert.assertEquals (org.testng.Assert.assertEquals)16 Session (com.facebook.presto.Session)15 PrestoException (com.facebook.presto.spi.PrestoException)15 File (java.io.File)15 TaskId (com.facebook.presto.execution.TaskId)14 ImmutableSet (com.google.common.collect.ImmutableSet)14 SECONDS (java.util.concurrent.TimeUnit.SECONDS)13 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 TestingHttpClient (io.airlift.http.client.testing.TestingHttpClient)12