Search in sources :

Example 11 with ImmutableMultimap

use of com.google.common.collect.ImmutableMultimap in project presto by prestodb.

the class HiveTableOperations method commit.

@Override
public void commit(@Nullable TableMetadata base, TableMetadata metadata) {
    requireNonNull(metadata, "metadata is null");
    // if the metadata is already out of date, reject it
    if (!Objects.equals(base, current())) {
        throw new CommitFailedException("Cannot commit: stale table metadata for %s", getSchemaTableName());
    }
    // if the metadata is not changed, return early
    if (Objects.equals(base, metadata)) {
        return;
    }
    String newMetadataLocation = writeNewMetadata(metadata, version + 1);
    Table table;
    // getting a process-level lock per table to avoid concurrent commit attempts to the same table from the same
    // JVM process, which would result in unnecessary and costly HMS lock acquisition requests
    Optional<Long> lockId = Optional.empty();
    ReentrantLock tableLevelMutex = commitLockCache.getUnchecked(database + "." + tableName);
    tableLevelMutex.lock();
    try {
        try {
            lockId = Optional.of(metastore.lock(metastoreContext, database, tableName));
            if (base == null) {
                String tableComment = metadata.properties().get(TABLE_COMMENT);
                Map<String, String> parameters = new HashMap<>();
                parameters.put("EXTERNAL", "TRUE");
                parameters.put(TABLE_TYPE_PROP, ICEBERG_TABLE_TYPE_VALUE);
                parameters.put(METADATA_LOCATION, newMetadataLocation);
                if (tableComment != null) {
                    parameters.put(TABLE_COMMENT, tableComment);
                }
                Table.Builder builder = Table.builder().setDatabaseName(database).setTableName(tableName).setOwner(owner.orElseThrow(() -> new IllegalStateException("Owner not set"))).setTableType(PrestoTableType.EXTERNAL_TABLE).setDataColumns(toHiveColumns(metadata.schema().columns())).withStorage(storage -> storage.setLocation(metadata.location())).withStorage(storage -> storage.setStorageFormat(STORAGE_FORMAT)).setParameters(parameters);
                table = builder.build();
            } else {
                Table currentTable = getTable();
                checkState(currentMetadataLocation != null, "No current metadata location for existing table");
                String metadataLocation = currentTable.getParameters().get(METADATA_LOCATION);
                if (!currentMetadataLocation.equals(metadataLocation)) {
                    throw new CommitFailedException("Metadata location [%s] is not same as table metadata location [%s] for %s", currentMetadataLocation, metadataLocation, getSchemaTableName());
                }
                table = Table.builder(currentTable).setDataColumns(toHiveColumns(metadata.schema().columns())).withStorage(storage -> storage.setLocation(metadata.location())).setParameter(METADATA_LOCATION, newMetadataLocation).setParameter(PREVIOUS_METADATA_LOCATION, currentMetadataLocation).build();
            }
        } catch (RuntimeException e) {
            try {
                io().deleteFile(newMetadataLocation);
            } catch (RuntimeException exception) {
                e.addSuppressed(exception);
            }
            throw e;
        }
        PrestoPrincipal owner = new PrestoPrincipal(USER, table.getOwner());
        PrincipalPrivileges privileges = new PrincipalPrivileges(ImmutableMultimap.<String, HivePrivilegeInfo>builder().put(table.getOwner(), new HivePrivilegeInfo(SELECT, true, owner, owner)).put(table.getOwner(), new HivePrivilegeInfo(INSERT, true, owner, owner)).put(table.getOwner(), new HivePrivilegeInfo(UPDATE, true, owner, owner)).put(table.getOwner(), new HivePrivilegeInfo(DELETE, true, owner, owner)).build(), ImmutableMultimap.of());
        if (base == null) {
            metastore.createTable(metastoreContext, table, privileges);
        } else {
            metastore.replaceTable(metastoreContext, database, tableName, table, privileges);
        }
    } finally {
        shouldRefresh = true;
        try {
            lockId.ifPresent(id -> metastore.unlock(metastoreContext, id));
        } catch (Exception e) {
            log.error(e, "Failed to unlock: %s", lockId.orElse(null));
        } finally {
            tableLevelMutex.unlock();
        }
    }
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) HdfsEnvironment(com.facebook.presto.hive.HdfsEnvironment) LocationProviders(org.apache.iceberg.LocationProviders) LoadingCache(com.google.common.cache.LoadingCache) IcebergUtil.isIcebergTable(com.facebook.presto.iceberg.IcebergUtil.isIcebergTable) PrestoPrincipal(com.facebook.presto.spi.security.PrestoPrincipal) HiveSchemaUtil(org.apache.iceberg.hive.HiveSchemaUtil) MetastoreContext(com.facebook.presto.hive.metastore.MetastoreContext) ICEBERG_TABLE_TYPE_VALUE(org.apache.iceberg.BaseMetastoreTableOperations.ICEBERG_TABLE_TYPE_VALUE) TABLE_TYPE_PROP(org.apache.iceberg.BaseMetastoreTableOperations.TABLE_TYPE_PROP) TableMetadata(org.apache.iceberg.TableMetadata) LocationProvider(org.apache.iceberg.io.LocationProvider) TableOperations(org.apache.iceberg.TableOperations) SchemaTableName(com.facebook.presto.spi.SchemaTableName) ExtendedHiveMetastore(com.facebook.presto.hive.metastore.ExtendedHiveMetastore) Map(java.util.Map) ICEBERG_INVALID_METADATA(com.facebook.presto.iceberg.IcebergErrorCode.ICEBERG_INVALID_METADATA) HdfsContext(com.facebook.presto.hive.HdfsContext) TableMetadataParser(org.apache.iceberg.TableMetadataParser) CommitFailedException(org.apache.iceberg.exceptions.CommitFailedException) StorageFormat(com.facebook.presto.hive.metastore.StorageFormat) PrincipalPrivileges(com.facebook.presto.hive.metastore.PrincipalPrivileges) FileInputFormat(org.apache.hadoop.mapred.FileInputFormat) NestedField(org.apache.iceberg.types.Types.NestedField) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) SELECT(com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege.SELECT) String.format(java.lang.String.format) Preconditions.checkState(com.google.common.base.Preconditions.checkState) CacheLoader(com.google.common.cache.CacheLoader) Objects(java.util.Objects) List(java.util.List) PrestoTableType(com.facebook.presto.hive.metastore.PrestoTableType) Optional(java.util.Optional) HivePrivilegeInfo(com.facebook.presto.hive.metastore.HivePrivilegeInfo) CacheBuilder(com.google.common.cache.CacheBuilder) FileOutputFormat(org.apache.hadoop.mapred.FileOutputFormat) TableMetadataParser.getFileExtension(org.apache.iceberg.TableMetadataParser.getFileExtension) Logger(com.facebook.airlift.log.Logger) Table(com.facebook.presto.hive.metastore.Table) Column(com.facebook.presto.hive.metastore.Column) HiveType(com.facebook.presto.hive.HiveType) WRITE_METADATA_LOCATION(org.apache.iceberg.TableProperties.WRITE_METADATA_LOCATION) OutputFile(org.apache.iceberg.io.OutputFile) HashMap(java.util.HashMap) PrestoException(com.facebook.presto.spi.PrestoException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Objects.requireNonNull(java.util.Objects.requireNonNull) TABLE_COMMENT(com.facebook.presto.hive.HiveMetadata.TABLE_COMMENT) METADATA_COMPRESSION_DEFAULT(org.apache.iceberg.TableProperties.METADATA_COMPRESSION_DEFAULT) DELETE(com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege.DELETE) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) Nullable(javax.annotation.Nullable) USER(com.facebook.presto.spi.security.PrincipalType.USER) INSERT(com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege.INSERT) UPDATE(com.facebook.presto.hive.metastore.HivePrivilegeInfo.HivePrivilege.UPDATE) METADATA_COMPRESSION(org.apache.iceberg.TableProperties.METADATA_COMPRESSION) ReentrantLock(java.util.concurrent.locks.ReentrantLock) LazySimpleSerDe(org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe) Integer.parseInt(java.lang.Integer.parseInt) TimeUnit(java.util.concurrent.TimeUnit) UUID.randomUUID(java.util.UUID.randomUUID) TableNotFoundException(com.facebook.presto.spi.TableNotFoundException) Tasks(org.apache.iceberg.util.Tasks) FileIO(org.apache.iceberg.io.FileIO) NotThreadSafe(javax.annotation.concurrent.NotThreadSafe) HivePrivilegeInfo(com.facebook.presto.hive.metastore.HivePrivilegeInfo) IcebergUtil.isIcebergTable(com.facebook.presto.iceberg.IcebergUtil.isIcebergTable) Table(com.facebook.presto.hive.metastore.Table) PrincipalPrivileges(com.facebook.presto.hive.metastore.PrincipalPrivileges) HashMap(java.util.HashMap) CommitFailedException(org.apache.iceberg.exceptions.CommitFailedException) PrestoException(com.facebook.presto.spi.PrestoException) TableNotFoundException(com.facebook.presto.spi.TableNotFoundException) CommitFailedException(org.apache.iceberg.exceptions.CommitFailedException) PrestoPrincipal(com.facebook.presto.spi.security.PrestoPrincipal)

Example 12 with ImmutableMultimap

use of com.google.common.collect.ImmutableMultimap in project presto by prestodb.

the class JoinGraph method joinWith.

private JoinGraph joinWith(JoinGraph other, List<JoinNode.EquiJoinClause> joinClauses, Context context, PlanNodeId newRoot) {
    for (PlanNode node : other.nodes) {
        checkState(!edges.containsKey(node.getId()), format("Node [%s] appeared in two JoinGraphs", node));
    }
    List<PlanNode> nodes = ImmutableList.<PlanNode>builder().addAll(this.nodes).addAll(other.nodes).build();
    ImmutableMultimap.Builder<PlanNodeId, Edge> edges = ImmutableMultimap.<PlanNodeId, Edge>builder().putAll(this.edges).putAll(other.edges);
    List<RowExpression> joinedFilters = ImmutableList.<RowExpression>builder().addAll(this.filters).addAll(other.filters).build();
    for (JoinNode.EquiJoinClause edge : joinClauses) {
        VariableReferenceExpression leftVariable = edge.getLeft();
        VariableReferenceExpression rightVariable = edge.getRight();
        checkState(context.containsVariable(leftVariable));
        checkState(context.containsVariable(rightVariable));
        PlanNode left = context.getVariableSource(leftVariable);
        PlanNode right = context.getVariableSource(rightVariable);
        edges.put(left.getId(), new Edge(right, leftVariable, rightVariable));
        edges.put(right.getId(), new Edge(left, rightVariable, leftVariable));
    }
    return new JoinGraph(nodes, edges.build(), newRoot, joinedFilters, Optional.empty());
}
Also used : PlanNodeId(com.facebook.presto.spi.plan.PlanNodeId) PlanNode(com.facebook.presto.spi.plan.PlanNode) JoinNode(com.facebook.presto.sql.planner.plan.JoinNode) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) RowExpression(com.facebook.presto.spi.relation.RowExpression) ImmutableMultimap(com.google.common.collect.ImmutableMultimap)

Example 13 with ImmutableMultimap

use of com.google.common.collect.ImmutableMultimap in project presto by prestodb.

the class PlanRemotePojections method dedupVariables.

private static List<ProjectionContext> dedupVariables(List<ProjectionContext> projectionContexts) {
    ImmutableList.Builder<ProjectionContext> deduppedProjectionContexts = ImmutableList.builder();
    Set<VariableReferenceExpression> originalVariable = projectionContexts.get(projectionContexts.size() - 1).getProjections().keySet();
    SymbolMapper mapper = null;
    for (int i = 0; i < projectionContexts.size(); i++) {
        Map<VariableReferenceExpression, RowExpression> projections = projectionContexts.get(i).getProjections();
        // Apply mapping from previous projection
        if (mapper != null) {
            ImmutableMap.Builder<VariableReferenceExpression, RowExpression> newProjections = ImmutableMap.builder();
            for (Map.Entry<VariableReferenceExpression, RowExpression> entry : projections.entrySet()) {
                newProjections.put(entry.getKey(), mapper.map(entry.getValue()));
            }
            projections = newProjections.build();
        }
        // Dedup
        ImmutableMultimap.Builder<RowExpression, VariableReferenceExpression> reverseProjectionsBuilder = ImmutableMultimap.builder();
        projections.forEach((key, value) -> reverseProjectionsBuilder.put(value, key));
        ImmutableMultimap<RowExpression, VariableReferenceExpression> reverseProjections = reverseProjectionsBuilder.build();
        if (reverseProjections.keySet().size() == projectionContexts.get(i).getProjections().size() && reverseProjections.keySet().stream().noneMatch(VariableReferenceExpression.class::isInstance)) {
            // No duplication
            deduppedProjectionContexts.add(new ProjectionContext(projections, projectionContexts.get(i).isRemote()));
            mapper = null;
        } else {
            SymbolMapper.Builder mapperBuilder = SymbolMapper.builder();
            ImmutableMap.Builder<VariableReferenceExpression, RowExpression> dedupedProjectionsBuilder = ImmutableMap.builder();
            for (RowExpression key : reverseProjections.keySet()) {
                List<VariableReferenceExpression> values = ImmutableList.copyOf(reverseProjections.get(key));
                if (key instanceof VariableReferenceExpression) {
                    values.forEach(variable -> mapperBuilder.put(variable, (VariableReferenceExpression) key));
                    dedupedProjectionsBuilder.put((VariableReferenceExpression) key, key);
                } else if (values.size() > 1) {
                    // Consolidate to one variable, prefer variables from original plan
                    List<VariableReferenceExpression> fromOriginal = originalVariable.stream().filter(values::contains).collect(toImmutableList());
                    VariableReferenceExpression variable = fromOriginal.isEmpty() ? values.get(0) : getOnlyElement(fromOriginal);
                    for (int j = 0; j < values.size(); j++) {
                        if (!values.get(j).equals(variable)) {
                            mapperBuilder.put(values.get(j), variable);
                        }
                    }
                    dedupedProjectionsBuilder.put(variable, key);
                } else {
                    checkState(values.size() == 1, "Expect only 1 value");
                    dedupedProjectionsBuilder.put(values.get(0), key);
                }
            }
            deduppedProjectionContexts.add(new ProjectionContext(dedupedProjectionsBuilder.build(), projectionContexts.get(i).isRemote()));
            mapper = mapperBuilder.build();
        }
    }
    return deduppedProjectionContexts.build();
}
Also used : SymbolMapper(com.facebook.presto.sql.planner.optimizations.SymbolMapper) ImmutableList(com.google.common.collect.ImmutableList) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) RowExpression(com.facebook.presto.spi.relation.RowExpression) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) VariableReferenceExpression(com.facebook.presto.spi.relation.VariableReferenceExpression) ImmutableList(com.google.common.collect.ImmutableList) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) List(java.util.List) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap)

Example 14 with ImmutableMultimap

use of com.google.common.collect.ImmutableMultimap in project querydsl by querydsl.

the class GroupBy4Test method test6.

@Test
public void test6() {
    List<Table> data = Lists.newArrayList();
    data.add(new Table("1", "abc", "111"));
    data.add(new Table("1", "pqr", "222"));
    data.add(new Table("2", "abc", "333"));
    data.add(new Table("2", "pqr", "444"));
    data.add(new Table("3", "abc", "555"));
    data.add(new Table("3", "pqr", "666"));
    data.add(new Table("3", "pqr", "777"));
    QGroupBy4Test_Table table = QGroupBy4Test_Table.table;
    Map<String, Multimap<String, String>> transform = CollQueryFactory.from(table, data).transform(groupBy(table.col1).as(GuavaGroupBy.multimap(table.col2, table.col3)));
    ImmutableMap<String, Multimap<String, String>> expected = ImmutableMap.<String, Multimap<String, String>>builder().put("1", HashMultimap.create(ImmutableMultimap.<String, String>builder().putAll("abc", "111").putAll("pqr", "222").build())).put("2", HashMultimap.create(ImmutableMultimap.<String, String>builder().putAll("abc", "333").putAll("pqr", "444").build())).put("3", HashMultimap.create(ImmutableMultimap.<String, String>builder().putAll("abc", "555").putAll("pqr", "666", "777").build())).build();
    assertEquals(expected, transform);
}
Also used : Multimap(com.google.common.collect.Multimap) HashMultimap(com.google.common.collect.HashMultimap) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) ImmutableTable(com.google.common.collect.ImmutableTable) Test(org.junit.Test)

Example 15 with ImmutableMultimap

use of com.google.common.collect.ImmutableMultimap in project cassandra by apache.

the class NetworkTopologyStrategyTest method calculateNaturalEndpoints.

// Copy of older endpoints calculation algorithm for comparison
public static List<InetAddressAndPort> calculateNaturalEndpoints(Token searchToken, TokenMetadata tokenMetadata, Map<String, Integer> datacenters, IEndpointSnitch snitch) {
    // we want to preserve insertion order so that the first added endpoint becomes primary
    Set<InetAddressAndPort> replicas = new LinkedHashSet<>();
    // replicas we have found in each DC
    Map<String, Set<InetAddressAndPort>> dcReplicas = new HashMap<>(datacenters.size());
    for (Map.Entry<String, Integer> dc : datacenters.entrySet()) dcReplicas.put(dc.getKey(), new HashSet<InetAddressAndPort>(dc.getValue()));
    Topology topology = tokenMetadata.getTopology();
    // all endpoints in each DC, so we can check when we have exhausted all the members of a DC
    Multimap<String, InetAddressAndPort> allEndpoints = topology.getDatacenterEndpoints();
    // all racks in a DC so we can check when we have exhausted all racks in a DC
    Map<String, ImmutableMultimap<String, InetAddressAndPort>> racks = topology.getDatacenterRacks();
    assert !allEndpoints.isEmpty() && !racks.isEmpty() : "not aware of any cluster members";
    // tracks the racks we have already placed replicas in
    Map<String, Set<String>> seenRacks = new HashMap<>(datacenters.size());
    for (Map.Entry<String, Integer> dc : datacenters.entrySet()) seenRacks.put(dc.getKey(), new HashSet<String>());
    // tracks the endpoints that we skipped over while looking for unique racks
    // when we relax the rack uniqueness we can append this to the current result so we don't have to wind back the iterator
    Map<String, Set<InetAddressAndPort>> skippedDcEndpoints = new HashMap<>(datacenters.size());
    for (Map.Entry<String, Integer> dc : datacenters.entrySet()) skippedDcEndpoints.put(dc.getKey(), new LinkedHashSet<InetAddressAndPort>());
    Iterator<Token> tokenIter = TokenMetadata.ringIterator(tokenMetadata.sortedTokens(), searchToken, false);
    while (tokenIter.hasNext() && !hasSufficientReplicas(dcReplicas, allEndpoints, datacenters)) {
        Token next = tokenIter.next();
        InetAddressAndPort ep = tokenMetadata.getEndpoint(next);
        String dc = snitch.getDatacenter(ep);
        // have we already found all replicas for this dc?
        if (!datacenters.containsKey(dc) || hasSufficientReplicas(dc, dcReplicas, allEndpoints, datacenters))
            continue;
        // can we skip checking the rack?
        if (seenRacks.get(dc).size() == racks.get(dc).keySet().size()) {
            dcReplicas.get(dc).add(ep);
            replicas.add(ep);
        } else {
            String rack = snitch.getRack(ep);
            // is this a new rack?
            if (seenRacks.get(dc).contains(rack)) {
                skippedDcEndpoints.get(dc).add(ep);
            } else {
                dcReplicas.get(dc).add(ep);
                replicas.add(ep);
                seenRacks.get(dc).add(rack);
                // if we've run out of distinct racks, add the hosts we skipped past already (up to RF)
                if (seenRacks.get(dc).size() == racks.get(dc).keySet().size()) {
                    Iterator<InetAddressAndPort> skippedIt = skippedDcEndpoints.get(dc).iterator();
                    while (skippedIt.hasNext() && !hasSufficientReplicas(dc, dcReplicas, allEndpoints, datacenters)) {
                        InetAddressAndPort nextSkipped = skippedIt.next();
                        dcReplicas.get(dc).add(nextSkipped);
                        replicas.add(nextSkipped);
                    }
                }
            }
        }
    }
    return new ArrayList<InetAddressAndPort>(replicas);
}
Also used : LongToken(org.apache.cassandra.dht.Murmur3Partitioner.LongToken) StringToken(org.apache.cassandra.dht.OrderPreservingPartitioner.StringToken) Token(org.apache.cassandra.dht.Token) Topology(org.apache.cassandra.locator.TokenMetadata.Topology) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) ImmutableMap(com.google.common.collect.ImmutableMap)

Aggregations

ImmutableMultimap (com.google.common.collect.ImmutableMultimap)30 Path (java.nio.file.Path)9 ImmutableMap (com.google.common.collect.ImmutableMap)8 ImmutableSet (com.google.common.collect.ImmutableSet)7 Map (java.util.Map)6 BuildTarget (com.facebook.buck.model.BuildTarget)4 ImmutableList (com.google.common.collect.ImmutableList)4 SourcePath (com.facebook.buck.rules.SourcePath)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)3 Multimap (com.google.common.collect.Multimap)3 IOException (java.io.IOException)3 List (java.util.List)3 ClasspathTraversal (com.facebook.buck.jvm.java.classes.ClasspathTraversal)2 ClasspathTraverser (com.facebook.buck.jvm.java.classes.ClasspathTraverser)2 DefaultClasspathTraverser (com.facebook.buck.jvm.java.classes.DefaultClasspathTraverser)2 FileLike (com.facebook.buck.jvm.java.classes.FileLike)2 UnflavoredBuildTarget (com.facebook.buck.model.UnflavoredBuildTarget)2 Column (com.facebook.presto.hive.metastore.Column)2 ExtendedHiveMetastore (com.facebook.presto.hive.metastore.ExtendedHiveMetastore)2 HivePrivilegeInfo (com.facebook.presto.hive.metastore.HivePrivilegeInfo)2