Search in sources :

Example 1 with OutputBufferId

use of com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId in project presto by prestodb.

the class LegacySqlQueryScheduler method updateStageExecutions.

/**
 * Utility function that rebuild a StreamingPlanSection, re-create stageExecutionAndScheduler for each of its stage, and finally update the stageExecutions map.
 */
private void updateStageExecutions(StreamingPlanSection section, Map<PlanFragment, PlanFragment> oldToNewFragment) {
    StreamingPlanSection newSection = new StreamingPlanSection(rewriteStreamingSubPlan(section.getPlan(), oldToNewFragment), section.getChildren());
    PlanFragment sectionRootFragment = newSection.getPlan().getFragment();
    Optional<int[]> bucketToPartition;
    OutputBuffers outputBuffers;
    ExchangeLocationsConsumer locationsConsumer;
    if (isRootFragment(sectionRootFragment)) {
        bucketToPartition = Optional.of(new int[1]);
        outputBuffers = createInitialEmptyOutputBuffers(sectionRootFragment.getPartitioningScheme().getPartitioning().getHandle()).withBuffer(new OutputBufferId(0), BROADCAST_PARTITION_ID).withNoMoreBufferIds();
        OutputBufferId rootBufferId = getOnlyElement(outputBuffers.getBuffers().keySet());
        locationsConsumer = (fragmentId, tasks, noMoreExchangeLocations) -> updateQueryOutputLocations(queryStateMachine, rootBufferId, tasks, noMoreExchangeLocations);
    } else {
        bucketToPartition = Optional.empty();
        outputBuffers = createDiscardingOutputBuffers();
        locationsConsumer = (fragmentId, tasks, noMoreExchangeLocations) -> {
        };
    }
    SectionExecution sectionExecution = sectionExecutionFactory.createSectionExecutions(session, newSection, locationsConsumer, bucketToPartition, outputBuffers, summarizeTaskInfo, remoteTaskFactory, splitSourceFactory, 0);
    addStateChangeListeners(sectionExecution);
    Map<StageId, StageExecutionAndScheduler> updatedStageExecutions = sectionExecution.getSectionStages().stream().collect(toImmutableMap(execution -> execution.getStageExecution().getStageExecutionId().getStageId(), identity()));
    synchronized (this) {
        stageExecutions.putAll(updatedStageExecutions);
    }
}
Also used : BasicStageExecutionStats(com.facebook.presto.execution.BasicStageExecutionStats) FunctionAndTypeManager(com.facebook.presto.metadata.FunctionAndTypeManager) WarningCollector(com.facebook.presto.spi.WarningCollector) OutputBuffers.createInitialEmptyOutputBuffers(com.facebook.presto.execution.buffer.OutputBuffers.createInitialEmptyOutputBuffers) Traverser.forTree(com.google.common.graph.Traverser.forTree) GENERIC_INTERNAL_ERROR(com.facebook.presto.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR) SchedulingOrderVisitor.scheduleOrder(com.facebook.presto.sql.planner.SchedulingOrderVisitor.scheduleOrder) SystemSessionProperties.getMaxConcurrentMaterializations(com.facebook.presto.SystemSessionProperties.getMaxConcurrentMaterializations) OutputBufferId(com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId) SplitSourceFactory(com.facebook.presto.sql.planner.SplitSourceFactory) BROADCAST_PARTITION_ID(com.facebook.presto.execution.buffer.OutputBuffers.BROADCAST_PARTITION_ID) SqlStageExecution(com.facebook.presto.execution.SqlStageExecution) OutputBuffers.createDiscardingOutputBuffers(com.facebook.presto.execution.buffer.OutputBuffers.createDiscardingOutputBuffers) Duration(io.airlift.units.Duration) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) StageInfo(com.facebook.presto.execution.StageInfo) PlanFragment(com.facebook.presto.sql.planner.PlanFragment) Map(java.util.Map) MoreFutures.whenAnyComplete(com.facebook.airlift.concurrent.MoreFutures.whenAnyComplete) URI(java.net.URI) PlanPrinter.jsonFragmentPlan(com.facebook.presto.sql.planner.planPrinter.PlanPrinter.jsonFragmentPlan) PLANNED(com.facebook.presto.execution.StageExecutionState.PLANNED) RemoteTaskFactory(com.facebook.presto.execution.RemoteTaskFactory) ImmutableSet(com.google.common.collect.ImmutableSet) StageExecutionInfo(com.facebook.presto.execution.StageExecutionInfo) RUNNING(com.facebook.presto.execution.StageExecutionState.RUNNING) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) SqlParser(com.facebook.presto.sql.parser.SqlParser) DataSize(io.airlift.units.DataSize) List(java.util.List) MoreFutures.tryGetFutureValue(com.facebook.airlift.concurrent.MoreFutures.tryGetFutureValue) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) PlanVariableAllocator(com.facebook.presto.sql.planner.PlanVariableAllocator) FAILED(com.facebook.presto.execution.StageExecutionState.FAILED) Function.identity(java.util.function.Function.identity) Optional(java.util.Optional) StageId(com.facebook.presto.execution.StageId) Iterables(com.google.common.collect.Iterables) Logger(com.facebook.airlift.log.Logger) OutputBuffers(com.facebook.presto.execution.buffer.OutputBuffers) PlanOptimizer(com.facebook.presto.sql.planner.optimizations.PlanOptimizer) SystemSessionProperties.isPartialResultsEnabled(com.facebook.presto.SystemSessionProperties.isPartialResultsEnabled) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) SystemSessionProperties.getPartialResultsCompletionRatioThreshold(com.facebook.presto.SystemSessionProperties.getPartialResultsCompletionRatioThreshold) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) PrestoException(com.facebook.presto.spi.PrestoException) SCHEDULED(com.facebook.presto.execution.StageExecutionState.SCHEDULED) AtomicReference(java.util.concurrent.atomic.AtomicReference) SystemSessionProperties.isRuntimeOptimizerEnabled(com.facebook.presto.SystemSessionProperties.isRuntimeOptimizerEnabled) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) TimeStat(com.facebook.airlift.stats.TimeStat) SystemSessionProperties.getPartialResultsMaxExecutionTimeMultiplier(com.facebook.presto.SystemSessionProperties.getPartialResultsMaxExecutionTimeMultiplier) ABORTED(com.facebook.presto.execution.StageExecutionState.ABORTED) ImmutableList(com.google.common.collect.ImmutableList) PlanChecker(com.facebook.presto.sql.planner.sanity.PlanChecker) Objects.requireNonNull(java.util.Objects.requireNonNull) BasicStageExecutionStats.aggregateBasicStageStats(com.facebook.presto.execution.BasicStageExecutionStats.aggregateBasicStageStats) PlanFragmentId(com.facebook.presto.sql.planner.plan.PlanFragmentId) LinkedList(java.util.LinkedList) StageExecutionState(com.facebook.presto.execution.StageExecutionState) ExecutorService(java.util.concurrent.ExecutorService) CANCELED(com.facebook.presto.execution.StageExecutionState.CANCELED) SubPlan(com.facebook.presto.sql.planner.SubPlan) PlanNodeIdAllocator(com.facebook.presto.spi.plan.PlanNodeIdAllocator) SetThreadName(com.facebook.airlift.concurrent.SetThreadName) StreamingPlanSection.extractStreamingSections(com.facebook.presto.execution.scheduler.StreamingPlanSection.extractStreamingSections) Session(com.facebook.presto.Session) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) LocationFactory(com.facebook.presto.execution.LocationFactory) HttpUriBuilder.uriBuilderFrom(com.facebook.airlift.http.client.HttpUriBuilder.uriBuilderFrom) Streams.stream(com.google.common.collect.Streams.stream) PlanNode(com.facebook.presto.spi.plan.PlanNode) RemoteTask(com.facebook.presto.execution.RemoteTask) TaskId(com.facebook.presto.execution.TaskId) ROOT_FRAGMENT_ID(com.facebook.presto.sql.planner.PlanFragmenter.ROOT_FRAGMENT_ID) FINISHED(com.facebook.presto.execution.StageExecutionState.FINISHED) QueryState(com.facebook.presto.execution.QueryState) QueryStateMachine(com.facebook.presto.execution.QueryStateMachine) Collections(java.util.Collections) SECONDS(java.util.concurrent.TimeUnit.SECONDS) PartialResultQueryManager(com.facebook.presto.execution.PartialResultQueryManager) Metadata(com.facebook.presto.metadata.Metadata) OutputBuffers.createInitialEmptyOutputBuffers(com.facebook.presto.execution.buffer.OutputBuffers.createInitialEmptyOutputBuffers) OutputBuffers.createDiscardingOutputBuffers(com.facebook.presto.execution.buffer.OutputBuffers.createDiscardingOutputBuffers) OutputBuffers(com.facebook.presto.execution.buffer.OutputBuffers) StageId(com.facebook.presto.execution.StageId) OutputBufferId(com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId) PlanFragment(com.facebook.presto.sql.planner.PlanFragment)

Example 2 with OutputBufferId

use of com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId in project presto by prestodb.

the class ScaledOutputBufferManager method addOutputBuffers.

@SuppressWarnings("ObjectEquality")
@Override
public void addOutputBuffers(List<OutputBufferId> newBuffers, boolean noMoreBuffers) {
    OutputBuffers newOutputBuffers;
    synchronized (this) {
        if (outputBuffers.isNoMoreBufferIds()) {
            // so ignore the new buffers
            return;
        }
        OutputBuffers originalOutputBuffers = outputBuffers;
        for (OutputBufferId newBuffer : newBuffers) {
            outputBuffers = outputBuffers.withBuffer(newBuffer, newBuffer.getId());
        }
        if (noMoreBuffers) {
            outputBuffers = outputBuffers.withNoMoreBufferIds();
        }
        // don't update if nothing changed
        if (outputBuffers == originalOutputBuffers) {
            return;
        }
        newOutputBuffers = this.outputBuffers;
    }
    outputBufferTarget.accept(newOutputBuffers);
}
Also used : OutputBuffers.createInitialEmptyOutputBuffers(com.facebook.presto.execution.buffer.OutputBuffers.createInitialEmptyOutputBuffers) OutputBuffers(com.facebook.presto.execution.buffer.OutputBuffers) OutputBufferId(com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId)

Example 3 with OutputBufferId

use of com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId 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) {
    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();
    }, directExecutor());
    // For hard timeout, add an additional time to max wait for thread scheduling contention and GC
    Duration timeout = new Duration(waitTime.toMillis() + ADDITIONAL_WAIT_TIME.toMillis(), 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) JsonCodec(com.facebook.airlift.json.JsonCodec) Page(com.facebook.presto.common.Page) RolesAllowed(javax.annotation.security.RolesAllowed) Produces(javax.ws.rs.Produces) Iterables.transform(com.google.common.collect.Iterables.transform) TaskStatus(com.facebook.presto.execution.TaskStatus) SerializedPage(com.facebook.presto.spi.page.SerializedPage) Path(javax.ws.rs.Path) TaskState(com.facebook.presto.execution.TaskState) OutputBufferId(com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId) APPLICATION_THRIFT_COMPACT(com.facebook.airlift.http.client.thrift.ThriftRequestUtils.APPLICATION_THRIFT_COMPACT) Duration(io.airlift.units.Duration) DEFAULT_MAX_WAIT_TIME(com.facebook.presto.util.TaskUtils.DEFAULT_MAX_WAIT_TIME) PlanFragment(com.facebook.presto.sql.planner.PlanFragment) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) 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) MetadataUpdates(com.facebook.presto.metadata.MetadataUpdates) AsyncResponse(javax.ws.rs.container.AsyncResponse) APPLICATION_JACKSON_SMILE(com.facebook.presto.PrestoMediaTypes.APPLICATION_JACKSON_SMILE) GenericEntity(javax.ws.rs.core.GenericEntity) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Suspended(javax.ws.rs.container.Suspended) Codec(com.facebook.airlift.json.Codec) 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) UriInfo(javax.ws.rs.core.UriInfo) APPLICATION_THRIFT_BINARY(com.facebook.airlift.http.client.thrift.ThriftRequestUtils.APPLICATION_THRIFT_BINARY) PRESTO_CURRENT_STATE(com.facebook.presto.client.PrestoHeaders.PRESTO_CURRENT_STATE) TaskUtils.randomizeWaitTime(com.facebook.presto.util.TaskUtils.randomizeWaitTime) 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) TimeStat(com.facebook.airlift.stats.TimeStat) BoundedExecutor(com.facebook.airlift.concurrent.BoundedExecutor) MoreFutures.addTimeout(com.facebook.airlift.concurrent.MoreFutures.addTimeout) ImmutableList(com.google.common.collect.ImmutableList) Managed(org.weakref.jmx.Managed) PRESTO_MAX_SIZE(com.facebook.presto.client.PrestoHeaders.PRESTO_MAX_SIZE) SmileCodec(com.facebook.airlift.json.smile.SmileCodec) TaskManager(com.facebook.presto.execution.TaskManager) Objects.requireNonNull(java.util.Objects.requireNonNull) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) INTERNAL(com.facebook.presto.server.security.RoleType.INTERNAL) APPLICATION_THRIFT_FB_COMPACT(com.facebook.airlift.http.client.thrift.ThriftRequestUtils.APPLICATION_THRIFT_FB_COMPACT) PRESTO_PAGE_NEXT_TOKEN(com.facebook.presto.client.PrestoHeaders.PRESTO_PAGE_NEXT_TOKEN) SessionPropertyManager(com.facebook.presto.metadata.SessionPropertyManager) Status(javax.ws.rs.core.Response.Status) POST(javax.ws.rs.POST) AsyncResponseHandler.bindAsyncResponse(com.facebook.airlift.http.server.AsyncResponseHandler.bindAsyncResponse) 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) AsyncResponse(javax.ws.rs.container.AsyncResponse) Response(javax.ws.rs.core.Response) AsyncResponseHandler.bindAsyncResponse(com.facebook.airlift.http.server.AsyncResponseHandler.bindAsyncResponse) BufferResult(com.facebook.presto.execution.buffer.BufferResult) SerializedPage(com.facebook.presto.spi.page.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 4 with OutputBufferId

use of com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId in project presto by prestodb.

the class BroadcastOutputBufferManager method addOutputBuffers.

@Override
public void addOutputBuffers(List<OutputBufferId> newBuffers, boolean noMoreBuffers) {
    OutputBuffers newOutputBuffers;
    synchronized (this) {
        if (outputBuffers.isNoMoreBufferIds()) {
            // the new buffers
            return;
        }
        OutputBuffers originalOutputBuffers = outputBuffers;
        // Note: it does not matter which partition id the task is using, in broadcast all tasks read from the same partition
        for (OutputBufferId newBuffer : newBuffers) {
            outputBuffers = outputBuffers.withBuffer(newBuffer, BROADCAST_PARTITION_ID);
        }
        if (noMoreBuffers) {
            outputBuffers = outputBuffers.withNoMoreBufferIds();
        }
        // don't update if nothing changed
        if (outputBuffers == originalOutputBuffers) {
            return;
        }
        newOutputBuffers = this.outputBuffers;
    }
    outputBufferTarget.accept(newOutputBuffers);
}
Also used : OutputBuffers.createInitialEmptyOutputBuffers(com.facebook.presto.execution.buffer.OutputBuffers.createInitialEmptyOutputBuffers) OutputBuffers(com.facebook.presto.execution.buffer.OutputBuffers) OutputBufferId(com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId)

Example 5 with OutputBufferId

use of com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId in project presto by prestodb.

the class ArbitraryOutputBuffer method setOutputBuffers.

@Override
public void setOutputBuffers(OutputBuffers newOutputBuffers) {
    checkState(!Thread.holdsLock(this), "Can not set output buffers while holding a lock on this");
    requireNonNull(newOutputBuffers, "newOutputBuffers is null");
    synchronized (this) {
        // ignore buffers added after query finishes, which can happen when a query is canceled
        // also ignore old versions, which is normal
        BufferState state = this.state.get();
        if (state.isTerminal() || outputBuffers.getVersion() >= newOutputBuffers.getVersion()) {
            return;
        }
        // verify this is valid state change
        outputBuffers.checkValidTransition(newOutputBuffers);
        outputBuffers = newOutputBuffers;
        // add the new buffers
        for (OutputBufferId outputBufferId : outputBuffers.getBuffers().keySet()) {
            getBuffer(outputBufferId);
        }
        // Reset resume from position
        nextClientBufferIndex.set(0);
        // update state if no more buffers is set
        if (outputBuffers.isNoMoreBufferIds()) {
            this.state.compareAndSet(OPEN, NO_MORE_BUFFERS);
            this.state.compareAndSet(NO_MORE_PAGES, FLUSHING);
        }
    }
    if (!state.get().canAddBuffers()) {
        noMoreBuffers();
    }
    checkFlushComplete();
}
Also used : OutputBufferId(com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId)

Aggregations

OutputBufferId (com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId)10 OutputBuffers.createInitialEmptyOutputBuffers (com.facebook.presto.execution.buffer.OutputBuffers.createInitialEmptyOutputBuffers)6 OutputBuffers (com.facebook.presto.execution.buffer.OutputBuffers)5 TaskId (com.facebook.presto.execution.TaskId)3 PlanFragment (com.facebook.presto.sql.planner.PlanFragment)3 ImmutableList (com.google.common.collect.ImmutableList)3 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)3 Test (org.testng.annotations.Test)3 TimeStat (com.facebook.airlift.stats.TimeStat)2 Session (com.facebook.presto.Session)2 DataSize (io.airlift.units.DataSize)2 Duration (io.airlift.units.Duration)2 List (java.util.List)2 Objects.requireNonNull (java.util.Objects.requireNonNull)2 MILLISECONDS (java.util.concurrent.TimeUnit.MILLISECONDS)2 SECONDS (java.util.concurrent.TimeUnit.SECONDS)2 BoundedExecutor (com.facebook.airlift.concurrent.BoundedExecutor)1 MoreFutures.addTimeout (com.facebook.airlift.concurrent.MoreFutures.addTimeout)1 MoreFutures.tryGetFutureValue (com.facebook.airlift.concurrent.MoreFutures.tryGetFutureValue)1 MoreFutures.whenAnyComplete (com.facebook.airlift.concurrent.MoreFutures.whenAnyComplete)1