public void commit(Xid xid, boolean isOnePhase) throws XAException {
   // always call prepare() - even if this is just a 1PC!
   if (isOnePhase) prepare(xid);
   if (trace) log.trace("committing TransactionXaAdapter: " + globalTx);
   try {
     LocalTxInvocationContext ctx = icc.createTxInvocationContext();
     ctx.setXaCache(this);
     if (configuration.isOnePhaseCommit()) {
       checkMarkedForRollback();
       if (trace) log.trace("Doing an 1PC prepare call on the interceptor chain");
       PrepareCommand command = commandsFactory.buildPrepareCommand(globalTx, modifications, true);
       try {
         invoker.invoke(ctx, command);
       } catch (Throwable e) {
         log.error("Error while processing 1PC PrepareCommand", e);
         throw new XAException(XAException.XAER_RMERR);
       }
     } else {
       CommitCommand commitCommand = commandsFactory.buildCommitCommand(globalTx);
       try {
         invoker.invoke(ctx, commitCommand);
       } catch (Throwable e) {
         log.error("Error while processing 1PC PrepareCommand", e);
         throw new XAException(XAException.XAER_RMERR);
       }
     }
   } finally {
     txTable.removeLocalTransaction(transaction);
     this.modifications = null;
   }
 }
 public static void replicateCommand(Cache cache, VisitableCommand command) throws Throwable {
   ComponentRegistry cr = extractComponentRegistry(cache);
   InterceptorChain ic = cr.getComponent(InterceptorChain.class);
   InvocationContextContainer icc = cr.getComponent(InvocationContextContainer.class);
   InvocationContext ctxt = icc.createInvocationContext(true, -1);
   ic.invoke(ctxt, command);
 }
  /**
   * Replaces the existing interceptor chain in the cache wih one represented by the interceptor
   * passed in. This utility updates dependencies on all components that rely on the interceptor
   * chain as well.
   *
   * @param cache cache that needs to be altered
   * @param interceptor the first interceptor in the new chain.
   */
  public static void replaceInterceptorChain(Cache cache, CommandInterceptor interceptor) {
    ComponentRegistry cr = extractComponentRegistry(cache);
    // make sure all interceptors here are wired.
    CommandInterceptor i = interceptor;
    do {
      cr.wireDependencies(i);
    } while ((i = i.getNext()) != null);

    InterceptorChain inch = cr.getComponent(InterceptorChain.class);
    inch.setFirstInChain(interceptor);
  }
 @Override
 protected final void resetCaches(List<Cache<GroupKey, String>> cacheList) {
   for (Cache cache : cacheList) {
     InterceptorChain chain = TestingUtil.extractComponent(cache, InterceptorChain.class);
     if (chain.containsInterceptorType(BlockCommandInterceptor.class)) {
       ((BlockCommandInterceptor)
               chain.getInterceptorsWithClass(BlockCommandInterceptor.class).get(0))
           .reset();
     }
   }
 }
 /**
  * Replaces an existing interceptor of the given type in the interceptor chain with a new
  * interceptor instance passed as parameter.
  *
  * @param replacingInterceptor the interceptor to add to the interceptor chain
  * @param toBeReplacedInterceptorType the type of interceptor that should be swapped with the new
  *     one
  * @return true if the interceptor was replaced
  */
 public static boolean replaceInterceptor(
     Cache cache,
     CommandInterceptor replacingInterceptor,
     Class<? extends CommandInterceptor> toBeReplacedInterceptorType) {
   ComponentRegistry cr = extractComponentRegistry(cache);
   // make sure all interceptors here are wired.
   CommandInterceptor i = replacingInterceptor;
   do {
     cr.wireDependencies(i);
   } while ((i = i.getNext()) != null);
   InterceptorChain inch = cr.getComponent(InterceptorChain.class);
   return inch.replaceInterceptor(replacingInterceptor, toBeReplacedInterceptorType);
 }
 private static BlockCommandInterceptor injectBlockCommandInterceptorIfAbsent(
     Cache<GroupKey, String> cache) {
   InterceptorChain chain = TestingUtil.extractComponent(cache, InterceptorChain.class);
   BlockCommandInterceptor interceptor;
   if (chain.containsInterceptorType(BlockCommandInterceptor.class)) {
     interceptor =
         (BlockCommandInterceptor)
             chain.getInterceptorsWithClass(BlockCommandInterceptor.class).get(0);
   } else {
     interceptor = new BlockCommandInterceptor();
     chain.addInterceptorAfter(interceptor, EntryWrappingInterceptor.class);
   }
   interceptor.reset();
   return interceptor;
 }
예제 #7
0
 @SuppressWarnings("unchecked")
 final V get(Object key, EnumSet<Flag> explicitFlags, ClassLoader explicitClassLoader) {
   assertKeyNotNull(key);
   InvocationContext ctx = getInvocationContextForRead(null, explicitFlags, explicitClassLoader);
   GetKeyValueCommand command = commandsFactory.buildGetKeyValueCommand(key, ctx.getFlags());
   return (V) invoker.invoke(ctx, command);
 }
예제 #8
0
  private Object executeCommandAndCommitIfNeeded(InvocationContext ctx, VisitableCommand command) {
    final boolean txInjected =
        ctx.isInTxScope() && ((TxInvocationContext) ctx).isImplicitTransaction();
    Object result;
    try {
      result = invoker.invoke(ctx, command);
    } catch (RuntimeException e) {
      if (txInjected) tryRollback();
      throw e;
    }

    if (txInjected) {
      if (trace)
        log.tracef("Committing transaction as it was implicit: %s", getOngoingTransaction());
      try {
        transactionManager.commit();
      } catch (Throwable e) {
        log.couldNotCompleteInjectedTransaction(e);
        tryRollback();
        throw new CacheException("Could not commit implicit transaction", e);
      }
    }

    return result;
  }
 private void applyStateInTransaction(XSiteState[] chunk) throws Exception {
   try {
     transactionManager.begin();
     InvocationContext ctx =
         invocationContextFactory.createInvocationContext(
             transactionManager.getTransaction(), true);
     ((TxInvocationContext) ctx)
         .getCacheTransaction()
         .setStateTransferFlag(PUT_FOR_X_SITE_STATE_TRANSFER);
     for (XSiteState siteState : chunk) {
       interceptorChain.invoke(ctx, createPut(siteState));
       if (trace) {
         log.tracef("Successfully applied key'%s'", siteState);
       }
     }
     transactionManager.commit();
     if (debug) {
       log.debugf("Successfully applied state. %s keys inserted", chunk.length);
     }
   } catch (Exception e) {
     log.unableToApplyXSiteState(e);
     safeRollback();
     throw e;
   }
 }
예제 #10
0
 final boolean containsKey(
     Object key, EnumSet<Flag> explicitFlags, ClassLoader explicitClassLoader) {
   assertKeyNotNull(key);
   InvocationContext ctx = getInvocationContextForRead(null, explicitFlags, explicitClassLoader);
   GetKeyValueCommand command = commandsFactory.buildGetKeyValueCommand(key, ctx.getFlags());
   Object response = invoker.invoke(ctx, command);
   return response != null;
 }
예제 #11
0
 boolean lock(
     Collection<? extends K> keys, EnumSet<Flag> explicitFlags, ClassLoader explicitClassLoader) {
   if (keys == null || keys.isEmpty()) {
     throw new IllegalArgumentException("Cannot lock empty list of keys");
   }
   InvocationContext ctx = getInvocationContextForWrite(explicitFlags, explicitClassLoader);
   LockControlCommand command =
       commandsFactory.buildLockControlCommand(keys, false, ctx.getFlags());
   return (Boolean) invoker.invoke(ctx, command);
 }
  private void doTest(boolean mods) throws Exception {
    // force the prepare command to fail on c2
    FailInterceptor interceptor = new FailInterceptor();
    interceptor.failFor(PrepareCommand.class);
    InterceptorChain ic = TestingUtil.extractComponent(c2, InterceptorChain.class);
    ic.addInterceptorBefore(interceptor, TxDistributionInterceptor.class);

    MagicKey k1 = new MagicKey("k1", c1);
    MagicKey k2 = new MagicKey("k2", c2);

    tm(c1).begin();
    if (mods) {
      c1.put(k1, "v1");
      c1.put(k2, "v2");

      assertKeyLockedCorrectly(k1);
      assertKeyLockedCorrectly(k2);
    } else {
      c1.getAdvancedCache().lock(k1);
      c1.getAdvancedCache().lock(k2);

      assertNull(c1.get(k1));
      assertNull(c1.get(k2));

      assertKeyLockedCorrectly(k1);
      assertKeyLockedCorrectly(k2);
    }

    try {
      tm(c1).commit();
      assert false : "Commit should have failed";
    } catch (Exception e) {
      // expected
    }

    assertNotLocked(c1, k1);
    assertNotLocked(c2, k1);
    assertNotLocked(c1, k2);
    assertNotLocked(c2, k2);
  }
 public void applyRemoteTxLog(List<WriteCommand> commands) {
   for (WriteCommand cmd : commands) {
     try {
       // this is a remotely originating tx
       cf.initializeReplicableCommand(cmd, true);
       InvocationContext ctx = icc.createInvocationContext();
       ctx.setFlags(SKIP_REMOTE_LOOKUP, CACHE_MODE_LOCAL, SKIP_SHARED_CACHE_STORE, SKIP_LOCKING);
       interceptorChain.invoke(ctx, cmd);
     } catch (Exception e) {
       log.exceptionWhenReplaying(cmd, e);
     }
   }
 }
예제 #14
0
 public void rollback(Xid xid) throws XAException {
   RollbackCommand rollbackCommand = commandsFactory.buildRollbackCommand(globalTx);
   LocalTxInvocationContext ctx = icc.createTxInvocationContext();
   ctx.setXaCache(this);
   try {
     invoker.invoke(ctx, rollbackCommand);
   } catch (Throwable e) {
     log.error("Exception while rollback", e);
     throw new XAException(XAException.XA_HEURHAZ);
   } finally {
     txTable.removeLocalTransaction(transaction);
     this.modifications = null;
   }
 }
예제 #15
0
  private void createQueryInterceptorIfNeeded(
      ComponentRegistry cr, Configuration cfg, SearchFactoryIntegrator searchFactory) {
    QueryInterceptor queryInterceptor = cr.getComponent(QueryInterceptor.class);
    if (queryInterceptor == null) {
      queryInterceptor = buildQueryInterceptor(cfg, searchFactory);

      // Interceptor registration not needed, core configuration handling
      // already does it for all custom interceptors - UNLESS the InterceptorChain already exists in
      // the component registry!
      InterceptorChain ic = cr.getComponent(InterceptorChain.class);

      ConfigurationBuilder builder = new ConfigurationBuilder().read(cfg);
      InterceptorConfigurationBuilder interceptorBuilder =
          builder.customInterceptors().addInterceptor();
      interceptorBuilder.interceptor(queryInterceptor);

      if (!cfg.transaction().transactionMode().isTransactional()) {
        if (ic != null)
          ic.addInterceptorAfter(queryInterceptor, NonTransactionalLockingInterceptor.class);
        interceptorBuilder.after(NonTransactionalLockingInterceptor.class);
      } else if (cfg.transaction().lockingMode() == LockingMode.OPTIMISTIC) {
        if (ic != null)
          ic.addInterceptorAfter(queryInterceptor, OptimisticLockingInterceptor.class);
        interceptorBuilder.after(OptimisticLockingInterceptor.class);
      } else {
        if (ic != null)
          ic.addInterceptorAfter(queryInterceptor, PessimisticLockingInterceptor.class);
        interceptorBuilder.after(PessimisticLockingInterceptor.class);
      }
      if (ic != null) {
        cr.registerComponent(queryInterceptor, QueryInterceptor.class);
        cr.registerComponent(queryInterceptor, queryInterceptor.getClass().getName(), true);
      }
      cfg.customInterceptors().interceptors(builder.build().customInterceptors().interceptors());
    }
  }
예제 #16
0
  private void applyStateInNonTransaction(XSiteState[] chunk) {
    SingleKeyNonTxInvocationContext ctx =
        (SingleKeyNonTxInvocationContext)
            invocationContextFactory.createSingleKeyNonTxInvocationContext();

    for (XSiteState siteState : chunk) {
      PutKeyValueCommand command = createPut(siteState);
      ctx.setLockOwner(command.getLockOwner());
      interceptorChain.invoke(ctx, command);
      ctx.resetState(); // re-use same context. Old context is not longer needed
      if (trace) {
        log.tracef("Successfully applied key'%s'", siteState);
      }
    }
    if (debug) {
      log.debugf("Successfully applied state. %s keys inserted", chunk.length);
    }
  }
예제 #17
0
  public int prepare(Xid xid) throws XAException {
    checkMarkedForRollback();
    if (configuration.isOnePhaseCommit()) {
      if (trace)
        log.trace("Received prepare for tx: " + xid + " . Skipping call as 1PC will be used.");
      return XA_OK;
    }

    PrepareCommand prepareCommand =
        commandsFactory.buildPrepareCommand(
            globalTx, modifications, configuration.isOnePhaseCommit());
    if (trace) log.trace("Sending prepare command through the chain: " + prepareCommand);

    LocalTxInvocationContext ctx = icc.createTxInvocationContext();
    ctx.setXaCache(this);
    try {
      invoker.invoke(ctx, prepareCommand);
      return XA_OK;
    } catch (Throwable e) {
      log.error("Error while processing PrepareCommand", e);
      throw new XAException(XAException.XAER_RMERR);
    }
  }
  private Map<Object, InternalCacheValue> applyStateMap(
      Map<Object, InternalCacheValue> state, boolean withRetry) {
    Map<Object, InternalCacheValue> retry =
        withRetry ? new HashMap<Object, InternalCacheValue>() : null;

    for (Map.Entry<Object, InternalCacheValue> e : state.entrySet()) {
      InternalCacheValue v = e.getValue();
      InvocationContext ctx = icc.createInvocationContext();
      // locking not necessary in the case of a join since the node isn't doing anything else
      // TODO what if the node is already running?
      ctx.setFlags(
          CACHE_MODE_LOCAL,
          SKIP_CACHE_LOAD,
          SKIP_REMOTE_LOOKUP,
          SKIP_SHARED_CACHE_STORE,
          SKIP_LOCKING,
          SKIP_OWNERSHIP_CHECK);
      try {
        PutKeyValueCommand put =
            cf.buildPutKeyValueCommand(
                e.getKey(), v.getValue(), v.getLifespan(), v.getMaxIdle(), ctx.getFlags());
        interceptorChain.invoke(ctx, put);
      } catch (Exception ee) {
        if (withRetry) {
          if (trace)
            log.tracef(
                "Problem %s encountered when applying state for key %s. Adding entry to retry queue.",
                ee.getMessage(), e.getKey());
          retry.put(e.getKey(), e.getValue());
        } else {
          log.problemApplyingStateForKey(ee.getMessage(), e.getKey());
        }
      }
    }
    return retry;
  }
예제 #19
0
 @SuppressWarnings("unchecked")
 Set<Map.Entry<K, V>> entrySet(EnumSet<Flag> explicitFlags, ClassLoader explicitClassLoader) {
   InvocationContext ctx = getInvocationContextForRead(null, explicitFlags, explicitClassLoader);
   EntrySetCommand command = commandsFactory.buildEntrySetCommand();
   return (Set<Map.Entry<K, V>>) invoker.invoke(ctx, command);
 }
예제 #20
0
 private boolean verifyChainContainsQueryInterceptor(ComponentRegistry cr) {
   InterceptorChain interceptorChain = cr.getComponent(InterceptorChain.class);
   return interceptorChain.containsInterceptorType(QueryInterceptor.class, true);
 }
 private void removeCommandBlocked(Cache cache) {
   InterceptorChain chain = TestingUtil.extractComponent(cache, InterceptorChain.class);
   chain.removeInterceptor(CommandBlocker.class);
 }
 private CommandBlocker addCommandBlocker(Cache cache) {
   InterceptorChain chain = TestingUtil.extractComponent(cache, InterceptorChain.class);
   CommandBlocker blocker = new CommandBlocker();
   chain.addInterceptor(blocker, 0);
   return blocker;
 }
예제 #23
0
 public void removeInterceptor(Class<? extends CommandInterceptor> interceptorType) {
   invoker.removeInterceptor(interceptorType);
 }
예제 #24
0
 public void removeInterceptor(int position) {
   invoker.removeInterceptor(position);
 }
예제 #25
0
 public void addInterceptorBefore(
     CommandInterceptor i, Class<? extends CommandInterceptor> beforeInterceptor) {
   invoker.addInterceptorBefore(i, beforeInterceptor);
 }
예제 #26
0
 public void addInterceptorAfter(
     CommandInterceptor i, Class<? extends CommandInterceptor> afterInterceptor) {
   invoker.addInterceptorAfter(i, afterInterceptor);
 }
예제 #27
0
 public void addInterceptor(CommandInterceptor i, int position) {
   invoker.addInterceptor(i, position);
 }
예제 #28
0
 public List<CommandInterceptor> getInterceptorChain() {
   return invoker.asList();
 }
예제 #29
0
 final void evict(K key, EnumSet<Flag> explicitFlags, ClassLoader explicitClassLoader) {
   assertKeyNotNull(key);
   InvocationContext ctx = createNonTxInvocationContext(explicitFlags, explicitClassLoader);
   EvictCommand command = commandsFactory.buildEvictCommand(key);
   invoker.invoke(ctx, command);
 }
예제 #30
0
 @SuppressWarnings("unchecked")
 Collection<V> values(EnumSet<Flag> explicitFlags, ClassLoader explicitClassLoader) {
   InvocationContext ctx = getInvocationContextForRead(null, explicitFlags, explicitClassLoader);
   ValuesCommand command = commandsFactory.buildValuesCommand();
   return (Collection<V>) invoker.invoke(ctx, command);
 }