Search in sources :

Example 16 with Futures

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

the class ElasticSearchRefresh 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, sort, pageable, true, true, new GetPartitionsRequestDto(null, null, 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), defaultService);
    })).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), defaultService);
    }, defaultService);
    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), defaultService);
    }, defaultService);
}
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) Executors(java.util.concurrent.Executors) Objects(java.util.Objects) 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) GetTableServiceParameters(com.netflix.metacat.main.services.GetTableServiceParameters) 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) GetDatabaseServiceParameters(com.netflix.metacat.main.services.GetDatabaseServiceParameters) 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) Nullable(javax.annotation.Nullable) ExecutorService(java.util.concurrent.ExecutorService) Metrics(com.netflix.metacat.common.server.monitoring.Metrics) Functions(com.google.common.base.Functions) GetPartitionsRequestDto(com.netflix.metacat.common.dto.GetPartitionsRequestDto) 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) GetPartitionsRequestDto(com.netflix.metacat.common.dto.GetPartitionsRequestDto) 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)

Example 17 with Futures

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

the class DirectSqlGetPartition method getPartitions.

private List<PartitionHolder> getPartitions(final String databaseName, final String tableName, @Nullable final List<String> partitionIds, @Nullable final String filterExpression, @Nullable final Sort sort, @Nullable final Pageable pageable, final boolean includePartitionDetails, final boolean forceDisableAudit) {
    final FilterPartition filter = config.escapePartitionNameOnFilter() ? new HiveFilterPartition() : new FilterPartition();
    // batch exists
    final boolean isBatched = !Strings.isNullOrEmpty(filterExpression) && filterExpression.contains(FIELD_BATCHID);
    final boolean hasDateCreated = !Strings.isNullOrEmpty(filterExpression) && filterExpression.contains(FIELD_DATE_CREATED);
    // Handler for reading the result set
    final ResultSetExtractor<List<PartitionHolder>> handler = rs -> {
        final List<PartitionHolder> result = Lists.newArrayList();
        final QualifiedName tableQName = QualifiedName.ofTable(catalogName, databaseName, tableName);
        int noOfRows = 0;
        while (rs.next()) {
            noOfRows++;
            final String name = rs.getString("name");
            final String uri = rs.getString("uri");
            final long createdDate = rs.getLong(FIELD_DATE_CREATED);
            Map<String, String> values = null;
            if (hasDateCreated) {
                values = Maps.newHashMap();
                values.put(FIELD_DATE_CREATED, createdDate + "");
            }
            if (Strings.isNullOrEmpty(filterExpression) || filter.evaluatePartitionExpression(filterExpression, name, uri, isBatched, values)) {
                final Long id = rs.getLong("id");
                final Long sdId = rs.getLong("sd_id");
                final Long serdeId = rs.getLong("serde_id");
                final String inputFormat = rs.getString("input_format");
                final String outputFormat = rs.getString("output_format");
                final String serializationLib = rs.getString("slib");
                final StorageInfo storageInfo = new StorageInfo();
                storageInfo.setUri(uri);
                storageInfo.setInputFormat(inputFormat);
                storageInfo.setOutputFormat(outputFormat);
                storageInfo.setSerializationLib(serializationLib);
                final AuditInfo auditInfo = new AuditInfo();
                auditInfo.setCreatedDate(Date.from(Instant.ofEpochSecond(createdDate)));
                auditInfo.setLastModifiedDate(Date.from(Instant.ofEpochSecond(createdDate)));
                result.add(new PartitionHolder(id, sdId, serdeId, PartitionInfo.builder().name(QualifiedName.ofPartition(catalogName, databaseName, tableName, name)).auditInfo(auditInfo).serde(storageInfo).build()));
            }
            // Fail if the number of partitions exceeds the threshold limit.
            if (result.size() > config.getMaxPartitionsThreshold()) {
                registry.counter(registry.createId(HiveMetrics.CounterHiveGetPartitionsExceedThresholdFailure.getMetricName()).withTags(tableQName.parts())).increment();
                final String message = String.format("Number of partitions queried for table %s exceeded the threshold %d", tableQName, config.getMaxPartitionsThreshold());
                log.warn(message);
                throw new IllegalArgumentException(message);
            }
        }
        registry.gauge(registry.createId(HiveMetrics.GaugePreExpressionFilterGetPartitionsCount.getMetricName()).withTags(tableQName.parts())).set(noOfRows);
        return result;
    };
    final List<PartitionHolder> partitions = this.getHandlerResults(databaseName, tableName, filterExpression, partitionIds, SQL.SQL_GET_PARTITIONS, handler, sort, pageable, forceDisableAudit);
    if (includePartitionDetails && !partitions.isEmpty()) {
        final List<Long> partIds = Lists.newArrayListWithCapacity(partitions.size());
        final List<Long> sdIds = Lists.newArrayListWithCapacity(partitions.size());
        final List<Long> serdeIds = Lists.newArrayListWithCapacity(partitions.size());
        for (PartitionHolder partitionHolder : partitions) {
            partIds.add(partitionHolder.getId());
            sdIds.add(partitionHolder.getSdId());
            serdeIds.add(partitionHolder.getSerdeId());
        }
        final List<ListenableFuture<Void>> futures = Lists.newArrayList();
        final Map<Long, Map<String, String>> partitionParams = Maps.newHashMap();
        futures.add(threadServiceManager.getExecutor().submit(() -> populateParameters(partIds, SQL.SQL_GET_PARTITION_PARAMS, "part_id", partitionParams)));
        final Map<Long, Map<String, String>> sdParams = Maps.newHashMap();
        if (!sdIds.isEmpty()) {
            futures.add(threadServiceManager.getExecutor().submit(() -> populateParameters(sdIds, SQL.SQL_GET_SD_PARAMS, "sd_id", sdParams)));
        }
        final Map<Long, Map<String, String>> serdeParams = Maps.newHashMap();
        if (!serdeIds.isEmpty()) {
            futures.add(threadServiceManager.getExecutor().submit(() -> populateParameters(serdeIds, SQL.SQL_GET_SERDE_PARAMS, "serde_id", serdeParams)));
        }
        ListenableFuture<List<Void>> future = null;
        try {
            future = Futures.allAsList(futures);
            final int getPartitionsDetailsTimeout = Integer.parseInt(configuration.getOrDefault(HiveConfigConstants.GET_PARTITION_DETAILS_TIMEOUT, "120"));
            future.get(getPartitionsDetailsTimeout, TimeUnit.SECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            try {
                if (future != null) {
                    future.cancel(true);
                }
            } catch (Exception ignored) {
                log.warn("Failed cancelling the task that gets the partition details.");
            }
            Throwables.propagate(e);
        }
        for (PartitionHolder partitionHolder : partitions) {
            partitionHolder.getPartitionInfo().setMetadata(partitionParams.get(partitionHolder.getId()));
            partitionHolder.getPartitionInfo().getSerde().setParameters(sdParams.get(partitionHolder.getSdId()));
            partitionHolder.getPartitionInfo().getSerde().setSerdeInfoParameters(serdeParams.get(partitionHolder.getSerdeId()));
        }
    }
    return partitions;
}
Also used : HiveConfigConstants(com.netflix.metacat.connector.hive.util.HiveConfigConstants) HiveConnectorFastServiceMetric(com.netflix.metacat.connector.hive.util.HiveConnectorFastServiceMetric) PartitionKeyParserEval(com.netflix.metacat.common.server.partition.visitor.PartitionKeyParserEval) Date(java.util.Date) TimeoutException(java.util.concurrent.TimeoutException) PartitionFilterGenerator(com.netflix.metacat.connector.hive.util.PartitionFilterGenerator) PartitionParamParserEval(com.netflix.metacat.common.server.partition.visitor.PartitionParamParserEval) Matcher(java.util.regex.Matcher) ConnectorException(com.netflix.metacat.common.server.connectors.exception.ConnectorException) PartitionInfo(com.netflix.metacat.common.server.connectors.model.PartitionInfo) Map(java.util.Map) ConnectorContext(com.netflix.metacat.common.server.connectors.ConnectorContext) StorageInfo(com.netflix.metacat.common.server.connectors.model.StorageInfo) ConnectorRequestContext(com.netflix.metacat.common.server.connectors.ConnectorRequestContext) Collection(java.util.Collection) Pageable(com.netflix.metacat.common.dto.Pageable) QualifiedName(com.netflix.metacat.common.QualifiedName) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) HiveMetrics(com.netflix.metacat.connector.hive.monitoring.HiveMetrics) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) Joiner(com.google.common.base.Joiner) Sort(com.netflix.metacat.common.dto.Sort) Types(java.sql.Types) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) AuditInfo(com.netflix.metacat.common.server.connectors.model.AuditInfo) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) Strings(com.google.common.base.Strings) Lists(com.google.common.collect.Lists) ThreadServiceManager(com.netflix.metacat.common.server.util.ThreadServiceManager) ImmutableList(com.google.common.collect.ImmutableList) Qualifier(org.springframework.beans.factory.annotation.Qualifier) PartitionParser(com.netflix.metacat.common.server.partition.parser.PartitionParser) Config(com.netflix.metacat.common.server.properties.Config) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) Throwables(com.google.common.base.Throwables) Maps(com.google.common.collect.Maps) Table(org.apache.hadoop.hive.metastore.api.Table) SqlParameterValue(org.springframework.jdbc.core.SqlParameterValue) FilterPartition(com.netflix.metacat.common.server.partition.util.FilterPartition) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) FieldSchema(org.apache.hadoop.hive.metastore.api.FieldSchema) Futures(com.google.common.util.concurrent.Futures) StringReader(java.io.StringReader) Registry(com.netflix.spectator.api.Registry) PartitionListRequest(com.netflix.metacat.common.server.connectors.model.PartitionListRequest) HiveFilterPartition(com.netflix.metacat.connector.hive.util.HiveFilterPartition) VisibleForTesting(com.google.common.annotations.VisibleForTesting) HivePartitionKeyParserEval(com.netflix.metacat.connector.hive.util.HivePartitionKeyParserEval) ResultSetExtractor(org.springframework.jdbc.core.ResultSetExtractor) Transactional(org.springframework.transaction.annotation.Transactional) HiveFilterPartition(com.netflix.metacat.connector.hive.util.HiveFilterPartition) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) AuditInfo(com.netflix.metacat.common.server.connectors.model.AuditInfo) FilterPartition(com.netflix.metacat.common.server.partition.util.FilterPartition) HiveFilterPartition(com.netflix.metacat.connector.hive.util.HiveFilterPartition) QualifiedName(com.netflix.metacat.common.QualifiedName) TimeoutException(java.util.concurrent.TimeoutException) ConnectorException(com.netflix.metacat.common.server.connectors.exception.ConnectorException) ExecutionException(java.util.concurrent.ExecutionException) StorageInfo(com.netflix.metacat.common.server.connectors.model.StorageInfo) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Map(java.util.Map)

Example 18 with Futures

use of com.google.common.util.concurrent.Futures in project genius by opendaylight.

the class OvsInterfaceConfigAddHelper method addConfiguration.

public List<ListenableFuture<Void>> addConfiguration(ParentRefs parentRefs, Interface interfaceNew) {
    List<ListenableFuture<Void>> futures = new ArrayList<>();
    // TODO Disentangle the transactions
    futures.add(txRunner.callWithNewWriteOnlyTransactionAndSubmit(configTx -> {
        futures.add(txRunner.callWithNewWriteOnlyTransactionAndSubmit(operTx -> {
            IfTunnel ifTunnel = interfaceNew.getAugmentation(IfTunnel.class);
            if (ifTunnel != null) {
                addTunnelConfiguration(parentRefs, interfaceNew, ifTunnel, configTx, operTx, futures);
            } else {
                addVlanConfiguration(interfaceNew, parentRefs, configTx, operTx, futures);
            }
        }));
    }));
    return futures;
}
Also used : IfmConstants(org.opendaylight.genius.interfacemanager.IfmConstants) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) InterfaceChildEntry(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._interface.child.info._interface.parent.entry.InterfaceChildEntry) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) OvsInterfaceStateAddHelper(org.opendaylight.genius.interfacemanager.renderer.ovs.statehelpers.OvsInterfaceStateAddHelper) InterfaceParentEntryKey(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._interface.child.info.InterfaceParentEntryKey) LoggerFactory(org.slf4j.LoggerFactory) Callable(java.util.concurrent.Callable) Singleton(javax.inject.Singleton) IfL2vlan(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfL2vlan) ArrayList(java.util.ArrayList) Interface(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface) BridgeRefEntry(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.bridge.ref.info.BridgeRefEntry) Inject(javax.inject.Inject) IfTunnel(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel) Strings(com.google.common.base.Strings) ParentRefs(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs) OvsdbBridgeAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbBridgeAugmentation) TunnelTypeVxlan(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan) NodeConnectorId(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId) ManagedNewTransactionRunnerImpl(org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl) BigInteger(java.math.BigInteger) MDSALUtil(org.opendaylight.genius.mdsalutil.MDSALUtil) InterfaceParentEntry(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406._interface.child.info.InterfaceParentEntry) TunnelTypeLogicalGroup(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeLogicalGroup) Nonnull(javax.annotation.Nonnull) SouthboundUtils(org.opendaylight.genius.interfacemanager.renderer.ovs.utilities.SouthboundUtils) Nullable(javax.annotation.Nullable) IfmUtil(org.opendaylight.genius.interfacemanager.IfmUtil) AlivenessMonitorUtils(org.opendaylight.genius.interfacemanager.commons.AlivenessMonitorUtils) Logger(org.slf4j.Logger) Group(org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group) ManagedNewTransactionRunner(org.opendaylight.genius.infra.ManagedNewTransactionRunner) JobCoordinator(org.opendaylight.infrautils.jobcoordinator.JobCoordinator) InterfaceManagerCommonUtils(org.opendaylight.genius.interfacemanager.commons.InterfaceManagerCommonUtils) BridgeEntry(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.meta.rev160406.bridge._interface.info.BridgeEntry) WriteTransaction(org.opendaylight.controller.md.sal.binding.api.WriteTransaction) FutureCallback(com.google.common.util.concurrent.FutureCallback) DataBroker(org.opendaylight.controller.md.sal.binding.api.DataBroker) Futures(com.google.common.util.concurrent.Futures) List(java.util.List) InstanceIdentifier(org.opendaylight.yangtools.yang.binding.InstanceIdentifier) IMdsalApiManager(org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager) InterfaceMetaUtils(org.opendaylight.genius.interfacemanager.commons.InterfaceMetaUtils) GroupTypes(org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes) FlowBasedServicesUtils(org.opendaylight.genius.interfacemanager.servicebindings.flowbased.utilities.FlowBasedServicesUtils) Collections(java.util.Collections) ArrayList(java.util.ArrayList) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) IfTunnel(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.IfTunnel)

Example 19 with Futures

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

the class PrefetchServiceImpl method prefetchFiles.

private ListenableFuture<?> prefetchFiles(Project project, Set<File> excludeDirectories, Collection<File> files, boolean refetchCachedFiles, boolean fetchFileTypes) {
    if (files.isEmpty() || !enabled(project)) {
        return Futures.immediateFuture(null);
    }
    if (!refetchCachedFiles) {
        long startTime = System.currentTimeMillis();
        // ignore recently fetched files
        files = files.stream().filter(file -> shouldPrefetch(file, startTime)).collect(Collectors.toList());
    }
    FileOperationProvider provider = FileOperationProvider.getInstance();
    List<ListenableFuture<File>> canonicalFiles = files.stream().map(file -> FetchExecutor.EXECUTOR.submit(() -> toCanonicalFile(provider, file))).collect(Collectors.toList());
    List<ListenableFuture<?>> futures = Lists.newArrayList();
    for (Prefetcher prefetcher : Prefetcher.EP_NAME.getExtensions()) {
        futures.add(prefetcher.prefetchFiles(project, excludeDirectories, canonicalFiles, FetchExecutor.EXECUTOR, fetchFileTypes));
    }
    return Futures.allAsList(futures);
}
Also used : ListenableFuture(com.google.common.util.concurrent.ListenableFuture) LowMemoryWatcher(com.intellij.openapi.util.LowMemoryWatcher) HashSet(java.util.HashSet) BlazeProjectData(com.google.idea.blaze.base.model.BlazeProjectData) Lists(com.google.common.collect.Lists) Map(java.util.Map) Project(com.intellij.openapi.project.Project) Logger(com.intellij.openapi.diagnostic.Logger) Nullable(javax.annotation.Nullable) ImportRoots(com.google.idea.blaze.base.sync.projectview.ImportRoots) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) BlazeImportSettingsManager(com.google.idea.blaze.base.settings.BlazeImportSettingsManager) Set(java.util.Set) IOException(java.io.IOException) Maps(com.google.common.collect.Maps) Collectors(java.util.stream.Collectors) FileOperationProvider(com.google.idea.blaze.base.io.FileOperationProvider) File(java.io.File) BlazeImportSettings(com.google.idea.blaze.base.settings.BlazeImportSettings) TimeUnit(java.util.concurrent.TimeUnit) Futures(com.google.common.util.concurrent.Futures) List(java.util.List) ProjectViewSet(com.google.idea.blaze.base.projectview.ProjectViewSet) WorkspaceRoot(com.google.idea.blaze.base.model.primitives.WorkspaceRoot) ApplicationManager(com.intellij.openapi.application.ApplicationManager) WorkspacePath(com.google.idea.blaze.base.model.primitives.WorkspacePath) FileOperationProvider(com.google.idea.blaze.base.io.FileOperationProvider) ListenableFuture(com.google.common.util.concurrent.ListenableFuture)

Example 20 with Futures

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

the class BlazeIdeInterfaceAspectsImpl method updateState.

@Nullable
static State updateState(Project project, BlazeContext parentContext, @Nullable State prevState, ImmutableMap<File, Long> fileState, BlazeConfigurationHandler configHandler, WorkspaceLanguageSettings workspaceLanguageSettings, ImportRoots importRoots, AspectStrategy aspectStrategy, List<File> newFiles, List<File> removedFiles, boolean mergeWithOldState) {
    Result<State> result = Scope.push(parentContext, (ScopedFunction<Result<State>>) context -> {
        context.push(new TimingScope("UpdateTargetMap", EventType.Other));
        ImmutableMap<File, Long> nextFileState = fileState;
        if (mergeWithOldState && prevState != null) {
            ImmutableMap.Builder<File, Long> fileStateBuilder = ImmutableMap.<File, Long>builder().putAll(fileState);
            for (Map.Entry<File, Long> entry : prevState.fileState.entrySet()) {
                if (!fileState.containsKey(entry.getKey())) {
                    fileStateBuilder.put(entry);
                }
            }
            nextFileState = fileStateBuilder.build();
        }
        State state = new State();
        state.fileState = nextFileState;
        state.workspaceLanguageSettings = workspaceLanguageSettings;
        state.aspectStrategyName = aspectStrategy.getName();
        Map<TargetKey, TargetIdeInfo> targetMap = Maps.newHashMap();
        if (prevState != null) {
            targetMap.putAll(prevState.targetMap.map());
            state.fileToTargetMapKey.putAll(prevState.fileToTargetMapKey);
        }
        if (!mergeWithOldState) {
            for (File removedFile : removedFiles) {
                TargetKey key = state.fileToTargetMapKey.remove(removedFile);
                if (key != null) {
                    targetMap.remove(key);
                }
            }
        }
        AtomicLong totalSizeLoaded = new AtomicLong(0);
        Set<LanguageClass> ignoredLanguages = Sets.newConcurrentHashSet();
        ListeningExecutorService executor = BlazeExecutor.getInstance().getExecutor();
        List<ListenableFuture<TargetFilePair>> futures = Lists.newArrayList();
        for (File file : newFiles) {
            futures.add(executor.submit(() -> {
                totalSizeLoaded.addAndGet(file.length());
                IntellijIdeInfo.TargetIdeInfo message = aspectStrategy.readAspectFile(file);
                TargetIdeInfo target = protoToTarget(workspaceLanguageSettings, importRoots, message, ignoredLanguages);
                return new TargetFilePair(file, target);
            }));
        }
        Set<TargetKey> newTargets = new HashSet<>();
        Set<String> configurations = new LinkedHashSet<>();
        configurations.add(configHandler.defaultConfigurationPathComponent);
        int duplicateTargetLabels = 0;
        try {
            for (TargetFilePair targetFilePair : Futures.allAsList(futures).get()) {
                if (targetFilePair.target != null) {
                    File file = targetFilePair.file;
                    String config = configHandler.getConfigurationPathComponent(file);
                    configurations.add(config);
                    TargetKey key = targetFilePair.target.key;
                    if (targetMap.putIfAbsent(key, targetFilePair.target) == null) {
                        state.fileToTargetMapKey.forcePut(file, key);
                    } else {
                        if (!newTargets.add(key)) {
                            duplicateTargetLabels++;
                        }
                        if (Objects.equals(config, configHandler.defaultConfigurationPathComponent)) {
                            targetMap.put(key, targetFilePair.target);
                            state.fileToTargetMapKey.forcePut(file, key);
                        }
                    }
                }
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return Result.error(null);
        } catch (ExecutionException e) {
            return Result.error(e);
        }
        context.output(PrintOutput.log(String.format("Loaded %d aspect files, total size %dkB", newFiles.size(), totalSizeLoaded.get() / 1024)));
        if (duplicateTargetLabels > 0) {
            context.output(new PerformanceWarning(String.format("There were %d duplicate rules, built with the following " + "configurations: %s.\nYour IDE sync is slowed down by ~%d%%.", duplicateTargetLabels, configurations, (100 * duplicateTargetLabels / targetMap.size()))));
        }
        ignoredLanguages.retainAll(LanguageSupport.availableAdditionalLanguages(workspaceLanguageSettings.getWorkspaceType()));
        warnIgnoredLanguages(project, context, ignoredLanguages);
        state.targetMap = new TargetMap(ImmutableMap.copyOf(targetMap));
        return Result.of(state);
    });
    if (result.error != null) {
        logger.error(result.error);
        return null;
    }
    return result.result;
}
Also used : ExternalTask(com.google.idea.blaze.base.async.process.ExternalTask) AdditionalLanguagesHelper(com.google.idea.blaze.base.lang.AdditionalLanguagesHelper) Result(com.google.idea.blaze.base.scope.Result) LanguageSupport(com.google.idea.blaze.base.sync.projectview.LanguageSupport) PrefetchService(com.google.idea.blaze.base.prefetch.PrefetchService) ScopedFunction(com.google.idea.blaze.base.scope.ScopedFunction) Map(java.util.Map) TargetExpression(com.google.idea.blaze.base.model.primitives.TargetExpression) FileUtil(com.intellij.openapi.util.io.FileUtil) Logger(com.intellij.openapi.diagnostic.Logger) IntellijIdeInfo(com.google.devtools.intellij.ideinfo.IntellijIdeInfo) FileDiffer(com.google.idea.blaze.base.filecache.FileDiffer) BlazeConsoleLineProcessorProvider(com.google.idea.blaze.base.console.BlazeConsoleLineProcessorProvider) Blaze(com.google.idea.blaze.base.settings.Blaze) BiMap(com.google.common.collect.BiMap) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) AspectStrategy(com.google.idea.blaze.base.sync.aspects.strategy.AspectStrategy) Predicate(java.util.function.Predicate) Collection(java.util.Collection) BuildSystemProvider(com.google.idea.blaze.base.bazel.BuildSystemProvider) FutureUtil(com.google.idea.blaze.base.async.FutureUtil) Set(java.util.Set) WorkspaceLanguageSettings(com.google.idea.blaze.base.sync.projectview.WorkspaceLanguageSettings) BuildResultHelper(com.google.idea.blaze.base.command.buildresult.BuildResultHelper) PrintOutput(com.google.idea.blaze.base.scope.output.PrintOutput) Sets(com.google.common.collect.Sets) Serializable(java.io.Serializable) BlazeCommandName(com.google.idea.blaze.base.command.BlazeCommandName) Objects(java.util.Objects) List(java.util.List) LineProcessingOutputStream(com.google.idea.blaze.base.async.process.LineProcessingOutputStream) Status(com.google.idea.blaze.base.sync.aspects.BuildResult.Status) ProjectViewSet(com.google.idea.blaze.base.projectview.ProjectViewSet) WorkspaceRoot(com.google.idea.blaze.base.model.primitives.WorkspaceRoot) TargetKey(com.google.idea.blaze.base.ideinfo.TargetKey) ShardedTargetList(com.google.idea.blaze.base.sync.sharding.ShardedTargetList) ArtifactLocationDecoder(com.google.idea.blaze.base.sync.workspace.ArtifactLocationDecoder) TargetMap(com.google.idea.blaze.base.ideinfo.TargetMap) Joiner(com.google.common.base.Joiner) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) BlazeContext(com.google.idea.blaze.base.scope.BlazeContext) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) AspectStrategyProvider(com.google.idea.blaze.base.sync.aspects.strategy.AspectStrategyProvider) Function(java.util.function.Function) ArrayList(java.util.ArrayList) NavigatableAdapter(com.intellij.pom.NavigatableAdapter) HashSet(java.util.HashSet) Kind(com.google.idea.blaze.base.model.primitives.Kind) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) BuildSystem(com.google.idea.blaze.base.settings.Blaze.BuildSystem) Scope(com.google.idea.blaze.base.scope.Scope) OutputGroup(com.google.idea.blaze.base.sync.aspects.strategy.AspectStrategy.OutputGroup) IssueOutput(com.google.idea.blaze.base.scope.output.IssueOutput) TargetIdeInfo(com.google.idea.blaze.base.ideinfo.TargetIdeInfo) Project(com.intellij.openapi.project.Project) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) LanguageClass(com.google.idea.blaze.base.model.primitives.LanguageClass) PerformanceWarning(com.google.idea.blaze.base.scope.output.PerformanceWarning) ImportRoots(com.google.idea.blaze.base.sync.projectview.ImportRoots) PrefetchFileSource(com.google.idea.blaze.base.prefetch.PrefetchFileSource) SyncState(com.google.idea.blaze.base.model.SyncState) Maps(com.google.common.collect.Maps) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) BlazeExecutor(com.google.idea.blaze.base.async.executor.BlazeExecutor) AtomicLong(java.util.concurrent.atomic.AtomicLong) HashBiMap(com.google.common.collect.HashBiMap) Futures(com.google.common.util.concurrent.Futures) Ordering(com.google.common.collect.Ordering) BlazeVersionData(com.google.idea.blaze.base.model.BlazeVersionData) BlazeConfigurationHandler(com.google.idea.blaze.base.command.info.BlazeConfigurationHandler) TimingScope(com.google.idea.blaze.base.scope.scopes.TimingScope) BlazeFlags(com.google.idea.blaze.base.command.BlazeFlags) BlazeInvocationContext(com.google.idea.blaze.base.command.BlazeInvocationContext) BlazeCommand(com.google.idea.blaze.base.command.BlazeCommand) EventType(com.google.idea.blaze.base.scope.scopes.TimingScope.EventType) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) ProjectViewSet(com.google.idea.blaze.base.projectview.ProjectViewSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) PerformanceWarning(com.google.idea.blaze.base.scope.output.PerformanceWarning) Result(com.google.idea.blaze.base.scope.Result) TimingScope(com.google.idea.blaze.base.scope.scopes.TimingScope) List(java.util.List) ShardedTargetList(com.google.idea.blaze.base.sync.sharding.ShardedTargetList) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) ExecutionException(java.util.concurrent.ExecutionException) ImmutableMap(com.google.common.collect.ImmutableMap) TargetIdeInfo(com.google.idea.blaze.base.ideinfo.TargetIdeInfo) AtomicLong(java.util.concurrent.atomic.AtomicLong) SyncState(com.google.idea.blaze.base.model.SyncState) IntellijIdeInfo(com.google.devtools.intellij.ideinfo.IntellijIdeInfo) AtomicLong(java.util.concurrent.atomic.AtomicLong) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) TargetKey(com.google.idea.blaze.base.ideinfo.TargetKey) File(java.io.File) Map(java.util.Map) BiMap(com.google.common.collect.BiMap) ImmutableMap(com.google.common.collect.ImmutableMap) TargetMap(com.google.idea.blaze.base.ideinfo.TargetMap) HashBiMap(com.google.common.collect.HashBiMap) TargetMap(com.google.idea.blaze.base.ideinfo.TargetMap) Nullable(javax.annotation.Nullable)

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