-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathRemoteSpawnCache.java
315 lines (294 loc) · 14.1 KB
/
RemoteSpawnCache.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.remote;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.devtools.build.lib.profiler.ProfilerTask.REMOTE_DOWNLOAD;
import static com.google.devtools.build.lib.remote.util.Utils.createExecExceptionForCredentialHelperException;
import static com.google.devtools.build.lib.remote.util.Utils.createExecExceptionFromRemoteExecutionCapabilitiesException;
import static com.google.devtools.build.lib.remote.util.Utils.createSpawnResult;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Stopwatch;
import com.google.devtools.build.lib.actions.ActionInput;
import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.actions.FileArtifactValue;
import com.google.devtools.build.lib.actions.ForbiddenActionInputException;
import com.google.devtools.build.lib.actions.Spawn;
import com.google.devtools.build.lib.actions.SpawnMetrics;
import com.google.devtools.build.lib.actions.SpawnResult;
import com.google.devtools.build.lib.actions.cache.VirtualActionInput;
import com.google.devtools.build.lib.authandtls.credentialhelper.CredentialHelperException;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.exec.SpawnCache;
import com.google.devtools.build.lib.exec.SpawnRunner.SpawnExecutionContext;
import com.google.devtools.build.lib.profiler.Profiler;
import com.google.devtools.build.lib.profiler.ProfilerTask;
import com.google.devtools.build.lib.profiler.SilentCloseable;
import com.google.devtools.build.lib.remote.RemoteExecutionService.LocalExecution;
import com.google.devtools.build.lib.remote.RemoteExecutionService.RemoteActionResult;
import com.google.devtools.build.lib.remote.common.BulkTransferException;
import com.google.devtools.build.lib.remote.common.CacheNotFoundException;
import com.google.devtools.build.lib.remote.common.RemoteCacheClient;
import com.google.devtools.build.lib.remote.common.RemoteExecutionCapabilitiesException;
import com.google.devtools.build.lib.remote.options.RemoteOptions;
import com.google.devtools.build.lib.remote.util.DigestUtil;
import com.google.devtools.build.lib.remote.util.Utils;
import com.google.devtools.build.lib.remote.util.Utils.InMemoryOutput;
import com.google.devtools.build.lib.vfs.Path;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
/** A remote {@link SpawnCache} implementation. */
@ThreadSafe // If the RemoteActionCache implementation is thread-safe.
final class RemoteSpawnCache implements SpawnCache {
private final Path execRoot;
private final RemoteOptions options;
private final RemoteExecutionService remoteExecutionService;
private final DigestUtil digestUtil;
private final boolean verboseFailures;
private final ConcurrentHashMap<RemoteCacheClient.ActionKey, LocalExecution> inFlightExecutions =
new ConcurrentHashMap<>();
RemoteSpawnCache(
Path execRoot,
RemoteOptions options,
boolean verboseFailures,
RemoteExecutionService remoteExecutionService,
DigestUtil digestUtil) {
this.execRoot = execRoot;
this.options = options;
this.verboseFailures = verboseFailures;
this.remoteExecutionService = remoteExecutionService;
this.digestUtil = digestUtil;
}
@VisibleForTesting
RemoteExecutionService getRemoteExecutionService() {
return remoteExecutionService;
}
@Override
public CacheHandle lookup(Spawn spawn, SpawnExecutionContext context)
throws InterruptedException, IOException, ExecException, ForbiddenActionInputException {
boolean shouldAcceptCachedResult =
remoteExecutionService.getReadCachePolicy(spawn).allowAnyCache();
boolean shouldUploadLocalResults =
remoteExecutionService.getWriteCachePolicy(spawn).allowAnyCache();
if (!shouldAcceptCachedResult && !shouldUploadLocalResults) {
return SpawnCache.NO_RESULT_NO_STORE;
}
Stopwatch totalTime = Stopwatch.createStarted();
RemoteAction action = remoteExecutionService.buildRemoteAction(spawn, context);
SpawnMetrics.Builder spawnMetrics =
SpawnMetrics.Builder.forRemoteExec()
.setInputBytes(action.getInputBytes())
.setInputFiles(action.getInputFiles());
context.setDigest(digestUtil.asSpawnLogProto(action.getActionKey()));
Profiler prof = Profiler.instance();
LocalExecution thisExecution = null;
if (shouldAcceptCachedResult) {
// With path mapping enabled, different Spawns in a single build can have the same ActionKey.
// When their result isn't in the cache and two of them are scheduled concurrently, neither
// will result in a cache hit before the other finishes and uploads its result, which results
// in unnecessary work. To avoid this, we keep track of in-flight executions as long as their
// results haven't been uploaded to the cache yet and deduplicate all of them against the
// first one.
LocalExecution previousExecution = null;
try {
thisExecution = LocalExecution.createIfDeduplicatable(action);
if (shouldUploadLocalResults && thisExecution != null) {
LocalExecution previousOrThisExecution =
inFlightExecutions.merge(
action.getActionKey(),
thisExecution,
(existingExecution, thisExecutionArg) -> {
if (existingExecution.registerForOutputReuse()) {
return existingExecution;
} else {
// The existing execution has completed and its results may have already
// been modified by its action, so we can't deduplicate against it. Instead,
// start a new in-flight execution.
return thisExecutionArg;
}
});
previousExecution =
previousOrThisExecution == thisExecution ? null : previousOrThisExecution;
}
try {
RemoteActionResult result;
try (SilentCloseable c =
prof.profile(ProfilerTask.REMOTE_CACHE_CHECK, "check cache hit")) {
result = remoteExecutionService.lookupCache(action);
}
// In case the remote cache returned a failed action (exit code != 0) we treat it as a
// cache miss
if (result != null && result.getExitCode() == 0) {
Stopwatch fetchTime = Stopwatch.createStarted();
InMemoryOutput inMemoryOutput;
try (SilentCloseable c = prof.profile(REMOTE_DOWNLOAD, "download outputs")) {
inMemoryOutput = remoteExecutionService.downloadOutputs(action, result);
}
fetchTime.stop();
totalTime.stop();
spawnMetrics
.setFetchTimeInMs((int) fetchTime.elapsed().toMillis())
.setTotalTimeInMs((int) totalTime.elapsed().toMillis())
.setNetworkTimeInMs((int) action.getNetworkTime().getDuration().toMillis());
SpawnResult spawnResult =
createSpawnResult(
digestUtil,
action.getActionKey(),
result.getExitCode(),
/* cacheHit= */ true,
result.cacheName(),
inMemoryOutput,
result.getExecutionMetadata().getExecutionStartTimestamp(),
result.getExecutionMetadata().getExecutionCompletedTimestamp(),
spawnMetrics.build(),
spawn.getMnemonic());
return SpawnCache.success(spawnResult);
}
} catch (CacheNotFoundException e) {
// Intentionally left blank
} catch (CredentialHelperException e) {
throw createExecExceptionForCredentialHelperException(e);
} catch (RemoteExecutionCapabilitiesException e) {
throw createExecExceptionFromRemoteExecutionCapabilitiesException(e);
} catch (IOException e) {
if (BulkTransferException.allCausedByCacheNotFoundException(e)) {
// Intentionally left blank
} else {
String errorMessage = Utils.grpcAwareErrorMessage(e, verboseFailures);
if (isNullOrEmpty(errorMessage)) {
errorMessage = e.getClass().getSimpleName();
}
errorMessage = "Remote Cache: " + errorMessage;
remoteExecutionService.report(Event.warn(errorMessage));
}
}
if (previousExecution != null) {
Stopwatch fetchTime = Stopwatch.createStarted();
SpawnResult previousResult;
try (SilentCloseable c = prof.profile(REMOTE_DOWNLOAD, "reuse outputs")) {
previousResult =
remoteExecutionService.waitForAndReuseOutputs(action, previousExecution);
}
if (previousResult != null) {
spawnMetrics
.setFetchTimeInMs((int) fetchTime.elapsed().toMillis())
.setTotalTimeInMs((int) totalTime.elapsed().toMillis())
.setNetworkTimeInMs((int) action.getNetworkTime().getDuration().toMillis());
SpawnMetrics buildMetrics = spawnMetrics.build();
return SpawnCache.success(
new SpawnResult.DelegateSpawnResult(previousResult) {
@Override
public String getRunnerName() {
return "deduplicated";
}
@Override
public SpawnMetrics getMetrics() {
return buildMetrics;
}
});
}
// If we reach here, the previous execution was not successful (it encountered an
// exception or the spawn had an exit code != 0). Since it isn't possible to accurately
// recreate the failure without rerunning the action, we fall back to running the action
// locally. This means that we have introduced an unnecessary wait, but that can only
// happen in the case of a failing build with --keep_going.
}
} finally {
if (previousExecution != null) {
previousExecution.unregister();
}
}
}
if (shouldUploadLocalResults) {
final LocalExecution thisExecutionFinal = thisExecution;
return new CacheHandle() {
@Override
public boolean hasResult() {
return false;
}
@Override
public SpawnResult getResult() {
throw new NoSuchElementException();
}
@Override
public boolean willStore() {
return true;
}
@Override
public void store(SpawnResult result) throws ExecException, InterruptedException {
if (!remoteExecutionService.commitResultAndDecideWhetherToUpload(
result, thisExecutionFinal)) {
return;
}
if (options.experimentalGuardAgainstConcurrentChanges) {
try (SilentCloseable c = prof.profile("checkForConcurrentModifications")) {
checkForConcurrentModifications();
} catch (IOException | ForbiddenActionInputException e) {
var msg =
spawn.getTargetLabel()
+ ": Skipping uploading outputs because of concurrent modifications "
+ "with --experimental_guard_against_concurrent_changes enabled: "
+ e.getMessage();
remoteExecutionService.report(Event.warn(msg));
return;
}
}
// As soon as the result is in the cache, actions can get the result from it instead of
// from the first in-flight execution. Not keeping in-flight executions around
// indefinitely is important to avoid excessive memory pressure - Spawns can be very
// large.
remoteExecutionService.uploadOutputs(
action, result, () -> inFlightExecutions.remove(action.getActionKey()));
if (thisExecutionFinal != null
&& action.getSpawn().getResourceOwner().mayModifySpawnOutputsAfterExecution()) {
// In this case outputs have been uploaded synchronously and the callback above has run,
// so no new executions will be deduplicated against this one. We can safely await all
// existing executions finish the reuse.
// Note that while this call itself isn't interruptible, all operations it awaits are
// interruptible.
try (SilentCloseable c = prof.profile(REMOTE_DOWNLOAD, "await output reuse")) {
thisExecutionFinal.awaitAllOutputReuse();
}
}
}
private void checkForConcurrentModifications()
throws IOException, ForbiddenActionInputException {
for (ActionInput input : action.getInputMap(true).values()) {
if (input instanceof VirtualActionInput) {
continue;
}
FileArtifactValue metadata = context.getInputMetadataProvider().getInputMetadata(input);
Path path = execRoot.getRelative(input.getExecPath());
if (metadata.wasModifiedSinceDigest(path)) {
throw new IOException(path + " was modified during execution");
}
}
}
@Override
public void close() {
if (thisExecutionFinal != null) {
thisExecutionFinal.cancel();
}
}
};
} else {
return SpawnCache.NO_RESULT_NO_STORE;
}
}
@Override
public boolean usefulInDynamicExecution() {
return false;
}
}