Search in sources :

Example 1 with MockTime

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

the class CompactionPolicyFactoryTest method testCompactionPolicyFactory.

/**
 * Tests {@link CompactionPolicyFactory}
 * @throws Exception
 */
@Test
public void testCompactionPolicyFactory() throws Exception {
    List<Pair<String, String>> validCompactionPolicyInfos = new ArrayList<>();
    validCompactionPolicyInfos.add(new Pair<>("com.github.ambry.store.StatsBasedCompactionPolicyFactory", "com.github.ambry.store.StatsBasedCompactionPolicy"));
    validCompactionPolicyInfos.add(new Pair<>("com.github.ambry.store.CompactAllPolicyFactory", "com.github.ambry.store.CompactAllPolicy"));
    for (Pair<String, String> validCompactionPolicyInfo : validCompactionPolicyInfos) {
        Properties properties = new Properties();
        properties.setProperty("store.compaction.policy.factory", validCompactionPolicyInfo.getFirst());
        StoreConfig config = new StoreConfig(new VerifiableProperties(properties));
        Time time = new MockTime();
        CompactionPolicyFactory compactionPolicyFactory = Utils.getObj(config.storeCompactionPolicyFactory, config, time);
        Assert.assertEquals("Did not receive expected CompactionPolicy instance", validCompactionPolicyInfo.getFirst(), compactionPolicyFactory.getClass().getCanonicalName());
        CompactionPolicy compactionPolicy = compactionPolicyFactory.getCompactionPolicy();
        Assert.assertEquals("Did not receive expected CompactionPolicy instance", validCompactionPolicyInfo.getSecond(), compactionPolicy.getClass().getCanonicalName());
    }
}
Also used : VerifiableProperties(com.github.ambry.config.VerifiableProperties) ArrayList(java.util.ArrayList) MockTime(com.github.ambry.utils.MockTime) Time(com.github.ambry.utils.Time) Properties(java.util.Properties) VerifiableProperties(com.github.ambry.config.VerifiableProperties) StoreConfig(com.github.ambry.config.StoreConfig) MockTime(com.github.ambry.utils.MockTime) Pair(com.github.ambry.utils.Pair) Test(org.junit.Test)

Example 2 with MockTime

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

the class HardDeleterTest method setup.

@Before
public void setup() throws Exception {
    File rootDirectory = StoreTestUtils.createTempDirectory("ambry");
    File indexFile = new File(rootDirectory.getAbsolutePath());
    for (File c : indexFile.listFiles()) {
        c.delete();
    }
    scheduler = Utils.newScheduler(1, false);
    MetricRegistry metricRegistry = new MetricRegistry();
    StoreMetrics metrics = new StoreMetrics(metricRegistry);
    Properties props = new Properties();
    // the test will set the tokens, so disable the index persistor.
    props.setProperty("store.data.flush.interval.seconds", "3600");
    props.setProperty("store.deleted.message.retention.hours", "1");
    props.setProperty("store.index.max.number.of.inmem.elements", "2");
    props.setProperty("store.segment.size.in.bytes", "10000");
    // the following determines the number of entries that will be fetched at most. We need this to test the
    // case where the endToken does not reach the journal.
    props.setProperty("store.hard.delete.operations.bytes.per.sec", "40");
    StoreConfig config = new StoreConfig(new VerifiableProperties(props));
    log = new Log(rootDirectory.getAbsolutePath(), 10000, StoreTestUtils.DEFAULT_DISK_SPACE_ALLOCATOR, config, metrics, null);
    StoreKeyFactory factory = Utils.getObj("com.github.ambry.store.MockIdFactory");
    time = new MockTime(SystemTime.getInstance().milliseconds());
    helper = new HardDeleteTestHelper(0, 200);
    diskIOScheduler = new MockDiskIOScheduler();
    index = new MockIndex(rootDirectory.getAbsolutePath(), scheduler, log, config, factory, helper, diskIOScheduler, time, UUID.randomUUID());
    helper.setIndex(index, log);
    // Setting this below will not enable the hard delete thread. This being a unit test, the methods
    // are going to be called directly. We simply want to set the enabled flag to avoid those methods
    // from bailing out prematurely.
    index.setHardDeleteRunningStatus(true);
}
Also used : VerifiableProperties(com.github.ambry.config.VerifiableProperties) MetricRegistry(com.codahale.metrics.MetricRegistry) StoreConfig(com.github.ambry.config.StoreConfig) Properties(java.util.Properties) VerifiableProperties(com.github.ambry.config.VerifiableProperties) File(java.io.File) MockTime(com.github.ambry.utils.MockTime) Before(org.junit.Before)

Example 3 with MockTime

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

the class AmbryUrlSigningServiceTest method notSignedRequestFailuresTest.

/**
 * Tests for some failure scenarios in verification.
 * @throws Exception
 */
@Test
public void notSignedRequestFailuresTest() throws Exception {
    // positive test done in signAndVerifyTest()
    AmbryUrlSigningService signer = getUrlSignerWithDefaults(new MockTime());
    RestRequest request = getRequestFromUrl(RestMethod.GET, "/");
    assertFalse("Request should not be declared signed", signer.isRequestSigned(request));
    ensureVerificationFailure(signer, request, RestServiceErrorCode.InternalServerError);
    request.setArg(RestUtils.Headers.URL_TYPE, RestMethod.POST.name());
    assertFalse("Request should not be declared signed", signer.isRequestSigned(request));
    ensureVerificationFailure(signer, request, RestServiceErrorCode.InternalServerError);
}
Also used : MockRestRequest(com.github.ambry.rest.MockRestRequest) RestRequest(com.github.ambry.rest.RestRequest) MockTime(com.github.ambry.utils.MockTime) Test(org.junit.Test)

Example 4 with MockTime

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

the class MySqlStorageUsageRefresherTest method testFetchMonthlyStorageUsage.

/**
 * Test to update container storage usage monthly base.
 */
@Test
public void testFetchMonthlyStorageUsage() throws Exception {
    MockTime mockTime = new MockTime(SystemTime.getInstance().milliseconds());
    MySqlStorageUsageRefresher.time = mockTime;
    try {
        String currentMonth = MySqlStorageUsageRefresher.getCurrentMonth();
        Map<String, Map<String, Long>> containerStorageUsages = TestUtils.makeStorageMap(10, 10, 100000, 1000);
        StatsSnapshot snapshot = TestUtils.makeAccountStatsSnapshotFromContainerStorageMap(containerStorageUsages);
        accountStatsMySqlStore.storeAggregatedAccountStats(snapshot);
        accountStatsMySqlStore.takeSnapshotOfAggregatedAccountStatsAndUpdateMonth(currentMonth);
        properties.remove(StorageQuotaConfig.REFRESHER_POLLING_INTERVAL_MS);
        StorageQuotaConfig storageQuotaConfig = new StorageQuotaConfig(new VerifiableProperties(properties));
        AccountStatsMySqlStore newAccountStatsMySqlStore = createAccountStatsMySqlStore();
        MySqlStorageUsageRefresher refresher = new MySqlStorageUsageRefresher(newAccountStatsMySqlStore, scheduler, storageQuotaConfig, metrics);
        // Fetch monthly storage usage
        refresher.fetchStorageUsageMonthlyBase();
        assertEquals(containerStorageUsages, refresher.getContainerStorageUsageMonthlyBase());
        // Change the month
        String notCurrentMonth = "1970-01";
        Map<String, Map<String, Long>> newContainerStorageUsages = TestUtils.makeStorageMap(10, 10, 100000, 1000);
        snapshot = TestUtils.makeAccountStatsSnapshotFromContainerStorageMap(newContainerStorageUsages);
        accountStatsMySqlStore.storeAggregatedAccountStats(snapshot);
        accountStatsMySqlStore.takeSnapshotOfAggregatedAccountStatsAndUpdateMonth(notCurrentMonth);
        refresher.fetchStorageUsageMonthlyBase();
        // Monthly storage usage still the old one
        assertEquals(containerStorageUsages, refresher.getContainerStorageUsageMonthlyBase());
        // Change the month back to the current month
        accountStatsMySqlStore.takeSnapshotOfAggregatedAccountStatsAndUpdateMonth(currentMonth);
        // Wait for schedule to retry
        Thread.sleep(MYSQL_RETRY_BACKOFF_MS * 2);
        assertEquals(newContainerStorageUsages, refresher.getContainerStorageUsageMonthlyBase());
        // Forward the time to next month
        mockTime.sleep((MySqlStorageUsageRefresher.secondsToNextMonthTick(currentMonth, storageQuotaConfig.mysqlMonthlyBaseFetchOffsetSec) + 10) * 1000);
        String nextMonth = MySqlStorageUsageRefresher.getCurrentMonth();
        Function<String, Integer> stringMonthToInteger = (monthInStr) -> {
            String[] parts = monthInStr.split("-");
            int year = Integer.parseInt(parts[0]);
            int month = Integer.parseInt(parts[1]);
            return year * 12 + month;
        };
        assertEquals(stringMonthToInteger.apply(currentMonth) + 1, (int) stringMonthToInteger.apply(nextMonth));
        // Update the month to next month
        Map<String, Map<String, Long>> nextContainerStorageUsages = TestUtils.makeStorageMap(10, 10, 100000, 1000);
        snapshot = TestUtils.makeAccountStatsSnapshotFromContainerStorageMap(nextContainerStorageUsages);
        accountStatsMySqlStore.storeAggregatedAccountStats(snapshot);
        accountStatsMySqlStore.takeSnapshotOfAggregatedAccountStatsAndUpdateMonth(nextMonth);
        refresher.fetchStorageUsageMonthlyBase();
        assertEquals(nextContainerStorageUsages, refresher.getContainerStorageUsageMonthlyBase());
        // A backup file should be create as well
        assertEquals(nextContainerStorageUsages, refresher.getBackupFileManager().getBackupFileContent(nextMonth));
    } finally {
        MySqlStorageUsageRefresher.time = SystemTime.getInstance();
    }
}
Also used : HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) AccountStatsMySqlStoreFactory(com.github.ambry.accountstats.AccountStatsMySqlStoreFactory) TestUtils(com.github.ambry.utils.TestUtils) Map(java.util.Map) After(org.junit.After) SystemTime(com.github.ambry.utils.SystemTime) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Path(java.nio.file.Path) Before(org.junit.Before) AfterClass(org.junit.AfterClass) MetricRegistry(com.codahale.metrics.MetricRegistry) Properties(java.util.Properties) Files(java.nio.file.Files) AccountStatsMySqlStore(com.github.ambry.accountstats.AccountStatsMySqlStore) VerifiableProperties(com.github.ambry.config.VerifiableProperties) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Utils(com.github.ambry.utils.Utils) Test(org.junit.Test) AccountStatsMySqlConfig(com.github.ambry.config.AccountStatsMySqlConfig) TimeUnit(java.util.concurrent.TimeUnit) StorageQuotaConfig(com.github.ambry.config.StorageQuotaConfig) CountDownLatch(java.util.concurrent.CountDownLatch) MockTime(com.github.ambry.utils.MockTime) Paths(java.nio.file.Paths) StatsSnapshot(com.github.ambry.server.StatsSnapshot) ClusterMapConfig(com.github.ambry.config.ClusterMapConfig) Assert(org.junit.Assert) VerifiableProperties(com.github.ambry.config.VerifiableProperties) StorageQuotaConfig(com.github.ambry.config.StorageQuotaConfig) HashMap(java.util.HashMap) Map(java.util.Map) AccountStatsMySqlStore(com.github.ambry.accountstats.AccountStatsMySqlStore) MockTime(com.github.ambry.utils.MockTime) StatsSnapshot(com.github.ambry.server.StatsSnapshot) Test(org.junit.Test)

Example 5 with MockTime

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

the class CloudToStoreReplicationManagerTest method cloudReplicaAdditionTest.

/**
 * Test both success and failure cases when adding cloud replica
 * @throws Exception
 */
@Test
public void cloudReplicaAdditionTest() throws Exception {
    StorageManager storageManager = new StorageManager(storeConfig, new DiskManagerConfig(verifiableProperties), Utils.newScheduler(1, true), clusterMap.getMetricRegistry(), null, clusterMap, currentNode, null, Collections.singletonList(mockHelixParticipant), new MockTime(), null, new InMemAccountService(false, false));
    CloudToStoreReplicationManager cloudToStoreReplicationManager = new CloudToStoreReplicationManager(replicationConfig, clusterMapConfig, storeConfig, storageManager, storeKeyFactory, clusterMap, mockScheduler, currentNode, null, clusterMap.getMetricRegistry(), null, storeKeyConverterFactory, serverConfig.serverMessageTransformer, mockClusterSpectator, mockHelixParticipant);
    storageManager.start();
    cloudToStoreReplicationManager.start();
    mockClusterSpectator.spectate();
    // 1. test adding cloud replica that is not present locally
    mockHelixParticipant.onPartitionBecomeLeaderFromStandby(NEW_PARTITION_NAME);
    assertNull("Cloud replica thread should not be created", TestUtils.getThreadByThisName(REPLICA_THREAD_PREFIX));
    // create a new partition and add corresponding store in storage manager
    PartitionId newPartition = new MockPartitionId(Long.parseLong(NEW_PARTITION_NAME), MockClusterMap.DEFAULT_PARTITION_CLASS, clusterMap.getDataNodes(), 0);
    ReplicaId replicaToAdd = newPartition.getReplicaIds().get(0);
    assertTrue("Adding new store should succeed", storageManager.addBlobStore(replicaToAdd));
    // 2. we deliberately shut down the store to induce failure when adding cloud replica
    storageManager.shutdownBlobStore(newPartition);
    mockHelixParticipant.onPartitionBecomeLeaderFromStandby(NEW_PARTITION_NAME);
    assertNull("Cloud replica thread should not be created", TestUtils.getThreadByThisName(REPLICA_THREAD_PREFIX));
    storageManager.startBlobStore(newPartition);
    // 3. mock success case
    mockHelixParticipant.onPartitionBecomeLeaderFromStandby(NEW_PARTITION_NAME);
    assertNotNull("Cloud replica thread should be created for DC1", TestUtils.getThreadByThisName(REPLICA_THREAD_PREFIX));
    cloudToStoreReplicationManager.shutdown();
    storageManager.shutdown();
}
Also used : DiskManagerConfig(com.github.ambry.config.DiskManagerConfig) InMemAccountService(com.github.ambry.account.InMemAccountService) MockPartitionId(com.github.ambry.clustermap.MockPartitionId) StorageManager(com.github.ambry.store.StorageManager) MockPartitionId(com.github.ambry.clustermap.MockPartitionId) PartitionId(com.github.ambry.clustermap.PartitionId) MockTime(com.github.ambry.utils.MockTime) ReplicaId(com.github.ambry.clustermap.ReplicaId) Test(org.junit.Test)

Aggregations

MockTime (com.github.ambry.utils.MockTime)33 Test (org.junit.Test)21 VerifiableProperties (com.github.ambry.config.VerifiableProperties)19 Properties (java.util.Properties)18 MockClusterMap (com.github.ambry.clustermap.MockClusterMap)13 MetricRegistry (com.codahale.metrics.MetricRegistry)11 ArrayList (java.util.ArrayList)10 HashMap (java.util.HashMap)10 InMemAccountService (com.github.ambry.account.InMemAccountService)9 DataNodeId (com.github.ambry.clustermap.DataNodeId)9 RouterConfig (com.github.ambry.config.RouterConfig)9 CountDownLatch (java.util.concurrent.CountDownLatch)9 PartitionId (com.github.ambry.clustermap.PartitionId)8 LoggingNotificationSystem (com.github.ambry.commons.LoggingNotificationSystem)8 BlobProperties (com.github.ambry.messageformat.BlobProperties)8 Map (java.util.Map)8 MockDataNodeId (com.github.ambry.clustermap.MockDataNodeId)7 MockPartitionId (com.github.ambry.clustermap.MockPartitionId)7 StoreConfig (com.github.ambry.config.StoreConfig)7 StorageManager (com.github.ambry.store.StorageManager)7