Search in sources :

Example 41 with Multimap

use of com.google.common.collect.Multimap in project crate by crate.

the class SQLTransportIntegrationTest method assertNoJobExecutionContextAreLeftOpen.

@After
public void assertNoJobExecutionContextAreLeftOpen() throws Exception {
    final Field activeContexts = JobContextService.class.getDeclaredField("activeContexts");
    final Field activeOperationsSb = TransportShardAction.class.getDeclaredField("activeOperations");
    activeContexts.setAccessible(true);
    activeOperationsSb.setAccessible(true);
    try {
        assertBusy(new Runnable() {

            @Override
            public void run() {
                for (JobContextService jobContextService : internalCluster().getInstances(JobContextService.class)) {
                    try {
                        //noinspection unchecked
                        Map<UUID, JobExecutionContext> contexts = (Map<UUID, JobExecutionContext>) activeContexts.get(jobContextService);
                        assertThat(contexts.size(), is(0));
                    } catch (IllegalAccessException e) {
                        throw Throwables.propagate(e);
                    }
                }
                for (TransportShardUpsertAction action : internalCluster().getInstances(TransportShardUpsertAction.class)) {
                    try {
                        Multimap<UUID, KillableCallable> operations = (Multimap<UUID, KillableCallable>) activeOperationsSb.get(action);
                        assertThat(operations.size(), is(0));
                    } catch (IllegalAccessException e) {
                        throw Throwables.propagate(e);
                    }
                }
                for (TransportShardDeleteAction action : internalCluster().getInstances(TransportShardDeleteAction.class)) {
                    try {
                        Multimap<UUID, KillableCallable> operations = (Multimap<UUID, KillableCallable>) activeOperationsSb.get(action);
                        assertThat(operations.size(), is(0));
                    } catch (IllegalAccessException e) {
                        throw Throwables.propagate(e);
                    }
                }
            }
        }, 10L, TimeUnit.SECONDS);
    } catch (AssertionError e) {
        StringBuilder errorMessageBuilder = new StringBuilder();
        String[] nodeNames = internalCluster().getNodeNames();
        for (String nodeName : nodeNames) {
            JobContextService jobContextService = internalCluster().getInstance(JobContextService.class, nodeName);
            try {
                //noinspection unchecked
                Map<UUID, JobExecutionContext> contexts = (Map<UUID, JobExecutionContext>) activeContexts.get(jobContextService);
                String contextsString = contexts.toString();
                if (!"{}".equals(contextsString)) {
                    errorMessageBuilder.append("## node: ");
                    errorMessageBuilder.append(nodeName);
                    errorMessageBuilder.append("\n");
                    errorMessageBuilder.append(contextsString);
                    errorMessageBuilder.append("\n");
                }
                contexts.clear();
            } catch (IllegalAccessException ex) {
                throw Throwables.propagate(e);
            }
        }
        throw new AssertionError(errorMessageBuilder.toString(), e);
    }
}
Also used : TransportShardUpsertAction(io.crate.executor.transport.TransportShardUpsertAction) TransportShardDeleteAction(io.crate.executor.transport.TransportShardDeleteAction) KillableCallable(io.crate.executor.transport.kill.KillableCallable) Field(java.lang.reflect.Field) Multimap(com.google.common.collect.Multimap) JobExecutionContext(io.crate.jobs.JobExecutionContext) JobContextService(io.crate.jobs.JobContextService) After(org.junit.After)

Example 42 with Multimap

use of com.google.common.collect.Multimap in project crate by crate.

the class PlannerTest method testAllocateRouting.

@Test
public void testAllocateRouting() throws Exception {
    TableIdent custom = new TableIdent("custom", "t1");
    TableInfo tableInfo1 = TestingTableInfo.builder(custom, shardRouting("t1")).add("id", DataTypes.INTEGER, null).build();
    TableInfo tableInfo2 = TestingTableInfo.builder(custom, shardRoutingForReplicas("t1")).add("id", DataTypes.INTEGER, null).build();
    Planner.Context plannerContext = new Planner.Context(e.planner, clusterService, UUID.randomUUID(), null, normalizer, new TransactionContext(SessionContext.SYSTEM_SESSION), 0, 0);
    WhereClause whereClause = new WhereClause(new Function(new FunctionInfo(new FunctionIdent(EqOperator.NAME, Arrays.<DataType>asList(DataTypes.INTEGER, DataTypes.INTEGER)), DataTypes.BOOLEAN), Arrays.asList(tableInfo1.getReference(new ColumnIdent("id")), Literal.of(2))));
    plannerContext.allocateRouting(tableInfo1, WhereClause.MATCH_ALL, null);
    plannerContext.allocateRouting(tableInfo2, whereClause, null);
    // 2 routing allocations with different where clause must result in 2 allocated routings
    java.lang.reflect.Field tableRoutings = Planner.Context.class.getDeclaredField("tableRoutings");
    tableRoutings.setAccessible(true);
    Multimap<TableIdent, Planner.TableRouting> routing = (Multimap<TableIdent, Planner.TableRouting>) tableRoutings.get(plannerContext);
    assertThat(routing.size(), is(2));
    // The routings must be the same after merging the locations
    Iterator<Planner.TableRouting> iterator = routing.values().iterator();
    Routing routing1 = iterator.next().routing;
    Routing routing2 = iterator.next().routing;
    assertThat(routing1, is(routing2));
}
Also used : SessionContext(io.crate.action.sql.SessionContext) WhereClause(io.crate.analyze.WhereClause) TableDefinitions.shardRouting(io.crate.analyze.TableDefinitions.shardRouting) Function(io.crate.analyze.symbol.Function) Multimap(com.google.common.collect.Multimap) DataType(io.crate.types.DataType) TableInfo(io.crate.metadata.table.TableInfo) TestingTableInfo(io.crate.metadata.table.TestingTableInfo) Test(org.junit.Test) CrateUnitTest(io.crate.test.integration.CrateUnitTest)

Example 43 with Multimap

use of com.google.common.collect.Multimap in project atlas by alibaba.

the class PrepareSoLibTask method generate.

/**
     * 生成so的目录
     */
@TaskAction
void generate() {
    List<File> scanDirs = new ArrayList<File>();
    //先生成主bundle的jnifolder目录
    if (!getMainBundleOutputFolder().exists()) {
        getMainBundleOutputFolder().mkdirs();
    }
    for (File jniFolder : getJniFolders()) {
        if (jniFolder.exists() && jniFolder.isDirectory()) {
            NativeSoUtils.copyLocalNativeLibraries(jniFolder, getMainBundleOutputFolder(), getSupportAbis(), getRemoveSoFiles(), getILogger());
        }
    }
    scanDirs.add(getMainBundleOutputFolder());
    //增加主bundle依赖的solib的so
    for (SoLibrary mainSoLib : getMainDexSoLibraries()) {
        File explodeFolder = mainSoLib.getFolder();
        if (explodeFolder.exists() && explodeFolder.isDirectory()) {
            NativeSoUtils.copyLocalNativeLibraries(explodeFolder, getMainBundleOutputFolder(), getSupportAbis(), getRemoveSoFiles(), getILogger());
        }
    }
    //处理awb bundle的so
    for (AwbBundle awbLib : getAwbLibs()) {
        File awbOutputFolder = new File(appVariantOutputContext.getAwbJniFolder(awbLib), "lib");
        awbOutputFolder.mkdirs();
        scanDirs.add(awbOutputFolder);
        File awbJniFolder = awbLib.getJniFolder();
        if (awbJniFolder.exists() && awbJniFolder.isDirectory()) {
            NativeSoUtils.copyLocalNativeLibraries(awbJniFolder, awbOutputFolder, getSupportAbis(), getRemoveSoFiles(), getILogger());
        }
        //为了兼容之前老的aar,awb格式
        File libJniFolder = new File(awbLib.getFolder(), "libs");
        if (libJniFolder.exists() && libJniFolder.isDirectory()) {
            NativeSoUtils.copyLocalNativeLibraries(libJniFolder, awbOutputFolder, getSupportAbis(), getRemoveSoFiles(), getILogger());
        }
        List<? extends AndroidLibrary> deps = awbLib.getLibraryDependencies();
        for (AndroidLibrary dep : deps) {
            File depJniFolder = dep.getJniFolder();
            if (depJniFolder.exists() && depJniFolder.isDirectory()) {
                NativeSoUtils.copyLocalNativeLibraries(depJniFolder, awbOutputFolder, getSupportAbis(), getRemoveSoFiles(), getILogger());
            }
            //为了兼容之前老的aar,awb格式
            File depLibsFolder = new File(dep.getFolder(), "libs");
            if (depLibsFolder.exists() && depLibsFolder.isDirectory()) {
                NativeSoUtils.copyLocalNativeLibraries(depLibsFolder, awbOutputFolder, getSupportAbis(), getRemoveSoFiles(), getILogger());
            }
        }
        List<SoLibrary> solibs = awbLib.getSoLibraries();
        if (null != solibs) {
            for (SoLibrary solib : solibs) {
                File explodeFolder = solib.getFolder();
                if (explodeFolder.exists() && explodeFolder.isDirectory()) {
                    NativeSoUtils.copyLocalNativeLibraries(explodeFolder, awbOutputFolder, getSupportAbis(), getRemoveSoFiles(), getILogger());
                }
            }
        }
    }
    //判断是否有重复的so文件
    // 进行重复文件的查询
    Map<String, Multimap<String, File>> soMaps = NativeSoUtils.getAbiSoFiles(getSupportAbis(), getRemoveSoFiles(), scanDirs);
    boolean hasDup = false;
    for (Map.Entry<String, Multimap<String, File>> entry : soMaps.entrySet()) {
        String abi = entry.getKey();
        Multimap<String, File> soFiles = soMaps.get(abi);
        for (String soKey : soFiles.keys()) {
            if (soFiles.get(soKey).size() > 1) {
                getILogger().warning("[SO Duplicate][" + abi + "]:" + StringUtils.join(soFiles.get(soKey), ","));
                hasDup = true;
            } else {
                getILogger().verbose("[SO][" + abi + "]:" + StringUtils.join(soFiles.get(soKey), ","));
            }
        }
    }
//        if (hasDup && getFailOnDuplicateSo()) {
//            throw new RuntimeException("SO file has duplicate files!See detail info!");
//        }
}
Also used : SoLibrary(com.taobao.android.builder.dependency.model.SoLibrary) Multimap(com.google.common.collect.Multimap) AndroidLibrary(com.android.builder.model.AndroidLibrary) AwbBundle(com.taobao.android.builder.dependency.model.AwbBundle) File(java.io.File) MtlBaseTaskAction(com.taobao.android.builder.tasks.manager.MtlBaseTaskAction) TaskAction(org.gradle.api.tasks.TaskAction)

Example 44 with Multimap

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

the class BucketBalancer method computeAssignmentChanges.

private static Multimap<String, BucketAssignment> computeAssignmentChanges(ClusterState clusterState) {
    Multimap<String, BucketAssignment> sourceToAllocationChanges = HashMultimap.create();
    Map<String, Long> allocationBytes = new HashMap<>(clusterState.getAssignedBytes());
    Set<String> activeNodes = clusterState.getActiveNodes();
    for (Distribution distribution : clusterState.getDistributionAssignments().keySet()) {
        // number of buckets in this distribution assigned to a node
        Multiset<String> allocationCounts = HashMultiset.create();
        Collection<BucketAssignment> distributionAssignments = clusterState.getDistributionAssignments().get(distribution);
        distributionAssignments.stream().map(BucketAssignment::getNodeIdentifier).forEach(allocationCounts::add);
        int currentMin = allocationBytes.keySet().stream().mapToInt(allocationCounts::count).min().getAsInt();
        int currentMax = allocationBytes.keySet().stream().mapToInt(allocationCounts::count).max().getAsInt();
        int numBuckets = distributionAssignments.size();
        int targetMin = (int) Math.floor((numBuckets * 1.0) / clusterState.getActiveNodes().size());
        int targetMax = (int) Math.ceil((numBuckets * 1.0) / clusterState.getActiveNodes().size());
        log.info("Distribution %s: Current bucket skew: min %s, max %s. Target bucket skew: min %s, max %s", distribution.getId(), currentMin, currentMax, targetMin, targetMax);
        for (String source : ImmutableSet.copyOf(allocationCounts)) {
            List<BucketAssignment> existingAssignments = distributionAssignments.stream().filter(assignment -> assignment.getNodeIdentifier().equals(source)).collect(toList());
            for (BucketAssignment existingAssignment : existingAssignments) {
                if (activeNodes.contains(source) && allocationCounts.count(source) <= targetMin) {
                    break;
                }
                // identify nodes with bucket counts lower than the computed target, and greedily select from this set based on projected disk utilization.
                // greediness means that this may produce decidedly non-optimal results if one looks at the global distribution of buckets->nodes.
                // also, this assumes that nodes in a cluster have identical storage capacity
                String target = activeNodes.stream().filter(candidate -> !candidate.equals(source) && allocationCounts.count(candidate) < targetMax).sorted(comparingInt(allocationCounts::count)).min(Comparator.comparingDouble(allocationBytes::get)).orElseThrow(() -> new VerifyException("unable to find target for rebalancing"));
                long bucketSize = clusterState.getDistributionBucketSize().get(distribution);
                // only move bucket if it reduces imbalance
                if (activeNodes.contains(source) && (allocationCounts.count(source) == targetMax && allocationCounts.count(target) == targetMin)) {
                    break;
                }
                allocationCounts.remove(source);
                allocationCounts.add(target);
                allocationBytes.compute(source, (k, v) -> v - bucketSize);
                allocationBytes.compute(target, (k, v) -> v + bucketSize);
                sourceToAllocationChanges.put(existingAssignment.getNodeIdentifier(), new BucketAssignment(existingAssignment.getDistributionId(), existingAssignment.getBucketNumber(), target));
            }
        }
    }
    return sourceToAllocationChanges;
}
Also used : Nested(org.weakref.jmx.Nested) NodeSupplier(com.facebook.presto.raptor.NodeSupplier) Logger(io.airlift.log.Logger) Multiset(com.google.common.collect.Multiset) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CounterStat(io.airlift.stats.CounterStat) HashMap(java.util.HashMap) Multimap(com.google.common.collect.Multimap) Duration(io.airlift.units.Duration) Inject(javax.inject.Inject) PreDestroy(javax.annotation.PreDestroy) Executors.newSingleThreadScheduledExecutor(java.util.concurrent.Executors.newSingleThreadScheduledExecutor) HashMultimap(com.google.common.collect.HashMultimap) Node(com.facebook.presto.spi.Node) Managed(org.weakref.jmx.Managed) Collectors.toMap(java.util.stream.Collectors.toMap) HashMultiset(com.google.common.collect.HashMultiset) Threads.daemonThreadsNamed(io.airlift.concurrent.Threads.daemonThreadsNamed) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ShardManager(com.facebook.presto.raptor.metadata.ShardManager) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) BackupService(com.facebook.presto.raptor.backup.BackupService) Collectors.toSet(java.util.stream.Collectors.toSet) VerifyException(com.google.common.base.VerifyException) Distribution(com.facebook.presto.raptor.metadata.Distribution) Comparator.comparingInt(java.util.Comparator.comparingInt) ImmutableSet(com.google.common.collect.ImmutableSet) NodeManager(com.facebook.presto.spi.NodeManager) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) Set(java.util.Set) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) BucketNode(com.facebook.presto.raptor.metadata.BucketNode) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) RaptorConnectorId(com.facebook.presto.raptor.RaptorConnectorId) PostConstruct(javax.annotation.PostConstruct) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Comparator(java.util.Comparator) HashMap(java.util.HashMap) VerifyException(com.google.common.base.VerifyException) Distribution(com.facebook.presto.raptor.metadata.Distribution)

Example 45 with Multimap

use of com.google.common.collect.Multimap in project torodb by torodb.

the class AbstractReadInterface method getCollectionDidsWithFieldsInBatch.

@SuppressFBWarnings(value = { "OBL_UNSATISFIED_OBLIGATION", "ODR_OPEN_DATABASE_RESOURCE" }, justification = "ResultSet is wrapped in a Cursor<Integer>. It's iterated and closed in caller code")
private Cursor<Integer> getCollectionDidsWithFieldsInBatch(DSLContext dsl, MetaDatabase metaDatabase, MetaCollection metaCol, MetaDocPart metaDocPart, Multimap<MetaField, KvValue<?>> valuesMultimap) throws SQLException {
    @SuppressWarnings("checkstyle:LineLength") Provider<Stream<Map.Entry<MetaField, Collection<KvValue<?>>>>> valuesMultimapSortedStreamProvider = () -> valuesMultimap.asMap().entrySet().stream().sorted((e1, e2) -> e1.getKey().getIdentifier().compareTo(e2.getKey().getIdentifier()));
    String statement = getReadCollectionDidsWithFieldInStatement(metaDatabase.getIdentifier(), metaDocPart.getIdentifier(), valuesMultimapSortedStreamProvider.get().map(e -> new Tuple2<String, Integer>(e.getKey().getIdentifier(), e.getValue().size())));
    Connection connection = dsl.configuration().connectionProvider().acquire();
    try {
        PreparedStatement preparedStatement = connection.prepareStatement(statement);
        int parameterIndex = 1;
        Iterator<Map.Entry<MetaField, Collection<KvValue<?>>>> valuesMultimapSortedIterator = valuesMultimapSortedStreamProvider.get().iterator();
        while (valuesMultimapSortedIterator.hasNext()) {
            Map.Entry<MetaField, Collection<KvValue<?>>> valuesMultimapEntry = valuesMultimapSortedIterator.next();
            for (KvValue<?> value : valuesMultimapEntry.getValue()) {
                sqlHelper.setPreparedStatementValue(preparedStatement, parameterIndex, valuesMultimapEntry.getKey().getType(), value);
                parameterIndex++;
            }
        }
        return new DefaultDidCursor(errorHandler, preparedStatement.executeQuery());
    } finally {
        dsl.configuration().connectionProvider().release(connection);
    }
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) Connection(java.sql.Connection) Provider(javax.inject.Provider) IteratorCursor(com.torodb.core.cursors.IteratorCursor) Multimap(com.google.common.collect.Multimap) Seq(org.jooq.lambda.Seq) Singleton(javax.inject.Singleton) ArrayList(java.util.ArrayList) TableRefFactory(com.torodb.core.TableRefFactory) KvValue(com.torodb.kvdocument.values.KvValue) Tuple2(org.jooq.lambda.tuple.Tuple2) SQLException(java.sql.SQLException) MetaDatabase(com.torodb.core.transaction.metainf.MetaDatabase) ResultSetDocPartResult(com.torodb.backend.d2r.ResultSetDocPartResult) ResultSet(java.sql.ResultSet) Map(java.util.Map) DSLContext(org.jooq.DSLContext) Context(com.torodb.backend.ErrorHandler.Context) Nonnull(javax.annotation.Nonnull) MetaCollection(com.torodb.core.transaction.metainf.MetaCollection) Unchecked(org.jooq.lambda.Unchecked) Iterator(java.util.Iterator) Cursor(com.torodb.core.cursors.Cursor) Collection(java.util.Collection) EmptyCursor(com.torodb.core.cursors.EmptyCursor) DocPartTableFields(com.torodb.backend.tables.MetaDocPartTable.DocPartTableFields) PreparedStatement(java.sql.PreparedStatement) Collectors(java.util.stream.Collectors) TableRef(com.torodb.core.TableRef) List(java.util.List) MetaField(com.torodb.core.transaction.metainf.MetaField) Stream(java.util.stream.Stream) DocPartResult(com.torodb.core.d2r.DocPartResult) Entry(java.util.Map.Entry) MetaDocPart(com.torodb.core.transaction.metainf.MetaDocPart) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) MetaField(com.torodb.core.transaction.metainf.MetaField) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Entry(java.util.Map.Entry) Tuple2(org.jooq.lambda.tuple.Tuple2) MetaCollection(com.torodb.core.transaction.metainf.MetaCollection) Collection(java.util.Collection) Stream(java.util.stream.Stream) Map(java.util.Map) KvValue(com.torodb.kvdocument.values.KvValue) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Aggregations

Multimap (com.google.common.collect.Multimap)61 HashMultimap (com.google.common.collect.HashMultimap)25 List (java.util.List)25 Test (org.junit.Test)20 Map (java.util.Map)17 ImmutableList (com.google.common.collect.ImmutableList)15 Collection (java.util.Collection)14 Set (java.util.Set)14 ImmutableMap (com.google.common.collect.ImmutableMap)13 HashMap (java.util.HashMap)13 ImmutableMultimap (com.google.common.collect.ImmutableMultimap)12 ImmutableSet (com.google.common.collect.ImmutableSet)11 ArrayList (java.util.ArrayList)11 Collectors (java.util.stream.Collectors)11 ArrayListMultimap (com.google.common.collect.ArrayListMultimap)10 Nullable (javax.annotation.Nullable)10 IOException (java.io.IOException)9 Stream (java.util.stream.Stream)9 InetAddress (java.net.InetAddress)8 Objects (java.util.Objects)8