Search in sources :

Example 86 with MockClusterMap

use of com.github.ambry.clustermap.MockClusterMap in project ambry by linkedin.

the class RestServerTest method startShutdownTestWithReporterFactory.

/**
 * Tests {@link RestServer#start()} and {@link RestServer#shutdown()} with a custom {@link JmxReporter} factory.
 * @throws Exception
 */
@Test
public void startShutdownTestWithReporterFactory() throws Exception {
    Properties properties = new Properties();
    VerifiableProperties verifiableProperties = getVProps(properties);
    ClusterMap clusterMap = new MockClusterMap();
    NotificationSystem notificationSystem = new LoggingNotificationSystem();
    ObjectNameFactory spyObjectNameFactory = spy(new DefaultObjectNameFactory());
    Function<MetricRegistry, JmxReporter> reporterFactory = reporter -> JmxReporter.forRegistry(reporter).createsObjectNamesWith(spyObjectNameFactory).build();
    RestServer server = new RestServer(verifiableProperties, clusterMap, notificationSystem, SSL_FACTORY, Collections.emptyList(), reporterFactory);
    server.start();
    // check that the custom ObjectNameFactory specified in reporterFactory was used.
    verify(spyObjectNameFactory, atLeastOnce()).createName(anyString(), anyString(), anyString());
    server.shutdown();
    server.awaitShutdown();
}
Also used : DefaultObjectNameFactory(com.codahale.metrics.jmx.DefaultObjectNameFactory) MetricRegistry(com.codahale.metrics.MetricRegistry) Properties(java.util.Properties) SSLFactory(com.github.ambry.commons.SSLFactory) VerifiableProperties(com.github.ambry.config.VerifiableProperties) ObjectNameFactory(com.codahale.metrics.jmx.ObjectNameFactory) ClusterMap(com.github.ambry.clustermap.ClusterMap) IOException(java.io.IOException) Test(org.junit.Test) Function(java.util.function.Function) JmxReporter(com.codahale.metrics.jmx.JmxReporter) Mockito(org.mockito.Mockito) InMemoryRouterFactory(com.github.ambry.router.InMemoryRouterFactory) LoggingNotificationSystem(com.github.ambry.commons.LoggingNotificationSystem) Assert(org.junit.Assert) Collections(java.util.Collections) MockClusterMap(com.github.ambry.clustermap.MockClusterMap) NotificationSystem(com.github.ambry.notification.NotificationSystem) ClusterMap(com.github.ambry.clustermap.ClusterMap) MockClusterMap(com.github.ambry.clustermap.MockClusterMap) VerifiableProperties(com.github.ambry.config.VerifiableProperties) DefaultObjectNameFactory(com.codahale.metrics.jmx.DefaultObjectNameFactory) ObjectNameFactory(com.codahale.metrics.jmx.ObjectNameFactory) MetricRegistry(com.codahale.metrics.MetricRegistry) LoggingNotificationSystem(com.github.ambry.commons.LoggingNotificationSystem) NotificationSystem(com.github.ambry.notification.NotificationSystem) Properties(java.util.Properties) VerifiableProperties(com.github.ambry.config.VerifiableProperties) DefaultObjectNameFactory(com.codahale.metrics.jmx.DefaultObjectNameFactory) JmxReporter(com.codahale.metrics.jmx.JmxReporter) LoggingNotificationSystem(com.github.ambry.commons.LoggingNotificationSystem) MockClusterMap(com.github.ambry.clustermap.MockClusterMap) Test(org.junit.Test)

Example 87 with MockClusterMap

use of com.github.ambry.clustermap.MockClusterMap in project ambry by linkedin.

the class RestServerTest method doBadFactoryClassTest.

/**
 * Tests for bad factory class name for {@code configKey} in {@link RestServer}.
 * @param configKey the property whose value is the bad factory class
 * @throws Exception
 */
private void doBadFactoryClassTest(String configKey) throws Exception {
    Properties properties = new Properties();
    setMandatoryValues(properties);
    // Non existent class.
    properties.setProperty(configKey, "non.existent.factory");
    VerifiableProperties verifiableProperties = new VerifiableProperties(properties);
    try {
        new RestServer(verifiableProperties, new MockClusterMap(), new LoggingNotificationSystem(), SSL_FACTORY);
        fail("Properties file contained non existent " + configKey + ", yet no exception was thrown");
    } catch (ClassNotFoundException e) {
    // nothing to do. expected.
    }
    // invalid factory class.
    properties.setProperty(configKey, RestServerTest.class.getCanonicalName());
    verifiableProperties = new VerifiableProperties(properties);
    try {
        new RestServer(verifiableProperties, new MockClusterMap(), new LoggingNotificationSystem(), SSL_FACTORY);
        fail("Properties file contained invalid " + configKey + " class, yet no exception was thrown");
    } catch (NoSuchMethodException e) {
    // nothing to do. expected.
    }
    // faulty factory class
    properties.setProperty(configKey, FaultyFactory.class.getCanonicalName());
    verifiableProperties = new VerifiableProperties(properties);
    try {
        RestServer restServer = new RestServer(verifiableProperties, new MockClusterMap(), new LoggingNotificationSystem(), SSL_FACTORY);
        restServer.start();
        fail("Properties file contained faulty " + configKey + " class, yet no exception was thrown");
    } catch (InstantiationException e) {
    // nothing to do. expected.
    }
}
Also used : VerifiableProperties(com.github.ambry.config.VerifiableProperties) LoggingNotificationSystem(com.github.ambry.commons.LoggingNotificationSystem) Properties(java.util.Properties) VerifiableProperties(com.github.ambry.config.VerifiableProperties) MockClusterMap(com.github.ambry.clustermap.MockClusterMap)

Example 88 with MockClusterMap

use of com.github.ambry.clustermap.MockClusterMap in project ambry by linkedin.

the class RestServerTest method startShutdownTest.

/**
 * Tests {@link RestServer#start()} and {@link RestServer#shutdown()}.
 * @throws Exception
 */
@Test
public void startShutdownTest() throws Exception {
    Properties properties = new Properties();
    VerifiableProperties verifiableProperties = getVProps(properties);
    ClusterMap clusterMap = new MockClusterMap();
    NotificationSystem notificationSystem = new LoggingNotificationSystem();
    RestServer server = new RestServer(verifiableProperties, clusterMap, notificationSystem, SSL_FACTORY);
    server.start();
    server.shutdown();
    server.awaitShutdown();
}
Also used : ClusterMap(com.github.ambry.clustermap.ClusterMap) MockClusterMap(com.github.ambry.clustermap.MockClusterMap) VerifiableProperties(com.github.ambry.config.VerifiableProperties) LoggingNotificationSystem(com.github.ambry.commons.LoggingNotificationSystem) LoggingNotificationSystem(com.github.ambry.commons.LoggingNotificationSystem) NotificationSystem(com.github.ambry.notification.NotificationSystem) Properties(java.util.Properties) VerifiableProperties(com.github.ambry.config.VerifiableProperties) MockClusterMap(com.github.ambry.clustermap.MockClusterMap) Test(org.junit.Test)

Example 89 with MockClusterMap

use of com.github.ambry.clustermap.MockClusterMap in project ambry by linkedin.

the class CloudOperationTest method getBlobAndAssertSuccess.

/**
 * Construct GetBlob operations with appropriate callbacks, then poll those operations until they complete,
 * and ensure that the whole blob data is read out and the contents match.
 * @param blobId id of the blob to get
 * @param expectedLifeVersion the expected lifeVersion from get operation.
 * @param expectedBlobSize the expected blob size
 * @param expectedBlobProperties  the expected {@link BlobProperties} for the blob.
 * @param expectedUserMetadata the expected user meta data
 * @param expectPutContent the expected blob content
 * @param options options of the get blob operation
 * @throws Exception Any unexpected exception
 */
private void getBlobAndAssertSuccess(final BlobId blobId, final short expectedLifeVersion, final int expectedBlobSize, final BlobProperties expectedBlobProperties, final byte[] expectedUserMetadata, final byte[] expectPutContent, final GetBlobOptionsInternal options) throws Exception {
    final CountDownLatch readCompleteLatch = new CountDownLatch(1);
    final AtomicLong readCompleteResult = new AtomicLong(0);
    // callback to compare the data
    Callback<GetBlobResultInternal> callback = (result, exception) -> {
        Assert.assertNull("Shouldn't have exception", exception);
        try {
            BlobInfo blobInfo;
            switch(options.getBlobOptions.getOperationType()) {
                case All:
                    Assert.assertFalse("not supposed to be raw mode", options.getBlobOptions.isRawMode());
                    blobInfo = result.getBlobResult.getBlobInfo();
                    Assert.assertTrue("Blob properties must be the same", RouterTestHelpers.arePersistedFieldsEquivalent(expectedBlobProperties, blobInfo.getBlobProperties()));
                    Assert.assertEquals("Blob size should in received blobProperties should be the same as actual", expectedBlobSize, blobInfo.getBlobProperties().getBlobSize());
                    Assert.assertArrayEquals("User metadata must be the same", expectedUserMetadata, blobInfo.getUserMetadata());
                    Assert.assertEquals("LifeVersion mismatch", expectedLifeVersion, blobInfo.getLifeVersion());
                    break;
                case Data:
                    Assert.assertNull("Unexpected blob info in operation result", result.getBlobResult.getBlobInfo());
                    break;
                case BlobInfo:
                    blobInfo = result.getBlobResult.getBlobInfo();
                    Assert.assertTrue("Blob properties must be the same", RouterTestHelpers.arePersistedFieldsEquivalent(expectedBlobProperties, blobInfo.getBlobProperties()));
                    Assert.assertEquals("Blob size should in received blobProperties should be the same as actual", expectedBlobSize, blobInfo.getBlobProperties().getBlobSize());
                    Assert.assertNull("Unexpected blob data in operation result", result.getBlobResult.getBlobDataChannel());
                    Assert.assertEquals("LifeVersion mismatch", expectedLifeVersion, blobInfo.getLifeVersion());
            }
        } catch (Throwable e) {
            Assert.fail("Shouldn't receive exception here");
        }
        if (options.getBlobOptions.getOperationType() != GetBlobOptions.OperationType.BlobInfo) {
            final ByteBufferAsyncWritableChannel asyncWritableChannel = new ByteBufferAsyncWritableChannel();
            Utils.newThread(() -> {
                Future<Long> readIntoFuture = result.getBlobResult.getBlobDataChannel().readInto(asyncWritableChannel, null);
                assertBlobReadSuccess(options.getBlobOptions, readIntoFuture, asyncWritableChannel, result.getBlobResult.getBlobDataChannel(), readCompleteLatch, readCompleteResult, expectedBlobSize, expectPutContent);
            }, false).start();
        } else {
            readCompleteLatch.countDown();
        }
    };
    // create GetBlobOperation
    final Map<Integer, GetOperation> correlationIdToGetOperation = new HashMap<>();
    final RequestRegistrationCallback<GetOperation> requestRegistrationCallback = new RequestRegistrationCallback<>(correlationIdToGetOperation);
    NonBlockingRouter.currentOperationsCount.incrementAndGet();
    GetBlobOperation op = new GetBlobOperation(routerConfig, routerMetrics, mockClusterMap, responseHandler, blobId, options, callback, routerCallback, blobIdFactory, null, null, null, time, false, null);
    requestRegistrationCallback.setRequestsToSend(new ArrayList<>());
    // Wait operation to complete
    while (!op.isOperationComplete()) {
        op.poll(requestRegistrationCallback);
        List<ResponseInfo> responses = sendAndWaitForResponses(requestRegistrationCallback.getRequestsToSend());
        for (ResponseInfo responseInfo : responses) {
            GetResponse getResponse = RouterUtils.extractResponseAndNotifyResponseHandler(responseHandler, routerMetrics, responseInfo, stream -> GetResponse.readFrom(stream, mockClusterMap), response -> {
                ServerErrorCode serverError = response.getError();
                if (serverError == ServerErrorCode.No_Error) {
                    serverError = response.getPartitionResponseInfoList().get(0).getErrorCode();
                }
                return serverError;
            });
            op.handleResponse(responseInfo, getResponse);
            responseInfo.release();
        }
    }
    readCompleteLatch.await();
    Assert.assertTrue("Operation should be complete at this time", op.isOperationComplete());
    // Ensure that a ChannelClosed exception is not set when the ReadableStreamChannel is closed correctly.
    Assert.assertNull("Callback operation exception should be null", op.getOperationException());
    if (options.getBlobOptions.getOperationType() != GetBlobOptions.OperationType.BlobInfo && !options.getBlobOptions.isRawMode() && !options.getChunkIdsOnly) {
        int sizeWritten = expectedBlobSize;
        if (options.getBlobOptions.getRange() != null) {
            ByteRange range = options.getBlobOptions.getRange().toResolvedByteRange(expectedBlobSize, options.getBlobOptions.resolveRangeOnEmptyBlob());
            sizeWritten = (int) range.getRangeSize();
        }
        Assert.assertEquals("Size read must equal size written", sizeWritten, readCompleteResult.get());
    }
}
Also used : ResponseInfo(com.github.ambry.network.ResponseInfo) Arrays(java.util.Arrays) BlobProperties(com.github.ambry.messageformat.BlobProperties) LocalNetworkClientFactory(com.github.ambry.network.LocalNetworkClientFactory) Random(java.util.Random) StoreErrorCodes(com.github.ambry.store.StoreErrorCodes) ByteBuffer(java.nio.ByteBuffer) GetResponse(com.github.ambry.protocol.GetResponse) Future(java.util.concurrent.Future) PortType(com.github.ambry.network.PortType) Map(java.util.Map) After(org.junit.After) NetworkConfig(com.github.ambry.config.NetworkConfig) NettyByteBufLeakHelper(com.github.ambry.utils.NettyByteBufLeakHelper) Parameterized(org.junit.runners.Parameterized) EnumMap(java.util.EnumMap) Collection(java.util.Collection) Utils(com.github.ambry.utils.Utils) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) Collectors(java.util.stream.Collectors) BlobInfo(com.github.ambry.messageformat.BlobInfo) RouterConfig(com.github.ambry.config.RouterConfig) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) MockTime(com.github.ambry.utils.MockTime) LoggingNotificationSystem(com.github.ambry.commons.LoggingNotificationSystem) Callback(com.github.ambry.commons.Callback) BlobType(com.github.ambry.messageformat.BlobType) InMemAccountService(com.github.ambry.account.InMemAccountService) PartitionId(com.github.ambry.clustermap.PartitionId) BlobId(com.github.ambry.commons.BlobId) ResponseHandler(com.github.ambry.commons.ResponseHandler) NetworkMetrics(com.github.ambry.network.NetworkMetrics) DataInputStream(java.io.DataInputStream) CloudDestinationFactory(com.github.ambry.cloud.CloudDestinationFactory) ServerErrorCode(com.github.ambry.server.ServerErrorCode) RunWith(org.junit.runner.RunWith) AccountService(com.github.ambry.account.AccountService) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) CloudConfig(com.github.ambry.config.CloudConfig) NettyByteBufDataInputStream(com.github.ambry.utils.NettyByteBufDataInputStream) RequestHandlerPool(com.github.ambry.protocol.RequestHandlerPool) ByteBuf(io.netty.buffer.ByteBuf) LatchBasedInMemoryCloudDestination(com.github.ambry.cloud.LatchBasedInMemoryCloudDestination) LocalRequestResponseChannel(com.github.ambry.network.LocalRequestResponseChannel) PutRequest(com.github.ambry.protocol.PutRequest) NetworkClientFactory(com.github.ambry.network.NetworkClientFactory) Before(org.junit.Before) Properties(java.util.Properties) Iterator(java.util.Iterator) ReplicaType(com.github.ambry.clustermap.ReplicaType) NetworkClient(com.github.ambry.network.NetworkClient) VerifiableProperties(com.github.ambry.config.VerifiableProperties) ByteBufferAsyncWritableChannel(com.github.ambry.commons.ByteBufferAsyncWritableChannel) Test(org.junit.Test) BlobIdFactory(com.github.ambry.commons.BlobIdFactory) LatchBasedInMemoryCloudDestinationFactory(com.github.ambry.cloud.LatchBasedInMemoryCloudDestinationFactory) RequestInfo(com.github.ambry.network.RequestInfo) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) CompositeNetworkClientFactory(com.github.ambry.network.CompositeNetworkClientFactory) ReplicaId(com.github.ambry.clustermap.ReplicaId) Port(com.github.ambry.network.Port) Assert(org.junit.Assert) Collections(java.util.Collections) MockClusterMap(com.github.ambry.clustermap.MockClusterMap) ResponseInfo(com.github.ambry.network.ResponseInfo) HashMap(java.util.HashMap) BlobInfo(com.github.ambry.messageformat.BlobInfo) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBufferAsyncWritableChannel(com.github.ambry.commons.ByteBufferAsyncWritableChannel) GetResponse(com.github.ambry.protocol.GetResponse) ServerErrorCode(com.github.ambry.server.ServerErrorCode) AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicLong(java.util.concurrent.atomic.AtomicLong)

Example 90 with MockClusterMap

use of com.github.ambry.clustermap.MockClusterMap in project ambry by linkedin.

the class NonBlockingRouterTest method testBadCallbackForUpdateTtl.

/**
 * Test that a bad user defined callback will not crash the router or the manager.
 * @throws Exception
 */
@Test
public void testBadCallbackForUpdateTtl() throws Exception {
    try {
        MockServerLayout serverLayout = new MockServerLayout(mockClusterMap);
        setRouter(getNonBlockingRouterProperties("DC1"), serverLayout, new LoggingNotificationSystem());
        setOperationParams();
        String blobId = router.putBlob(putBlobProperties, putUserMetadata, putChannel, new PutBlobOptionsBuilder().build()).get(AWAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
        putChannel = new ByteBufferReadableStreamChannel(ByteBuffer.wrap(putContent));
        String blobIdCheck = router.putBlob(putBlobProperties, putUserMetadata, putChannel, new PutBlobOptionsBuilder().build()).get(AWAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
        testWithErrorCodes(Collections.singletonMap(ServerErrorCode.No_Error, 9), serverLayout, null, expectedError -> {
            final CountDownLatch callbackCalled = new CountDownLatch(1);
            router.updateBlobTtl(blobId, null, Utils.Infinite_Time, (result, exception) -> {
                callbackCalled.countDown();
                throw new RuntimeException("Throwing an exception in the user callback");
            }, null).get(AWAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
            assertTrue("Callback not called.", callbackCalled.await(10, TimeUnit.MILLISECONDS));
            assertEquals("All operations should be finished.", 0, router.getOperationsCount());
            assertTrue("Router should not be closed", router.isOpen());
            assertTtl(router, Collections.singleton(blobId), Utils.Infinite_Time);
            // Test that TtlUpdateManager is still functional
            router.updateBlobTtl(blobIdCheck, null, Utils.Infinite_Time).get(AWAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
            assertTtl(router, Collections.singleton(blobIdCheck), Utils.Infinite_Time);
        });
    } finally {
        if (router != null) {
            router.close();
        }
    }
}
Also used : ResponseInfo(com.github.ambry.network.ResponseInfo) GetOption(com.github.ambry.protocol.GetOption) MockRestRequest(com.github.ambry.rest.MockRestRequest) Arrays(java.util.Arrays) ArgumentMatchers(org.mockito.ArgumentMatchers) BlobProperties(com.github.ambry.messageformat.BlobProperties) DataNodeId(com.github.ambry.clustermap.DataNodeId) LoggerFactory(org.slf4j.LoggerFactory) ByteBufferReadableStreamChannel(com.github.ambry.commons.ByteBufferReadableStreamChannel) ByteBuffer(java.nio.ByteBuffer) Future(java.util.concurrent.Future) JSONObject(org.json.JSONObject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) NetworkClientErrorCode(com.github.ambry.network.NetworkClientErrorCode) TestUtils(com.github.ambry.utils.TestUtils) Map(java.util.Map) RequestOrResponseType(com.github.ambry.protocol.RequestOrResponseType) Parameterized(org.junit.runners.Parameterized) Container(com.github.ambry.account.Container) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Utils(com.github.ambry.utils.Utils) Collectors(java.util.stream.Collectors) RouterConfig(com.github.ambry.config.RouterConfig) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) MockTime(com.github.ambry.utils.MockTime) Account(com.github.ambry.account.Account) LoggingNotificationSystem(com.github.ambry.commons.LoggingNotificationSystem) BlobId(com.github.ambry.commons.BlobId) ResponseHandler(com.github.ambry.commons.ResponseHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServerErrorCode(com.github.ambry.server.ServerErrorCode) RunWith(org.junit.runner.RunWith) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) SystemTime(com.github.ambry.utils.SystemTime) SocketNetworkClient(com.github.ambry.network.SocketNetworkClient) Assume(org.junit.Assume) LinkedList(java.util.LinkedList) NetworkClientFactory(com.github.ambry.network.NetworkClientFactory) MockDataNodeId(com.github.ambry.clustermap.MockDataNodeId) Properties(java.util.Properties) LongStream(java.util.stream.LongStream) Logger(org.slf4j.Logger) RestMethod(com.github.ambry.rest.RestMethod) NetworkClient(com.github.ambry.network.NetworkClient) VerifiableProperties(com.github.ambry.config.VerifiableProperties) RouterTestHelpers(com.github.ambry.router.RouterTestHelpers) Test(org.junit.Test) PrimitiveIterator(java.util.PrimitiveIterator) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Mockito(org.mockito.Mockito) KMSConfig(com.github.ambry.config.KMSConfig) ReplicaId(com.github.ambry.clustermap.ReplicaId) MessageFormatRecord(com.github.ambry.messageformat.MessageFormatRecord) Assert(org.junit.Assert) RestRequest(com.github.ambry.rest.RestRequest) Collections(java.util.Collections) MockClusterMap(com.github.ambry.clustermap.MockClusterMap) ByteBufferReadableStreamChannel(com.github.ambry.commons.ByteBufferReadableStreamChannel) LoggingNotificationSystem(com.github.ambry.commons.LoggingNotificationSystem) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Aggregations

MockClusterMap (com.github.ambry.clustermap.MockClusterMap)109 Test (org.junit.Test)78 MockPartitionId (com.github.ambry.clustermap.MockPartitionId)57 VerifiableProperties (com.github.ambry.config.VerifiableProperties)55 Properties (java.util.Properties)50 ArrayList (java.util.ArrayList)44 PartitionId (com.github.ambry.clustermap.PartitionId)42 MockDataNodeId (com.github.ambry.clustermap.MockDataNodeId)40 HashMap (java.util.HashMap)36 Map (java.util.Map)33 BlobId (com.github.ambry.commons.BlobId)32 ClusterMap (com.github.ambry.clustermap.ClusterMap)31 MetricRegistry (com.codahale.metrics.MetricRegistry)30 Port (com.github.ambry.network.Port)29 List (java.util.List)28 DataNodeId (com.github.ambry.clustermap.DataNodeId)26 ReplicaId (com.github.ambry.clustermap.ReplicaId)26 BlobIdFactory (com.github.ambry.commons.BlobIdFactory)26 BlobProperties (com.github.ambry.messageformat.BlobProperties)23 DataInputStream (java.io.DataInputStream)23