You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@servicecomb.apache.org by GitBox <gi...@apache.org> on 2018/10/08 01:14:15 UTC

[GitHub] oliugian closed pull request #311: SCB-915:saga alpha event scanner optimization

oliugian closed pull request #311: SCB-915:saga alpha event scanner optimization
URL: https://github.com/apache/incubator-servicecomb-saga/pull/311
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git a/omega/omega-spring-tx/src/test/java/org/apache/servicecomb/saga/omega/transaction/spring/TransactionInterceptionTest.java b/omega/omega-spring-tx/src/test/java/org/apache/servicecomb/saga/omega/transaction/spring/TransactionInterceptionTest.java
index 6b66befb..4775f6b6 100644
--- a/omega/omega-spring-tx/src/test/java/org/apache/servicecomb/saga/omega/transaction/spring/TransactionInterceptionTest.java
+++ b/omega/omega-spring-tx/src/test/java/org/apache/servicecomb/saga/omega/transaction/spring/TransactionInterceptionTest.java
@@ -202,19 +202,13 @@ public void retryTillSuccess() {
       fail("unexpected exception throw: " + e);
     }
 
-    assertThat(messages.size(), is(4));
+    assertThat(messages.size(), is(2));
 
     assertThat(messages.get(0),
         is(new TxStartedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod2, 0, retryMethod, 2, user, 1)
             .toString()));
 
-    String abortedEvent = messages.get(1);
-    assertThat(abortedEvent, allOf(containsString("TxAbortedEvent"), containsString("Retry harder")));
-
-    assertThat(messages.get(2),
-        is(new TxStartedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod2, 0, retryMethod, 1, user, 1)
-            .toString()));
-    assertThat(messages.get(3),
+    assertThat(messages.get(1),
         is(new TxEndedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod2).toString()));
 
     assertThat(userRepository.count(), is(1L));
@@ -233,7 +227,7 @@ public void retryReachesMaximumThenThrowsException() {
       assertThat(e.getMessage(), is("Retry harder"));
     }
 
-    assertThat(messages.size(), is(4));
+    assertThat(messages.size(), is(2));
     assertThat(messages.get(0),
         is(new TxStartedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod2, 0, retryMethod, 2, user, 3)
             .toString()));
@@ -241,12 +235,6 @@ public void retryReachesMaximumThenThrowsException() {
     String abortedEvent1 = messages.get(1);
     assertThat(abortedEvent1, allOf(containsString("TxAbortedEvent"), containsString("Retry harder")));
 
-    assertThat(messages.get(2),
-        is(new TxStartedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod2, 0, retryMethod, 1, user, 3)
-            .toString()));
-
-    String abortedEvent2 = messages.get(3);
-    assertThat(abortedEvent2, allOf(containsString("TxAbortedEvent"), containsString("Retry harder")));
 
     assertThat(userRepository.count(), is(0L));
   }
diff --git a/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/DefaultRecovery.java b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/DefaultRecovery.java
index 08449813..b37f78db 100644
--- a/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/DefaultRecovery.java
+++ b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/DefaultRecovery.java
@@ -64,13 +64,41 @@ public Object apply(ProceedingJoinPoint joinPoint, Compensable compensable, Comp
       throw new InvalidTransactionException("Abort sub transaction " + abortedLocalTxId +
           " because global transaction " + context.globalTxId() + " has already aborted.");
     }
-
+    int remains = retries;
     try {
-      Object result = joinPoint.proceed();
-      interceptor.postIntercept(parentTxId, compensationSignature);
+      while (true) {
+        try {
+          Object result = joinPoint.proceed();
+          interceptor.postIntercept(parentTxId, compensationSignature);
+          return result;
+        } catch (Throwable throwable) {
+          if (remains == 0){
+            throw throwable;
+          }
+          remains = remains == -1 ? -1 : remains - 1;
+          if (remains == 0) {
+            LOG.error(
+                "Retried sub tx failed maximum times, global tx id: {}, local tx id: {}, method: {}, retried times: {}",
+                context.globalTxId(), context.localTxId(), method.toString(), retries);
+            throw throwable;
+          }
 
-      return result;
-    } catch (Throwable throwable) {
+          LOG.warn(
+              "Retrying sub tx failed, global tx id: {}, local tx id: {}, method: {}, remains: {}",
+              context.globalTxId(), context.localTxId(), method.toString(), remains);
+          Thread.sleep(compensable.retryDelayInMilliseconds());
+        }
+      }
+    }
+    catch(InterruptedException e)
+    {
+      String errorMessage = "Failed to handle tx because it is interrupted, global tx id: " + context.globalTxId()
+          + ", local tx id: " + context.localTxId() + ", method: " + method.toString();
+      LOG.error(errorMessage);
+      interceptor.onError(parentTxId, compensationMethodSignature(joinPoint, compensable, method), e);
+      throw new OmegaException(errorMessage);
+    }
+    catch (Throwable throwable) {
       interceptor.onError(parentTxId, compensationSignature, throwable);
       throw throwable;
     }
diff --git a/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/ForwardRecovery.java b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/ForwardRecovery.java
deleted file mode 100644
index d1a28c2e..00000000
--- a/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/ForwardRecovery.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.servicecomb.saga.omega.transaction;
-
-import java.lang.invoke.MethodHandles;
-import java.lang.reflect.Method;
-
-import javax.transaction.InvalidTransactionException;
-
-import org.apache.servicecomb.saga.omega.context.OmegaContext;
-import org.apache.servicecomb.saga.omega.transaction.annotations.Compensable;
-import org.aspectj.lang.ProceedingJoinPoint;
-import org.aspectj.lang.reflect.MethodSignature;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * ForwardRecovery is used to execute business logic with the given retries times.
- * If retries is above 0, it will retry the given times at most.
- * If retries == -1, it will retry forever until interrupted.
- */
-public class ForwardRecovery extends DefaultRecovery {
-  private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
-
-  // TODO: 2018/03/10 we do not support retry with timeout yet
-  @Override
-  public Object apply(ProceedingJoinPoint joinPoint, Compensable compensable, CompensableInterceptor interceptor,
-      OmegaContext context, String parentTxId, int retries) throws Throwable {
-    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
-    int remains = retries;
-    try {
-      while (true) {
-        try {
-          return super.apply(joinPoint, compensable, interceptor, context, parentTxId, remains);
-        } catch (Throwable throwable) {
-          if (throwable instanceof InvalidTransactionException) {
-            throw throwable;
-          }
-
-          remains = remains == -1 ? -1 : remains - 1;
-          if (remains == 0) {
-            LOG.error(
-                "Retried sub tx failed maximum times, global tx id: {}, local tx id: {}, method: {}, retried times: {}",
-                context.globalTxId(), context.localTxId(), method.toString(), retries);
-            throw throwable;
-          }
-
-          LOG.warn("Retrying sub tx failed, global tx id: {}, local tx id: {}, method: {}, remains: {}",
-              context.globalTxId(), context.localTxId(), method.toString(), remains);
-          Thread.sleep(compensable.retryDelayInMilliseconds());
-        }
-      }
-    } catch (InterruptedException e) {
-      String errorMessage = "Failed to handle tx because it is interrupted, global tx id: " + context.globalTxId()
-          + ", local tx id: " + context.localTxId() + ", method: " + method.toString();
-      LOG.error(errorMessage);
-      interceptor.onError(parentTxId, compensationMethodSignature(joinPoint, compensable, method), e);
-      throw new OmegaException(errorMessage);
-    }
-  }
-}
diff --git a/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/RecoveryPolicyFactory.java b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/RecoveryPolicyFactory.java
index f59ac2b3..9f6426c9 100644
--- a/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/RecoveryPolicyFactory.java
+++ b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/RecoveryPolicyFactory.java
@@ -20,14 +20,13 @@
 public class RecoveryPolicyFactory {
   private static final RecoveryPolicy DEFAULT_RECOVERY = new DefaultRecovery();
 
-  private static final RecoveryPolicy FORWARD_RECOVERY = new ForwardRecovery();
 
   /**
    * If retries == 0, use the default recovery to execute only once.
    * If retries > 0, it will use the forward recovery and retry the given times at most.
    * If retries == -1, it will use the forward recovery and retry forever until interrupted.
    */
-  static RecoveryPolicy getRecoveryPolicy(int retries) {
-    return retries != 0 ? FORWARD_RECOVERY : DEFAULT_RECOVERY;
+  static RecoveryPolicy getRecoveryPolicy() {
+    return DEFAULT_RECOVERY;
   }
 }
diff --git a/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/TransactionAspect.java b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/TransactionAspect.java
index f7a98ee7..d7359006 100644
--- a/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/TransactionAspect.java
+++ b/omega/omega-transaction/src/main/java/org/apache/servicecomb/saga/omega/transaction/TransactionAspect.java
@@ -50,7 +50,7 @@ Object advise(ProceedingJoinPoint joinPoint, Compensable compensable) throws Thr
     LOG.debug("Updated context {} for compensable method {} ", context, method.toString());
 
     int retries = compensable.retries();
-    RecoveryPolicy recoveryPolicy = RecoveryPolicyFactory.getRecoveryPolicy(retries);
+    RecoveryPolicy recoveryPolicy = RecoveryPolicyFactory.getRecoveryPolicy();
     try {
       return recoveryPolicy.apply(joinPoint, compensable, interceptor, context, localTxId, retries);
     } finally {
diff --git a/omega/omega-transaction/src/test/java/org/apache/servicecomb/saga/omega/transaction/ForwardRecoveryTest.java b/omega/omega-transaction/src/test/java/org/apache/servicecomb/saga/omega/transaction/ForwardRecoveryTest.java
deleted file mode 100644
index 9ba4b474..00000000
--- a/omega/omega-transaction/src/test/java/org/apache/servicecomb/saga/omega/transaction/ForwardRecoveryTest.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.servicecomb.saga.omega.transaction;
-
-import static com.seanyinx.github.unit.scaffolding.AssertUtils.expectFailing;
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
-
-import javax.transaction.InvalidTransactionException;
-
-import org.apache.servicecomb.saga.common.EventType;
-import org.apache.servicecomb.saga.omega.context.IdGenerator;
-import org.apache.servicecomb.saga.omega.context.OmegaContext;
-import org.apache.servicecomb.saga.omega.transaction.annotations.Compensable;
-import org.aspectj.lang.ProceedingJoinPoint;
-import org.aspectj.lang.reflect.MethodSignature;
-import org.junit.Before;
-import org.junit.Test;
-
-public class ForwardRecoveryTest {
-  private final List<TxEvent> messages = new ArrayList<>();
-
-  private final String globalTxId = UUID.randomUUID().toString();
-
-  private final String localTxId = UUID.randomUUID().toString();
-
-  private final String parentTxId = UUID.randomUUID().toString();
-
-  private final String newLocalTxId = UUID.randomUUID().toString();
-
-  private final RuntimeException oops = new RuntimeException("oops");
-
-  @SuppressWarnings("unchecked")
-  private final IdGenerator<String> idGenerator = mock(IdGenerator.class);
-
-  private final OmegaContext omegaContext = new OmegaContext(idGenerator);
-
-  private final ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class);
-
-  private final MethodSignature methodSignature = mock(MethodSignature.class);
-
-  private final Compensable compensable = mock(Compensable.class);
-
-  private final MessageSender sender = new MessageSender() {
-    @Override
-    public void onConnected() {
-
-    }
-
-    @Override
-    public void onDisconnected() {
-
-    }
-
-    @Override
-    public void close() {
-
-    }
-
-    @Override
-    public String target() {
-      return "UNKNOWN";
-    }
-
-    @Override
-    public AlphaResponse send(TxEvent event) {
-      messages.add(event);
-      return new AlphaResponse(false);
-    }
-  };
-
-  private final CompensableInterceptor interceptor = new CompensableInterceptor(omegaContext, sender);
-
-  private final RecoveryPolicy recoveryPolicy = new ForwardRecovery();
-
-  private volatile OmegaException exception;
-
-  @Before
-  public void setUp() throws Exception {
-    when(idGenerator.nextId()).thenReturn(newLocalTxId);
-    when(joinPoint.getSignature()).thenReturn(methodSignature);
-    when(joinPoint.getTarget()).thenReturn(this);
-
-    when(methodSignature.getMethod()).thenReturn(this.getClass().getDeclaredMethod("doNothing"));
-    when(compensable.compensationMethod()).thenReturn("doNothing");
-    when(compensable.retries()).thenReturn(0);
-
-    omegaContext.setGlobalTxId(globalTxId);
-    omegaContext.setLocalTxId(localTxId);
-  }
-
-  @Test
-  public void forwardExceptionWhenGlobalTxAborted() {
-    MessageSender sender = mock(MessageSender.class);
-    when(sender.send(any(TxEvent.class))).thenReturn(new AlphaResponse(true));
-
-    CompensableInterceptor interceptor = new CompensableInterceptor(omegaContext, sender);
-
-    try {
-      recoveryPolicy.apply(joinPoint, compensable, interceptor, omegaContext, parentTxId, 0);
-      expectFailing(InvalidTransactionException.class);
-    } catch (InvalidTransactionException e) {
-      assertThat(e.getMessage().contains("Abort sub transaction"), is(true));
-    } catch (Throwable throwable) {
-      fail("unexpected exception throw: " + throwable);
-    }
-
-    verify(sender, times(1)).send(any(TxEvent.class));
-  }
-
-  @Test
-  public void throwExceptionWhenRetryReachesMaximum() throws Throwable {
-    when(compensable.retries()).thenReturn(2);
-    when(joinPoint.proceed()).thenThrow(oops);
-
-    try {
-      recoveryPolicy.apply(joinPoint, compensable, interceptor, omegaContext, parentTxId, 2);
-      expectFailing(RuntimeException.class);
-    } catch (RuntimeException e) {
-      assertThat(e.getMessage(), is("oops"));
-    }
-
-    assertThat(messages.size(), is(4));
-    assertThat(messages.get(0).type(), is(EventType.TxStartedEvent));
-    assertThat(messages.get(1).type(), is(EventType.TxAbortedEvent));
-    assertThat(messages.get(2).type(), is(EventType.TxStartedEvent));
-    assertThat(messages.get(3).type(), is(EventType.TxAbortedEvent));
-  }
-
-  @Test
-  public void keepRetryingTillInterrupted() throws Throwable {
-    when(compensable.retries()).thenReturn(-1);
-    when(compensable.retryDelayInMilliseconds()).thenReturn(1000);
-    when(joinPoint.proceed()).thenThrow(oops);
-
-    Thread thread = new Thread(new Runnable() {
-      @Override
-      public void run() {
-        try {
-          recoveryPolicy.apply(joinPoint, compensable, interceptor, omegaContext, parentTxId, -1);
-          expectFailing(OmegaException.class);
-        } catch (OmegaException e) {
-          exception = e;
-        } catch (Throwable throwable) {
-          fail("unexpected exception throw: " + throwable);
-        }
-      }
-    });
-    thread.start();
-
-    thread.interrupt();
-    thread.join();
-
-    assertThat(exception.getMessage().contains("Failed to handle tx because it is interrupted"), is(true));
-  }
-
-  private String doNothing() {
-    return "doNothing";
-  }
-}
diff --git a/omega/omega-transaction/src/test/java/org/apache/servicecomb/saga/omega/transaction/TransactionAspectTest.java b/omega/omega-transaction/src/test/java/org/apache/servicecomb/saga/omega/transaction/TransactionAspectTest.java
index d7fade6b..a27741ba 100644
--- a/omega/omega-transaction/src/test/java/org/apache/servicecomb/saga/omega/transaction/TransactionAspectTest.java
+++ b/omega/omega-transaction/src/test/java/org/apache/servicecomb/saga/omega/transaction/TransactionAspectTest.java
@@ -151,7 +151,7 @@ public void retryReachesMaximumAndForwardException() throws Throwable {
       assertThat(e.getMessage(), is("oops"));
     }
 
-    assertThat(messages.size(), is(6));
+    assertThat(messages.size(), is(2));
 
     TxEvent startedEvent1 = messages.get(0);
     assertThat(startedEvent1.globalTxId(), is(globalTxId));
@@ -161,24 +161,11 @@ public void retryReachesMaximumAndForwardException() throws Throwable {
     assertThat(startedEvent1.retries(), is(3));
     assertThat(startedEvent1.retryMethod(), is(this.getClass().getDeclaredMethod("doNothing").toString()));
 
-    assertThat(messages.get(1).type(), is(EventType.TxAbortedEvent));
-
-    TxEvent startedEvent2 = messages.get(2);
+    TxEvent startedEvent2 = messages.get(1);
     assertThat(startedEvent2.localTxId(), is(newLocalTxId));
-    assertThat(startedEvent2.type(), is(EventType.TxStartedEvent));
-    assertThat(startedEvent2.retries(), is(2));
-
-    assertThat(messages.get(3).type(), is(EventType.TxAbortedEvent));
-
-    TxEvent startedEvent3 = messages.get(4);
-    assertThat(startedEvent3.localTxId(), is(newLocalTxId));
-    assertThat(startedEvent3.type(), is(EventType.TxStartedEvent));
-    assertThat(startedEvent3.retries(), is(1));
+    assertThat(startedEvent2.type(), is(EventType.TxAbortedEvent));
+    assertThat(startedEvent2.retries(), is(0));
 
-    assertThat(messages.get(5).type(), is(EventType.TxAbortedEvent));
-
-    assertThat(omegaContext.globalTxId(), is(globalTxId));
-    assertThat(omegaContext.localTxId(), is(localTxId));
   }
 
   @Test
@@ -189,7 +176,7 @@ public void keepRetryingTillSuccess() throws Throwable {
 
     aspect.advise(joinPoint, compensable);
 
-    assertThat(messages.size(), is(6));
+    assertThat(messages.size(), is(2));
 
     TxEvent startedEvent1 = messages.get(0);
     assertThat(startedEvent1.globalTxId(), is(globalTxId));
@@ -199,21 +186,7 @@ public void keepRetryingTillSuccess() throws Throwable {
     assertThat(startedEvent1.retries(), is(-1));
     assertThat(startedEvent1.retryMethod(), is(this.getClass().getDeclaredMethod("doNothing").toString()));
 
-    assertThat(messages.get(1).type(), is(EventType.TxAbortedEvent));
-
-    TxEvent startedEvent2 = messages.get(2);
-    assertThat(startedEvent2.localTxId(), is(newLocalTxId));
-    assertThat(startedEvent2.type(), is(EventType.TxStartedEvent));
-    assertThat(startedEvent2.retries(), is(-1));
-
-    assertThat(messages.get(3).type(), is(EventType.TxAbortedEvent));
-
-    TxEvent startedEvent3 = messages.get(4);
-    assertThat(startedEvent3.localTxId(), is(newLocalTxId));
-    assertThat(startedEvent3.type(), is(EventType.TxStartedEvent));
-    assertThat(startedEvent3.retries(), is(-1));
-
-    assertThat(messages.get(5).type(), is(EventType.TxEndedEvent));
+    assertThat(messages.get(1).type(), is(EventType.TxEndedEvent));
 
     assertThat(omegaContext.globalTxId(), is(globalTxId));
     assertThat(omegaContext.localTxId(), is(localTxId));


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services