Search in sources :

Example 6 with Request

use of com.facebook.airlift.http.client.Request in project presto by prestodb.

the class HttpQueryStatsClient method getQueryStats.

@Override
public Optional<QueryStats> getQueryStats(String queryId) {
    URI uri = uriBuilderFrom(baseUri).appendPath("/v1/query").appendPath(queryId).build();
    Request request = prepareGet().setUri(uri).build();
    return httpClient.execute(request, new GetQueryStatsResponseHandler());
}
Also used : Request(com.facebook.airlift.http.client.Request) URI(java.net.URI)

Example 7 with Request

use of com.facebook.airlift.http.client.Request in project presto by prestodb.

the class DistributedQueryRunner method getCoordinatorInfoState.

private NodeState getCoordinatorInfoState(int coordinator) {
    URI uri = URI.create(getCoordinator(coordinator).getBaseUrl().toString() + "/v1/info/state");
    Request request = prepareGet().setHeader(PRESTO_USER, DEFAULT_USER).setUri(uri).build();
    NodeState state = client.execute(request, createJsonResponseHandler(jsonCodec(NodeState.class)));
    return state;
}
Also used : NodeState(com.facebook.presto.spi.NodeState) Request(com.facebook.airlift.http.client.Request) URI(java.net.URI)

Example 8 with Request

use of com.facebook.airlift.http.client.Request in project presto by prestodb.

the class TestPageBufferClient method testExceptionFromResponseHandler.

@Test
public void testExceptionFromResponseHandler() throws Exception {
    DataSize expectedMaxSize = new DataSize(10, Unit.MEGABYTE);
    TestingTicker ticker = new TestingTicker();
    AtomicReference<Duration> tickerIncrement = new AtomicReference<>(new Duration(0, TimeUnit.SECONDS));
    TestingHttpClient.Processor processor = (input) -> {
        Duration delta = tickerIncrement.get();
        ticker.increment(delta.toMillis(), TimeUnit.MILLISECONDS);
        throw new RuntimeException("Foo");
    };
    CyclicBarrier requestComplete = new CyclicBarrier(2);
    TestingClientCallback callback = new TestingClientCallback(requestComplete);
    URI location = URI.create("http://localhost:8080");
    PageBufferClient client = new PageBufferClient(new HttpRpcShuffleClient(new TestingHttpClient(processor, scheduler), location), new Duration(30, TimeUnit.SECONDS), true, location, Optional.empty(), callback, scheduler, ticker, pageBufferClientCallbackExecutor);
    assertStatus(client, location, "queued", 0, 0, 0, 0, "not scheduled");
    // request processor will throw exception, verify the request is marked a completed
    // this starts the error stopwatch
    client.scheduleRequest(expectedMaxSize);
    requestComplete.await(10, TimeUnit.SECONDS);
    assertEquals(callback.getPages().size(), 0);
    assertEquals(callback.getCompletedRequests(), 1);
    assertEquals(callback.getFinishedBuffers(), 0);
    assertEquals(callback.getFailedBuffers(), 0);
    assertStatus(client, location, "queued", 0, 1, 1, 1, "not scheduled");
    // advance time forward, but not enough to fail the client
    tickerIncrement.set(new Duration(30, TimeUnit.SECONDS));
    // verify that the client has not failed
    client.scheduleRequest(expectedMaxSize);
    requestComplete.await(10, TimeUnit.SECONDS);
    assertEquals(callback.getPages().size(), 0);
    assertEquals(callback.getCompletedRequests(), 2);
    assertEquals(callback.getFinishedBuffers(), 0);
    assertEquals(callback.getFailedBuffers(), 0);
    assertStatus(client, location, "queued", 0, 2, 2, 2, "not scheduled");
    // advance time forward beyond the minimum error duration
    tickerIncrement.set(new Duration(31, TimeUnit.SECONDS));
    // verify that the client has failed
    client.scheduleRequest(expectedMaxSize);
    requestComplete.await(10, TimeUnit.SECONDS);
    assertEquals(callback.getPages().size(), 0);
    assertEquals(callback.getCompletedRequests(), 3);
    assertEquals(callback.getFinishedBuffers(), 0);
    assertEquals(callback.getFailedBuffers(), 1);
    assertInstanceOf(callback.getFailure(), PageTransportTimeoutException.class);
    assertContains(callback.getFailure().getMessage(), WORKER_NODE_ERROR + " (http://localhost:8080/0 - 3 failures, failure duration 31.00s, total failed request time 31.00s)");
    assertStatus(client, location, "queued", 0, 3, 3, 3, "not scheduled");
}
Also used : TestingTicker(com.facebook.airlift.testing.TestingTicker) TestingPagesSerdeFactory.testingPagesSerde(com.facebook.presto.execution.buffer.TestingPagesSerdeFactory.testingPagesSerde) Page(com.facebook.presto.common.Page) SerializedPage(com.facebook.presto.spi.page.SerializedPage) TimeoutException(java.util.concurrent.TimeoutException) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) Unit(io.airlift.units.DataSize.Unit) AtomicReference(java.util.concurrent.atomic.AtomicReference) CONTENT_TYPE(com.google.common.net.HttpHeaders.CONTENT_TYPE) ClientCallback(com.facebook.presto.operator.PageBufferClient.ClientCallback) HttpStatus(com.facebook.airlift.http.client.HttpStatus) Duration(io.airlift.units.Duration) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Executors.newScheduledThreadPool(java.util.concurrent.Executors.newScheduledThreadPool) TestingHttpClient(com.facebook.airlift.http.client.testing.TestingHttpClient) PAGE_TOO_LARGE(com.facebook.presto.spi.StandardErrorCode.PAGE_TOO_LARGE) Response(com.facebook.airlift.http.client.Response) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TestingResponse(com.facebook.airlift.http.client.testing.TestingResponse) Assertions.assertInstanceOf(com.facebook.airlift.testing.Assertions.assertInstanceOf) URI(java.net.URI) ExecutorService(java.util.concurrent.ExecutorService) PAGE_TRANSPORT_ERROR(com.facebook.presto.spi.StandardErrorCode.PAGE_TRANSPORT_ERROR) AfterClass(org.testng.annotations.AfterClass) CyclicBarrier(java.util.concurrent.CyclicBarrier) BeforeClass(org.testng.annotations.BeforeClass) HostAddress(com.facebook.presto.spi.HostAddress) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) Assertions.assertContains(com.facebook.airlift.testing.Assertions.assertContains) PAGE_TRANSPORT_TIMEOUT(com.facebook.presto.spi.StandardErrorCode.PAGE_TRANSPORT_TIMEOUT) WORKER_NODE_ERROR(com.facebook.presto.util.Failures.WORKER_NODE_ERROR) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) Threads.daemonThreadsNamed(com.facebook.airlift.concurrent.Threads.daemonThreadsNamed) DataSize(io.airlift.units.DataSize) List(java.util.List) PRESTO_PAGES(com.facebook.presto.PrestoMediaTypes.PRESTO_PAGES) Request(com.facebook.airlift.http.client.Request) PagesSerde(com.facebook.presto.spi.page.PagesSerde) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) Optional(java.util.Optional) Collections(java.util.Collections) TestingTicker(com.facebook.airlift.testing.TestingTicker) Duration(io.airlift.units.Duration) AtomicReference(java.util.concurrent.atomic.AtomicReference) URI(java.net.URI) CyclicBarrier(java.util.concurrent.CyclicBarrier) DataSize(io.airlift.units.DataSize) TestingHttpClient(com.facebook.airlift.http.client.testing.TestingHttpClient) Test(org.testng.annotations.Test)

Example 9 with Request

use of com.facebook.airlift.http.client.Request in project presto by prestodb.

the class TaskInfoFetcher method sendMetadataUpdates.

private synchronized void sendMetadataUpdates(MetadataUpdates results) {
    TaskStatus taskStatus = getTaskInfo().getTaskStatus();
    // we already have the final task info
    if (isDone(getTaskInfo())) {
        stop();
        return;
    }
    // outstanding request?
    if (metadataUpdateFuture != null && !metadataUpdateFuture.isDone()) {
        // this should never happen
        return;
    }
    byte[] metadataUpdatesJson = metadataUpdatesCodec.toBytes(results);
    Request request = setContentTypeHeaders(isBinaryTransportEnabled, preparePost()).setUri(uriBuilderFrom(taskStatus.getSelf()).appendPath("metadataresults").build()).setBodyGenerator(createStaticBodyGenerator(metadataUpdatesJson)).build();
    errorTracker.startRequest();
    metadataUpdateFuture = httpClient.executeAsync(request, new ResponseHandler<Response, RuntimeException>() {

        @Override
        public Response handleException(Request request, Exception exception) {
            throw propagate(request, exception);
        }

        @Override
        public Response handle(Request request, Response response) {
            return response;
        }
    });
    currentRequestStartNanos.set(System.nanoTime());
}
Also used : Response(com.facebook.airlift.http.client.Response) BaseResponse(com.facebook.presto.server.smile.BaseResponse) SimpleHttpResponseHandler(com.facebook.presto.server.SimpleHttpResponseHandler) FullSmileResponseHandler.createFullSmileResponseHandler(com.facebook.presto.server.smile.FullSmileResponseHandler.createFullSmileResponseHandler) ResponseHandler(com.facebook.airlift.http.client.ResponseHandler) AdaptingJsonResponseHandler.createAdaptingJsonResponseHandler(com.facebook.presto.server.smile.AdaptingJsonResponseHandler.createAdaptingJsonResponseHandler) Request(com.facebook.airlift.http.client.Request) TaskStatus(com.facebook.presto.execution.TaskStatus)

Example 10 with Request

use of com.facebook.airlift.http.client.Request in project presto by prestodb.

the class HttpRemoteTask method sendUpdate.

private synchronized void sendUpdate() {
    TaskStatus taskStatus = getTaskStatus();
    // don't update if the task hasn't been started yet or if it is already finished
    if (!started.get() || !needsUpdate.get() || taskStatus.getState().isDone()) {
        return;
    }
    // if there is a request already running, wait for it to complete
    if (this.currentRequest != null && !this.currentRequest.isDone()) {
        return;
    }
    // if throttled due to error, asynchronously wait for timeout and try again
    ListenableFuture<?> errorRateLimit = updateErrorTracker.acquireRequestPermit();
    if (!errorRateLimit.isDone()) {
        errorRateLimit.addListener(this::sendUpdate, executor);
        return;
    }
    List<TaskSource> sources = getSources();
    Optional<byte[]> fragment = sendPlan.get() ? Optional.of(planFragment.toBytes(planFragmentCodec)) : Optional.empty();
    Optional<TableWriteInfo> writeInfo = sendPlan.get() ? Optional.of(tableWriteInfo) : Optional.empty();
    TaskUpdateRequest updateRequest = new TaskUpdateRequest(session.toSessionRepresentation(), session.getIdentity().getExtraCredentials(), fragment, sources, outputBuffers.get(), writeInfo);
    byte[] taskUpdateRequestJson = taskUpdateRequestCodec.toBytes(updateRequest);
    taskUpdateRequestSize.add(taskUpdateRequestJson.length);
    if (taskUpdateRequestJson.length > maxTaskUpdateSizeInBytes) {
        failTask(new PrestoException(EXCEEDED_TASK_UPDATE_SIZE_LIMIT, format("TaskUpdate size of %d Bytes has exceeded the limit of %d Bytes", taskUpdateRequestJson.length, maxTaskUpdateSizeInBytes)));
    }
    if (fragment.isPresent()) {
        stats.updateWithPlanSize(taskUpdateRequestJson.length);
    } else {
        if (ThreadLocalRandom.current().nextDouble() < UPDATE_WITHOUT_PLAN_STATS_SAMPLE_RATE) {
            // This is to keep track of the task update size even when the plan fragment is NOT present
            stats.updateWithoutPlanSize(taskUpdateRequestJson.length);
        }
    }
    HttpUriBuilder uriBuilder = getHttpUriBuilder(taskStatus);
    Request request = setContentTypeHeaders(binaryTransportEnabled, preparePost()).setUri(uriBuilder.build()).setBodyGenerator(createStaticBodyGenerator(taskUpdateRequestJson)).build();
    ResponseHandler responseHandler;
    if (binaryTransportEnabled) {
        responseHandler = createFullSmileResponseHandler((SmileCodec<TaskInfo>) taskInfoCodec);
    } else {
        responseHandler = createAdaptingJsonResponseHandler((JsonCodec<TaskInfo>) taskInfoCodec);
    }
    updateErrorTracker.startRequest();
    ListenableFuture<BaseResponse<TaskInfo>> future = httpClient.executeAsync(request, responseHandler);
    currentRequest = future;
    currentRequestStartNanos = System.nanoTime();
    // The needsUpdate flag needs to be set to false BEFORE adding the Future callback since callback might change the flag value
    // and does so without grabbing the instance lock.
    needsUpdate.set(false);
    Futures.addCallback(future, new SimpleHttpResponseHandler<>(new UpdateResponseHandler(sources), request.getUri(), stats.getHttpResponseStats(), REMOTE_TASK_ERROR), executor);
}
Also used : SmileCodec(com.facebook.airlift.json.smile.SmileCodec) TableWriteInfo(com.facebook.presto.execution.scheduler.TableWriteInfo) SimpleHttpResponseHandler(com.facebook.presto.server.SimpleHttpResponseHandler) StatusResponseHandler.createStatusResponseHandler(com.facebook.airlift.http.client.StatusResponseHandler.createStatusResponseHandler) FullSmileResponseHandler.createFullSmileResponseHandler(com.facebook.presto.server.smile.FullSmileResponseHandler.createFullSmileResponseHandler) ResponseHandler(com.facebook.airlift.http.client.ResponseHandler) AdaptingJsonResponseHandler.createAdaptingJsonResponseHandler(com.facebook.presto.server.smile.AdaptingJsonResponseHandler.createAdaptingJsonResponseHandler) TaskUpdateRequest(com.facebook.presto.server.TaskUpdateRequest) TaskUpdateRequest(com.facebook.presto.server.TaskUpdateRequest) Request(com.facebook.airlift.http.client.Request) PrestoException(com.facebook.presto.spi.PrestoException) TaskStatus(com.facebook.presto.execution.TaskStatus) BaseResponse(com.facebook.presto.server.smile.BaseResponse) JsonCodec(com.facebook.airlift.json.JsonCodec) HttpUriBuilder(com.facebook.airlift.http.client.HttpUriBuilder) TaskSource(com.facebook.presto.execution.TaskSource)

Aggregations

Request (com.facebook.airlift.http.client.Request)40 URI (java.net.URI)16 Test (org.testng.annotations.Test)14 QueryResults (com.facebook.presto.client.QueryResults)7 ResponseHandler (com.facebook.airlift.http.client.ResponseHandler)5 TaskStatus (com.facebook.presto.execution.TaskStatus)5 AdaptingJsonResponseHandler.createAdaptingJsonResponseHandler (com.facebook.presto.server.smile.AdaptingJsonResponseHandler.createAdaptingJsonResponseHandler)5 FullSmileResponseHandler.createFullSmileResponseHandler (com.facebook.presto.server.smile.FullSmileResponseHandler.createFullSmileResponseHandler)5 List (java.util.List)5 HttpUriBuilder (com.facebook.airlift.http.client.HttpUriBuilder)4 Response (com.facebook.airlift.http.client.Response)4 JsonCodec (com.facebook.airlift.json.JsonCodec)4 SimpleHttpResponseHandler (com.facebook.presto.server.SimpleHttpResponseHandler)4 TaskUpdateRequest (com.facebook.presto.server.TaskUpdateRequest)4 NodeState (com.facebook.presto.spi.NodeState)4 Duration (io.airlift.units.Duration)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 SmileCodec (com.facebook.airlift.json.smile.SmileCodec)3 BaseResponse (com.facebook.presto.server.smile.BaseResponse)3 TestingPrestoServer (com.facebook.presto.server.testing.TestingPrestoServer)3