Search in sources :

Example 11 with TxnStatus

use of io.pravega.controller.stream.api.grpc.v1.Controller.TxnStatus in project pravega by pravega.

the class ZkStreamTest method testTransaction.

@Test(timeout = 10000)
public void testTransaction() throws Exception {
    final ScalingPolicy policy = ScalingPolicy.fixed(5);
    final StreamMetadataStore store = new ZKStreamMetadataStore(cli, executor);
    final String streamName = "testTx";
    store.createScope(SCOPE).get();
    final Predicate<Throwable> operationNotAllowedPredicate = ex -> Exceptions.unwrap(ex) instanceof StoreException.IllegalStateException;
    StreamConfiguration streamConfig = StreamConfiguration.builder().scope(SCOPE).streamName(streamName).scalingPolicy(policy).build();
    store.createStream(SCOPE, streamName, streamConfig, System.currentTimeMillis(), null, executor).get();
    store.setState(SCOPE, streamName, State.ACTIVE, null, executor).get();
    OperationContext context = store.createContext(ZkStreamTest.SCOPE, streamName);
    UUID txnId1 = UUID.randomUUID();
    VersionedTransactionData tx = store.createTransaction(SCOPE, streamName, txnId1, 10000, 600000, 30000, context, executor).get();
    Assert.assertEquals(txnId1, tx.getId());
    UUID txnId2 = UUID.randomUUID();
    VersionedTransactionData tx2 = store.createTransaction(SCOPE, streamName, txnId2, 10000, 600000, 30000, context, executor).get();
    Assert.assertEquals(txnId2, tx2.getId());
    store.sealTransaction(SCOPE, streamName, tx.getId(), true, Optional.<Integer>empty(), context, executor).get();
    assert store.transactionStatus(SCOPE, streamName, tx.getId(), context, executor).get().equals(TxnStatus.COMMITTING);
    // Test to ensure that sealTransaction is idempotent.
    Assert.assertEquals(TxnStatus.COMMITTING, store.sealTransaction(SCOPE, streamName, tx.getId(), true, Optional.empty(), context, executor).join().getKey());
    // Test to ensure that COMMITTING transaction cannot be aborted.
    testAbortFailure(store, SCOPE, streamName, tx.getEpoch(), tx.getId(), context, operationNotAllowedPredicate);
    CompletableFuture<TxnStatus> f1 = store.commitTransaction(SCOPE, streamName, tx.getEpoch(), tx.getId(), context, executor);
    store.sealTransaction(SCOPE, streamName, tx2.getId(), false, Optional.<Integer>empty(), context, executor).get();
    assert store.transactionStatus(SCOPE, streamName, tx2.getId(), context, executor).get().equals(TxnStatus.ABORTING);
    // Test to ensure that sealTransaction is idempotent.
    Assert.assertEquals(TxnStatus.ABORTING, store.sealTransaction(SCOPE, streamName, tx2.getId(), false, Optional.empty(), context, executor).join().getKey());
    // Test to ensure that ABORTING transaction cannot be committed.
    testCommitFailure(store, SCOPE, streamName, tx2.getEpoch(), tx2.getId(), context, operationNotAllowedPredicate);
    CompletableFuture<TxnStatus> f2 = store.abortTransaction(SCOPE, streamName, tx2.getEpoch(), tx2.getId(), context, executor);
    CompletableFuture.allOf(f1, f2).get();
    assert store.transactionStatus(SCOPE, streamName, tx.getId(), context, executor).get().equals(TxnStatus.COMMITTED);
    assert store.transactionStatus(SCOPE, streamName, tx2.getId(), context, executor).get().equals(TxnStatus.ABORTED);
    // Test to ensure that sealTransaction, to commit it, on committed transaction does not throw an error.
    Assert.assertEquals(TxnStatus.COMMITTED, store.sealTransaction(SCOPE, streamName, tx.getId(), true, Optional.empty(), context, executor).join().getKey());
    // Test to ensure that commitTransaction is idempotent.
    Assert.assertEquals(TxnStatus.COMMITTED, store.commitTransaction(SCOPE, streamName, tx.getEpoch(), tx.getId(), context, executor).join());
    // Test to ensure that sealTransaction, to abort it, and abortTransaction on committed transaction throws error.
    testAbortFailure(store, SCOPE, streamName, tx.getEpoch(), tx.getId(), context, operationNotAllowedPredicate);
    // Test to ensure that sealTransaction, to abort it, on aborted transaction does not throw an error.
    Assert.assertEquals(TxnStatus.ABORTED, store.sealTransaction(SCOPE, streamName, tx2.getId(), false, Optional.empty(), context, executor).join().getKey());
    // Test to ensure that abortTransaction is idempotent.
    Assert.assertEquals(TxnStatus.ABORTED, store.abortTransaction(SCOPE, streamName, tx2.getEpoch(), tx2.getId(), context, executor).join());
    // Test to ensure that sealTransaction, to abort it, and abortTransaction on committed transaction throws error.
    testCommitFailure(store, SCOPE, streamName, tx2.getEpoch(), tx2.getId(), context, operationNotAllowedPredicate);
    assert store.commitTransaction(ZkStreamTest.SCOPE, streamName, 0, UUID.randomUUID(), null, executor).handle((ok, ex) -> {
        if (ex.getCause() instanceof StoreException.DataNotFoundException) {
            return true;
        } else {
            throw new RuntimeException("assert failed");
        }
    }).get();
    assert store.abortTransaction(ZkStreamTest.SCOPE, streamName, 0, UUID.randomUUID(), null, executor).handle((ok, ex) -> {
        if (ex.getCause() instanceof StoreException.DataNotFoundException) {
            return true;
        } else {
            throw new RuntimeException("assert failed");
        }
    }).get();
    assert store.transactionStatus(ZkStreamTest.SCOPE, streamName, UUID.randomUUID(), context, executor).get().equals(TxnStatus.UNKNOWN);
}
Also used : CuratorFrameworkFactory(org.apache.curator.framework.CuratorFrameworkFactory) Arrays(java.util.Arrays) CreateScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.CreateScopeStatus) AssertExtensions(io.pravega.test.common.AssertExtensions) Exceptions(io.pravega.common.Exceptions) CompletableFuture(java.util.concurrent.CompletableFuture) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) ArrayList(java.util.ArrayList) RetryOneTime(org.apache.curator.retry.RetryOneTime) Lists(com.google.common.collect.Lists) TestingServerStarter(io.pravega.test.common.TestingServerStarter) After(org.junit.After) Map(java.util.Map) TestingServer(org.apache.curator.test.TestingServer) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) DeleteScopeStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteScopeStatus) Before(org.junit.Before) Predicate(java.util.function.Predicate) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) UUID(java.util.UUID) State(io.pravega.controller.store.stream.tables.State) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) ExecutionException(java.util.concurrent.ExecutionException) Mockito(org.mockito.Mockito) AbstractMap(java.util.AbstractMap) List(java.util.List) CuratorFramework(org.apache.curator.framework.CuratorFramework) Assert.assertFalse(org.junit.Assert.assertFalse) Optional(java.util.Optional) Assert(org.junit.Assert) Collections(java.util.Collections) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) Assert.assertEquals(org.junit.Assert.assertEquals) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) UUID(java.util.UUID) Test(org.junit.Test)

Example 12 with TxnStatus

use of io.pravega.controller.stream.api.grpc.v1.Controller.TxnStatus in project pravega by pravega.

the class StreamTransactionMetadataTasks method sealTxnBody.

/**
 * Seals a txn and transitions it to COMMITTING (resp. ABORTING) state if commit param is true (resp. false).
 *
 * Post-condition:
 * 1. If seal completes successfully, then
 *     (a) txn state is COMMITTING/ABORTING,
 *     (b) CommitEvent/AbortEvent is present in the commit stream/abort stream,
 *     (c) txn is removed from host-txn index,
 *     (d) txn is removed from the timeout service.
 *
 * 2. If process fails after transitioning txn to COMMITTING/ABORTING state, but before responding to client, then
 * since txn is present in the host-txn index, some other controller process shall put CommitEvent/AbortEvent to
 * commit stream/abort stream.
 *
 * @param host    host id. It is different from hostId iff invoked from TxnSweeper for aborting orphaned txn.
 * @param scope   scope name.
 * @param stream  stream name.
 * @param commit  boolean indicating whether to commit txn.
 * @param txnId   txn id.
 * @param version expected version of txn node in store.
 * @param ctx     context.
 * @return        Txn status after sealing it.
 */
CompletableFuture<TxnStatus> sealTxnBody(final String host, final String scope, final String stream, final boolean commit, final UUID txnId, final Integer version, final OperationContext ctx) {
    TxnResource resource = new TxnResource(scope, stream, txnId);
    Optional<Integer> versionOpt = Optional.ofNullable(version);
    // Step 1. Add txn to current host's index, if it is not already present
    CompletableFuture<Void> addIndex = host.equals(hostId) && !timeoutService.containsTxn(scope, stream, txnId) ? // then txn would no longer be open.
    streamMetadataStore.addTxnToIndex(hostId, resource, Integer.MAX_VALUE) : CompletableFuture.completedFuture(null);
    addIndex.whenComplete((v, e) -> {
        if (e != null) {
            log.debug("Txn={}, already present/newly added to host-txn index of host={}", txnId, hostId);
        } else {
            log.debug("Txn={}, added txn to host-txn index of host={}", txnId, hostId);
        }
    });
    // Step 2. Seal txn
    CompletableFuture<AbstractMap.SimpleEntry<TxnStatus, Integer>> sealFuture = addIndex.thenComposeAsync(x -> streamMetadataStore.sealTransaction(scope, stream, txnId, commit, versionOpt, ctx, executor), executor).whenComplete((v, e) -> {
        if (e != null) {
            log.debug("Txn={}, failed sealing txn", txnId);
        } else {
            log.debug("Txn={}, sealed successfully, commit={}", txnId, commit);
        }
    });
    // Step 3. write event to corresponding stream.
    return sealFuture.thenComposeAsync(pair -> {
        TxnStatus status = pair.getKey();
        switch(status) {
            case COMMITTING:
                return writeCommitEvent(scope, stream, pair.getValue(), txnId, status);
            case ABORTING:
                return writeAbortEvent(scope, stream, pair.getValue(), txnId, status);
            case ABORTED:
            case COMMITTED:
                return CompletableFuture.completedFuture(status);
            case OPEN:
            case UNKNOWN:
            default:
                // exception would be thrown.
                return CompletableFuture.completedFuture(status);
        }
    }, executor).thenComposeAsync(status -> {
        // Step 4. Remove txn from timeoutService, and from the index.
        timeoutService.removeTxn(scope, stream, txnId);
        log.debug("Txn={}, removed from timeout service", txnId);
        return streamMetadataStore.removeTxnFromIndex(host, resource, true).whenComplete((v, e) -> {
            if (e != null) {
                log.debug("Txn={}, failed removing txn from host-txn index of host={}", txnId, hostId);
            } else {
                log.debug("Txn={}, removed txn from host-txn index of host={}", txnId, hostId);
            }
        }).thenApply(x -> status);
    }, executor);
}
Also used : CommitEvent(io.pravega.shared.controller.event.CommitEvent) OperationContext(io.pravega.controller.store.stream.OperationContext) ControllerEventProcessors(io.pravega.controller.server.eventProcessor.ControllerEventProcessors) Getter(lombok.Getter) EventStreamWriter(io.pravega.client.stream.EventStreamWriter) SegmentHelper(io.pravega.controller.server.SegmentHelper) PravegaInterceptor(io.pravega.controller.server.rpc.auth.PravegaInterceptor) CompletableFuture(java.util.concurrent.CompletableFuture) TimeoutServiceConfig(io.pravega.controller.timeout.TimeoutServiceConfig) Status(io.pravega.controller.stream.api.grpc.v1.Controller.PingTxnStatus.Status) AbortEvent(io.pravega.shared.controller.event.AbortEvent) Pair(org.apache.commons.lang3.tuple.Pair) Duration(java.time.Duration) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) RETRYABLE_PREDICATE(io.pravega.controller.util.RetryHelper.RETRYABLE_PREDICATE) Segment(io.pravega.controller.store.stream.Segment) TimerWheelTimeoutService(io.pravega.controller.timeout.TimerWheelTimeoutService) ConnectionFactory(io.pravega.client.netty.impl.ConnectionFactory) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) RetryHelper.withRetriesAsync(io.pravega.controller.util.RetryHelper.withRetriesAsync) ControllerEventProcessorConfig(io.pravega.controller.server.eventProcessor.ControllerEventProcessorConfig) BlockingQueue(java.util.concurrent.BlockingQueue) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) TxnResource(io.pravega.controller.store.task.TxnResource) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractMap(java.util.AbstractMap) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Config(io.pravega.controller.util.Config) HostControllerStore(io.pravega.controller.store.host.HostControllerStore) TxnStatus(io.pravega.controller.store.stream.TxnStatus) ClientFactory(io.pravega.client.ClientFactory) VersionedTransactionData(io.pravega.controller.store.stream.VersionedTransactionData) Optional(java.util.Optional) TimeoutService(io.pravega.controller.timeout.TimeoutService) VisibleForTesting(com.google.common.annotations.VisibleForTesting) StreamMetadataStore(io.pravega.controller.store.stream.StreamMetadataStore) PingTxnStatus(io.pravega.controller.stream.api.grpc.v1.Controller.PingTxnStatus) Futures(io.pravega.common.concurrent.Futures) TxnResource(io.pravega.controller.store.task.TxnResource) TxnStatus(io.pravega.controller.store.stream.TxnStatus) PingTxnStatus(io.pravega.controller.stream.api.grpc.v1.Controller.PingTxnStatus)

Aggregations

TxnStatus (io.pravega.controller.store.stream.TxnStatus)9 VersionedTransactionData (io.pravega.controller.store.stream.VersionedTransactionData)9 PingTxnStatus (io.pravega.controller.stream.api.grpc.v1.Controller.PingTxnStatus)9 Test (org.junit.Test)9 CompletableFuture (java.util.concurrent.CompletableFuture)6 UUID (java.util.UUID)5 ScalingPolicy (io.pravega.client.stream.ScalingPolicy)3 StreamConfiguration (io.pravega.client.stream.StreamConfiguration)3 Controller (io.pravega.controller.stream.api.grpc.v1.Controller)3 ClientFactory (io.pravega.client.ClientFactory)2 ConnectionFactory (io.pravega.client.netty.impl.ConnectionFactory)2 EventStreamWriter (io.pravega.client.stream.EventStreamWriter)2 AuthenticationException (io.pravega.common.auth.AuthenticationException)2 Futures (io.pravega.common.concurrent.Futures)2 ControllerService (io.pravega.controller.server.ControllerService)2 SegmentHelper (io.pravega.controller.server.SegmentHelper)2 HostControllerStore (io.pravega.controller.store.host.HostControllerStore)2 TxnStatus (io.pravega.controller.stream.api.grpc.v1.Controller.TxnStatus)2 AbortEvent (io.pravega.shared.controller.event.AbortEvent)2 CommitEvent (io.pravega.shared.controller.event.CommitEvent)2