diff options
author | ulfjack <ulfjack@google.com> | 2017-04-05 12:16:33 +0000 |
---|---|---|
committer | Damien Martin-Guillerez <dmarting@google.com> | 2017-04-05 15:22:50 +0200 |
commit | d31eab12024751866ba590f941cabe535b7b9bc3 (patch) | |
tree | fb080413b43c4580099af1a1a77104a77d292997 /src | |
parent | 2753264d75256b2ff61e13101e1d893cb5b41288 (diff) |
Add a new CachedLocalSpawnRunner to implement remote caching + local exec
The new class wraps an existing SpawnRunner and adds remote caching. Ideally,
the wrapped runner should be local and sandboxed, but this is not currently
enforced. The new class is not hooked up to anything yet.
The added test indicates that the RemoteActionCache interface is still more
complex than necessary - in particular, we should merge downloadAllResults and
downloadBlobs (for stdout/stderr) into a single method, and also change the
upload to a single combined method in a similar way instead of two calls. Doing
so allows the RemoteActionCache implementation more leeway in how it wants to
implement these, potentially improving parallelism and performance.
One step towards #1413.
PiperOrigin-RevId: 152245644
Diffstat (limited to 'src')
6 files changed, 774 insertions, 298 deletions
diff --git a/src/main/java/com/google/devtools/build/lib/remote/CachedLocalSpawnRunner.java b/src/main/java/com/google/devtools/build/lib/remote/CachedLocalSpawnRunner.java new file mode 100644 index 0000000000..a4daf8e7eb --- /dev/null +++ b/src/main/java/com/google/devtools/build/lib/remote/CachedLocalSpawnRunner.java @@ -0,0 +1,187 @@ +// 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 java.nio.charset.StandardCharsets.UTF_8; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.devtools.build.lib.actions.ActionInput; +import com.google.devtools.build.lib.actions.ExecException; +import com.google.devtools.build.lib.actions.Spawn; +import com.google.devtools.build.lib.actions.UserExecException; +import com.google.devtools.build.lib.exec.SpawnResult; +import com.google.devtools.build.lib.exec.SpawnRunner; +import com.google.devtools.build.lib.remote.ContentDigests.ActionKey; +import com.google.devtools.build.lib.remote.RemoteProtocol.Action; +import com.google.devtools.build.lib.remote.RemoteProtocol.ActionResult; +import com.google.devtools.build.lib.remote.RemoteProtocol.Command; +import com.google.devtools.build.lib.remote.RemoteProtocol.ContentDigest; +import com.google.devtools.build.lib.remote.RemoteProtocol.Platform; +import com.google.devtools.build.lib.remote.TreeNodeRepository.TreeNode; +import com.google.devtools.build.lib.util.io.FileOutErr; +import com.google.devtools.build.lib.vfs.Path; +import com.google.devtools.build.lib.vfs.PathFragment; +import com.google.protobuf.TextFormat; +import com.google.protobuf.TextFormat.ParseException; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.SortedMap; +import java.util.TreeSet; + +/** + * A {@link SpawnRunner} implementation that adds a remote cache on top of an underlying local + * {@link SpawnRunner} implementation. + */ +final class CachedLocalSpawnRunner implements SpawnRunner { + private final Path execRoot; + private final RemoteOptions options; + // TODO(olaola): This will be set on a per-action basis instead. + private final Platform platform; + + private final RemoteActionCache actionCache; + private final SpawnRunner delegate; + + CachedLocalSpawnRunner( + Path execRoot, + RemoteOptions options, + RemoteActionCache actionCache, + SpawnRunner delegate) { + this.execRoot = execRoot; + this.options = options; + if (options.experimentalRemotePlatformOverride != null) { + Platform.Builder platformBuilder = Platform.newBuilder(); + try { + TextFormat.getParser().merge(options.experimentalRemotePlatformOverride, platformBuilder); + } catch (ParseException e) { + throw new RuntimeException("Failed to parse --experimental_remote_platform_override", e); + } + platform = platformBuilder.build(); + } else { + platform = null; + } + this.actionCache = actionCache; + this.delegate = delegate; + } + + @Override + public SpawnResult exec( + Spawn spawn, + SpawnExecutionPolicy policy) + throws InterruptedException, IOException, ExecException { + ActionKey actionKey = null; + String mnemonic = spawn.getMnemonic(); + + try { + // Temporary hack: the TreeNodeRepository should be created and maintained upstream! + TreeNodeRepository repository = + new TreeNodeRepository(execRoot, policy.getActionInputFileCache()); + SortedMap<PathFragment, ActionInput> inputMap = policy.getInputMapping(); + TreeNode inputRoot = repository.buildFromActionInputs(inputMap); + repository.computeMerkleDigests(inputRoot); + Command command = buildCommand(spawn.getArguments(), spawn.getEnvironment()); + Action action = + buildAction( + spawn.getOutputFiles(), + ContentDigests.computeDigest(command), + repository.getMerkleDigest(inputRoot)); + + // Look up action cache, and reuse the action output if it is found. + actionKey = ContentDigests.computeActionKey(action); + ActionResult result = + this.options.remoteAcceptCached ? actionCache.getCachedActionResult(actionKey) : null; + if (result != null) { + // We don't cache failed actions, so we know the outputs exist. + // For now, download all outputs locally; in the future, we can reuse the digests to + // just update the TreeNodeRepository and continue the build. + try { + // TODO(ulfjack): Download stdout, stderr, and the output files in a single call. + actionCache.downloadAllResults(result, execRoot); + passRemoteOutErr(result, policy.getFileOutErr()); + return new SpawnResult.Builder() + .setSetupSuccess(true) + .setExitCode(result.getReturnCode()) + .build(); + } catch (CacheNotFoundException e) { + // TODO(ulfjack): Track down who throws this exception in what cases and double-check that + // ignoring the exception here is acceptable. Possible change it so that we throw in some + // cases - we don't want to hide failures in the remote cache from the user. + } + } + SpawnResult spawnResult = delegate.exec(spawn, policy); + if (options.remoteLocalExecUploadResults && spawnResult.setupSuccess()) { + writeCacheEntry(spawn, actionKey); + } + return spawnResult; + } catch (StatusRuntimeException e) { + throw new UserExecException(mnemonic + " remote work failed (" + e + ")", e); + } + } + + private Action buildAction( + Collection<? extends ActionInput> outputs, ContentDigest command, ContentDigest inputRoot) { + Action.Builder action = Action.newBuilder(); + action.setCommandDigest(command); + action.setInputRootDigest(inputRoot); + // Somewhat ugly: we rely on the stable order of outputs here for remote action caching. + for (ActionInput output : outputs) { + action.addOutputPath(output.getExecPathString()); + } + if (platform != null) { + action.setPlatform(platform); + } + return action.build(); + } + + private static Command buildCommand( + List<String> arguments, ImmutableMap<String, String> environment) { + Command.Builder command = Command.newBuilder(); + command.addAllArgv(arguments); + // Sorting the environment pairs by variable name. + TreeSet<String> variables = new TreeSet<>(environment.keySet()); + for (String var : variables) { + command.addEnvironmentBuilder().setVariable(var).setValue(environment.get(var)); + } + return command.build(); + } + + private void passRemoteOutErr( + ActionResult result, FileOutErr outErr) + throws CacheNotFoundException { + ImmutableList<byte[]> streams = + actionCache.downloadBlobs( + ImmutableList.of(result.getStdoutDigest(), result.getStderrDigest())); + outErr.printOut(new String(streams.get(0), UTF_8)); + outErr.printErr(new String(streams.get(1), UTF_8)); + } + + private void writeCacheEntry(Spawn spawn, ActionKey actionKey) + throws IOException, InterruptedException { + ArrayList<Path> outputFiles = new ArrayList<>(); + for (ActionInput output : spawn.getOutputFiles()) { + Path outputPath = execRoot.getRelative(output.getExecPathString()); + // TODO(ulfjack): Store the actual list of output files in SpawnResult and use that instead + // of statting the files here again. + if (outputPath.exists()) { + outputFiles.add(outputPath); + } + } + ActionResult.Builder result = ActionResult.newBuilder(); + actionCache.uploadAllResults(execRoot, outputFiles, result); + actionCache.setCachedActionResult(actionKey, result.build()); + } +} diff --git a/src/test/java/com/google/devtools/build/lib/remote/CachedLocalSpawnRunnerTest.java b/src/test/java/com/google/devtools/build/lib/remote/CachedLocalSpawnRunnerTest.java new file mode 100644 index 0000000000..74b7bc9ba0 --- /dev/null +++ b/src/test/java/com/google/devtools/build/lib/remote/CachedLocalSpawnRunnerTest.java @@ -0,0 +1,229 @@ +// 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.truth.Truth.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.devtools.build.lib.actions.ActionInput; +import com.google.devtools.build.lib.actions.ActionInputFileCache; +import com.google.devtools.build.lib.actions.ActionInputHelper; +import com.google.devtools.build.lib.actions.Artifact; +import com.google.devtools.build.lib.actions.Artifact.ArtifactExpander; +import com.google.devtools.build.lib.actions.ResourceSet; +import com.google.devtools.build.lib.actions.SimpleSpawn; +import com.google.devtools.build.lib.actions.Spawn; +import com.google.devtools.build.lib.exec.SpawnInputExpander; +import com.google.devtools.build.lib.exec.SpawnResult; +import com.google.devtools.build.lib.exec.SpawnRunner; +import com.google.devtools.build.lib.exec.SpawnRunner.SpawnExecutionPolicy; +import com.google.devtools.build.lib.remote.ContentDigests.ActionKey; +import com.google.devtools.build.lib.remote.RemoteProtocol.ActionResult; +import com.google.devtools.build.lib.remote.RemoteProtocol.ContentDigest; +import com.google.devtools.build.lib.util.io.FileOutErr; +import com.google.devtools.build.lib.vfs.FileSystem; +import com.google.devtools.build.lib.vfs.FileSystemUtils; +import com.google.devtools.build.lib.vfs.Path; +import com.google.devtools.build.lib.vfs.PathFragment; +import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem; +import com.google.devtools.common.options.Options; +import com.google.protobuf.ByteString; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Collection; +import java.util.SortedMap; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mockito; + +/** Tests for {@link CachedLocalSpawnRunner}. */ +@RunWith(JUnit4.class) +public class CachedLocalSpawnRunnerTest { + private static final ArtifactExpander SIMPLE_ARTIFACT_EXPANDER = new ArtifactExpander() { + @Override + public void expand(Artifact artifact, Collection<? super Artifact> output) { + output.add(artifact); + } + }; + + private FileSystem fs; + private Path execRoot; + private SimpleSpawn simpleSpawn; + private FakeActionInputFileCache fakeFileCache; + + private FileOutErr outErr; + + private final SpawnExecutionPolicy simplePolicy = new SpawnExecutionPolicy() { + @Override + public boolean shouldPrefetchInputsForLocalExecution(Spawn spawn) { + throw new UnsupportedOperationException(); + } + + @Override + public void lockOutputFiles() throws InterruptedException { + throw new UnsupportedOperationException(); + } + + @Override + public ActionInputFileCache getActionInputFileCache() { + return fakeFileCache; + } + + @Override + public long getTimeoutMillis() { + return 0; + } + + @Override + public FileOutErr getFileOutErr() { + return outErr; + } + + @Override + public SortedMap<PathFragment, ActionInput> getInputMapping() throws IOException { + return new SpawnInputExpander(/*strict*/false) + .getInputMapping(simpleSpawn, SIMPLE_ARTIFACT_EXPANDER, fakeFileCache, "workspace"); + } + }; + + @Before + public final void setUp() throws Exception { + fs = new InMemoryFileSystem(); + execRoot = fs.getPath("/exec/root"); + FileSystemUtils.createDirectoryAndParents(execRoot); + fakeFileCache = new FakeActionInputFileCache(execRoot); + simpleSpawn = new SimpleSpawn( + new FakeOwner("Mnemonic", "Progress Message"), + ImmutableList.of("/bin/echo", "Hi!"), + ImmutableMap.of("VARIABLE", "value"), + /*executionInfo=*/ImmutableMap.<String, String>of(), + /*inputs=*/ImmutableList.of(ActionInputHelper.fromPath("input")), + /*outputs=*/ImmutableList.<ActionInput>of(), + ResourceSet.ZERO + ); + + Path stdout = fs.getPath("/tmp/stdout"); + Path stderr = fs.getPath("/tmp/stderr"); + FileSystemUtils.createDirectoryAndParents(stdout.getParentDirectory()); + FileSystemUtils.createDirectoryAndParents(stderr.getParentDirectory()); + outErr = new FileOutErr(stdout, stderr); + } + + private void scratch(ActionInput input, String content) throws IOException { + Path inputFile = execRoot.getRelative(input.getExecPath()); + FileSystemUtils.writeContentAsLatin1(inputFile, content); + fakeFileCache.setDigest( + simpleSpawn.getInputFiles().get(0), ByteString.copyFrom(inputFile.getSHA1Digest())); + } + + @SuppressWarnings("unchecked") + @Test + public void cacheHit() throws Exception { + RemoteOptions options = Options.getDefaults(RemoteOptions.class); + RemoteActionCache cache = Mockito.mock(RemoteActionCache.class); + SpawnRunner delegate = Mockito.mock(SpawnRunner.class); + CachedLocalSpawnRunner runner = + new CachedLocalSpawnRunner(execRoot, options, cache, delegate); + when(cache.getCachedActionResult(any(ActionKey.class))) + .thenReturn(ActionResult.newBuilder().setReturnCode(0).build()); + when(cache.downloadBlobs(any(Iterable.class))) + .thenReturn(ImmutableList.of(new byte[0], new byte[0])); + + scratch(simpleSpawn.getInputFiles().get(0), "xyz"); + + SpawnResult result = runner.exec(simpleSpawn, simplePolicy); + // We use verify to check that each method is called exactly once. + // TODO(ulfjack): Check that we also call it with exactly the right parameters, not just any. + verify(cache).getCachedActionResult(any(ActionKey.class)); + verify(cache).downloadAllResults(any(ActionResult.class), any(Path.class)); + verify(cache).downloadBlobs(any(Iterable.class)); + assertThat(result.setupSuccess()).isTrue(); + assertThat(result.exitCode()).isEqualTo(0); + assertThat(outErr.hasRecordedOutput()).isFalse(); + assertThat(outErr.hasRecordedStderr()).isFalse(); + } + + @SuppressWarnings("unchecked") + @Test + public void cacheHitWithOutput() throws Exception { + RemoteOptions options = Options.getDefaults(RemoteOptions.class); + RemoteActionCache cache = Mockito.mock(RemoteActionCache.class); + SpawnRunner delegate = Mockito.mock(SpawnRunner.class); + CachedLocalSpawnRunner runner = + new CachedLocalSpawnRunner(execRoot, options, cache, delegate); + when(cache.getCachedActionResult(any(ActionKey.class))) + .thenReturn(ActionResult.newBuilder().setReturnCode(0).build()); + + scratch(simpleSpawn.getInputFiles().get(0), "xyz"); + byte[] cacheStdOut = "stdout".getBytes(StandardCharsets.UTF_8); + byte[] cacheStdErr = "stderr".getBytes(StandardCharsets.UTF_8); + ContentDigest stdOutDigest = ContentDigests.computeDigest(cacheStdOut); + ContentDigest stdErrDigest = ContentDigests.computeDigest(cacheStdErr); + + ActionResult actionResult = ActionResult.newBuilder() + .setReturnCode(0) + .setStdoutDigest(stdOutDigest) + .setStderrDigest(stdErrDigest) + .build(); + when(cache.getCachedActionResult(any(ActionKey.class))).thenReturn(actionResult); + when(cache.downloadBlobs(any(Iterable.class))) + .thenReturn(ImmutableList.of(cacheStdOut, cacheStdErr)); + + SpawnResult result = runner.exec(simpleSpawn, simplePolicy); + // We use verify to check that each method is called exactly once. + verify(cache).getCachedActionResult(any(ActionKey.class)); + verify(cache).downloadAllResults(any(ActionResult.class), any(Path.class)); + verify(cache).downloadBlobs(any(Iterable.class)); + assertThat(result.setupSuccess()).isTrue(); + assertThat(result.exitCode()).isEqualTo(0); + assertThat(outErr.outAsLatin1()).isEqualTo("stdout"); + assertThat(outErr.errAsLatin1()).isEqualTo("stderr"); + } + + @SuppressWarnings("unchecked") + @Test + public void cacheMiss() throws Exception { + RemoteOptions options = Options.getDefaults(RemoteOptions.class); + RemoteActionCache cache = Mockito.mock(RemoteActionCache.class); + SpawnRunner delegate = Mockito.mock(SpawnRunner.class); + CachedLocalSpawnRunner runner = + new CachedLocalSpawnRunner(execRoot, options, cache, delegate); + when(cache.getCachedActionResult(any(ActionKey.class))) + .thenReturn(ActionResult.newBuilder().setReturnCode(0).build()); + + scratch(simpleSpawn.getInputFiles().get(0), "xyz"); + + when(cache.getCachedActionResult(any(ActionKey.class))).thenReturn(null); + SpawnResult delegateResult = new SpawnResult.Builder() + .setExitCode(0) + .setSetupSuccess(true) + .build(); + when(delegate.exec(any(Spawn.class), any(SpawnExecutionPolicy.class))) + .thenReturn(delegateResult); + + SpawnResult result = runner.exec(simpleSpawn, simplePolicy); + // We use verify to check that each method is called exactly once. + verify(cache) + .uploadAllResults(any(Path.class), any(Collection.class), any(ActionResult.Builder.class)); + verify(cache).setCachedActionResult(any(ActionKey.class), any(ActionResult.class)); + assertThat(result.setupSuccess()).isTrue(); + assertThat(result.exitCode()).isEqualTo(0); + } +} diff --git a/src/test/java/com/google/devtools/build/lib/remote/FakeActionInputFileCache.java b/src/test/java/com/google/devtools/build/lib/remote/FakeActionInputFileCache.java new file mode 100644 index 0000000000..74994aabdd --- /dev/null +++ b/src/test/java/com/google/devtools/build/lib/remote/FakeActionInputFileCache.java @@ -0,0 +1,74 @@ +// 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 com.google.common.base.Preconditions; +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; +import com.google.common.hash.HashCode; +import com.google.devtools.build.lib.actions.ActionInput; +import com.google.devtools.build.lib.actions.ActionInputFileCache; +import com.google.devtools.build.lib.actions.Artifact; +import com.google.devtools.build.lib.vfs.Path; +import com.google.protobuf.ByteString; +import java.io.IOException; +import javax.annotation.Nullable; + +/** A fake implementation of the {@link ActionInputFileCache} interface. */ +final class FakeActionInputFileCache implements ActionInputFileCache { + private final Path execRoot; + private final BiMap<ActionInput, ByteString> cas = HashBiMap.create(); + + FakeActionInputFileCache(Path execRoot) { + this.execRoot = execRoot; + } + + void setDigest(ActionInput input, ByteString digest) { + cas.put(input, digest); + } + + @Override + @Nullable + public byte[] getDigest(ActionInput input) throws IOException { + return Preconditions.checkNotNull(cas.get(input), input).toByteArray(); + } + + @Override + public boolean isFile(Artifact input) { + return execRoot.getRelative(input.getExecPath()).isFile(); + } + + @Override + public long getSizeInBytes(ActionInput input) throws IOException { + return execRoot.getRelative(input.getExecPath()).getFileSize(); + } + + @Override + public boolean contentsAvailableLocally(ByteString digest) { + throw new UnsupportedOperationException(); + } + + @Override + @Nullable + public ActionInput getInputFromDigest(ByteString hexDigest) { + HashCode code = HashCode.fromString(hexDigest.toStringUtf8()); + ByteString digest = ByteString.copyFrom(code.asBytes()); + return Preconditions.checkNotNull(cas.inverse().get(digest)); + } + + @Override + public Path getInputPath(ActionInput input) { + throw new UnsupportedOperationException(); + } +}
\ No newline at end of file diff --git a/src/test/java/com/google/devtools/build/lib/remote/FakeOwner.java b/src/test/java/com/google/devtools/build/lib/remote/FakeOwner.java new file mode 100644 index 0000000000..f1654b4727 --- /dev/null +++ b/src/test/java/com/google/devtools/build/lib/remote/FakeOwner.java @@ -0,0 +1,137 @@ +// 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 org.mockito.Mockito.mock; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import com.google.devtools.build.lib.actions.ActionAnalysisMetadata; +import com.google.devtools.build.lib.actions.ActionExecutionContext; +import com.google.devtools.build.lib.actions.ActionExecutionMetadata; +import com.google.devtools.build.lib.actions.ActionOwner; +import com.google.devtools.build.lib.actions.Artifact; +import com.google.devtools.build.lib.actions.RunfilesSupplier; + +/** A fake implementation of ActionExecutionMetadata as needed for SpawnRunner test. */ +final class FakeOwner implements ActionExecutionMetadata { + private final String mnemonic; + private final String progressMessage; + + FakeOwner(String mnemonic, String progressMessage) { + this.mnemonic = mnemonic; + this.progressMessage = progressMessage; + } + + @Override + public ActionOwner getOwner() { + return mock(ActionOwner.class); + } + + @Override + public String getMnemonic() { + return mnemonic; + } + + @Override + public String getProgressMessage() { + return progressMessage; + } + + @Override + public boolean inputsDiscovered() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean discoversInputs() { + throw new UnsupportedOperationException(); + } + + @Override + public Iterable<Artifact> getTools() { + throw new UnsupportedOperationException(); + } + + @Override + public Iterable<Artifact> getInputs() { + throw new UnsupportedOperationException(); + } + + @Override + public RunfilesSupplier getRunfilesSupplier() { + throw new UnsupportedOperationException(); + } + + @Override + public ImmutableSet<Artifact> getOutputs() { + throw new UnsupportedOperationException(); + } + + @Override + public Iterable<String> getClientEnvironmentVariables() { + throw new UnsupportedOperationException(); + } + + @Override + public Artifact getPrimaryInput() { + throw new UnsupportedOperationException(); + } + + @Override + public Artifact getPrimaryOutput() { + throw new UnsupportedOperationException(); + } + + @Override + public Iterable<Artifact> getMandatoryInputs() { + throw new UnsupportedOperationException(); + } + + @Override + public String getKey() { + throw new UnsupportedOperationException(); + } + + @Override + public String describeKey() { + throw new UnsupportedOperationException(); + } + + @Override + public String prettyPrint() { + throw new UnsupportedOperationException(); + } + + @Override + public Iterable<Artifact> getInputFilesForExtraAction( + ActionExecutionContext actionExecutionContext) { + return ImmutableList.<Artifact>of(); + } + + @Override + public ImmutableSet<Artifact> getMandatoryOutputs() { + throw new UnsupportedOperationException(); + } + + @Override + public MiddlemanType getActionType() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean shouldReportPathPrefixConflict(ActionAnalysisMetadata action) { + throw new UnsupportedOperationException(); + } +}
\ No newline at end of file diff --git a/src/test/java/com/google/devtools/build/lib/remote/GrpcRemoteExecutionClientTest.java b/src/test/java/com/google/devtools/build/lib/remote/GrpcRemoteExecutionClientTest.java index 97fa28a2cb..7f9620f0d4 100644 --- a/src/test/java/com/google/devtools/build/lib/remote/GrpcRemoteExecutionClientTest.java +++ b/src/test/java/com/google/devtools/build/lib/remote/GrpcRemoteExecutionClientTest.java @@ -14,48 +14,25 @@ package com.google.devtools.build.lib.remote; import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.mock; +import static org.mockito.Matchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import com.google.common.base.Preconditions; -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; import com.google.common.eventbus.EventBus; -import com.google.common.hash.HashCode; -import com.google.devtools.build.lib.actions.ActionAnalysisMetadata; -import com.google.devtools.build.lib.actions.ActionExecutionContext; -import com.google.devtools.build.lib.actions.ActionExecutionMetadata; import com.google.devtools.build.lib.actions.ActionInput; import com.google.devtools.build.lib.actions.ActionInputFileCache; import com.google.devtools.build.lib.actions.ActionInputHelper; -import com.google.devtools.build.lib.actions.ActionOwner; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.Artifact.ArtifactExpander; import com.google.devtools.build.lib.actions.ResourceSet; -import com.google.devtools.build.lib.actions.RunfilesSupplier; import com.google.devtools.build.lib.actions.SimpleSpawn; import com.google.devtools.build.lib.actions.Spawn; import com.google.devtools.build.lib.exec.SpawnInputExpander; import com.google.devtools.build.lib.exec.SpawnResult; import com.google.devtools.build.lib.exec.SpawnRunner.SpawnExecutionPolicy; import com.google.devtools.build.lib.remote.RemoteProtocol.ActionResult; -import com.google.devtools.build.lib.remote.RemoteProtocol.BlobChunk; -import com.google.devtools.build.lib.remote.RemoteProtocol.CasDownloadBlobRequest; -import com.google.devtools.build.lib.remote.RemoteProtocol.CasDownloadReply; -import com.google.devtools.build.lib.remote.RemoteProtocol.CasDownloadTreeMetadataReply; -import com.google.devtools.build.lib.remote.RemoteProtocol.CasDownloadTreeMetadataRequest; -import com.google.devtools.build.lib.remote.RemoteProtocol.CasLookupReply; -import com.google.devtools.build.lib.remote.RemoteProtocol.CasLookupRequest; -import com.google.devtools.build.lib.remote.RemoteProtocol.CasStatus; -import com.google.devtools.build.lib.remote.RemoteProtocol.CasUploadBlobReply; -import com.google.devtools.build.lib.remote.RemoteProtocol.CasUploadBlobRequest; -import com.google.devtools.build.lib.remote.RemoteProtocol.CasUploadTreeMetadataReply; -import com.google.devtools.build.lib.remote.RemoteProtocol.CasUploadTreeMetadataRequest; import com.google.devtools.build.lib.remote.RemoteProtocol.ContentDigest; import com.google.devtools.build.lib.remote.RemoteProtocol.ExecuteReply; import com.google.devtools.build.lib.remote.RemoteProtocol.ExecuteRequest; @@ -71,18 +48,10 @@ import com.google.devtools.build.lib.vfs.PathFragment; import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem; import com.google.devtools.common.options.Options; import com.google.protobuf.ByteString; -import io.grpc.stub.StreamObserver; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; import java.util.SortedMap; -import javax.annotation.Nullable; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -92,269 +61,6 @@ import org.mockito.Mockito; /** Tests for {@link RemoteSpawnRunner} in combination with {@link GrpcRemoteExecutor}. */ @RunWith(JUnit4.class) public class GrpcRemoteExecutionClientTest { - private static class MockOwner implements ActionExecutionMetadata { - private final String mnemonic; - private final String progressMessage; - - MockOwner(String mnemonic, String progressMessage) { - this.mnemonic = mnemonic; - this.progressMessage = progressMessage; - } - - @Override - public ActionOwner getOwner() { - return mock(ActionOwner.class); - } - - @Override - public String getMnemonic() { - return mnemonic; - } - - @Override - public String getProgressMessage() { - return progressMessage; - } - - @Override - public boolean inputsDiscovered() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean discoversInputs() { - throw new UnsupportedOperationException(); - } - - @Override - public Iterable<Artifact> getTools() { - throw new UnsupportedOperationException(); - } - - @Override - public Iterable<Artifact> getInputs() { - throw new UnsupportedOperationException(); - } - - @Override - public RunfilesSupplier getRunfilesSupplier() { - throw new UnsupportedOperationException(); - } - - @Override - public ImmutableSet<Artifact> getOutputs() { - throw new UnsupportedOperationException(); - } - - @Override - public Iterable<String> getClientEnvironmentVariables() { - throw new UnsupportedOperationException(); - } - - @Override - public Artifact getPrimaryInput() { - throw new UnsupportedOperationException(); - } - - @Override - public Artifact getPrimaryOutput() { - throw new UnsupportedOperationException(); - } - - @Override - public Iterable<Artifact> getMandatoryInputs() { - throw new UnsupportedOperationException(); - } - - @Override - public String getKey() { - throw new UnsupportedOperationException(); - } - - @Override - public String describeKey() { - throw new UnsupportedOperationException(); - } - - @Override - public String prettyPrint() { - throw new UnsupportedOperationException(); - } - - @Override - public Iterable<Artifact> getInputFilesForExtraAction( - ActionExecutionContext actionExecutionContext) { - return ImmutableList.<Artifact>of(); - } - - @Override - public ImmutableSet<Artifact> getMandatoryOutputs() { - throw new UnsupportedOperationException(); - } - - @Override - public MiddlemanType getActionType() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean shouldReportPathPrefixConflict(ActionAnalysisMetadata action) { - throw new UnsupportedOperationException(); - } - } - - private static final class FakeCas implements GrpcCasInterface { - private final Map<ByteString, ByteString> content = new HashMap<>(); - - public ContentDigest put(byte[] data) { - ContentDigest digest = ContentDigests.computeDigest(data); - ByteString key = digest.getDigest(); - ByteString value = ByteString.copyFrom(data); - content.put(key, value); - return digest; - } - - @Override - public CasLookupReply lookup(CasLookupRequest request) { - CasStatus.Builder result = CasStatus.newBuilder(); - for (ContentDigest digest : request.getDigestList()) { - ByteString key = digest.getDigest(); - if (!content.containsKey(key)) { - result.addMissingDigest(digest); - } - } - if (result.getMissingDigestCount() != 0) { - result.setError(CasStatus.ErrorCode.MISSING_DIGEST); - } else { - result.setSucceeded(true); - } - return CasLookupReply.newBuilder().setStatus(result).build(); - } - - @Override - public CasUploadTreeMetadataReply uploadTreeMetadata(CasUploadTreeMetadataRequest request) { - return CasUploadTreeMetadataReply.newBuilder() - .setStatus(CasStatus.newBuilder().setSucceeded(true)) - .build(); - } - - @Override - public CasDownloadTreeMetadataReply downloadTreeMetadata( - CasDownloadTreeMetadataRequest request) { - throw new UnsupportedOperationException(); - } - - @Override - public Iterator<CasDownloadReply> downloadBlob(CasDownloadBlobRequest request) { - List<CasDownloadReply> result = new ArrayList<>(); - for (ContentDigest digest : request.getDigestList()) { - CasDownloadReply.Builder builder = CasDownloadReply.newBuilder(); - ByteString item = content.get(digest.getDigest()); - if (item != null) { - builder.setStatus(CasStatus.newBuilder().setSucceeded(true)); - builder.setData(BlobChunk.newBuilder().setData(item).setDigest(digest)); - } else { - throw new IllegalStateException(); - } - result.add(builder.build()); - } - return result.iterator(); - } - - @Override - public StreamObserver<CasUploadBlobRequest> uploadBlobAsync( - final StreamObserver<CasUploadBlobReply> responseObserver) { - return new StreamObserver<CasUploadBlobRequest>() { - private ContentDigest digest; - private ByteArrayOutputStream current; - - @Override - public void onNext(CasUploadBlobRequest value) { - BlobChunk chunk = value.getData(); - if (chunk.hasDigest()) { - Preconditions.checkState(digest == null); - digest = chunk.getDigest(); - current = new ByteArrayOutputStream(); - } - try { - current.write(chunk.getData().toByteArray()); - } catch (IOException e) { - throw new RuntimeException(e); - } - responseObserver.onNext( - CasUploadBlobReply.newBuilder() - .setStatus(CasStatus.newBuilder().setSucceeded(true)) - .build()); - } - - @Override - public void onError(Throwable t) { - throw new RuntimeException(t); - } - - @Override - public void onCompleted() { - ContentDigest check = ContentDigests.computeDigest(current.toByteArray()); - Preconditions.checkState(check.equals(digest), "%s != %s", digest, check); - ByteString key = digest.getDigest(); - ByteString value = ByteString.copyFrom(current.toByteArray()); - digest = null; - current = null; - content.put(key, value); - responseObserver.onCompleted(); - } - }; - } - } - - private static final class FakeActionInputFileCache implements ActionInputFileCache { - private final Path execRoot; - private final BiMap<ActionInput, ByteString> cas = HashBiMap.create(); - - FakeActionInputFileCache(Path execRoot) { - this.execRoot = execRoot; - } - - void setDigest(ActionInput input, ByteString digest) { - cas.put(input, digest); - } - - @Override - @Nullable - public byte[] getDigest(ActionInput input) throws IOException { - return Preconditions.checkNotNull(cas.get(input), input).toByteArray(); - } - - @Override - public boolean isFile(Artifact input) { - return execRoot.getRelative(input.getExecPath()).isFile(); - } - - @Override - public long getSizeInBytes(ActionInput input) throws IOException { - return execRoot.getRelative(input.getExecPath()).getFileSize(); - } - - @Override - public boolean contentsAvailableLocally(ByteString digest) { - throw new UnsupportedOperationException(); - } - - @Override - @Nullable - public ActionInput getInputFromDigest(ByteString hexDigest) { - HashCode code = - HashCode.fromString(new String(hexDigest.toByteArray(), StandardCharsets.UTF_8)); - ByteString digest = ByteString.copyFrom(code.asBytes()); - return Preconditions.checkNotNull(cas.inverse().get(digest)); - } - - @Override - public Path getInputPath(ActionInput input) { - throw new UnsupportedOperationException(); - } - } - private static final ArtifactExpander SIMPLE_ARTIFACT_EXPANDER = new ArtifactExpander() { @Override public void expand(Artifact artifact, Collection<? super Artifact> output) { @@ -412,7 +118,7 @@ public class GrpcRemoteExecutionClientTest { eventBus = new EventBus(); fakeFileCache = new FakeActionInputFileCache(execRoot); simpleSpawn = new SimpleSpawn( - new MockOwner("Mnemonic", "Progress Message"), + new FakeOwner("Mnemonic", "Progress Message"), ImmutableList.of("/bin/echo", "Hi!"), ImmutableMap.of("VARIABLE", "value"), /*executionInfo=*/ImmutableMap.<String, String>of(), @@ -464,7 +170,7 @@ public class GrpcRemoteExecutionClientTest { @Test public void cacheHitWithOutput() throws Exception { - FakeCas casIface = new FakeCas(); + InMemoryCas casIface = new InMemoryCas(); GrpcExecutionCacheInterface cacheIface = Mockito.mock(GrpcExecutionCacheInterface.class); GrpcExecutionInterface executionIface = Mockito.mock(GrpcExecutionInterface.class); RemoteOptions options = Options.getDefaults(RemoteOptions.class); @@ -498,7 +204,7 @@ public class GrpcRemoteExecutionClientTest { @Test public void remotelyExecute() throws Exception { - FakeCas casIface = new FakeCas(); + InMemoryCas casIface = new InMemoryCas(); GrpcExecutionCacheInterface cacheIface = Mockito.mock(GrpcExecutionCacheInterface.class); GrpcExecutionInterface executionIface = Mockito.mock(GrpcExecutionInterface.class); RemoteOptions options = Options.getDefaults(RemoteOptions.class); diff --git a/src/test/java/com/google/devtools/build/lib/remote/InMemoryCas.java b/src/test/java/com/google/devtools/build/lib/remote/InMemoryCas.java new file mode 100644 index 0000000000..cba62a536f --- /dev/null +++ b/src/test/java/com/google/devtools/build/lib/remote/InMemoryCas.java @@ -0,0 +1,143 @@ +// 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 com.google.common.base.Preconditions; +import com.google.devtools.build.lib.remote.RemoteProtocol.BlobChunk; +import com.google.devtools.build.lib.remote.RemoteProtocol.CasDownloadBlobRequest; +import com.google.devtools.build.lib.remote.RemoteProtocol.CasDownloadReply; +import com.google.devtools.build.lib.remote.RemoteProtocol.CasDownloadTreeMetadataReply; +import com.google.devtools.build.lib.remote.RemoteProtocol.CasDownloadTreeMetadataRequest; +import com.google.devtools.build.lib.remote.RemoteProtocol.CasLookupReply; +import com.google.devtools.build.lib.remote.RemoteProtocol.CasLookupRequest; +import com.google.devtools.build.lib.remote.RemoteProtocol.CasStatus; +import com.google.devtools.build.lib.remote.RemoteProtocol.CasUploadBlobReply; +import com.google.devtools.build.lib.remote.RemoteProtocol.CasUploadBlobRequest; +import com.google.devtools.build.lib.remote.RemoteProtocol.CasUploadTreeMetadataReply; +import com.google.devtools.build.lib.remote.RemoteProtocol.CasUploadTreeMetadataRequest; +import com.google.devtools.build.lib.remote.RemoteProtocol.ContentDigest; +import com.google.protobuf.ByteString; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** An in-memory implementation of GrpcCasInterface. */ +final class InMemoryCas implements GrpcCasInterface { + private final Map<ByteString, ByteString> content = new HashMap<>(); + + public ContentDigest put(byte[] data) { + ContentDigest digest = ContentDigests.computeDigest(data); + ByteString key = digest.getDigest(); + ByteString value = ByteString.copyFrom(data); + content.put(key, value); + return digest; + } + + @Override + public CasLookupReply lookup(CasLookupRequest request) { + CasStatus.Builder result = CasStatus.newBuilder(); + for (ContentDigest digest : request.getDigestList()) { + ByteString key = digest.getDigest(); + if (!content.containsKey(key)) { + result.addMissingDigest(digest); + } + } + if (result.getMissingDigestCount() != 0) { + result.setError(CasStatus.ErrorCode.MISSING_DIGEST); + } else { + result.setSucceeded(true); + } + return CasLookupReply.newBuilder().setStatus(result).build(); + } + + @Override + public CasUploadTreeMetadataReply uploadTreeMetadata(CasUploadTreeMetadataRequest request) { + return CasUploadTreeMetadataReply.newBuilder() + .setStatus(CasStatus.newBuilder().setSucceeded(true)) + .build(); + } + + @Override + public CasDownloadTreeMetadataReply downloadTreeMetadata( + CasDownloadTreeMetadataRequest request) { + throw new UnsupportedOperationException(); + } + + @Override + public Iterator<CasDownloadReply> downloadBlob(CasDownloadBlobRequest request) { + List<CasDownloadReply> result = new ArrayList<>(); + for (ContentDigest digest : request.getDigestList()) { + CasDownloadReply.Builder builder = CasDownloadReply.newBuilder(); + ByteString item = content.get(digest.getDigest()); + if (item != null) { + builder.setStatus(CasStatus.newBuilder().setSucceeded(true)); + builder.setData(BlobChunk.newBuilder().setData(item).setDigest(digest)); + } else { + throw new IllegalStateException(); + } + result.add(builder.build()); + } + return result.iterator(); + } + + @Override + public StreamObserver<CasUploadBlobRequest> uploadBlobAsync( + final StreamObserver<CasUploadBlobReply> responseObserver) { + return new StreamObserver<CasUploadBlobRequest>() { + private ContentDigest digest; + private ByteArrayOutputStream current; + + @Override + public void onNext(CasUploadBlobRequest value) { + BlobChunk chunk = value.getData(); + if (chunk.hasDigest()) { + Preconditions.checkState(digest == null); + digest = chunk.getDigest(); + current = new ByteArrayOutputStream(); + } + try { + current.write(chunk.getData().toByteArray()); + } catch (IOException e) { + throw new RuntimeException(e); + } + responseObserver.onNext( + CasUploadBlobReply.newBuilder() + .setStatus(CasStatus.newBuilder().setSucceeded(true)) + .build()); + } + + @Override + public void onError(Throwable t) { + throw new RuntimeException(t); + } + + @Override + public void onCompleted() { + ContentDigest check = ContentDigests.computeDigest(current.toByteArray()); + Preconditions.checkState(check.equals(digest), "%s != %s", digest, check); + ByteString key = digest.getDigest(); + ByteString value = ByteString.copyFrom(current.toByteArray()); + digest = null; + current = null; + content.put(key, value); + responseObserver.onCompleted(); + } + }; + } +}
\ No newline at end of file |