4848import com .google .devtools .build .lib .cmdline .RepositoryName ;
4949import com .google .devtools .build .lib .events .Event ;
5050import com .google .devtools .build .lib .events .ExtendedEventHandler ;
51+ import com .google .devtools .build .lib .profiler .Profiler ;
52+ import com .google .devtools .build .lib .profiler .ProfilerTask ;
53+ import com .google .devtools .build .lib .profiler .SilentCloseable ;
5154import com .google .devtools .build .lib .remote .common .ActionKey ;
5255import com .google .devtools .build .lib .remote .common .RemoteActionExecutionContext ;
5356import com .google .devtools .build .lib .remote .common .RemoteActionExecutionContext .CachePolicy ;
5457import com .google .devtools .build .lib .remote .common .RemoteCacheClient .Blob ;
5558import com .google .devtools .build .lib .remote .common .RemotePathResolver ;
56- import com .google .devtools .build .lib .remote .util .DigestUtil ;
5759import com .google .devtools .build .lib .remote .util .TracingMetadataUtils ;
5860import com .google .devtools .build .lib .rules .repository .RepoRecordedInput ;
5961import com .google .devtools .build .lib .runtime .RemoteRepoContentsCache ;
@@ -202,21 +204,27 @@ public void addToCache(
202204 var action = buildAction (finalHash );
203205 var actionKey = new ActionKey (cache .digestUtil ().compute (action ));
204206 var remotePathResolver = new RepoRemotePathResolver (fetchedRepoMarkerFile , fetchedRepoDir );
205- var manifest =
206- UploadManifest .create (
207- cache .getRemoteCacheCapabilities (),
208- cache .digestUtil (),
209- remotePathResolver ,
210- actionKey ,
211- action ,
212- COMMAND ,
213- ImmutableList .of (fetchedRepoMarkerFile , fetchedRepoDir ),
214- /* outErr= */ null ,
215- /* exitCode= */ 0 ,
216- /* startTime= */ Instant .now (),
217- /* wallTimeInMs= */ 0 ,
218- /* preserveExecutableBit= */ true );
219- var result = manifest .upload (context , cache , reporter , /* force= */ false );
207+ UploadManifest manifest ;
208+ try (var span = profile (repoName , "Build repository upload manifest" )) {
209+ manifest =
210+ UploadManifest .create (
211+ cache .getRemoteCacheCapabilities (),
212+ cache .digestUtil (),
213+ remotePathResolver ,
214+ actionKey ,
215+ action ,
216+ COMMAND ,
217+ ImmutableList .of (fetchedRepoMarkerFile , fetchedRepoDir ),
218+ /* outErr= */ null ,
219+ /* exitCode= */ 0 ,
220+ /* startTime= */ Instant .now (),
221+ /* wallTimeInMs= */ 0 ,
222+ /* preserveExecutableBit= */ true );
223+ }
224+ ActionResult result ;
225+ try (var span = profile (repoName , "Upload repository contents" )) {
226+ result = manifest .upload (context , cache , reporter , /* force= */ false );
227+ }
220228 // Relative repository-root symlinks have no directory Tree to install.
221229 if (result .getOutputDirectoriesCount () != 1 ) {
222230 return ;
@@ -240,13 +248,26 @@ public boolean lookupCache(
240248 String predeclaredInputHash ,
241249 SkyFunction .Environment env )
242250 throws IOException , InterruptedException {
251+ var profiler = Profiler .instance ();
252+ long profileStart =
253+ profiler .isProfiling (ProfilerTask .REPO_CONTENTS_CACHE ) ? profiler .nanoTimeMaybe () : -1 ;
254+ String outcome = "error" ;
243255 try {
244- return doLookupCache (repoName , repoDir , predeclaredInputHash , env );
256+ boolean hit = doLookupCache (repoName , repoDir , predeclaredInputHash , env );
257+ if (profileStart != -1 ) {
258+ outcome = hit ? "hit" : env .valuesMissing () ? "restart" : "miss" ;
259+ }
260+ return hit ;
245261 } catch (IOException e ) {
246262 throw new IOException (
247263 "Failed to look up repo %s in the remote repo contents cache: %s"
248264 .formatted (repoName , maybeGetStackTrace (e )),
249265 e );
266+ } finally {
267+ if (profileStart != -1 ) {
268+ profiler .logSimpleTask (
269+ profileStart , ProfilerTask .REPO_CONTENTS_CACHE , "Lookup " + outcome + ": " + repoName );
270+ }
250271 }
251272 }
252273
@@ -264,31 +285,40 @@ private boolean doLookupCache(
264285 if (!context .getReadCachePolicy ().allowRemoteCache ()) {
265286 return false ;
266287 }
267- var finalEntry = fetchFinalCacheEntry (env , context , predeclaredInputHash );
288+ CacheEntry .Final finalEntry ;
289+ try (var span = profile (repoName , "Resolve cache entry" )) {
290+ finalEntry = fetchFinalCacheEntry (env , context , repoName , predeclaredInputHash );
291+ }
268292 if (env .valuesMissing () || finalEntry == null ) {
269293 return false ;
270294 }
271295
272296 ListenableFuture <byte []> markerFileContentFuture ;
273- var markerFile = finalEntry .markerFile ();
274- // Inlining is an optional feature, so we have to be prepared to download the marker file.
275- if (markerFile .getContents ().isEmpty ()) {
276- markerFileContentFuture =
277- cache .downloadBlob (
278- context , MARKER_FILE_PATH , /* execPath= */ null , markerFile .getDigest ());
279- } else {
280- markerFileContentFuture = immediateFuture (markerFile .getContents ().toByteArray ());
297+ ListenableFuture <Tree > repoDirectoryContentFuture ;
298+ try (var span = profile (repoName , "Read cache marker and Tree" )) {
299+ var markerFile = finalEntry .markerFile ();
300+ // Inlining is an optional feature, so we have to be prepared to download the marker file.
301+ if (markerFile .getContents ().isEmpty ()) {
302+ markerFileContentFuture =
303+ cache .downloadBlob (
304+ context , MARKER_FILE_PATH , /* execPath= */ null , markerFile .getDigest ());
305+ } else {
306+ markerFileContentFuture = immediateFuture (markerFile .getContents ().toByteArray ());
307+ }
308+ var repoDirectory = finalEntry .repoDirectory ();
309+ repoDirectoryContentFuture =
310+ transformAsync (
311+ cache .downloadBlobAsByteString (
312+ context ,
313+ REPO_DIRECTORY_PATH ,
314+ /* execPath= */ null ,
315+ repoDirectory .getTreeDigest ()),
316+ (treeBytes ) ->
317+ immediateFuture (
318+ Tree .parseFrom (treeBytes , ExtensionRegistryLite .getEmptyRegistry ())),
319+ directExecutor ());
320+ waitForBulkTransfer (ImmutableList .of (markerFileContentFuture , repoDirectoryContentFuture ));
281321 }
282- var repoDirectory = finalEntry .repoDirectory ();
283- var repoDirectoryContentFuture =
284- transformAsync (
285- cache .downloadBlobAsByteString (
286- context , REPO_DIRECTORY_PATH , /* execPath= */ null , repoDirectory .getTreeDigest ()),
287- (treeBytes ) ->
288- immediateFuture (
289- Tree .parseFrom (treeBytes , ExtensionRegistryLite .getEmptyRegistry ())),
290- directExecutor ());
291- waitForBulkTransfer (ImmutableList .of (markerFileContentFuture , repoDirectoryContentFuture ));
292322
293323 String markerFileContent = new String (markerFileContentFuture .resultNow (), ISO_8859_1 );
294324 var maybeRecordedInputs = DigestWriter .readMarkerFile (markerFileContent , predeclaredInputHash );
@@ -306,8 +336,14 @@ private boolean doLookupCache(
306336 return false ;
307337 }
308338
309- return remoteFs .injectRemoteRepo (
310- repoName , repoDirectoryContentFuture .resultNow (), markerFileContent );
339+ try (var span = profile (repoName , "Install cached repository" )) {
340+ return remoteFs .injectRemoteRepo (
341+ repoName , repoDirectoryContentFuture .resultNow (), markerFileContent );
342+ }
343+ }
344+
345+ private static SilentCloseable profile (RepositoryName repo , String phase ) {
346+ return Profiler .instance ().profile (ProfilerTask .REPO_CONTENTS_CACHE , () -> phase + ": " + repo );
311347 }
312348
313349 private enum CacheOp {
@@ -480,13 +516,14 @@ record Invalid(String reason) implements CacheEntry {}
480516 private CacheEntry .Final fetchFinalCacheEntry (
481517 SkyFunction .Environment env ,
482518 RemoteActionExecutionContext context ,
519+ RepositoryName repoName ,
483520 String predeclaredInputHash )
484521 throws IOException , InterruptedException {
485522 var currentHashes = ImmutableList .of (predeclaredInputHash );
486523 while (!currentHashes .isEmpty ()) {
487524 var nextHashes = ImmutableList .<String >builder ();
488525 for (var hash : currentHashes ) {
489- switch (fetchCacheEntry (env , context , hash )) {
526+ switch (fetchCacheEntry (env , context , repoName , hash )) {
490527 case CacheEntry .Final finalEntry -> {
491528 return finalEntry ;
492529 }
@@ -510,15 +547,21 @@ private CacheEntry.Final fetchFinalCacheEntry(
510547 // Returns null if and only if values are missing.
511548 @ Nullable
512549 private CacheEntry fetchCacheEntry (
513- SkyFunction .Environment env , RemoteActionExecutionContext context , String inputHash )
550+ SkyFunction .Environment env ,
551+ RemoteActionExecutionContext context ,
552+ RepositoryName repoName ,
553+ String inputHash )
514554 throws IOException , InterruptedException {
515555 var actionKey = new ActionKey (cache .digestUtil ().compute (buildAction (inputHash )));
516556 // The marker file is read right after and thus requested to be inlined. If the action result
517557 // is an intermediate node, the full result will be contained in the stdout, which should thus
518558 // also be inlined.
519- var cachedActionResult =
520- cache .downloadActionResult (
521- context , actionKey , /* inlineOutErr= */ true , ImmutableSet .of (MARKER_FILE_PATH ));
559+ CombinedCache .CachedActionResult cachedActionResult ;
560+ try (var span = profile (repoName , "Read cache action result" )) {
561+ cachedActionResult =
562+ cache .downloadActionResult (
563+ context , actionKey , /* inlineOutErr= */ true , ImmutableSet .of (MARKER_FILE_PATH ));
564+ }
522565 if (cachedActionResult == null ) {
523566 return new CacheEntry .Intermediate (ImmutableList .of ());
524567 }
@@ -543,45 +586,50 @@ && hasStdout(actionResult))) {
543586 "Unexpected intermediate action result for remotely cached repo %s:\n %s"
544587 .formatted (context .getRequestMetadata ().getActionId (), actionResult ));
545588 }
546- var stdoutFuture = fetchStdout (context , actionResult );
547- waitForBulkTransfer (ImmutableList .of (stdoutFuture ));
548-
549- // The action result's stdout contains multiple lines, each representing a batch of
550- // RepoRecordedInputs separated by spaces. A given batch is valid only if all inputs in the
551- // batch are, but separate batches are tried independently.
552- var nextInputBatches =
553- SPLIT_ON_NEWLINE
554- .splitToStream (stdoutFuture .resultNow ())
555- .map (
556- line ->
557- SPLIT_ON_SPACE
558- .splitToStream (line )
559- .map (RepoRecordedInput ::parse )
560- .collect (toImmutableList ()))
561- .collect (toImmutableList ());
562- var uniqueNextInputs =
563- nextInputBatches .stream ().flatMap (List ::stream ).collect (toImmutableSet ());
564- RepoRecordedInput .prefetch (env , directories , uniqueNextInputs );
565- if (env .valuesMissing ()) {
566- return null ;
589+ String recordedInputs ;
590+ try (var span = profile (repoName , "Read cache recorded input batch" )) {
591+ var stdoutFuture = fetchStdout (context , actionResult );
592+ waitForBulkTransfer (ImmutableList .of (stdoutFuture ));
593+ recordedInputs = stdoutFuture .resultNow ();
567594 }
568- var nextHashes = ImmutableList .<String >builder ();
569- nextBatch :
570- for (var batch : nextInputBatches ) {
571- var rollingHash = inputHash ;
572- for (var input : batch ) {
573- var value = input .getValue (env , directories );
574- // Values have been prefetched above.
575- Preconditions .checkState (!env .valuesMissing ());
576- if (!(value instanceof RepoRecordedInput .MaybeValue .Valid (String valueString ))) {
577- continue nextBatch ;
595+
596+ try (var span = profile (repoName , "Check cache recorded inputs" )) {
597+ // The action result's stdout contains multiple lines, each representing a batch of
598+ // RepoRecordedInputs separated by spaces. A given batch is valid only if all inputs in the
599+ // batch are, but separate batches are tried independently.
600+ var nextInputBatches =
601+ SPLIT_ON_NEWLINE
602+ .splitToStream (recordedInputs )
603+ .map (line ->
604+ SPLIT_ON_SPACE
605+ .splitToStream (line )
606+ .map (RepoRecordedInput ::parse )
607+ .collect (toImmutableList ()))
608+ .collect (toImmutableList ());
609+ var uniqueNextInputs =
610+ nextInputBatches .stream ().flatMap (List ::stream ).collect (toImmutableSet ());
611+ RepoRecordedInput .prefetch (env , directories , uniqueNextInputs );
612+ if (env .valuesMissing ()) {
613+ return null ;
614+ }
615+ var nextHashes = ImmutableList .<String >builder ();
616+ nextBatch :
617+ for (var batch : nextInputBatches ) {
618+ var rollingHash = inputHash ;
619+ for (var input : batch ) {
620+ var value = input .getValue (env , directories );
621+ // Values have been prefetched above.
622+ Preconditions .checkState (!env .valuesMissing ());
623+ if (!(value instanceof RepoRecordedInput .MaybeValue .Valid (String valueString ))) {
624+ continue nextBatch ;
625+ }
626+ rollingHash =
627+ rollForwardHash (rollingHash , new RepoRecordedInput .WithValue (input , valueString ));
578628 }
579- rollingHash =
580- rollForwardHash (rollingHash , new RepoRecordedInput .WithValue (input , valueString ));
629+ nextHashes .add (rollingHash );
581630 }
582- nextHashes .add ( rollingHash );
631+ return new CacheEntry . Intermediate ( nextHashes .build () );
583632 }
584- return new CacheEntry .Intermediate (nextHashes .build ());
585633 }
586634
587635 private String rollForwardHash (String hash , RepoRecordedInput .WithValue inputWithValue ) {
0 commit comments