Search in sources :

Example 16 with Pair

use of com.github.ambry.utils.Pair in project ambry by linkedin.

the class AccountStatsMySqlStoreIntegrationTest method testHostPartitionClassStorageStats.

/**
 * Test methods to store and fetch partition class, partition name partition id and partition class storage stats.
 * @throws Exception
 */
@Test
public void testHostPartitionClassStorageStats() throws Exception {
    // First write some stats to account reports
    testMultiStoreStats();
    HostAccountStorageStatsWrapper accountStats1 = mySqlStore.queryHostAccountStorageStatsByHost(hostname1, port1);
    HostAccountStorageStatsWrapper accountStats2 = mySqlStore.queryHostAccountStorageStatsByHost(hostname2, port2);
    AccountStatsMySqlStore mySqlStore3 = createAccountStatsMySqlStore(clusterName2, hostname3, port3);
    HostAccountStorageStatsWrapper accountStats3 = mySqlStore3.queryHostAccountStorageStatsByHost(hostname3, port3);
    // From this account stats, create partition class stats;
    Set<Long> allPartitionKeys = new HashSet<Long>() {

        {
            addAll(accountStats1.getStats().getStorageStats().keySet());
            addAll(accountStats2.getStats().getStorageStats().keySet());
            addAll(accountStats3.getStats().getStorageStats().keySet());
        }
    };
    List<String> partitionClassNames = Arrays.asList("default", "new");
    Map<Long, String> partitionIdToClassName = new HashMap<>();
    int ind = 0;
    for (long partitionId : allPartitionKeys) {
        partitionIdToClassName.put(partitionId, partitionClassNames.get(ind % partitionClassNames.size()));
        ind++;
    }
    HostPartitionClassStorageStatsWrapper partitionClassStats1 = convertHostAccountStorageStatsToHostPartitionClassStorageStats(accountStats1, partitionIdToClassName);
    HostPartitionClassStorageStatsWrapper partitionClassStats2 = convertHostAccountStorageStatsToHostPartitionClassStorageStats(accountStats2, partitionIdToClassName);
    HostPartitionClassStorageStatsWrapper partitionClassStats3 = convertHostAccountStorageStatsToHostPartitionClassStorageStats(accountStats3, partitionIdToClassName);
    mySqlStore.storeHostPartitionClassStorageStats(partitionClassStats1);
    mySqlStore.storeHostPartitionClassStorageStats(partitionClassStats2);
    mySqlStore3.storeHostPartitionClassStorageStats(partitionClassStats3);
    Map<String, Set<Integer>> partitionNameAndIds = mySqlStore.queryPartitionNameAndIds();
    assertEquals(new HashSet<>(partitionClassNames), partitionNameAndIds.keySet());
    Map<Long, String> dbPartitionKeyToClassName = partitionNameAndIds.entrySet().stream().flatMap(ent -> ent.getValue().stream().map(pid -> new Pair<>(ent.getKey(), (long) pid))).collect(Collectors.toMap(Pair::getSecond, Pair::getFirst));
    assertEquals(partitionIdToClassName, dbPartitionKeyToClassName);
    // Fetch HostPartitionClassStorageStats
    HostPartitionClassStorageStatsWrapper obtainedStats1 = mySqlStore.queryHostPartitionClassStorageStatsByHost(hostname1, port1, partitionNameAndIds);
    assertEquals(partitionClassStats1.getStats().getStorageStats(), obtainedStats1.getStats().getStorageStats());
    HostPartitionClassStorageStatsWrapper obtainedStats2 = mySqlStore.queryHostPartitionClassStorageStatsByHost(hostname2, port2, partitionNameAndIds);
    assertEquals(partitionClassStats2.getStats().getStorageStats(), obtainedStats2.getStats().getStorageStats());
    HostPartitionClassStorageStatsWrapper obtainedStats3 = mySqlStore3.queryHostPartitionClassStorageStatsByHost(hostname3, port3, partitionNameAndIds);
    assertEquals(partitionClassStats3.getStats().getStorageStats(), obtainedStats3.getStats().getStorageStats());
    // Fetch StatsSnapshot
    StatsWrapper obtainedStats = mySqlStore.queryPartitionClassStatsByHost(hostname1, port1, partitionNameAndIds);
    assertEquals(StorageStatsUtil.convertHostPartitionClassStorageStatsToStatsSnapshot(obtainedStats1.getStats(), false), obtainedStats.getSnapshot());
    mySqlStore3.shutdown();
}
Also used : HostPartitionClassStorageStats(com.github.ambry.server.storagestats.HostPartitionClassStorageStats) HostAccountStorageStatsWrapper(com.github.ambry.server.HostAccountStorageStatsWrapper) Arrays(java.util.Arrays) Connection(java.sql.Connection) AggregatedPartitionClassStorageStats(com.github.ambry.server.storagestats.AggregatedPartitionClassStorageStats) StatsHeader(com.github.ambry.server.StatsHeader) RunWith(org.junit.runner.RunWith) HostAccountStorageStats(com.github.ambry.server.storagestats.HostAccountStorageStats) HashMap(java.util.HashMap) Random(java.util.Random) ContainerStorageStats(com.github.ambry.server.storagestats.ContainerStorageStats) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) SQLException(java.sql.SQLException) TestUtils(com.github.ambry.utils.TestUtils) ResultSet(java.sql.ResultSet) Map(java.util.Map) After(org.junit.After) Path(java.nio.file.Path) Parameterized(org.junit.runners.Parameterized) StatsWrapper(com.github.ambry.server.StatsWrapper) Before(org.junit.Before) MetricRegistry(com.codahale.metrics.MetricRegistry) Properties(java.util.Properties) Pair(com.github.ambry.utils.Pair) Files(java.nio.file.Files) VerifiableProperties(com.github.ambry.config.VerifiableProperties) Set(java.util.Set) Utils(com.github.ambry.utils.Utils) IOException(java.io.IOException) Test(org.junit.Test) Collectors(java.util.stream.Collectors) AccountStatsMySqlConfig(com.github.ambry.config.AccountStatsMySqlConfig) AggregatedAccountStorageStats(com.github.ambry.server.storagestats.AggregatedAccountStorageStats) List(java.util.List) StorageStatsUtil(com.github.ambry.server.StorageStatsUtil) StatsReportType(com.github.ambry.server.StatsReportType) StatsSnapshot(com.github.ambry.server.StatsSnapshot) ClusterMapConfig(com.github.ambry.config.ClusterMapConfig) Statement(java.sql.Statement) Assert(org.junit.Assert) HostPartitionClassStorageStatsWrapper(com.github.ambry.server.HostPartitionClassStorageStatsWrapper) Collections(java.util.Collections) StorageStatsUtilTest(com.github.ambry.server.StorageStatsUtilTest) HostAccountStorageStatsWrapper(com.github.ambry.server.HostAccountStorageStatsWrapper) HashSet(java.util.HashSet) ResultSet(java.sql.ResultSet) Set(java.util.Set) HashMap(java.util.HashMap) HostPartitionClassStorageStatsWrapper(com.github.ambry.server.HostPartitionClassStorageStatsWrapper) HostAccountStorageStatsWrapper(com.github.ambry.server.HostAccountStorageStatsWrapper) StatsWrapper(com.github.ambry.server.StatsWrapper) HostPartitionClassStorageStatsWrapper(com.github.ambry.server.HostPartitionClassStorageStatsWrapper) HashSet(java.util.HashSet) Test(org.junit.Test) StorageStatsUtilTest(com.github.ambry.server.StorageStatsUtilTest)

Example 17 with Pair

use of com.github.ambry.utils.Pair in project ambry by linkedin.

the class MessageFormatRecordTest method testBlobRecordWithMetadataContentV3.

@Test
public void testBlobRecordWithMetadataContentV3() throws IOException, MessageFormatException {
    int numKeys = 5;
    List<StoreKey> keys = getKeys(60, numKeys);
    List<Pair<StoreKey, Long>> keysAndContentSizes = new ArrayList<>();
    long total = 0;
    for (int i = 0; i < numKeys; i++) {
        long randNum = ThreadLocalRandom.current().nextLong(1, 10000000);
        total += randNum;
        keysAndContentSizes.add(new Pair<>(keys.get(i), randNum));
    }
    ByteBuffer metadataContent = getSerializedMetadataContentV3(total, keysAndContentSizes);
    int metadataContentSize = MessageFormatRecord.Metadata_Content_Format_V3.getMetadataContentSize(keys.get(0).sizeInBytes(), keys.size());
    long blobSize = MessageFormatRecord.Blob_Format_V2.getBlobRecordSize(metadataContentSize);
    ByteBuffer blob = ByteBuffer.allocate((int) blobSize);
    BlobData blobData = getBlobRecordV2(metadataContentSize, BlobType.MetadataBlob, metadataContent, blob);
    Assert.assertEquals(metadataContentSize, blobData.getSize());
    byte[] verify = new byte[metadataContentSize];
    blobData.content().readBytes(verify);
    Assert.assertArrayEquals("Metadata content mismatch", metadataContent.array(), verify);
    blobData.release();
    metadataContent.rewind();
    CompositeBlobInfo compositeBlobInfo = deserializeMetadataContentV3(metadataContent, new MockIdFactory());
    Assert.assertEquals("Total size doesn't match", total, compositeBlobInfo.getTotalSize());
    Assert.assertEquals("List of keys dont match", keys, compositeBlobInfo.getKeys());
    List<CompositeBlobInfo.ChunkMetadata> list = compositeBlobInfo.getChunkMetadataList();
    Assert.assertEquals("ChunkMetadata and input list have different sizes", list.size(), keysAndContentSizes.size());
    long sum = 0;
    for (int i = 0; i < list.size(); i++) {
        Assert.assertEquals(keysAndContentSizes.get(i).getFirst(), list.get(i).getStoreKey());
        Assert.assertEquals((long) keysAndContentSizes.get(i).getSecond(), list.get(i).getSize());
        Assert.assertEquals(sum, list.get(i).getOffset());
        sum += list.get(i).getSize();
    }
}
Also used : ArrayList(java.util.ArrayList) StoreKey(com.github.ambry.store.StoreKey) ByteBuffer(java.nio.ByteBuffer) MockIdFactory(com.github.ambry.store.MockIdFactory) Pair(com.github.ambry.utils.Pair) Test(org.junit.Test)

Example 18 with Pair

use of com.github.ambry.utils.Pair in project ambry by linkedin.

the class MessageFormatRecordTest method testMetadataContentRecordV3.

@Test
public void testMetadataContentRecordV3() throws IOException, MessageFormatException {
    // Test Metadata Blob V3
    int numKeys = 5;
    List<StoreKey> keys = getKeys(60, numKeys);
    List<Pair<StoreKey, Long>> keysAndContentSizes = new ArrayList<>();
    long total = 0;
    for (int i = 0; i < numKeys; i++) {
        long randNum = ThreadLocalRandom.current().nextLong(1, 10000000);
        total += randNum;
        keysAndContentSizes.add(new Pair<>(keys.get(i), randNum));
    }
    ByteBuffer metadataContent = getSerializedMetadataContentV3(total, keysAndContentSizes);
    CompositeBlobInfo compositeBlobInfo = deserializeMetadataContentV3(metadataContent, new MockIdFactory());
    Assert.assertEquals("Total size doesn't match", total, compositeBlobInfo.getTotalSize());
    Assert.assertEquals("List of keys dont match", keys, compositeBlobInfo.getKeys());
    List<CompositeBlobInfo.ChunkMetadata> list = compositeBlobInfo.getChunkMetadataList();
    Assert.assertEquals("ChunkMetadata and input list have different sizes", list.size(), keysAndContentSizes.size());
    long sum = 0;
    for (int i = 0; i < list.size(); i++) {
        Assert.assertEquals(keysAndContentSizes.get(i).getFirst(), list.get(i).getStoreKey());
        Assert.assertEquals((long) keysAndContentSizes.get(i).getSecond(), list.get(i).getSize());
        Assert.assertEquals(sum, list.get(i).getOffset());
        sum += list.get(i).getSize();
    }
}
Also used : ArrayList(java.util.ArrayList) StoreKey(com.github.ambry.store.StoreKey) ByteBuffer(java.nio.ByteBuffer) MockIdFactory(com.github.ambry.store.MockIdFactory) Pair(com.github.ambry.utils.Pair) Test(org.junit.Test)

Example 19 with Pair

use of com.github.ambry.utils.Pair in project ambry by linkedin.

the class CompositeBlobInfoTest method createKeysAndContentSizes.

/**
 * Creates a list of pairs of StoreKeys and content sizes, where each pair is of a random size
 * @param keySize size of the actual store key
 * @param lowerBound the smallest random content size value allowed
 * @param higherBound the largest random content size value allowed
 * @param numKeys number of keys to populate the list
 * @return a list of pairs of StoreKeys and content sizes, where each pair is of a random size
 */
private List<Pair<StoreKey, Long>> createKeysAndContentSizes(int keySize, int lowerBound, int higherBound, int numKeys) {
    List<Pair<StoreKey, Long>> keysAndContentSizes = new ArrayList<>();
    Random rand = new Random();
    for (int i = 0; i < numKeys; i++) {
        keysAndContentSizes.add(new Pair<>(new MockId(TestUtils.getRandomString(keySize)), (long) rand.nextInt(higherBound - lowerBound) + lowerBound));
    }
    return keysAndContentSizes;
}
Also used : Random(java.util.Random) ArrayList(java.util.ArrayList) MockId(com.github.ambry.store.MockId) Pair(com.github.ambry.utils.Pair)

Example 20 with Pair

use of com.github.ambry.utils.Pair in project ambry by linkedin.

the class MySqlDataAccessor method connectToBestAvailableEndpoint.

/**
 * Connect to the best available database instance that matches the specified criteria.<br/>
 * Order of preference for instances to connect to:
 * <OL>
 *    <LI/> Writeable instance in local colo
 *    <LI/> Writable instance in any colo
 *    <LI/> Read-only instance in local colo (if needWritable is false)
 *    <LI/> Read-only instance in any colo (if needWritable is false)
 *  </OL>
 * @param needWritable whether the endpoint needs to be writable
 * @return a pair of {@link DbEndpoint} and corresponding {@link Connection}.
 * @throws SQLException if connection could not be made to a suitable endpoint.
 */
private Pair<DbEndpoint, Connection> connectToBestAvailableEndpoint(boolean needWritable) throws SQLException {
    SQLException lastException = null;
    for (DbEndpoint candidateEndpoint : sortedDbEndpoints) {
        if (!isBetterEndpoint(candidateEndpoint, connectedEndpoint)) {
            // What we have is the best we can do.  Is it good enough?
            if (needWritable && !connectedEndpoint.isWriteable()) {
                throw Optional.ofNullable(lastException).orElse(noWritableEndpointException);
            } else {
                return new Pair<>(connectedEndpoint, activeConnection);
            }
        }
        if (needWritable && !candidateEndpoint.isWriteable()) {
            throw Optional.ofNullable(lastException).orElse(noWritableEndpointException);
        }
        // Attempt to connect to candidate endpoint
        Properties credentials = new Properties();
        credentials.setProperty("user", candidateEndpoint.getUsername());
        credentials.setProperty("password", candidateEndpoint.getPassword());
        try {
            Connection connection = mysqlDriver.connect(candidateEndpoint.getUrl(), credentials);
            metrics.connectionSuccessCount.inc();
            return new Pair<>(candidateEndpoint, connection);
        } catch (SQLException e) {
            logger.warn("Unable to connect to endpoint {} due to {}", candidateEndpoint.getUrl(), e.getMessage());
            metrics.connectionFailureCount.inc();
            if (isCredentialError(e)) {
                // fail fast
                throw e;
            } else {
                lastException = e;
            }
        }
    }
    throw Optional.ofNullable(lastException).orElse(noEndpointException);
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) Properties(java.util.Properties) Pair(com.github.ambry.utils.Pair)

Aggregations

Pair (com.github.ambry.utils.Pair)64 ArrayList (java.util.ArrayList)29 HashMap (java.util.HashMap)28 Map (java.util.Map)28 Test (org.junit.Test)20 IOException (java.io.IOException)15 MetricRegistry (com.codahale.metrics.MetricRegistry)14 List (java.util.List)14 ByteBuffer (java.nio.ByteBuffer)13 Collections (java.util.Collections)13 File (java.io.File)12 Assert (org.junit.Assert)12 VerifiableProperties (com.github.ambry.config.VerifiableProperties)11 Utils (com.github.ambry.utils.Utils)10 HashSet (java.util.HashSet)10 Properties (java.util.Properties)10 Container (com.github.ambry.account.Container)9 TestUtils (com.github.ambry.utils.TestUtils)9 Arrays (java.util.Arrays)9 Set (java.util.Set)9