Search in sources :

Example 1 with CacheResult

use of com.facebook.buck.artifact_cache.CacheResult in project buck by facebook.

the class ArtifactCacheHandler method handleGet.

private int handleGet(Request baseRequest, HttpServletResponse response) throws IOException {
    if (!artifactCache.isPresent()) {
        response.getWriter().write("Serving local cache is disabled for this instance.");
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }
    String path = baseRequest.getUri().getPath();
    String[] pathElements = path.split("/");
    if (pathElements.length != 4 || !pathElements[2].equals("key")) {
        response.getWriter().write("Incorrect url format.");
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }
    RuleKey ruleKey = new RuleKey(pathElements[3]);
    Path temp = null;
    try {
        projectFilesystem.mkdirs(projectFilesystem.getBuckPaths().getScratchDir());
        temp = projectFilesystem.createTempFile(projectFilesystem.getBuckPaths().getScratchDir(), "outgoing_rulekey", ".tmp");
        CacheResult fetchResult = artifactCache.get().fetch(ruleKey, LazyPath.ofInstance(temp));
        if (!fetchResult.getType().isSuccess()) {
            return HttpServletResponse.SC_NOT_FOUND;
        }
        final Path tempFinal = temp;
        HttpArtifactCacheBinaryProtocol.FetchResponse fetchResponse = new HttpArtifactCacheBinaryProtocol.FetchResponse(ImmutableSet.of(ruleKey), fetchResult.getMetadata(), new ByteSource() {

            @Override
            public InputStream openStream() throws IOException {
                return projectFilesystem.newFileInputStream(tempFinal);
            }
        });
        fetchResponse.write(response.getOutputStream());
        response.setContentLengthLong(fetchResponse.getContentLength());
        return HttpServletResponse.SC_OK;
    } finally {
        if (temp != null) {
            projectFilesystem.deleteFileAtPathIfExists(temp);
        }
    }
}
Also used : BorrowablePath(com.facebook.buck.io.BorrowablePath) LazyPath(com.facebook.buck.io.LazyPath) Path(java.nio.file.Path) RuleKey(com.facebook.buck.rules.RuleKey) DataInputStream(java.io.DataInputStream) InputStream(java.io.InputStream) HttpArtifactCacheBinaryProtocol(com.facebook.buck.artifact_cache.HttpArtifactCacheBinaryProtocol) CacheResult(com.facebook.buck.artifact_cache.CacheResult) ByteSource(com.google.common.io.ByteSource) IOException(java.io.IOException)

Example 2 with CacheResult

use of com.facebook.buck.artifact_cache.CacheResult in project buck by facebook.

the class CachingBuildEngine method processBuildRule.

private ListenableFuture<BuildResult> processBuildRule(final BuildRule rule, final BuildEngineBuildContext buildContext, final ExecutionContext executionContext, final OnDiskBuildInfo onDiskBuildInfo, final BuildInfoRecorder buildInfoRecorder, final BuildableContext buildableContext, final ConcurrentLinkedQueue<ListenableFuture<Void>> asyncCallbacks) {
    // If we've already seen a failure, exit early.
    if (!buildContext.isKeepGoing() && firstFailure != null) {
        return Futures.immediateFuture(BuildResult.canceled(rule, firstFailure));
    }
    final RuleKeyFactories ruleKeyFactory = ruleKeyFactories.apply(rule.getProjectFilesystem());
    try (BuildRuleEvent.Scope scope = BuildRuleEvent.resumeSuspendScope(buildContext.getEventBus(), rule, buildRuleDurationTracker, ruleKeyFactory.getDefaultRuleKeyFactory())) {
        // 1. Check if it's already built.
        Optional<RuleKey> cachedRuleKey = onDiskBuildInfo.getRuleKey(BuildInfo.MetadataKey.RULE_KEY);
        final RuleKey defaultRuleKey = ruleKeyFactory.getDefaultRuleKeyFactory().build(rule);
        if (defaultRuleKey.equals(cachedRuleKey.orElse(null))) {
            return Futures.transform(markRuleAsUsed(rule, buildContext.getEventBus()), Functions.constant(BuildResult.success(rule, BuildRuleSuccessType.MATCHING_RULE_KEY, CacheResult.localKeyUnchangedHit())));
        }
        // 2. Rule key cache lookup.
        ListenableFuture<CacheResult> rulekeyCacheResult = cacheActivityService.submit(() -> {
            CacheResult cacheResult = tryToFetchArtifactFromBuildCacheAndOverlayOnTopOfProjectFilesystem(rule, defaultRuleKey, buildContext.getArtifactCache(), // TODO(shs96c): This should be a shared between all tests, not one per cell
            rule.getProjectFilesystem(), buildContext);
            if (cacheResult.getType().isSuccess()) {
                fillMissingBuildMetadataFromCache(cacheResult, buildInfoRecorder, BuildInfo.MetadataKey.INPUT_BASED_RULE_KEY, BuildInfo.MetadataKey.DEP_FILE_RULE_KEY, BuildInfo.MetadataKey.DEP_FILE);
            }
            return cacheResult;
        }, CACHE_CHECK_RESOURCE_AMOUNTS);
        return Futures.transformAsync(rulekeyCacheResult, ruleAsyncFunction(rule, buildContext.getEventBus(), (cacheResult) -> handleRuleKeyCacheResult(rule, buildContext, executionContext, onDiskBuildInfo, buildInfoRecorder, buildableContext, asyncCallbacks, ruleKeyFactory, cacheResult)), serviceByAdjustingDefaultWeightsTo(SCHEDULING_MORE_WORK_RESOURCE_AMOUNTS));
    }
}
Also used : OptionalCompat(com.facebook.buck.util.OptionalCompat) NoSuchFileException(java.nio.file.NoSuchFileException) GZIPInputStream(java.util.zip.GZIPInputStream) ArtifactCache(com.facebook.buck.artifact_cache.ArtifactCache) BufferedInputStream(java.io.BufferedInputStream) StepRunner(com.facebook.buck.step.StepRunner) BuckEvent(com.facebook.buck.event.BuckEvent) RuleKeyCalculationEvent(com.facebook.buck.event.RuleKeyCalculationEvent) ObjectMappers(com.facebook.buck.util.ObjectMappers) MoreFutures(com.facebook.buck.util.concurrent.MoreFutures) SettableFuture(com.google.common.util.concurrent.SettableFuture) ArtifactCompressionEvent(com.facebook.buck.event.ArtifactCompressionEvent) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) RuleKeyAndInputs(com.facebook.buck.rules.keys.RuleKeyAndInputs) Map(java.util.Map) RuleKeyFactories(com.facebook.buck.rules.keys.RuleKeyFactories) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ArtifactInfo(com.facebook.buck.artifact_cache.ArtifactInfo) Path(java.nio.file.Path) WeightedListeningExecutorService(com.facebook.buck.util.concurrent.WeightedListeningExecutorService) Function(com.google.common.base.Function) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Set(java.util.Set) SizeLimiter(com.facebook.buck.rules.keys.SizeLimiter) DefaultFileHashCache(com.facebook.buck.util.cache.DefaultFileHashCache) BuildTarget(com.facebook.buck.model.BuildTarget) Sets(com.google.common.collect.Sets) List(java.util.List) Stream(java.util.stream.Stream) StepFailedException(com.facebook.buck.step.StepFailedException) LazyPath(com.facebook.buck.io.LazyPath) ByteStreams(com.google.common.io.ByteStreams) DependencyFileEntry(com.facebook.buck.rules.keys.DependencyFileEntry) Optional(java.util.Optional) GZIPOutputStream(java.util.zip.GZIPOutputStream) MoreFunctions(com.facebook.buck.util.MoreFunctions) RuleKeyFactoryManager(com.facebook.buck.rules.keys.RuleKeyFactoryManager) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) BuckEventBus(com.facebook.buck.event.BuckEventBus) ProjectFileHashCache(com.facebook.buck.util.cache.ProjectFileHashCache) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) Step(com.facebook.buck.step.Step) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConsoleEvent(com.facebook.buck.event.ConsoleEvent) BufferedOutputStream(java.io.BufferedOutputStream) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) ExecutionContext(com.facebook.buck.step.ExecutionContext) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) ThrowableConsoleEvent(com.facebook.buck.event.ThrowableConsoleEvent) ResourceAmounts(com.facebook.buck.util.concurrent.ResourceAmounts) Atomics(com.google.common.util.concurrent.Atomics) Nonnull(javax.annotation.Nonnull) ImmutableSortedMap(com.google.common.collect.ImmutableSortedMap) Nullable(javax.annotation.Nullable) SupportsInputBasedRuleKey(com.facebook.buck.rules.keys.SupportsInputBasedRuleKey) MoreCollectors(com.facebook.buck.util.MoreCollectors) OutputStream(java.io.OutputStream) Logger(com.facebook.buck.log.Logger) Functions(com.google.common.base.Functions) CacheResultType(com.facebook.buck.artifact_cache.CacheResultType) Files(java.nio.file.Files) HashCode(com.google.common.hash.HashCode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) HumanReadableException(com.facebook.buck.util.HumanReadableException) Maps(com.google.common.collect.Maps) FutureCallback(com.google.common.util.concurrent.FutureCallback) ExecutionException(java.util.concurrent.ExecutionException) ContextualProcessExecutor(com.facebook.buck.util.ContextualProcessExecutor) Futures(com.google.common.util.concurrent.Futures) BorrowablePath(com.facebook.buck.io.BorrowablePath) Paths(java.nio.file.Paths) CacheResult(com.facebook.buck.artifact_cache.CacheResult) FileHashCache(com.facebook.buck.util.cache.FileHashCache) Unzip(com.facebook.buck.zip.Unzip) Preconditions(com.google.common.base.Preconditions) AsyncFunction(com.google.common.util.concurrent.AsyncFunction) VisibleForTesting(com.google.common.annotations.VisibleForTesting) MoreFiles(com.facebook.buck.io.MoreFiles) SupportsDependencyFileRuleKey(com.facebook.buck.rules.keys.SupportsDependencyFileRuleKey) Collections(java.util.Collections) InputStream(java.io.InputStream) RuleKeyFactories(com.facebook.buck.rules.keys.RuleKeyFactories) SupportsInputBasedRuleKey(com.facebook.buck.rules.keys.SupportsInputBasedRuleKey) SupportsDependencyFileRuleKey(com.facebook.buck.rules.keys.SupportsDependencyFileRuleKey) CacheResult(com.facebook.buck.artifact_cache.CacheResult)

Example 3 with CacheResult

use of com.facebook.buck.artifact_cache.CacheResult in project buck by facebook.

the class CachingBuildEngine method performInputBasedCacheFetch.

private Optional<BuildResult> performInputBasedCacheFetch(final BuildRule rule, final BuildEngineBuildContext context, final OnDiskBuildInfo onDiskBuildInfo, BuildInfoRecorder buildInfoRecorder, RuleKey inputRuleKey) {
    Preconditions.checkArgument(SupportsInputBasedRuleKey.isSupported(rule));
    buildInfoRecorder.addBuildMetadata(BuildInfo.MetadataKey.INPUT_BASED_RULE_KEY, inputRuleKey.toString());
    // Check the input-based rule key says we're already built.
    Optional<RuleKey> lastInputRuleKey = onDiskBuildInfo.getRuleKey(BuildInfo.MetadataKey.INPUT_BASED_RULE_KEY);
    if (inputRuleKey.equals(lastInputRuleKey.orElse(null))) {
        return Optional.of(BuildResult.success(rule, BuildRuleSuccessType.MATCHING_INPUT_BASED_RULE_KEY, CacheResult.localKeyUnchangedHit()));
    }
    // Try to fetch the artifact using the input-based rule key.
    CacheResult cacheResult = tryToFetchArtifactFromBuildCacheAndOverlayOnTopOfProjectFilesystem(rule, inputRuleKey, context.getArtifactCache(), // TODO(shs96c): Share this between all tests, not one per cell.
    rule.getProjectFilesystem(), context);
    if (cacheResult.getType().isSuccess()) {
        fillMissingBuildMetadataFromCache(cacheResult, buildInfoRecorder, BuildInfo.MetadataKey.DEP_FILE_RULE_KEY, BuildInfo.MetadataKey.DEP_FILE);
        return Optional.of(BuildResult.success(rule, BuildRuleSuccessType.FETCHED_FROM_CACHE_INPUT_BASED, cacheResult));
    }
    return Optional.empty();
}
Also used : SupportsInputBasedRuleKey(com.facebook.buck.rules.keys.SupportsInputBasedRuleKey) SupportsDependencyFileRuleKey(com.facebook.buck.rules.keys.SupportsDependencyFileRuleKey) CacheResult(com.facebook.buck.artifact_cache.CacheResult)

Example 4 with CacheResult

use of com.facebook.buck.artifact_cache.CacheResult in project buck by facebook.

the class ServedCacheIntegrationTest method containsKey.

private boolean containsKey(ArtifactCache cache, RuleKey ruleKey) throws Exception {
    Path fetchedContents = tmpDir.newFile();
    CacheResult cacheResult = cache.fetch(ruleKey, LazyPath.ofInstance(fetchedContents));
    assertThat(cacheResult.getType(), Matchers.oneOf(CacheResultType.HIT, CacheResultType.MISS));
    return cacheResult.getType().isSuccess();
}
Also used : Path(java.nio.file.Path) BorrowablePath(com.facebook.buck.io.BorrowablePath) LazyPath(com.facebook.buck.io.LazyPath) CacheResult(com.facebook.buck.artifact_cache.CacheResult)

Example 5 with CacheResult

use of com.facebook.buck.artifact_cache.CacheResult in project buck by facebook.

the class ServedCacheIntegrationTest method testStoreAndFetchBorrowable.

@Test
public void testStoreAndFetchBorrowable() throws Exception {
    webServer = new WebServer(/* port */
    0, projectFilesystem, "/static/", MAPPER);
    webServer.updateAndStartIfNeeded(ArtifactCaches.newServedCache(createMockLocalConfig("[cache]", "dir = test-cache", "serve_local_cache = true", "served_local_cache_mode = readwrite"), projectFilesystem));
    ArtifactCache serverBackedCache = createArtifactCache(createMockLocalHttpCacheConfig(webServer.getPort().get()));
    RuleKey ruleKey = new RuleKey("00111222333444");
    ImmutableMap<String, String> metadata = ImmutableMap.of("some key", "some value");
    Path originalDataPath = tmpDir.newFile();
    String data = "you won't believe this!";
    projectFilesystem.writeContentsToPath(data, originalDataPath);
    LazyPath fetchedContents = LazyPath.ofInstance(tmpDir.newFile());
    CacheResult cacheResult = serverBackedCache.fetch(ruleKey, fetchedContents);
    assertThat(cacheResult.getType().isSuccess(), Matchers.is(false));
    serverBackedCache.store(ArtifactInfo.builder().addRuleKeys(ruleKey).setMetadata(metadata).build(), BorrowablePath.borrowablePath(originalDataPath));
    cacheResult = serverBackedCache.fetch(ruleKey, fetchedContents);
    assertThat(cacheResult.getType().isSuccess(), Matchers.is(true));
    assertThat(cacheResult.getMetadata(), Matchers.equalTo(metadata));
    assertThat(projectFilesystem.readFileIfItExists(fetchedContents.get()).get(), Matchers.equalTo(data));
}
Also used : Path(java.nio.file.Path) BorrowablePath(com.facebook.buck.io.BorrowablePath) LazyPath(com.facebook.buck.io.LazyPath) RuleKey(com.facebook.buck.rules.RuleKey) CacheResult(com.facebook.buck.artifact_cache.CacheResult) LazyPath(com.facebook.buck.io.LazyPath) ArtifactCache(com.facebook.buck.artifact_cache.ArtifactCache) Test(org.junit.Test)

Aggregations

CacheResult (com.facebook.buck.artifact_cache.CacheResult)15 LazyPath (com.facebook.buck.io.LazyPath)12 BorrowablePath (com.facebook.buck.io.BorrowablePath)10 Path (java.nio.file.Path)10 ArtifactCache (com.facebook.buck.artifact_cache.ArtifactCache)8 Test (org.junit.Test)7 RuleKey (com.facebook.buck.rules.RuleKey)5 InputStream (java.io.InputStream)4 SupportsDependencyFileRuleKey (com.facebook.buck.rules.keys.SupportsDependencyFileRuleKey)3 SupportsInputBasedRuleKey (com.facebook.buck.rules.keys.SupportsInputBasedRuleKey)3 ProjectFilesystem (com.facebook.buck.io.ProjectFilesystem)2 BuildTarget (com.facebook.buck.model.BuildTarget)2 IOException (java.io.IOException)2 ArtifactInfo (com.facebook.buck.artifact_cache.ArtifactInfo)1 CacheResultType (com.facebook.buck.artifact_cache.CacheResultType)1 HttpArtifactCacheBinaryProtocol (com.facebook.buck.artifact_cache.HttpArtifactCacheBinaryProtocol)1 ArtifactCompressionEvent (com.facebook.buck.event.ArtifactCompressionEvent)1 BuckEvent (com.facebook.buck.event.BuckEvent)1 BuckEventBus (com.facebook.buck.event.BuckEventBus)1 ConsoleEvent (com.facebook.buck.event.ConsoleEvent)1