Search in sources :

Example 21 with Futures

use of com.google.common.util.concurrent.Futures in project intellij by bazelbuild.

the class DirectoryStructure method walkDirectoryStructure.

private static ListenableFuture<PathStructurePair> walkDirectoryStructure(WorkspaceRoot workspaceRoot, Set<WorkspacePath> excludeDirectories, FileOperationProvider fileOperationProvider, ListeningExecutorService executorService, WorkspacePath workspacePath) {
    if (excludeDirectories.contains(workspacePath)) {
        return Futures.immediateFuture(null);
    }
    File file = workspaceRoot.fileForPath(workspacePath);
    if (!fileOperationProvider.isDirectory(file)) {
        return Futures.immediateFuture(null);
    }
    ListenableFuture<File[]> childrenFuture = executorService.submit(() -> fileOperationProvider.listFiles(file));
    return Futures.transformAsync(childrenFuture, children -> {
        if (children == null) {
            return Futures.immediateFuture(null);
        }
        List<ListenableFuture<PathStructurePair>> futures = Lists.newArrayListWithExpectedSize(children.length);
        for (File child : children) {
            WorkspacePath childWorkspacePath;
            try {
                childWorkspacePath = workspaceRoot.workspacePathFor(child);
            } catch (IllegalArgumentException e) {
                // stop at directories with unhandled characters.
                continue;
            }
            futures.add(walkDirectoryStructure(workspaceRoot, excludeDirectories, fileOperationProvider, executorService, childWorkspacePath));
        }
        return Futures.transform(Futures.allAsList(futures), (Function<List<PathStructurePair>, PathStructurePair>) pairs -> {
            Builder<WorkspacePath, DirectoryStructure> result = ImmutableMap.builder();
            for (PathStructurePair pair : pairs) {
                if (pair != null) {
                    result.put(pair.path, pair.directoryStructure);
                }
            }
            return new PathStructurePair(workspacePath, new DirectoryStructure(result.build()));
        }, executorService);
    }, executorService);
}
Also used : WorkspacePath(com.google.idea.blaze.base.model.primitives.WorkspacePath) Blaze(com.google.idea.blaze.base.settings.Blaze) ImportRoots(com.google.idea.blaze.base.sync.projectview.ImportRoots) Function(com.google.common.base.Function) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) Set(java.util.Set) FileOperationProvider(com.google.idea.blaze.base.io.FileOperationProvider) File(java.io.File) Builder(com.google.common.collect.ImmutableMap.Builder) ExecutionException(java.util.concurrent.ExecutionException) Futures(com.google.common.util.concurrent.Futures) List(java.util.List) Lists(com.google.common.collect.Lists) ProjectViewSet(com.google.idea.blaze.base.projectview.ProjectViewSet) WorkspaceRoot(com.google.idea.blaze.base.model.primitives.WorkspaceRoot) Project(com.intellij.openapi.project.Project) WorkspacePath(com.google.idea.blaze.base.model.primitives.WorkspacePath) FetchExecutor(com.google.idea.blaze.base.prefetch.FetchExecutor) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) Builder(com.google.common.collect.ImmutableMap.Builder) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) List(java.util.List) File(java.io.File)

Example 22 with Futures

use of com.google.common.util.concurrent.Futures in project presto by prestodb.

the class HivePageSink method doFinish.

private ListenableFuture<Collection<Slice>> doFinish() {
    ImmutableList.Builder<PartitionUpdate> partitionUpdatesBuilder = ImmutableList.builder();
    List<Callable<Object>> verificationTasks = new ArrayList<>();
    for (HiveWriter writer : writers) {
        writer.commit();
        partitionUpdatesBuilder.add(writer.getPartitionUpdate());
        writer.getVerificationTask().map(Executors::callable).ifPresent(verificationTasks::add);
    }
    List<PartitionUpdate> partitionUpdates = partitionUpdatesBuilder.build();
    boolean optimizedPartitionUpdateSerializationEnabled = isOptimizedPartitionUpdateSerializationEnabled(session);
    if (optimizedPartitionUpdateSerializationEnabled) {
        // Merge multiple partition updates for a single partition into one.
        // Multiple partition updates for a single partition are produced when writing into a bucketed table.
        // Merged partition updates will contain multiple items in the fileWriteInfos list (one per bucket).
        // This optimization should be enabled only together with the optimized serialization (compression + binary encoding).
        // Since serialized fragments will be transmitted as Presto pages serializing a merged partition update to JSON without
        // compression is unsafe, as it may cross the maximum page size limit.
        partitionUpdates = mergePartitionUpdates(partitionUpdates);
    }
    ImmutableList.Builder<Slice> serializedPartitionUpdatesBuilder = ImmutableList.builder();
    for (PartitionUpdate partitionUpdate : partitionUpdates) {
        byte[] serializedBytes;
        if (optimizedPartitionUpdateSerializationEnabled) {
            serializedBytes = serializeZstdCompressed(partitionUpdateSmileCodec, partitionUpdate);
        } else {
            serializedBytes = partitionUpdateCodec.toBytes(partitionUpdate);
        }
        serializedPartitionUpdatesBuilder.add(wrappedBuffer(serializedBytes));
    }
    List<Slice> serializedPartitionUpdates = serializedPartitionUpdatesBuilder.build();
    writtenBytes = writers.stream().mapToLong(HiveWriter::getWrittenBytes).sum();
    validationCpuNanos = writers.stream().mapToLong(HiveWriter::getValidationCpuNanos).sum();
    if (waitForFileRenaming && verificationTasks.isEmpty()) {
        // Use CopyOnWriteArrayList to prevent race condition when callbacks try to add partitionUpdates to this list
        List<Slice> partitionUpdatesWithRenamedFileNames = new CopyOnWriteArrayList<>();
        List<ListenableFuture<?>> futures = new ArrayList<>();
        for (int i = 0; i < writers.size(); i++) {
            int writerIndex = i;
            ListenableFuture<?> fileNameFuture = toListenableFuture(hiveMetadataUpdater.getMetadataResult(writerIndex));
            SettableFuture renamingFuture = SettableFuture.create();
            futures.add(renamingFuture);
            addSuccessCallback(fileNameFuture, obj -> renameFiles((String) obj, writerIndex, renamingFuture, partitionUpdatesWithRenamedFileNames));
        }
        return Futures.transform(Futures.allAsList(futures), input -> partitionUpdatesWithRenamedFileNames, directExecutor());
    }
    if (verificationTasks.isEmpty()) {
        return Futures.immediateFuture(serializedPartitionUpdates);
    }
    try {
        List<ListenableFuture<?>> futures = writeVerificationExecutor.invokeAll(verificationTasks).stream().map(future -> (ListenableFuture<?>) future).collect(toList());
        return Futures.transform(Futures.allAsList(futures), input -> serializedPartitionUpdates, directExecutor());
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) MoreFutures(com.facebook.airlift.concurrent.MoreFutures) JsonCodec(com.facebook.airlift.json.JsonCodec) Page(com.facebook.presto.common.Page) HiveBucketFunction.createPrestoNativeBucketFunction(com.facebook.presto.hive.HiveBucketFunction.createPrestoNativeBucketFunction) SettableFuture(com.google.common.util.concurrent.SettableFuture) Slices.wrappedBuffer(io.airlift.slice.Slices.wrappedBuffer) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) HiveSessionProperties.isOptimizedPartitionUpdateSerializationEnabled(com.facebook.presto.hive.HiveSessionProperties.isOptimizedPartitionUpdateSerializationEnabled) Map(java.util.Map) ConnectorPageSink(com.facebook.presto.spi.ConnectorPageSink) PageIndexerFactory(com.facebook.presto.spi.PageIndexerFactory) Path(org.apache.hadoop.fs.Path) FileWriteInfo(com.facebook.presto.hive.PartitionUpdate.FileWriteInfo) Object2IntOpenHashMap(it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap) PartitionUpdate.mergePartitionUpdates(com.facebook.presto.hive.PartitionUpdate.mergePartitionUpdates) ExtendedFileSystem(com.facebook.presto.hive.filesystem.ExtendedFileSystem) Collection(java.util.Collection) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) HIVE_TOO_MANY_OPEN_PARTITIONS(com.facebook.presto.hive.HiveErrorCode.HIVE_TOO_MANY_OPEN_PARTITIONS) Executors(java.util.concurrent.Executors) String.format(java.lang.String.format) MoreExecutors.directExecutor(com.google.common.util.concurrent.MoreExecutors.directExecutor) ConnectorSession(com.facebook.presto.spi.ConnectorSession) List(java.util.List) MoreFutures.addSuccessCallback(com.facebook.airlift.concurrent.MoreFutures.addSuccessCallback) INTEGER(com.facebook.presto.common.type.IntegerType.INTEGER) IntArrayBlockBuilder(com.facebook.presto.common.block.IntArrayBlockBuilder) Optional(java.util.Optional) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Logger(com.facebook.airlift.log.Logger) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Slice(io.airlift.slice.Slice) HIVE_WRITER_CLOSE_ERROR(com.facebook.presto.hive.HiveErrorCode.HIVE_WRITER_CLOSE_ERROR) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) HiveBucketFunction.createHiveCompatibleBucketFunction(com.facebook.presto.hive.HiveBucketFunction.createHiveCompatibleBucketFunction) PrestoException(com.facebook.presto.spi.PrestoException) OptionalInt(java.util.OptionalInt) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) Verify.verify(com.google.common.base.Verify.verify) SmileCodec(com.facebook.airlift.json.smile.SmileCodec) TypeManager(com.facebook.presto.common.type.TypeManager) Objects.requireNonNull(java.util.Objects.requireNonNull) HiveSessionProperties.isFileRenamingEnabled(com.facebook.presto.hive.HiveSessionProperties.isFileRenamingEnabled) Type(com.facebook.presto.common.type.Type) PageIndexer(com.facebook.presto.spi.PageIndexer) IOException(java.io.IOException) Ints(com.google.common.primitives.Ints) MoreFutures.toListenableFuture(com.facebook.airlift.concurrent.MoreFutures.toListenableFuture) Futures(com.google.common.util.concurrent.Futures) HIVE_FILESYSTEM_ERROR(com.facebook.presto.hive.HiveErrorCode.HIVE_FILESYSTEM_ERROR) Collectors.toList(java.util.stream.Collectors.toList) Object2IntMap(it.unimi.dsi.fastutil.objects.Object2IntMap) Block(com.facebook.presto.common.block.Block) HiveUtil.serializeZstdCompressed(com.facebook.presto.hive.HiveUtil.serializeZstdCompressed) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) Callable(java.util.concurrent.Callable) Slice(io.airlift.slice.Slice) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) MoreFutures.toListenableFuture(com.facebook.airlift.concurrent.MoreFutures.toListenableFuture) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 23 with Futures

use of com.google.common.util.concurrent.Futures in project druid by druid-io.

the class ConcurrentGrouper method parallelSortAndGetGroupersIterator.

private List<CloseableIterator<Entry<KeyType>>> parallelSortAndGetGroupersIterator() {
    // The number of groupers is same with the number of processing threads in the executor
    final List<ListenableFuture<CloseableIterator<Entry<KeyType>>>> futures = groupers.stream().map(grouper -> executor.submit(new AbstractPrioritizedCallable<CloseableIterator<Entry<KeyType>>>(priority) {

        @Override
        public CloseableIterator<Entry<KeyType>> call() {
            return grouper.iterator(true);
        }
    })).collect(Collectors.toList());
    ListenableFuture<List<CloseableIterator<Entry<KeyType>>>> future = Futures.allAsList(futures);
    try {
        final long timeout = queryTimeoutAt - System.currentTimeMillis();
        return hasQueryTimeout ? future.get(timeout, TimeUnit.MILLISECONDS) : future.get();
    } catch (InterruptedException | CancellationException e) {
        GuavaUtils.cancelAll(true, future, futures);
        throw new QueryInterruptedException(e);
    } catch (TimeoutException e) {
        GuavaUtils.cancelAll(true, future, futures);
        throw new QueryTimeoutException();
    } catch (ExecutionException e) {
        GuavaUtils.cancelAll(true, future, futures);
        throw new RuntimeException(e.getCause());
    }
}
Also used : Arrays(java.util.Arrays) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Supplier(com.google.common.base.Supplier) TimeoutException(java.util.concurrent.TimeoutException) ByteBuffer(java.nio.ByteBuffer) DefaultLimitSpec(org.apache.druid.query.groupby.orderby.DefaultLimitSpec) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) AbstractPrioritizedCallable(org.apache.druid.query.AbstractPrioritizedCallable) ColumnSelectorFactory(org.apache.druid.segment.ColumnSelectorFactory) ImmutableList(com.google.common.collect.ImmutableList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Suppliers(com.google.common.base.Suppliers) CloseableIterator(org.apache.druid.java.util.common.parsers.CloseableIterator) Nullable(javax.annotation.Nullable) CancellationException(java.util.concurrent.CancellationException) QueryInterruptedException(org.apache.druid.query.QueryInterruptedException) AggregatorFactory(org.apache.druid.query.aggregation.AggregatorFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) GroupByQueryConfig(org.apache.druid.query.groupby.GroupByQueryConfig) Set(java.util.Set) ISE(org.apache.druid.java.util.common.ISE) Collectors(java.util.stream.Collectors) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Futures(com.google.common.util.concurrent.Futures) List(java.util.List) CloseableIterators(org.apache.druid.java.util.common.CloseableIterators) QueryTimeoutException(org.apache.druid.query.QueryTimeoutException) GuavaUtils(org.apache.druid.common.guava.GuavaUtils) Preconditions(com.google.common.base.Preconditions) Comparator(java.util.Comparator) ReferenceCountingResourceHolder(org.apache.druid.collections.ReferenceCountingResourceHolder) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) CloseableIterator(org.apache.druid.java.util.common.parsers.CloseableIterator) QueryInterruptedException(org.apache.druid.query.QueryInterruptedException) QueryTimeoutException(org.apache.druid.query.QueryTimeoutException) CancellationException(java.util.concurrent.CancellationException) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) ExecutionException(java.util.concurrent.ExecutionException) QueryInterruptedException(org.apache.druid.query.QueryInterruptedException) TimeoutException(java.util.concurrent.TimeoutException) QueryTimeoutException(org.apache.druid.query.QueryTimeoutException)

Example 24 with Futures

use of com.google.common.util.concurrent.Futures in project buck by facebook.

the class Build method executeBuild.

/**
   * If {@code isKeepGoing} is false, then this returns a future that succeeds only if all of
   * {@code rulesToBuild} build successfully. Otherwise, this returns a future that should always
   * succeed, even if individual rules fail to build. In that case, a failed build rule is indicated
   * by a {@code null} value in the corresponding position in the iteration order of
   * {@code rulesToBuild}.
   * @param targetish The targets to build. All targets in this iterable must be unique.
   */
@SuppressWarnings("PMD.EmptyCatchBlock")
public BuildExecutionResult executeBuild(Iterable<? extends BuildTarget> targetish, boolean isKeepGoing) throws IOException, ExecutionException, InterruptedException {
    BuildId buildId = executionContext.getBuildId();
    BuildEngineBuildContext buildContext = BuildEngineBuildContext.builder().setBuildContext(BuildContext.builder().setActionGraph(actionGraph).setSourcePathResolver(new SourcePathResolver(new SourcePathRuleFinder(ruleResolver))).setJavaPackageFinder(javaPackageFinder).setEventBus(executionContext.getBuckEventBus()).setAndroidPlatformTargetSupplier(executionContext.getAndroidPlatformTargetSupplier()).build()).setClock(clock).setArtifactCache(artifactCache).setBuildId(buildId).setObjectMapper(objectMapper).putAllEnvironment(executionContext.getEnvironment()).setKeepGoing(isKeepGoing).build();
    // It is important to use this logic to determine the set of rules to build rather than
    // build.getActionGraph().getNodesWithNoIncomingEdges() because, due to graph enhancement,
    // there could be disconnected subgraphs in the DependencyGraph that we do not want to build.
    ImmutableSet<BuildTarget> targetsToBuild = StreamSupport.stream(targetish.spliterator(), false).collect(MoreCollectors.toImmutableSet());
    // It is important to use this logic to determine the set of rules to build rather than
    // build.getActionGraph().getNodesWithNoIncomingEdges() because, due to graph enhancement,
    // there could be disconnected subgraphs in the DependencyGraph that we do not want to build.
    ImmutableList<BuildRule> rulesToBuild = ImmutableList.copyOf(targetsToBuild.stream().map(buildTarget -> {
        try {
            return getRuleResolver().requireRule(buildTarget);
        } catch (NoSuchBuildTargetException e) {
            throw new HumanReadableException("No build rule found for target %s", buildTarget);
        }
    }).collect(MoreCollectors.toImmutableSet()));
    // Calculate and post the number of rules that need to built.
    int numRules = buildEngine.getNumRulesToBuild(rulesToBuild);
    getExecutionContext().getBuckEventBus().post(BuildEvent.ruleCountCalculated(targetsToBuild, numRules));
    // Setup symlinks required when configuring the output path.
    createConfiguredBuckOutSymlinks();
    List<ListenableFuture<BuildResult>> futures = rulesToBuild.stream().map(rule -> buildEngine.build(buildContext, executionContext, rule)).collect(MoreCollectors.toImmutableList());
    // Get the Future representing the build and then block until everything is built.
    ListenableFuture<List<BuildResult>> buildFuture = Futures.allAsList(futures);
    List<BuildResult> results;
    try {
        results = buildFuture.get();
        if (!isKeepGoing) {
            for (BuildResult result : results) {
                Throwable thrown = result.getFailure();
                if (thrown != null) {
                    throw new ExecutionException(thrown);
                }
            }
        }
    } catch (ExecutionException | InterruptedException | RuntimeException e) {
        Throwable t = Throwables.getRootCause(e);
        if (e instanceof InterruptedException || t instanceof InterruptedException || t instanceof ClosedByInterruptException) {
            try {
                buildFuture.cancel(true);
            } catch (CancellationException ignored) {
            // Rethrow original InterruptedException instead.
            }
            Thread.currentThread().interrupt();
        }
        throw e;
    }
    // Insertion order matters
    LinkedHashMap<BuildRule, Optional<BuildResult>> resultBuilder = new LinkedHashMap<>();
    Preconditions.checkState(rulesToBuild.size() == results.size());
    for (int i = 0, len = rulesToBuild.size(); i < len; i++) {
        BuildRule rule = rulesToBuild.get(i);
        resultBuilder.put(rule, Optional.ofNullable(results.get(i)));
    }
    return BuildExecutionResult.builder().setFailures(FluentIterable.from(results).filter(input -> input.getSuccess() == null)).setResults(resultBuilder).build();
}
Also used : ArtifactCache(com.facebook.buck.artifact_cache.ArtifactCache) ActionGraph(com.facebook.buck.rules.ActionGraph) SourcePathRuleFinder(com.facebook.buck.rules.SourcePathRuleFinder) AdbOptions(com.facebook.buck.step.AdbOptions) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) BuckConfig(com.facebook.buck.cli.BuckConfig) BuildId(com.facebook.buck.model.BuildId) WorkerProcessPool(com.facebook.buck.shell.WorkerProcessPool) FluentIterable(com.google.common.collect.FluentIterable) SourcePathResolver(com.facebook.buck.rules.SourcePathResolver) Map(java.util.Map) Clock(com.facebook.buck.timing.Clock) ConcurrencyLimit(com.facebook.buck.util.concurrent.ConcurrencyLimit) Cell(com.facebook.buck.rules.Cell) Path(java.nio.file.Path) JavaPackageFinder(com.facebook.buck.jvm.core.JavaPackageFinder) AndroidPlatformTarget(com.facebook.buck.android.AndroidPlatformTarget) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) CancellationException(java.util.concurrent.CancellationException) Platform(com.facebook.buck.util.environment.Platform) BuckPaths(com.facebook.buck.io.BuckPaths) BuildTarget(com.facebook.buck.model.BuildTarget) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) List(java.util.List) BuildEngineBuildContext(com.facebook.buck.rules.BuildEngineBuildContext) StepFailedException(com.facebook.buck.step.StepFailedException) ExceptionWithHumanReadableMessage(com.facebook.buck.util.ExceptionWithHumanReadableMessage) ExecutorPool(com.facebook.buck.step.ExecutorPool) Optional(java.util.Optional) BuildRuleResolver(com.facebook.buck.rules.BuildRuleResolver) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) BuckEventBus(com.facebook.buck.event.BuckEventBus) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Supplier(com.google.common.base.Supplier) ConsoleEvent(com.facebook.buck.event.ConsoleEvent) ConcurrentMap(java.util.concurrent.ConcurrentMap) BuildRule(com.facebook.buck.rules.BuildRule) ExecutionContext(com.facebook.buck.step.ExecutionContext) LinkedHashMap(java.util.LinkedHashMap) ImmutableList(com.google.common.collect.ImmutableList) ThrowableConsoleEvent(com.facebook.buck.event.ThrowableConsoleEvent) Files(com.google.common.io.Files) Value(org.immutables.value.Value) NoSuchBuildTargetException(com.facebook.buck.parser.NoSuchBuildTargetException) StreamSupport(java.util.stream.StreamSupport) MoreCollectors(com.facebook.buck.util.MoreCollectors) Logger(com.facebook.buck.log.Logger) Charsets(com.google.common.base.Charsets) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) TargetDeviceOptions(com.facebook.buck.step.TargetDeviceOptions) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) Console(com.facebook.buck.util.Console) HumanReadableException(com.facebook.buck.util.HumanReadableException) BuckStyleImmutable(com.facebook.buck.util.immutables.BuckStyleImmutable) TargetDevice(com.facebook.buck.step.TargetDevice) BuildResult(com.facebook.buck.rules.BuildResult) ExecutionException(java.util.concurrent.ExecutionException) Futures(com.google.common.util.concurrent.Futures) BuildEvent(com.facebook.buck.rules.BuildEvent) BuildEngine(com.facebook.buck.rules.BuildEngine) Closeable(java.io.Closeable) BuildContext(com.facebook.buck.rules.BuildContext) Preconditions(com.google.common.base.Preconditions) LinkedHashMap(java.util.LinkedHashMap) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) BuildTarget(com.facebook.buck.model.BuildTarget) BuildEngineBuildContext(com.facebook.buck.rules.BuildEngineBuildContext) BuildRule(com.facebook.buck.rules.BuildRule) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) ExecutionException(java.util.concurrent.ExecutionException) Optional(java.util.Optional) SourcePathResolver(com.facebook.buck.rules.SourcePathResolver) SourcePathRuleFinder(com.facebook.buck.rules.SourcePathRuleFinder) BuildResult(com.facebook.buck.rules.BuildResult) BuildId(com.facebook.buck.model.BuildId) CancellationException(java.util.concurrent.CancellationException) HumanReadableException(com.facebook.buck.util.HumanReadableException) NoSuchBuildTargetException(com.facebook.buck.parser.NoSuchBuildTargetException) ListenableFuture(com.google.common.util.concurrent.ListenableFuture)

Example 25 with Futures

use of com.google.common.util.concurrent.Futures in project metacat by Netflix.

the class ElasticSearchMetacatRefresh method _processPartitions.

@SuppressWarnings("checkstyle:methodname")
private ListenableFuture<Void> _processPartitions(final List<QualifiedName> qNames) {
    final List<QualifiedName> excludeQualifiedNames = config.getElasticSearchRefreshExcludeQualifiedNames();
    final List<String> tables = elasticSearchUtil.getTableIdsByCatalogs(ElasticSearchDoc.Type.table.name(), qNames, excludeQualifiedNames);
    final List<ListenableFuture<ListenableFuture<Void>>> futures = tables.stream().map(s -> service.submit(() -> {
        final QualifiedName tableName = QualifiedName.fromString(s, false);
        final List<ListenableFuture<Void>> indexFutures = Lists.newArrayList();
        int offset = 0;
        int count;
        final Sort sort;
        if ("s3".equals(tableName.getCatalogName()) || "aegisthus".equals(tableName.getCatalogName())) {
            sort = new Sort("id", SortOrder.ASC);
        } else {
            sort = new Sort("part_id", SortOrder.ASC);
        }
        final Pageable pageable = new Pageable(10000, offset);
        do {
            final List<PartitionDto> partitionDtos = partitionService.list(tableName, null, null, sort, pageable, true, true, true);
            count = partitionDtos.size();
            if (!partitionDtos.isEmpty()) {
                final List<List<PartitionDto>> partitionedPartitionDtos = Lists.partition(partitionDtos, 1000);
                partitionedPartitionDtos.forEach(subPartitionsDtos -> indexFutures.add(indexPartitionDtos(tableName, subPartitionsDtos)));
                offset = offset + count;
                pageable.setOffset(offset);
            }
        } while (count == 10000);
        return Futures.transform(Futures.successfulAsList(indexFutures), Functions.constant((Void) null));
    })).collect(Collectors.toList());
    final ListenableFuture<Void> processPartitionsFuture = Futures.transformAsync(Futures.successfulAsList(futures), input -> {
        final List<ListenableFuture<Void>> inputFuturesWithoutNulls = input.stream().filter(NOT_NULL).collect(Collectors.toList());
        return Futures.transform(Futures.successfulAsList(inputFuturesWithoutNulls), Functions.constant(null));
    });
    return Futures.transformAsync(processPartitionsFuture, input -> {
        elasticSearchUtil.refresh();
        final List<ListenableFuture<Void>> cleanUpFutures = tables.stream().map(s -> service.submit(() -> partitionsCleanUp(QualifiedName.fromString(s, false), excludeQualifiedNames))).collect(Collectors.toList());
        return Futures.transform(Futures.successfulAsList(cleanUpFutures), Functions.constant(null));
    });
}
Also used : UserMetadataService(com.netflix.metacat.common.server.usermetadata.UserMetadataService) CatalogService(com.netflix.metacat.main.services.CatalogService) MetacatEventBus(com.netflix.metacat.common.server.events.MetacatEventBus) SortOrder(com.netflix.metacat.common.dto.SortOrder) MetacatContextManager(com.netflix.metacat.common.server.util.MetacatContextManager) PartitionService(com.netflix.metacat.main.services.PartitionService) DatabaseDto(com.netflix.metacat.common.dto.DatabaseDto) TagService(com.netflix.metacat.common.server.usermetadata.TagService) DatabaseService(com.netflix.metacat.main.services.DatabaseService) Splitter(com.google.common.base.Splitter) NonNull(lombok.NonNull) Predicate(java.util.function.Predicate) Pageable(com.netflix.metacat.common.dto.Pageable) Set(java.util.Set) CatalogMappingDto(com.netflix.metacat.common.dto.CatalogMappingDto) QualifiedName(com.netflix.metacat.common.QualifiedName) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) CatalogDto(com.netflix.metacat.common.dto.CatalogDto) HasMetadata(com.netflix.metacat.common.dto.HasMetadata) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) PartitionDto(com.netflix.metacat.common.dto.PartitionDto) Optional(java.util.Optional) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) Sort(com.netflix.metacat.common.dto.Sort) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) MetacatDeleteTablePostEvent(com.netflix.metacat.common.server.events.MetacatDeleteTablePostEvent) TableDto(com.netflix.metacat.common.dto.TableDto) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Supplier(java.util.function.Supplier) DatabaseNotFoundException(com.netflix.metacat.common.server.connectors.exception.DatabaseNotFoundException) Strings(com.google.common.base.Strings) Lists(com.google.common.collect.Lists) TableService(com.netflix.metacat.main.services.TableService) MetacatRequestContext(com.netflix.metacat.common.MetacatRequestContext) Config(com.netflix.metacat.common.server.properties.Config) Nonnull(javax.annotation.Nonnull) ExecutorService(java.util.concurrent.ExecutorService) Metrics(com.netflix.metacat.common.server.monitoring.Metrics) Functions(com.google.common.base.Functions) Throwables(com.google.common.base.Throwables) TimeUnit(java.util.concurrent.TimeUnit) Futures(com.google.common.util.concurrent.Futures) Registry(com.netflix.spectator.api.Registry) Instant(org.joda.time.Instant) QualifiedName(com.netflix.metacat.common.QualifiedName) Pageable(com.netflix.metacat.common.dto.Pageable) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Sort(com.netflix.metacat.common.dto.Sort) PartitionDto(com.netflix.metacat.common.dto.PartitionDto) List(java.util.List)

Aggregations

Futures (com.google.common.util.concurrent.Futures)42 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)42 List (java.util.List)38 ArrayList (java.util.ArrayList)32 MoreExecutors (com.google.common.util.concurrent.MoreExecutors)26 Map (java.util.Map)21 ExecutionException (java.util.concurrent.ExecutionException)21 Collectors (java.util.stream.Collectors)21 Set (java.util.Set)19 Nullable (javax.annotation.Nullable)19 FutureCallback (com.google.common.util.concurrent.FutureCallback)18 Collections (java.util.Collections)18 Collection (java.util.Collection)17 Optional (java.util.Optional)17 Logger (org.slf4j.Logger)16 LoggerFactory (org.slf4j.LoggerFactory)16 HashSet (java.util.HashSet)15 TimeUnit (java.util.concurrent.TimeUnit)15 Inject (javax.inject.Inject)15 Lists (com.google.common.collect.Lists)14