Search in sources :

Example 6 with RequestMetadata

use of com.google.cloud.talent.v4.RequestMetadata in project bazel-buildfarm by bazelbuild.

the class ShardInstance method transformAndQueue.

private ListenableFuture<Void> transformAndQueue(ExecuteEntry executeEntry, Poller poller, Operation operation, Stopwatch stopwatch, Duration timeout) {
    long checkCacheUSecs = stopwatch.elapsed(MICROSECONDS);
    ExecuteOperationMetadata metadata;
    try {
        metadata = operation.getMetadata().unpack(ExecuteOperationMetadata.class);
    } catch (InvalidProtocolBufferException e) {
        return immediateFailedFuture(e);
    }
    Digest actionDigest = metadata.getActionDigest();
    SettableFuture<Void> queueFuture = SettableFuture.create();
    logger.log(Level.FINE, format("ShardInstance(%s): queue(%s): fetching action %s", getName(), operation.getName(), actionDigest.getHash()));
    RequestMetadata requestMetadata = executeEntry.getRequestMetadata();
    ListenableFuture<Action> actionFuture = catchingAsync(transformAsync(expectAction(actionDigest, requestMetadata), (action) -> {
        if (action == null) {
            throw Status.NOT_FOUND.asException();
        } else if (action.getDoNotCache()) {
            // invalidate our action cache result as well as watcher owner
            readThroughActionCache.invalidate(DigestUtil.asActionKey(actionDigest));
            backplane.putOperation(operation.toBuilder().setMetadata(Any.pack(action)).build(), metadata.getStage());
        }
        return immediateFuture(action);
    }, operationTransformService), StatusException.class, (e) -> {
        Status st = Status.fromThrowable(e);
        if (st.getCode() == Code.NOT_FOUND) {
            PreconditionFailure.Builder preconditionFailure = PreconditionFailure.newBuilder();
            preconditionFailure.addViolationsBuilder().setType(VIOLATION_TYPE_MISSING).setSubject("blobs/" + DigestUtil.toString(actionDigest)).setDescription(MISSING_ACTION);
            checkPreconditionFailure(actionDigest, preconditionFailure.build());
        }
        throw st.asRuntimeException();
    }, operationTransformService);
    QueuedOperation.Builder queuedOperationBuilder = QueuedOperation.newBuilder();
    ListenableFuture<ProfiledQueuedOperationMetadata.Builder> queuedFuture = transformAsync(actionFuture, (action) -> {
        logger.log(Level.FINE, format("ShardInstance(%s): queue(%s): fetched action %s transforming queuedOperation", getName(), operation.getName(), actionDigest.getHash()));
        Stopwatch transformStopwatch = Stopwatch.createStarted();
        return transform(transformQueuedOperation(operation.getName(), action, action.getCommandDigest(), action.getInputRootDigest(), queuedOperationBuilder, operationTransformService, requestMetadata), (queuedOperation) -> ProfiledQueuedOperationMetadata.newBuilder().setQueuedOperation(queuedOperation).setQueuedOperationMetadata(buildQueuedOperationMetadata(metadata, requestMetadata, queuedOperation)).setTransformedIn(Durations.fromMicros(transformStopwatch.elapsed(MICROSECONDS))), operationTransformService);
    }, operationTransformService);
    ListenableFuture<ProfiledQueuedOperationMetadata.Builder> validatedFuture = transformAsync(queuedFuture, (profiledQueuedMetadata) -> {
        logger.log(Level.FINE, format("ShardInstance(%s): queue(%s): queuedOperation %s transformed, validating", getName(), operation.getName(), DigestUtil.toString(profiledQueuedMetadata.getQueuedOperationMetadata().getQueuedOperationDigest())));
        long startValidateUSecs = stopwatch.elapsed(MICROSECONDS);
        /* sync, throws StatusException */
        validateQueuedOperation(actionDigest, profiledQueuedMetadata.getQueuedOperation());
        return immediateFuture(profiledQueuedMetadata.setValidatedIn(Durations.fromMicros(stopwatch.elapsed(MICROSECONDS) - startValidateUSecs)));
    }, operationTransformService);
    ListenableFuture<ProfiledQueuedOperationMetadata> queuedOperationCommittedFuture = transformAsync(validatedFuture, (profiledQueuedMetadata) -> {
        logger.log(Level.FINE, format("ShardInstance(%s): queue(%s): queuedOperation %s validated, uploading", getName(), operation.getName(), DigestUtil.toString(profiledQueuedMetadata.getQueuedOperationMetadata().getQueuedOperationDigest())));
        ByteString queuedOperationBlob = profiledQueuedMetadata.getQueuedOperation().toByteString();
        Digest queuedOperationDigest = profiledQueuedMetadata.getQueuedOperationMetadata().getQueuedOperationDigest();
        long startUploadUSecs = stopwatch.elapsed(MICROSECONDS);
        return transform(writeBlobFuture(queuedOperationDigest, queuedOperationBlob, requestMetadata, timeout), (committedSize) -> profiledQueuedMetadata.setUploadedIn(Durations.fromMicros(stopwatch.elapsed(MICROSECONDS) - startUploadUSecs)).build(), operationTransformService);
    }, operationTransformService);
    // onQueue call?
    addCallback(queuedOperationCommittedFuture, new FutureCallback<ProfiledQueuedOperationMetadata>() {

        @Override
        public void onSuccess(ProfiledQueuedOperationMetadata profiledQueuedMetadata) {
            QueuedOperationMetadata queuedOperationMetadata = profiledQueuedMetadata.getQueuedOperationMetadata();
            Operation queueOperation = operation.toBuilder().setMetadata(Any.pack(queuedOperationMetadata)).build();
            QueueEntry queueEntry = QueueEntry.newBuilder().setExecuteEntry(executeEntry).setQueuedOperationDigest(queuedOperationMetadata.getQueuedOperationDigest()).setPlatform(profiledQueuedMetadata.getQueuedOperation().getCommand().getPlatform()).build();
            try {
                ensureCanQueue(stopwatch);
                long startQueueUSecs = stopwatch.elapsed(MICROSECONDS);
                poller.pause();
                backplane.queue(queueEntry, queueOperation);
                long elapsedUSecs = stopwatch.elapsed(MICROSECONDS);
                long queueUSecs = elapsedUSecs - startQueueUSecs;
                logger.log(Level.FINE, format("ShardInstance(%s): queue(%s): %dus checkCache, %dus transform, %dus validate, %dus upload, %dus queue, %dus elapsed", getName(), queueOperation.getName(), checkCacheUSecs, Durations.toMicros(profiledQueuedMetadata.getTransformedIn()), Durations.toMicros(profiledQueuedMetadata.getValidatedIn()), Durations.toMicros(profiledQueuedMetadata.getUploadedIn()), queueUSecs, elapsedUSecs));
                queueFuture.set(null);
            } catch (IOException e) {
                onFailure(e.getCause() == null ? e : e.getCause());
            } catch (InterruptedException e) {
            // ignore
            }
        }

        @Override
        public void onFailure(Throwable t) {
            poller.pause();
            com.google.rpc.Status status = StatusProto.fromThrowable(t);
            if (status == null) {
                logger.log(Level.SEVERE, "no rpc status from exception for " + operation.getName(), t);
                status = asExecutionStatus(t);
            } else if (com.google.rpc.Code.forNumber(status.getCode()) == com.google.rpc.Code.DEADLINE_EXCEEDED) {
                logger.log(Level.WARNING, "an rpc status was thrown with DEADLINE_EXCEEDED for " + operation.getName() + ", discarding it", t);
                status = com.google.rpc.Status.newBuilder().setCode(com.google.rpc.Code.UNAVAILABLE.getNumber()).setMessage("SUPPRESSED DEADLINE_EXCEEDED: " + t.getMessage()).build();
            }
            logFailedStatus(actionDigest, status);
            errorOperationFuture(operation, requestMetadata, status, queueFuture);
        }
    }, operationTransformService);
    return queueFuture;
}
Also used : ExecuteOperationMetadata(build.bazel.remote.execution.v2.ExecuteOperationMetadata) AsyncCache(com.github.benmanes.caffeine.cache.AsyncCache) LoadingCache(com.google.common.cache.LoadingCache) DirectoryNode(build.bazel.remote.execution.v2.DirectoryNode) ExecuteEntry(build.buildfarm.v1test.ExecuteEntry) ExecutionStage(build.bazel.remote.execution.v2.ExecutionStage) Durations(com.google.protobuf.util.Durations) Executors.newSingleThreadScheduledExecutor(java.util.concurrent.Executors.newSingleThreadScheduledExecutor) StatusProto(io.grpc.protobuf.StatusProto) Tree(build.buildfarm.v1test.Tree) Map(java.util.Map) Status(io.grpc.Status) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) Futures.allAsList(com.google.common.util.concurrent.Futures.allAsList) EntryLimitException(build.buildfarm.common.EntryLimitException) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) MoreExecutors.directExecutor(com.google.common.util.concurrent.MoreExecutors.directExecutor) MatchListener(build.buildfarm.instance.MatchListener) AbstractServerInstance(build.buildfarm.instance.server.AbstractServerInstance) VIOLATION_TYPE_MISSING(build.buildfarm.common.Errors.VIOLATION_TYPE_MISSING) DirectoryEntry(build.buildfarm.common.TreeIterator.DirectoryEntry) OperationIteratorToken(build.buildfarm.v1test.OperationIteratorToken) QueueEntry(build.buildfarm.v1test.QueueEntry) Any(com.google.protobuf.Any) MICROSECONDS(java.util.concurrent.TimeUnit.MICROSECONDS) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) Actions.checkPreconditionFailure(build.buildfarm.common.Actions.checkPreconditionFailure) Directory(build.bazel.remote.execution.v2.Directory) ShardInstanceConfig(build.buildfarm.v1test.ShardInstanceConfig) Iterables(com.google.common.collect.Iterables) Command(build.bazel.remote.execution.v2.Command) MINUTES(java.util.concurrent.TimeUnit.MINUTES) QueuedOperation(build.buildfarm.v1test.QueuedOperation) Util.correctMissingBlob(build.buildfarm.instance.shard.Util.correctMissingBlob) ResultsCachePolicy(build.bazel.remote.execution.v2.ResultsCachePolicy) Cache(com.github.benmanes.caffeine.cache.Cache) Supplier(java.util.function.Supplier) DigestUtil(build.buildfarm.common.DigestUtil) ArrayList(java.util.ArrayList) Code(io.grpc.Status.Code) Action(build.bazel.remote.execution.v2.Action) UniformDelegateServerCallStreamObserver(build.buildfarm.common.grpc.UniformDelegateServerCallStreamObserver) Futures.addCallback(com.google.common.util.concurrent.Futures.addCallback) Actions.asExecutionStatus(build.buildfarm.common.Actions.asExecutionStatus) Watcher(build.buildfarm.common.Watcher) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) VIOLATION_TYPE_INVALID(build.buildfarm.common.Errors.VIOLATION_TYPE_INVALID) Nullable(javax.annotation.Nullable) Backplane(build.buildfarm.backplane.Backplane) Futures.immediateFuture(com.google.common.util.concurrent.Futures.immediateFuture) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) BaseEncoding(com.google.common.io.BaseEncoding) Executor(java.util.concurrent.Executor) Poller(build.buildfarm.common.Poller) Throwables(com.google.common.base.Throwables) PreconditionFailure(com.google.rpc.PreconditionFailure) IOException(java.io.IOException) QueueStatus(build.buildfarm.v1test.QueueStatus) FutureCallback(com.google.common.util.concurrent.FutureCallback) StatusRuntimeException(io.grpc.StatusRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) Futures(com.google.common.util.concurrent.Futures) Duration(com.google.protobuf.Duration) FutureConverter.toCompletableFuture(net.javacrumbs.futureconverter.java8guava.FutureConverter.toCompletableFuture) ExecuteResponse(build.bazel.remote.execution.v2.ExecuteResponse) ArrayDeque(java.util.ArrayDeque) Futures.transform(com.google.common.util.concurrent.Futures.transform) Context(io.grpc.Context) Futures.transformAsync(com.google.common.util.concurrent.Futures.transformAsync) BiFunction(java.util.function.BiFunction) RequestMetadata(build.bazel.remote.execution.v2.RequestMetadata) Random(java.util.Random) Actions.invalidActionVerboseMessage(build.buildfarm.common.Actions.invalidActionVerboseMessage) ActionKey(build.buildfarm.common.DigestUtil.ActionKey) SettableFuture(com.google.common.util.concurrent.SettableFuture) ExecutionProperties(build.buildfarm.common.ExecutionProperties) TokenizableIterator(build.buildfarm.common.TokenizableIterator) Digest(build.bazel.remote.execution.v2.Digest) CasIndexResults(build.buildfarm.common.CasIndexResults) Gauge(io.prometheus.client.Gauge) Histogram(io.prometheus.client.Histogram) Executors.newSingleThreadExecutor(java.util.concurrent.Executors.newSingleThreadExecutor) Timestamps(com.google.protobuf.util.Timestamps) BackplaneStatus(build.buildfarm.v1test.BackplaneStatus) UUID(java.util.UUID) Logger(java.util.logging.Logger) Platform(build.bazel.remote.execution.v2.Platform) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) String.format(java.lang.String.format) Instance(build.buildfarm.instance.Instance) Sets(com.google.common.collect.Sets) Parser(com.google.protobuf.Parser) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ByteString(com.google.protobuf.ByteString) QueuedOperationMetadata(build.buildfarm.v1test.QueuedOperationMetadata) List(java.util.List) Queue(java.util.Queue) FutureConverter.toListenableFuture(net.javacrumbs.futureconverter.java8guava.FutureConverter.toListenableFuture) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) MoreExecutors.listeningDecorator(com.google.common.util.concurrent.MoreExecutors.listeningDecorator) GetClientStartTimeRequest(build.buildfarm.v1test.GetClientStartTimeRequest) TreeIterator(build.buildfarm.common.TreeIterator) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Deadline(io.grpc.Deadline) Property(build.bazel.remote.execution.v2.Platform.Property) Stopwatch(com.google.common.base.Stopwatch) StatusException(io.grpc.StatusException) ProfiledQueuedOperationMetadata(build.buildfarm.v1test.ProfiledQueuedOperationMetadata) CompletableFuture(java.util.concurrent.CompletableFuture) ConfigurationException(javax.naming.ConfigurationException) Operation(com.google.longrunning.Operation) Deque(java.util.Deque) Counter(io.prometheus.client.Counter) Level(java.util.logging.Level) SHARD_IS_RETRIABLE(build.buildfarm.instance.shard.Util.SHARD_IS_RETRIABLE) ImmutableList(com.google.common.collect.ImmutableList) GetClientStartTimeResult(build.buildfarm.v1test.GetClientStartTimeResult) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) FindOperationsResults(build.buildfarm.operations.FindOperationsResults) ActionResult(build.bazel.remote.execution.v2.ActionResult) ExecutorService(java.util.concurrent.ExecutorService) OutputStream(java.io.OutputStream) Iterator(java.util.Iterator) Futures.catching(com.google.common.util.concurrent.Futures.catching) ExecutionPolicy(build.bazel.remote.execution.v2.ExecutionPolicy) Executors.newFixedThreadPool(java.util.concurrent.Executors.newFixedThreadPool) Write(build.buildfarm.common.Write) Futures.catchingAsync(com.google.common.util.concurrent.Futures.catchingAsync) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Futures.immediateFailedFuture(com.google.common.util.concurrent.Futures.immediateFailedFuture) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) SECONDS(java.util.concurrent.TimeUnit.SECONDS) InputStream(java.io.InputStream) ProfiledQueuedOperationMetadata(build.buildfarm.v1test.ProfiledQueuedOperationMetadata) Action(build.bazel.remote.execution.v2.Action) ByteString(com.google.protobuf.ByteString) Stopwatch(com.google.common.base.Stopwatch) QueuedOperation(build.buildfarm.v1test.QueuedOperation) Operation(com.google.longrunning.Operation) Status(io.grpc.Status) Actions.asExecutionStatus(build.buildfarm.common.Actions.asExecutionStatus) QueueStatus(build.buildfarm.v1test.QueueStatus) BackplaneStatus(build.buildfarm.v1test.BackplaneStatus) Digest(build.bazel.remote.execution.v2.Digest) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) IOException(java.io.IOException) QueueEntry(build.buildfarm.v1test.QueueEntry) RequestMetadata(build.bazel.remote.execution.v2.RequestMetadata) Actions.checkPreconditionFailure(build.buildfarm.common.Actions.checkPreconditionFailure) PreconditionFailure(com.google.rpc.PreconditionFailure) QueuedOperation(build.buildfarm.v1test.QueuedOperation) ExecuteOperationMetadata(build.bazel.remote.execution.v2.ExecuteOperationMetadata) QueuedOperationMetadata(build.buildfarm.v1test.QueuedOperationMetadata) ProfiledQueuedOperationMetadata(build.buildfarm.v1test.ProfiledQueuedOperationMetadata)

Example 7 with RequestMetadata

use of com.google.cloud.talent.v4.RequestMetadata in project bazel-buildfarm by bazelbuild.

the class ShardInstance method validateAndRequeueOperation.

private ListenableFuture<Void> validateAndRequeueOperation(Operation operation, QueueEntry queueEntry, Duration timeout) {
    ExecuteEntry executeEntry = queueEntry.getExecuteEntry();
    String operationName = executeEntry.getOperationName();
    checkState(operationName.equals(operation.getName()));
    RequestMetadata requestMetadata = executeEntry.getRequestMetadata();
    ListenableFuture<QueuedOperation> fetchQueuedOperationFuture = expect(queueEntry.getQueuedOperationDigest(), QueuedOperation.parser(), operationTransformService, requestMetadata);
    Digest actionDigest = executeEntry.getActionDigest();
    ListenableFuture<QueuedOperation> queuedOperationFuture = catchingAsync(fetchQueuedOperationFuture, Throwable.class, (e) -> buildQueuedOperation(operation.getName(), actionDigest, operationTransformService, requestMetadata), directExecutor());
    PreconditionFailure.Builder preconditionFailure = PreconditionFailure.newBuilder();
    ListenableFuture<QueuedOperation> validatedFuture = transformAsync(queuedOperationFuture, (queuedOperation) -> {
        /* sync, throws StatusException - must be serviced via non-OTS */
        validateQueuedOperationAndInputs(actionDigest, queuedOperation, preconditionFailure, requestMetadata);
        return immediateFuture(queuedOperation);
    }, operationTransformService);
    // this little fork ensures that a successfully fetched QueuedOperation
    // will not be reuploaded
    ListenableFuture<QueuedOperationResult> uploadedFuture = transformAsync(validatedFuture, (queuedOperation) -> catchingAsync(transform(fetchQueuedOperationFuture, (fechedQueuedOperation) -> {
        QueuedOperationMetadata metadata = QueuedOperationMetadata.newBuilder().setExecuteOperationMetadata(executeOperationMetadata(executeEntry, ExecutionStage.Value.QUEUED)).setQueuedOperationDigest(queueEntry.getQueuedOperationDigest()).setRequestMetadata(requestMetadata).build();
        return new QueuedOperationResult(queueEntry, metadata);
    }, operationTransformService), Throwable.class, (e) -> uploadQueuedOperation(queuedOperation, executeEntry, operationTransformService, timeout), operationTransformService), directExecutor());
    SettableFuture<Void> requeuedFuture = SettableFuture.create();
    addCallback(uploadedFuture, new FutureCallback<QueuedOperationResult>() {

        @Override
        public void onSuccess(QueuedOperationResult result) {
            Operation queueOperation = operation.toBuilder().setMetadata(Any.pack(result.metadata)).build();
            try {
                backplane.queue(result.entry, queueOperation);
                requeuedFuture.set(null);
            } catch (IOException e) {
                onFailure(e);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            logger.log(Level.SEVERE, "failed to requeue: " + operationName, t);
            com.google.rpc.Status status = StatusProto.fromThrowable(t);
            if (status == null) {
                logger.log(Level.SEVERE, "no rpc status from exception for " + operationName, t);
                status = asExecutionStatus(t);
            } else if (com.google.rpc.Code.forNumber(status.getCode()) == com.google.rpc.Code.DEADLINE_EXCEEDED) {
                logger.log(Level.WARNING, "an rpc status was thrown with DEADLINE_EXCEEDED for " + operationName + ", discarding it", t);
                status = com.google.rpc.Status.newBuilder().setCode(com.google.rpc.Code.UNAVAILABLE.getNumber()).setMessage("SUPPRESSED DEADLINE_EXCEEDED: " + t.getMessage()).build();
            }
            logFailedStatus(actionDigest, status);
            SettableFuture<Void> errorFuture = SettableFuture.create();
            errorOperationFuture(operation, requestMetadata, status, errorFuture);
            errorFuture.addListener(() -> requeuedFuture.set(null), operationTransformService);
        }
    }, operationTransformService);
    return requeuedFuture;
}
Also used : ExecuteOperationMetadata(build.bazel.remote.execution.v2.ExecuteOperationMetadata) AsyncCache(com.github.benmanes.caffeine.cache.AsyncCache) LoadingCache(com.google.common.cache.LoadingCache) DirectoryNode(build.bazel.remote.execution.v2.DirectoryNode) ExecuteEntry(build.buildfarm.v1test.ExecuteEntry) ExecutionStage(build.bazel.remote.execution.v2.ExecutionStage) Durations(com.google.protobuf.util.Durations) Executors.newSingleThreadScheduledExecutor(java.util.concurrent.Executors.newSingleThreadScheduledExecutor) StatusProto(io.grpc.protobuf.StatusProto) Tree(build.buildfarm.v1test.Tree) Map(java.util.Map) Status(io.grpc.Status) ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) Futures.allAsList(com.google.common.util.concurrent.Futures.allAsList) EntryLimitException(build.buildfarm.common.EntryLimitException) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) MoreExecutors.directExecutor(com.google.common.util.concurrent.MoreExecutors.directExecutor) MatchListener(build.buildfarm.instance.MatchListener) AbstractServerInstance(build.buildfarm.instance.server.AbstractServerInstance) VIOLATION_TYPE_MISSING(build.buildfarm.common.Errors.VIOLATION_TYPE_MISSING) DirectoryEntry(build.buildfarm.common.TreeIterator.DirectoryEntry) OperationIteratorToken(build.buildfarm.v1test.OperationIteratorToken) QueueEntry(build.buildfarm.v1test.QueueEntry) Any(com.google.protobuf.Any) MICROSECONDS(java.util.concurrent.TimeUnit.MICROSECONDS) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) Actions.checkPreconditionFailure(build.buildfarm.common.Actions.checkPreconditionFailure) Directory(build.bazel.remote.execution.v2.Directory) ShardInstanceConfig(build.buildfarm.v1test.ShardInstanceConfig) Iterables(com.google.common.collect.Iterables) Command(build.bazel.remote.execution.v2.Command) MINUTES(java.util.concurrent.TimeUnit.MINUTES) QueuedOperation(build.buildfarm.v1test.QueuedOperation) Util.correctMissingBlob(build.buildfarm.instance.shard.Util.correctMissingBlob) ResultsCachePolicy(build.bazel.remote.execution.v2.ResultsCachePolicy) Cache(com.github.benmanes.caffeine.cache.Cache) Supplier(java.util.function.Supplier) DigestUtil(build.buildfarm.common.DigestUtil) ArrayList(java.util.ArrayList) Code(io.grpc.Status.Code) Action(build.bazel.remote.execution.v2.Action) UniformDelegateServerCallStreamObserver(build.buildfarm.common.grpc.UniformDelegateServerCallStreamObserver) Futures.addCallback(com.google.common.util.concurrent.Futures.addCallback) Actions.asExecutionStatus(build.buildfarm.common.Actions.asExecutionStatus) Watcher(build.buildfarm.common.Watcher) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) VIOLATION_TYPE_INVALID(build.buildfarm.common.Errors.VIOLATION_TYPE_INVALID) Nullable(javax.annotation.Nullable) Backplane(build.buildfarm.backplane.Backplane) Futures.immediateFuture(com.google.common.util.concurrent.Futures.immediateFuture) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) BaseEncoding(com.google.common.io.BaseEncoding) Executor(java.util.concurrent.Executor) Poller(build.buildfarm.common.Poller) Throwables(com.google.common.base.Throwables) PreconditionFailure(com.google.rpc.PreconditionFailure) IOException(java.io.IOException) QueueStatus(build.buildfarm.v1test.QueueStatus) FutureCallback(com.google.common.util.concurrent.FutureCallback) StatusRuntimeException(io.grpc.StatusRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) Futures(com.google.common.util.concurrent.Futures) Duration(com.google.protobuf.Duration) FutureConverter.toCompletableFuture(net.javacrumbs.futureconverter.java8guava.FutureConverter.toCompletableFuture) ExecuteResponse(build.bazel.remote.execution.v2.ExecuteResponse) ArrayDeque(java.util.ArrayDeque) Futures.transform(com.google.common.util.concurrent.Futures.transform) Context(io.grpc.Context) Futures.transformAsync(com.google.common.util.concurrent.Futures.transformAsync) BiFunction(java.util.function.BiFunction) RequestMetadata(build.bazel.remote.execution.v2.RequestMetadata) Random(java.util.Random) Actions.invalidActionVerboseMessage(build.buildfarm.common.Actions.invalidActionVerboseMessage) ActionKey(build.buildfarm.common.DigestUtil.ActionKey) SettableFuture(com.google.common.util.concurrent.SettableFuture) ExecutionProperties(build.buildfarm.common.ExecutionProperties) TokenizableIterator(build.buildfarm.common.TokenizableIterator) Digest(build.bazel.remote.execution.v2.Digest) CasIndexResults(build.buildfarm.common.CasIndexResults) Gauge(io.prometheus.client.Gauge) Histogram(io.prometheus.client.Histogram) Executors.newSingleThreadExecutor(java.util.concurrent.Executors.newSingleThreadExecutor) Timestamps(com.google.protobuf.util.Timestamps) BackplaneStatus(build.buildfarm.v1test.BackplaneStatus) UUID(java.util.UUID) Logger(java.util.logging.Logger) Platform(build.bazel.remote.execution.v2.Platform) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) String.format(java.lang.String.format) Instance(build.buildfarm.instance.Instance) Sets(com.google.common.collect.Sets) Parser(com.google.protobuf.Parser) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ByteString(com.google.protobuf.ByteString) QueuedOperationMetadata(build.buildfarm.v1test.QueuedOperationMetadata) List(java.util.List) Queue(java.util.Queue) FutureConverter.toListenableFuture(net.javacrumbs.futureconverter.java8guava.FutureConverter.toListenableFuture) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) MoreExecutors.listeningDecorator(com.google.common.util.concurrent.MoreExecutors.listeningDecorator) GetClientStartTimeRequest(build.buildfarm.v1test.GetClientStartTimeRequest) TreeIterator(build.buildfarm.common.TreeIterator) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Deadline(io.grpc.Deadline) Property(build.bazel.remote.execution.v2.Platform.Property) Stopwatch(com.google.common.base.Stopwatch) StatusException(io.grpc.StatusException) ProfiledQueuedOperationMetadata(build.buildfarm.v1test.ProfiledQueuedOperationMetadata) CompletableFuture(java.util.concurrent.CompletableFuture) ConfigurationException(javax.naming.ConfigurationException) Operation(com.google.longrunning.Operation) Deque(java.util.Deque) Counter(io.prometheus.client.Counter) Level(java.util.logging.Level) SHARD_IS_RETRIABLE(build.buildfarm.instance.shard.Util.SHARD_IS_RETRIABLE) ImmutableList(com.google.common.collect.ImmutableList) GetClientStartTimeResult(build.buildfarm.v1test.GetClientStartTimeResult) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) FindOperationsResults(build.buildfarm.operations.FindOperationsResults) ActionResult(build.bazel.remote.execution.v2.ActionResult) ExecutorService(java.util.concurrent.ExecutorService) OutputStream(java.io.OutputStream) Iterator(java.util.Iterator) Futures.catching(com.google.common.util.concurrent.Futures.catching) ExecutionPolicy(build.bazel.remote.execution.v2.ExecutionPolicy) Executors.newFixedThreadPool(java.util.concurrent.Executors.newFixedThreadPool) Write(build.buildfarm.common.Write) Futures.catchingAsync(com.google.common.util.concurrent.Futures.catchingAsync) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Futures.immediateFailedFuture(com.google.common.util.concurrent.Futures.immediateFailedFuture) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) SECONDS(java.util.concurrent.TimeUnit.SECONDS) InputStream(java.io.InputStream) Status(io.grpc.Status) Actions.asExecutionStatus(build.buildfarm.common.Actions.asExecutionStatus) QueueStatus(build.buildfarm.v1test.QueueStatus) BackplaneStatus(build.buildfarm.v1test.BackplaneStatus) SettableFuture(com.google.common.util.concurrent.SettableFuture) Digest(build.bazel.remote.execution.v2.Digest) ExecuteEntry(build.buildfarm.v1test.ExecuteEntry) ByteString(com.google.protobuf.ByteString) QueuedOperation(build.buildfarm.v1test.QueuedOperation) Operation(com.google.longrunning.Operation) IOException(java.io.IOException) RequestMetadata(build.bazel.remote.execution.v2.RequestMetadata) Actions.checkPreconditionFailure(build.buildfarm.common.Actions.checkPreconditionFailure) PreconditionFailure(com.google.rpc.PreconditionFailure) QueuedOperation(build.buildfarm.v1test.QueuedOperation) QueuedOperationMetadata(build.buildfarm.v1test.QueuedOperationMetadata) ProfiledQueuedOperationMetadata(build.buildfarm.v1test.ProfiledQueuedOperationMetadata)

Example 8 with RequestMetadata

use of com.google.cloud.talent.v4.RequestMetadata in project bazel-buildfarm by bazelbuild.

the class RemoteInputStreamFactory method newInput.

@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
public InputStream newInput(Digest blobDigest, long offset, long deadlineAfter, TimeUnit deadlineAfterUnits, RequestMetadata requestMetadata) throws IOException, InterruptedException {
    Set<String> remoteWorkers;
    Set<String> locationSet;
    try {
        Set<String> workers = backplane.getWorkers();
        if (publicName == null) {
            remoteWorkers = workers;
        } else {
            synchronized (workers) {
                remoteWorkers = Sets.difference(workers, ImmutableSet.of(publicName)).immutableCopy();
            }
        }
        locationSet = Sets.newHashSet(Sets.intersection(backplane.getBlobLocationSet(blobDigest), workers));
    } catch (IOException e) {
        throw Status.fromThrowable(e).asRuntimeException();
    }
    if (publicName != null && locationSet.remove(publicName)) {
        backplane.removeBlobLocation(blobDigest, publicName);
    }
    List<String> workersList = new ArrayList<>(locationSet);
    boolean emptyWorkerList = workersList.isEmpty();
    final ListenableFuture<List<String>> populatedWorkerListFuture;
    if (emptyWorkerList) {
        populatedWorkerListFuture = transform(correctMissingBlob(backplane, remoteWorkers, locationSet, this::workerStub, blobDigest, newDirectExecutorService(), requestMetadata), (foundOnWorkers) -> {
            Iterables.addAll(workersList, foundOnWorkers);
            return workersList;
        }, directExecutor());
    } else {
        populatedWorkerListFuture = immediateFuture(workersList);
    }
    SettableFuture<InputStream> inputStreamFuture = SettableFuture.create();
    addCallback(populatedWorkerListFuture, new WorkersCallback(rand) {

        boolean triedCheck = emptyWorkerList;

        @Override
        public void onQueue(Deque<String> workers) {
            Set<String> locationSet = Sets.newHashSet(workers);
            boolean complete = false;
            while (!complete && !workers.isEmpty()) {
                try {
                    inputStreamFuture.set(fetchBlobFromRemoteWorker(blobDigest, workers, offset, deadlineAfter, deadlineAfterUnits, requestMetadata));
                    complete = true;
                } catch (IOException e) {
                    if (workers.isEmpty()) {
                        if (triedCheck) {
                            onFailure(e);
                            return;
                        }
                        triedCheck = true;
                        workersList.clear();
                        ListenableFuture<List<String>> checkedWorkerListFuture = transform(correctMissingBlob(backplane, remoteWorkers, locationSet, RemoteInputStreamFactory.this::workerStub, blobDigest, newDirectExecutorService(), requestMetadata), (foundOnWorkers) -> {
                            Iterables.addAll(workersList, foundOnWorkers);
                            return workersList;
                        }, directExecutor());
                        addCallback(checkedWorkerListFuture, this, directExecutor());
                        complete = true;
                    }
                } catch (InterruptedException e) {
                    complete = true;
                    onFailure(e);
                }
            }
        }

        @SuppressWarnings("NullableProblems")
        @Override
        public void onFailure(Throwable t) {
            Status status = Status.fromThrowable(t);
            if (status.getCode() == Code.NOT_FOUND) {
                inputStreamFuture.setException(new NoSuchFileException(DigestUtil.toString(blobDigest)));
            } else {
                inputStreamFuture.setException(t);
            }
        }
    }, directExecutor());
    try {
        return inputStreamFuture.get();
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        Throwables.throwIfUnchecked(cause);
        Throwables.throwIfInstanceOf(cause, IOException.class);
        Throwables.throwIfInstanceOf(cause, InterruptedException.class);
        throw new UncheckedExecutionException(cause);
    }
}
Also used : Iterables(com.google.common.collect.Iterables) NoSuchFileException(java.nio.file.NoSuchFileException) LoadingCache(com.google.common.cache.LoadingCache) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) MoreExecutors.newDirectExecutorService(com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService) RequestMetadata(build.bazel.remote.execution.v2.RequestMetadata) Random(java.util.Random) Util.correctMissingBlob(build.buildfarm.instance.shard.Util.correctMissingBlob) InputStreamFactory(build.buildfarm.common.InputStreamFactory) SettableFuture(com.google.common.util.concurrent.SettableFuture) Deque(java.util.Deque) DigestUtil(build.buildfarm.common.DigestUtil) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) SHARD_IS_RETRIABLE(build.buildfarm.instance.shard.Util.SHARD_IS_RETRIABLE) Code(io.grpc.Status.Code) Futures.addCallback(com.google.common.util.concurrent.Futures.addCallback) Digest(build.bazel.remote.execution.v2.Digest) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) Status(io.grpc.Status) Nullable(javax.annotation.Nullable) WorkersCallback(build.buildfarm.instance.shard.ShardInstance.WorkersCallback) Backplane(build.buildfarm.backplane.Backplane) Futures.immediateFuture(com.google.common.util.concurrent.Futures.immediateFuture) ImmutableSet(com.google.common.collect.ImmutableSet) Throwables(com.google.common.base.Throwables) Set(java.util.Set) IOException(java.io.IOException) Logger(java.util.logging.Logger) Instance(build.buildfarm.instance.Instance) Sets(com.google.common.collect.Sets) MoreExecutors.directExecutor(com.google.common.util.concurrent.MoreExecutors.directExecutor) StatusRuntimeException(io.grpc.StatusRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Futures.transform(com.google.common.util.concurrent.Futures.transform) SECONDS(java.util.concurrent.TimeUnit.SECONDS) InputStream(java.io.InputStream) Status(io.grpc.Status) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) NoSuchFileException(java.nio.file.NoSuchFileException) IOException(java.io.IOException) WorkersCallback(build.buildfarm.instance.shard.ShardInstance.WorkersCallback) ArrayList(java.util.ArrayList) List(java.util.List) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) ExecutionException(java.util.concurrent.ExecutionException)

Example 9 with RequestMetadata

use of com.google.cloud.talent.v4.RequestMetadata in project bazel-buildfarm by bazelbuild.

the class AbstractServerInstance method cancelOperation.

@Override
public void cancelOperation(String name) throws InterruptedException {
    Operation operation = getOperation(name);
    if (operation == null) {
        operation = Operation.newBuilder().setName(name).setMetadata(Any.pack(ExecuteOperationMetadata.getDefaultInstance())).build();
    }
    RequestMetadata requestMetadata = expectRequestMetadata(operation);
    errorOperation(operation, requestMetadata, com.google.rpc.Status.newBuilder().setCode(Code.CANCELLED.getNumber()).build());
}
Also used : QueuedOperation(build.buildfarm.v1test.QueuedOperation) EnrichedOperation(build.buildfarm.operations.EnrichedOperation) Operation(com.google.longrunning.Operation) RequestMetadata(build.bazel.remote.execution.v2.RequestMetadata)

Example 10 with RequestMetadata

use of com.google.cloud.talent.v4.RequestMetadata in project bazel-buildfarm by bazelbuild.

the class TracingMetadataUtils method attachMetadataInterceptor.

public static ClientInterceptor attachMetadataInterceptor(RequestMetadata metadata) {
    Metadata headers = new Metadata();
    headers.put(METADATA_KEY, metadata);
    return MetadataUtils.newAttachHeadersInterceptor(headers);
}
Also used : RequestMetadata(build.bazel.remote.execution.v2.RequestMetadata) Metadata(io.grpc.Metadata)

Aggregations

RequestMetadata (build.bazel.remote.execution.v2.RequestMetadata)17 Digest (build.bazel.remote.execution.v2.Digest)11 ByteString (com.google.protobuf.ByteString)8 ServerCallStreamObserver (io.grpc.stub.ServerCallStreamObserver)7 ActionResult (build.bazel.remote.execution.v2.ActionResult)6 ExecuteOperationMetadata (build.bazel.remote.execution.v2.ExecuteOperationMetadata)6 ExecuteResponse (build.bazel.remote.execution.v2.ExecuteResponse)6 ActionKey (build.buildfarm.common.DigestUtil.ActionKey)6 Operation (com.google.longrunning.Operation)6 DigestUtil (build.buildfarm.common.DigestUtil)5 Watcher (build.buildfarm.common.Watcher)5 Write (build.buildfarm.common.Write)5 Instance (build.buildfarm.instance.Instance)5 QueuedOperation (build.buildfarm.v1test.QueuedOperation)4 Job (com.google.cloud.talent.v4beta1.Job)4 JobServiceClient (com.google.cloud.talent.v4beta1.JobServiceClient)4 RequestMetadata (com.google.cloud.talent.v4beta1.RequestMetadata)4 SearchJobsRequest (com.google.cloud.talent.v4beta1.SearchJobsRequest)4 Duration (com.google.protobuf.Duration)4 Test (org.junit.Test)4