Search in sources :

Example 21 with RequestMetadata

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

the class ContentAddressableStorages method casMapDecorator.

/**
 * decorates a map with a CAS interface, does not react to removals with expirations
 */
public static ContentAddressableStorage casMapDecorator(Map<String, ByteString> map) {
    return new ContentAddressableStorage() {

        final Writes writes = new Writes(this);

        @Override
        public boolean contains(Digest digest, Digest.Builder result) {
            ByteString data = getData(digest);
            if (data != null) {
                result.mergeFrom(digest).setSizeBytes(data.size());
                return true;
            }
            return false;
        }

        @Override
        public Iterable<Digest> findMissingBlobs(Iterable<Digest> digests) {
            ImmutableList.Builder<Digest> missing = ImmutableList.builder();
            for (Digest digest : digests) {
                if (getData(digest) == null) {
                    missing.add(digest);
                }
            }
            return missing.build();
        }

        @Override
        public Write getWrite(Digest digest, UUID uuid, RequestMetadata requestMetadata) {
            return writes.get(digest, uuid);
        }

        @SuppressWarnings("ResultOfMethodCallIgnored")
        @Override
        public InputStream newInput(Digest digest, long offset) throws IOException {
            ByteString data = getData(digest);
            if (data == null) {
                throw new NoSuchFileException(digest.getHash());
            }
            InputStream in = data.newInput();
            in.skip(offset);
            return in;
        }

        @Override
        public void get(Digest digest, long offset, long count, ServerCallStreamObserver<ByteString> responseObserver, RequestMetadata requestMetadata) {
            ByteString data = getData(digest);
            if (data != null) {
                responseObserver.onNext(data);
                responseObserver.onCompleted();
            } else {
                responseObserver.onError(Status.NOT_FOUND.asException());
            }
        }

        private ByteString getData(Digest digest) {
            if (digest.getSizeBytes() == 0) {
                return ByteString.EMPTY;
            }
            ByteString data = map.get(digest.getHash());
            if (data == null || (digest.getSizeBytes() > 0 && digest.getSizeBytes() != data.size())) {
                return null;
            }
            return data;
        }

        @Override
        public ListenableFuture<Iterable<Response>> getAllFuture(Iterable<Digest> digests) {
            return immediateFuture(MemoryCAS.getAll(digests, this::getData));
        }

        @Override
        public Blob get(Digest digest) {
            ByteString data = getData(digest);
            if (data == null) {
                return null;
            }
            return new Blob(data, digest);
        }

        @Override
        public void put(Blob blob) {
            map.put(blob.getDigest().getHash(), blob.getData());
            writes.getFuture(blob.getDigest()).set(blob.getData());
        }

        @Override
        public void put(Blob blob, Runnable onExpiration) {
            put(blob);
        }

        @Override
        public long maxEntrySize() {
            return UNLIMITED_ENTRY_SIZE_MAX;
        }
    };
}
Also used : ServerCallStreamObserver(io.grpc.stub.ServerCallStreamObserver) Digest(build.bazel.remote.execution.v2.Digest) ByteString(com.google.protobuf.ByteString) ImmutableList(com.google.common.collect.ImmutableList) InputStream(java.io.InputStream) MultimapBuilder(com.google.common.collect.MultimapBuilder) NettyChannelBuilder(io.grpc.netty.NettyChannelBuilder) NoSuchFileException(java.nio.file.NoSuchFileException) RequestMetadata(build.bazel.remote.execution.v2.RequestMetadata) UUID(java.util.UUID)

Example 22 with RequestMetadata

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

the class WriteStreamObserver method errorResponse.

private boolean errorResponse(Throwable t) {
    if (exception.compareAndSet(null, t)) {
        boolean isEntryLimitException = t instanceof EntryLimitException;
        if (isEntryLimitException) {
            t = Status.OUT_OF_RANGE.withDescription(t.getMessage()).asException();
        }
        responseObserver.onError(t);
        if (isEntryLimitException) {
            RequestMetadata requestMetadata = TracingMetadataUtils.fromCurrentContext();
            logger.log(Level.WARNING, format("%s-%s: %s -> %s -> %s: exceeded entry limit for %s", requestMetadata.getToolDetails().getToolName(), requestMetadata.getToolDetails().getToolVersion(), requestMetadata.getCorrelatedInvocationsId(), requestMetadata.getToolInvocationId(), requestMetadata.getActionId(), name));
        }
        return true;
    }
    return false;
}
Also used : EntryLimitException(build.buildfarm.common.EntryLimitException) RequestMetadata(build.bazel.remote.execution.v2.RequestMetadata)

Example 23 with RequestMetadata

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

the class FetchService method fetchBlob.

private void fetchBlob(Instance instance, FetchBlobRequest request, StreamObserver<FetchBlobResponse> responseObserver) {
    Digest expectedDigest = null;
    RequestMetadata requestMetadata = TracingMetadataUtils.fromCurrentContext();
    if (request.getQualifiersCount() == 0) {
        throw Status.INVALID_ARGUMENT.withDescription("Empty qualifier list").asRuntimeException();
    }
    for (Qualifier qualifier : request.getQualifiersList()) {
        String name = qualifier.getName();
        if (name.equals("checksum.sri")) {
            expectedDigest = parseChecksumSRI(qualifier.getValue());
            Digest.Builder result = Digest.newBuilder();
            if (instance.containsBlob(expectedDigest, result, requestMetadata)) {
                responseObserver.onNext(FetchBlobResponse.newBuilder().setBlobDigest(result.build()).build());
            }
        } else {
            throw Status.INVALID_ARGUMENT.withDescription(format("Invalid qualifier '%s'", name)).asRuntimeException();
        }
    }
    if (request.getUrisCount() != 0) {
        addCallback(instance.fetchBlob(request.getUrisList(), expectedDigest, requestMetadata), new FutureCallback<Digest>() {

            @Override
            public void onSuccess(Digest actualDigest) {
                logger.log(Level.INFO, format("fetch blob succeeded: %s inserted into CAS", DigestUtil.toString(actualDigest)));
                responseObserver.onNext(FetchBlobResponse.newBuilder().setBlobDigest(actualDigest).build());
                responseObserver.onCompleted();
            }

            @SuppressWarnings("NullableProblems")
            @Override
            public void onFailure(Throwable t) {
                // handle NoSuchFileException
                logger.log(Level.SEVERE, "fetch blob failed", t);
                responseObserver.onError(t);
            }
        }, directExecutor());
    } else {
        responseObserver.onError(Status.INVALID_ARGUMENT.withDescription("Empty uris list").asRuntimeException());
    }
}
Also used : Digest(build.bazel.remote.execution.v2.Digest) Qualifier(build.bazel.remote.asset.v1.Qualifier) RequestMetadata(build.bazel.remote.execution.v2.RequestMetadata)

Example 24 with RequestMetadata

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

the class ShardInstance method getBlob.

@Override
public void getBlob(Digest blobDigest, long offset, long count, ServerCallStreamObserver<ByteString> blobObserver, RequestMetadata requestMetadata) {
    List<String> workersList;
    Set<String> workerSet;
    Set<String> locationSet;
    try {
        workerSet = backplane.getWorkers();
        locationSet = backplane.getBlobLocationSet(blobDigest);
        synchronized (workerSet) {
            workersList = new ArrayList<>(Sets.intersection(locationSet, workerSet));
        }
    } catch (IOException e) {
        blobObserver.onError(e);
        return;
    }
    boolean emptyWorkerList = workersList.isEmpty();
    final ListenableFuture<List<String>> populatedWorkerListFuture;
    if (emptyWorkerList) {
        logger.log(Level.FINE, format("worker list was initially empty for %s, attempting to correct", DigestUtil.toString(blobDigest)));
        populatedWorkerListFuture = transform(correctMissingBlob(backplane, workerSet, locationSet, this::workerStub, blobDigest, directExecutor(), RequestMetadata.getDefaultInstance()), (foundOnWorkers) -> {
            logger.log(Level.FINE, format("worker list was corrected for %s to be %s", DigestUtil.toString(blobDigest), foundOnWorkers.toString()));
            Iterables.addAll(workersList, foundOnWorkers);
            return workersList;
        }, directExecutor());
    } else {
        populatedWorkerListFuture = immediateFuture(workersList);
    }
    Context ctx = Context.current();
    ServerCallStreamObserver<ByteString> chunkObserver = new UniformDelegateServerCallStreamObserver<ByteString>(blobObserver) {

        boolean triedCheck = emptyWorkerList;

        @Override
        public void onNext(ByteString nextChunk) {
            blobObserver.onNext(nextChunk);
        }

        @Override
        public void onError(Throwable t) {
            Status status = Status.fromThrowable(t);
            if (status.getCode() == Code.NOT_FOUND && !triedCheck) {
                triedCheck = true;
                workersList.clear();
                final ListenableFuture<List<String>> workersListFuture;
                logger.log(Level.FINE, format("worker list was depleted for %s, attempting to correct", DigestUtil.toString(blobDigest)));
                workersListFuture = transform(correctMissingBlob(backplane, workerSet, locationSet, ShardInstance.this::workerStub, blobDigest, directExecutor(), RequestMetadata.getDefaultInstance()), (foundOnWorkers) -> {
                    logger.log(Level.FINE, format("worker list was corrected after depletion for %s to be %s", DigestUtil.toString(blobDigest), foundOnWorkers.toString()));
                    Iterables.addAll(workersList, foundOnWorkers);
                    return workersList;
                }, directExecutor());
                final ServerCallStreamObserver<ByteString> checkedChunkObserver = this;
                addCallback(workersListFuture, new WorkersCallback(rand) {

                    @Override
                    public void onQueue(Deque<String> workers) {
                        ctx.run(() -> fetchBlobFromWorker(blobDigest, workers, offset, count, checkedChunkObserver, requestMetadata));
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        blobObserver.onError(t);
                    }
                }, directExecutor());
            } else {
                blobObserver.onError(t);
            }
        }

        @Override
        public void onCompleted() {
            blobObserver.onCompleted();
        }
    };
    addCallback(populatedWorkerListFuture, new WorkersCallback(rand) {

        @Override
        public void onQueue(Deque<String> workers) {
            ctx.run(() -> fetchBlobFromWorker(blobDigest, workers, offset, count, chunkObserver, requestMetadata));
        }

        @Override
        public void onFailure(Throwable t) {
            blobObserver.onError(t);
        }
    }, directExecutor());
}
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) Context(io.grpc.Context) Status(io.grpc.Status) Actions.asExecutionStatus(build.buildfarm.common.Actions.asExecutionStatus) QueueStatus(build.buildfarm.v1test.QueueStatus) BackplaneStatus(build.buildfarm.v1test.BackplaneStatus) ByteString(com.google.protobuf.ByteString) ByteString(com.google.protobuf.ByteString) IOException(java.io.IOException) UniformDelegateServerCallStreamObserver(build.buildfarm.common.grpc.UniformDelegateServerCallStreamObserver) Futures.allAsList(com.google.common.util.concurrent.Futures.allAsList) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList)

Example 25 with RequestMetadata

use of com.google.cloud.talent.v4.RequestMetadata in project java-talent by googleapis.

the class JobSearchCustomRankingSearch method sampleSearchJobs.

/**
 * Search Jobs using custom rankings
 *
 * @param projectId Your Google Cloud Project ID
 * @param tenantId Identifier of the Tenantd
 */
public static void sampleSearchJobs(String projectId, String tenantId) {
    try (JobServiceClient jobServiceClient = JobServiceClient.create()) {
        TenantOrProjectName parent = TenantName.of(projectId, tenantId);
        String domain = "www.example.com";
        String sessionId = "Hashed session identifier";
        String userId = "Hashed user identifier";
        RequestMetadata requestMetadata = RequestMetadata.newBuilder().setDomain(domain).setSessionId(sessionId).setUserId(userId).build();
        SearchJobsRequest.CustomRankingInfo.ImportanceLevel importanceLevel = SearchJobsRequest.CustomRankingInfo.ImportanceLevel.EXTREME;
        String rankingExpression = "(someFieldLong + 25) * 0.25";
        SearchJobsRequest.CustomRankingInfo customRankingInfo = SearchJobsRequest.CustomRankingInfo.newBuilder().setImportanceLevel(importanceLevel).setRankingExpression(rankingExpression).build();
        String orderBy = "custom_ranking desc";
        SearchJobsRequest request = SearchJobsRequest.newBuilder().setParent(parent.toString()).setRequestMetadata(requestMetadata).setCustomRankingInfo(customRankingInfo).setOrderBy(orderBy).build();
        for (SearchJobsResponse.MatchingJob responseItem : jobServiceClient.searchJobs(request).iterateAll()) {
            System.out.printf("Job summary: %s\n", responseItem.getJobSummary());
            System.out.printf("Job title snippet: %s\n", responseItem.getJobTitleSnippet());
            Job job = responseItem.getJob();
            System.out.printf("Job name: %s\n", job.getName());
            System.out.printf("Job title: %s\n", job.getTitle());
        }
    } catch (Exception exception) {
        System.err.println("Failed to create the client due to: " + exception);
    }
}
Also used : SearchJobsRequest(com.google.cloud.talent.v4beta1.SearchJobsRequest) JobServiceClient(com.google.cloud.talent.v4beta1.JobServiceClient) TenantOrProjectName(com.google.cloud.talent.v4beta1.TenantOrProjectName) Job(com.google.cloud.talent.v4beta1.Job) RequestMetadata(com.google.cloud.talent.v4beta1.RequestMetadata)

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