Search in sources :

Example 1 with Request

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

the class TestTaskInfoResource method testGetTaskInfo.

@Test
public void testGetTaskInfo() {
    String sql = "SELECT * FROM tpch.sf1.customer WHERE tpch.sf1.customer.nationkey = 1";
    ResultWithQueryId<MaterializedResult> result = queryRunner.executeWithQueryId(queryRunner.getDefaultSession(), sql);
    QueryId queryId = result.getQueryId();
    Optional<StageInfo> stageInfo = server.getQueryManager().getFullQueryInfo(queryId).getOutputStage();
    if (stageInfo.isPresent()) {
        Stream<TaskInfo> latestTaskInfo = stageInfo.get().getAllStages().stream().flatMap(stage -> stage.getLatestAttemptExecutionInfo().getTasks().stream());
        Iterable<TaskInfo> iterableTaskInfo = latestTaskInfo::iterator;
        for (TaskInfo taskInfo : iterableTaskInfo) {
            URI taskURI = taskUri("v1/taskInfo/", taskInfo.getTaskId().toString());
            Request taskInfoRequest = prepareGet().setUri(taskURI).build();
            TaskInfo responseTaskInfo = client.execute(taskInfoRequest, createJsonResponseHandler(jsonCodec(TaskInfo.class)));
            compareTasks(taskInfo, responseTaskInfo);
        }
    } else {
        fail("StageInfo not present");
    }
}
Also used : TaskInfo(com.facebook.presto.execution.TaskInfo) StageInfo(com.facebook.presto.execution.StageInfo) ResultWithQueryId(com.facebook.presto.tests.ResultWithQueryId) QueryId(com.facebook.presto.spi.QueryId) Request(com.facebook.airlift.http.client.Request) MaterializedResult(com.facebook.presto.testing.MaterializedResult) URI(java.net.URI) Test(org.testng.annotations.Test)

Example 2 with Request

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

the class TestTaskInfoResource method testInvalidQueryId.

@Test
public void testInvalidQueryId() {
    String invalidTaskId = queryIdGenerator.createNextQueryId().toString() + ".0.0.0";
    URI invalidTaskURI = taskUri("v1/taskInfo/", invalidTaskId);
    Request taskInfoRequest = prepareGet().setUri(invalidTaskURI).build();
    StringResponseHandler.StringResponse stringResponse = client.execute(taskInfoRequest, createStringResponseHandler());
    assertEquals(stringResponse.getStatusCode(), 404);
}
Also used : StringResponseHandler.createStringResponseHandler(com.facebook.airlift.http.client.StringResponseHandler.createStringResponseHandler) StringResponseHandler(com.facebook.airlift.http.client.StringResponseHandler) Request(com.facebook.airlift.http.client.Request) URI(java.net.URI) Test(org.testng.annotations.Test)

Example 3 with Request

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

the class RemoteNodeMemory method asyncRefresh.

public void asyncRefresh(MemoryPoolAssignmentsRequest assignments) {
    Duration sinceUpdate = nanosSince(lastUpdateNanos.get());
    if (nanosSince(lastWarningLogged.get()).toMillis() > 1_000 && sinceUpdate.toMillis() > 10_000 && future.get() != null) {
        log.warn("Memory info update request to %s has not returned in %s", memoryInfoUri, sinceUpdate.toString(SECONDS));
        lastWarningLogged.set(System.nanoTime());
    }
    if (sinceUpdate.toMillis() > 1_000 && future.get() == null) {
        Request request = setContentTypeHeaders(isBinaryTransportEnabled, preparePost()).setUri(memoryInfoUri).setBodyGenerator(createBodyGenerator(assignments)).build();
        ResponseHandler responseHandler;
        if (isBinaryTransportEnabled) {
            responseHandler = createFullSmileResponseHandler((SmileCodec<MemoryInfo>) memoryInfoCodec);
        } else {
            responseHandler = createAdaptingJsonResponseHandler((JsonCodec<MemoryInfo>) memoryInfoCodec);
        }
        HttpResponseFuture<BaseResponse<MemoryInfo>> responseFuture = httpClient.executeAsync(request, responseHandler);
        future.compareAndSet(null, responseFuture);
        Futures.addCallback(responseFuture, new FutureCallback<BaseResponse<MemoryInfo>>() {

            @Override
            public void onSuccess(@Nullable BaseResponse<MemoryInfo> result) {
                lastUpdateNanos.set(System.nanoTime());
                future.compareAndSet(responseFuture, null);
                long version = currentAssignmentVersion.get();
                if (result != null) {
                    if (result.hasValue()) {
                        memoryInfo.set(Optional.ofNullable(result.getValue()));
                    }
                    if (result.getStatusCode() != OK.code()) {
                        log.warn("Error fetching memory info from %s returned status %d: %s", memoryInfoUri, result.getStatusCode(), result.getStatusMessage());
                        return;
                    }
                }
                currentAssignmentVersion.compareAndSet(version, assignments.getVersion());
            }

            @Override
            public void onFailure(Throwable t) {
                log.warn("Error fetching memory info from %s: %s", memoryInfoUri, t.getMessage());
                lastUpdateNanos.set(System.nanoTime());
                future.compareAndSet(responseFuture, null);
            }
        }, directExecutor());
    }
}
Also used : BaseResponse(com.facebook.presto.server.smile.BaseResponse) SmileCodec(com.facebook.airlift.json.smile.SmileCodec) JsonCodec(com.facebook.airlift.json.JsonCodec) 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) Duration(io.airlift.units.Duration)

Example 4 with Request

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

the class TestExchangeClient method testInitialRequestLimit.

@Test
public void testInitialRequestLimit() {
    DataSize bufferCapacity = new DataSize(16, MEGABYTE);
    DataSize maxResponseSize = new DataSize(DEFAULT_MAX_PAGE_SIZE_IN_BYTES, BYTE);
    CountDownLatch countDownLatch = new CountDownLatch(1);
    MockExchangeRequestProcessor processor = new MockExchangeRequestProcessor(maxResponseSize) {

        @Override
        public Response handle(Request request) {
            if (!awaitUninterruptibly(countDownLatch, 10, SECONDS)) {
                throw new UncheckedTimeoutException();
            }
            return super.handle(request);
        }
    };
    List<URI> locations = new ArrayList<>();
    int numLocations = 16;
    List<DataSize> expectedMaxSizes = new ArrayList<>();
    // add pages
    for (int i = 0; i < numLocations; i++) {
        URI location = URI.create("http://localhost:" + (8080 + i));
        locations.add(location);
        processor.addPage(location, createPage(DEFAULT_MAX_PAGE_SIZE_IN_BYTES));
        processor.addPage(location, createPage(DEFAULT_MAX_PAGE_SIZE_IN_BYTES));
        processor.addPage(location, createPage(DEFAULT_MAX_PAGE_SIZE_IN_BYTES));
        processor.setComplete(location);
        expectedMaxSizes.add(maxResponseSize);
    }
    try (ExchangeClient exchangeClient = createExchangeClient(processor, bufferCapacity, maxResponseSize)) {
        for (int i = 0; i < numLocations; i++) {
            exchangeClient.addLocation(locations.get(i), TaskId.valueOf("taskid.0.0." + i));
        }
        exchangeClient.noMoreLocations();
        assertFalse(exchangeClient.isClosed());
        long start = System.nanoTime();
        countDownLatch.countDown();
        // wait for a page to be fetched
        do {
            // there is no thread coordination here, so sleep is the best we can do
            assertLessThan(Duration.nanosSince(start), new Duration(5, TimeUnit.SECONDS));
            sleepUninterruptibly(100, MILLISECONDS);
        } while (exchangeClient.getStatus().getBufferedPages() < 16);
        // Client should have sent 16 requests for a single page (0) and gotten them back
        // The memory limit should be hit immediately and then it doesn't fetch the third page from each
        assertEquals(exchangeClient.getStatus().getBufferedPages(), 16);
        assertTrue(exchangeClient.getStatus().getBufferedBytes() > 0);
        List<PageBufferClientStatus> pageBufferClientStatuses = exchangeClient.getStatus().getPageBufferClientStatuses();
        assertEquals(16, pageBufferClientStatuses.stream().filter(status -> status.getPagesReceived() == 1).mapToInt(PageBufferClientStatus::getPagesReceived).sum());
        assertEquals(processor.getRequestMaxSizes(), expectedMaxSizes);
        for (int i = 0; i < numLocations * 3; i++) {
            assertNotNull(getNextPage(exchangeClient));
        }
        do {
            // there is no thread coordination here, so sleep is the best we can do
            assertLessThan(Duration.nanosSince(start), new Duration(5, TimeUnit.SECONDS));
            sleepUninterruptibly(100, MILLISECONDS);
        } while (processor.getRequestMaxSizes().size() < 64);
        for (int i = 0; i < 48; i++) {
            expectedMaxSizes.add(maxResponseSize);
        }
        assertEquals(processor.getRequestMaxSizes(), expectedMaxSizes);
    }
}
Also used : TestingPagesSerdeFactory.testingPagesSerde(com.facebook.presto.execution.buffer.TestingPagesSerdeFactory.testingPagesSerde) Page(com.facebook.presto.common.Page) SerializedPage(com.facebook.presto.spi.page.SerializedPage) Test(org.testng.annotations.Test) Maps.uniqueIndex(com.google.common.collect.Maps.uniqueIndex) BlockAssertions(com.facebook.presto.block.BlockAssertions) Duration(io.airlift.units.Duration) Assertions.assertLessThan(com.facebook.airlift.testing.Assertions.assertLessThan) Uninterruptibles.awaitUninterruptibly(com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly) Executors.newScheduledThreadPool(java.util.concurrent.Executors.newScheduledThreadPool) TestingHttpClient(com.facebook.airlift.http.client.testing.TestingHttpClient) Response(com.facebook.airlift.http.client.Response) URI(java.net.URI) Assert.assertFalse(org.testng.Assert.assertFalse) DEFAULT_MAX_PAGE_SIZE_IN_BYTES(com.facebook.presto.common.block.PageBuilderStatus.DEFAULT_MAX_PAGE_SIZE_IN_BYTES) ImmutableMap(com.google.common.collect.ImmutableMap) BeforeClass(org.testng.annotations.BeforeClass) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Assert.assertNotNull(org.testng.Assert.assertNotNull) Uninterruptibles.sleepUninterruptibly(com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly) Executors(java.util.concurrent.Executors) MoreExecutors.directExecutor(com.google.common.util.concurrent.MoreExecutors.directExecutor) Threads.daemonThreadsNamed(com.facebook.airlift.concurrent.Threads.daemonThreadsNamed) CountDownLatch(java.util.concurrent.CountDownLatch) DataSize(io.airlift.units.DataSize) List(java.util.List) MoreFutures.tryGetFutureValue(com.facebook.airlift.concurrent.MoreFutures.tryGetFutureValue) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Assert.assertNull(org.testng.Assert.assertNull) MEGABYTE(io.airlift.units.DataSize.Unit.MEGABYTE) Assert.assertEquals(org.testng.Assert.assertEquals) MINUTES(java.util.concurrent.TimeUnit.MINUTES) PrestoException(com.facebook.presto.spi.PrestoException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) SimpleLocalMemoryContext(com.facebook.presto.memory.context.SimpleLocalMemoryContext) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) AggregatedMemoryContext.newSimpleAggregatedMemoryContext(com.facebook.presto.memory.context.AggregatedMemoryContext.newSimpleAggregatedMemoryContext) ExecutorService(java.util.concurrent.ExecutorService) AfterClass(org.testng.annotations.AfterClass) TimeUnit(java.util.concurrent.TimeUnit) Futures(com.google.common.util.concurrent.Futures) Executors.newCachedThreadPool(java.util.concurrent.Executors.newCachedThreadPool) Request(com.facebook.airlift.http.client.Request) PagesSerde(com.facebook.presto.spi.page.PagesSerde) TaskId(com.facebook.presto.execution.TaskId) Assert.assertTrue(org.testng.Assert.assertTrue) BYTE(io.airlift.units.DataSize.Unit.BYTE) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Request(com.facebook.airlift.http.client.Request) ArrayList(java.util.ArrayList) UncheckedTimeoutException(com.google.common.util.concurrent.UncheckedTimeoutException) Duration(io.airlift.units.Duration) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) DataSize(io.airlift.units.DataSize) Test(org.testng.annotations.Test)

Example 5 with Request

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

the class PinotClusterInfoFetcher method doHttpActionWithHeaders.

public String doHttpActionWithHeaders(Request.Builder requestBuilder, Optional<String> requestBody, Optional<String> rpcService) {
    requestBuilder = requestBuilder.setHeader(HttpHeaders.ACCEPT, APPLICATION_JSON);
    if (requestBody.isPresent()) {
        requestBuilder.setHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON);
    }
    if (rpcService.isPresent()) {
        requestBuilder.setHeader(pinotConfig.getCallerHeaderParam(), pinotConfig.getCallerHeaderValue()).setHeader(pinotConfig.getServiceHeaderParam(), rpcService.get());
    }
    if (requestBody.isPresent()) {
        requestBuilder.setBodyGenerator(StaticBodyGenerator.createStaticBodyGenerator(requestBody.get(), StandardCharsets.UTF_8));
    }
    pinotConfig.getExtraHttpHeaders().forEach(requestBuilder::setHeader);
    Request request = requestBuilder.build();
    long startTime = ticker.read();
    long duration;
    StringResponseHandler.StringResponse response;
    try {
        response = httpClient.execute(request, createStringResponseHandler());
    } finally {
        duration = ticker.read() - startTime;
    }
    pinotMetrics.monitorRequest(request, response, duration, TimeUnit.NANOSECONDS);
    String responseBody = response.getBody();
    if (PinotUtils.isValidPinotHttpResponseCode(response.getStatusCode())) {
        return responseBody;
    } else {
        throw new PinotException(PINOT_HTTP_ERROR, Optional.empty(), String.format("Unexpected response status: %d for request %s to url %s, with headers %s, full response %s", response.getStatusCode(), requestBody.orElse(""), request.getUri(), request.getHeaders(), responseBody));
    }
}
Also used : StringResponseHandler.createStringResponseHandler(com.facebook.airlift.http.client.StringResponseHandler.createStringResponseHandler) StringResponseHandler(com.facebook.airlift.http.client.StringResponseHandler) Request(com.facebook.airlift.http.client.Request)

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