Ejemplo n.º 1
0
 private static ConsistentHash constructConsistentHashInstance(Configuration c) {
   Class<? extends ConsistentHash> chClass =
       Util.loadClass(c.getConsistentHashClass(), c.getClassLoader());
   Hash h = (Hash) Util.getInstance(c.getHashFunctionClass(), c.getClassLoader());
   HashSeed hs =
       c.getHashSeed() != null
           ? c.getHashSeed()
           : (HashSeed) Util.getInstance(c.getHashSeedClass(), c.getClassLoader());
   return constructConsistentHashInstance(
       chClass, h, hs, c.getNumVirtualNodes(), new GroupManagerImpl(c.getGroupers()));
 }
Ejemplo n.º 2
0
  @Override
  public void start() throws CacheLoaderException {

    try {
      dataSource = new DataSource(config.getPoolProperties());
      readConsistencyLevel = ConsistencyLevel.valueOf(config.readConsistencyLevel);
      writeConsistencyLevel = ConsistencyLevel.valueOf(config.writeConsistencyLevel);
      entryColumnPath =
          new ColumnPath(config.entryColumnFamily)
              .setColumn(ENTRY_COLUMN_NAME.getBytes(UTF8Charset));
      entryColumnParent = new ColumnParent(config.entryColumnFamily);
      entryKeyPrefix = ENTRY_KEY_PREFIX + (config.isSharedKeyspace() ? cacheName + "_" : "");
      expirationColumnParent = new ColumnParent(config.expirationColumnFamily);
      expirationKey =
          ByteBufferUtil.bytes(EXPIRATION_KEY + (config.isSharedKeyspace() ? "_" + cacheName : ""));
      keyMapper = (TwoWayKey2StringMapper) Util.getInstance(config.getKeyMapper());
    } catch (Exception e) {
      throw new ConfigurationException(e);
    }

    log.debug("cleaning up expired entries...");
    purgeInternal();

    log.debug("started");
    super.start();
  }
 public synchronized RspList<Object> getResponseList() throws Exception {
   while (expectedResponses > 0 && retval == null) {
     try {
       this.wait(timeout);
     } catch (InterruptedException e) {
       // reset interruption flag
       Thread.currentThread().interrupt();
       expectedResponses = -1;
     }
   }
   // Now we either have the response we need or aren't expecting any more responses - or have
   // run out of time.
   if (retval != null) return retval;
   else if (exception != null) throw exception;
   else if (expectedResponses == 0)
     throw new RpcException(
         format(
             "No more valid responses.  Received invalid responses from all of %s",
             futures.values()));
   else
     throw new TimeoutException(
         format(
             "Timed out waiting for %s for valid responses from any of %s.",
             Util.prettyPrintTime(timeout), futures.values()));
 }
Ejemplo n.º 4
0
  private void shutDownGracefully() {
    if (log.isDebugEnabled())
      log.debugf(
          "Wait for on-going transactions to finish for %s.",
          Util.prettyPrintTime(
              configuration.transaction().cacheStopTimeout(), TimeUnit.MILLISECONDS));
    long failTime = currentMillisFromNanotime() + configuration.transaction().cacheStopTimeout();
    boolean txsOnGoing = areTxsOnGoing();
    while (txsOnGoing && currentMillisFromNanotime() < failTime) {
      try {
        Thread.sleep(30);
        txsOnGoing = areTxsOnGoing();
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        if (clustered) {
          log.debugf(
              "Interrupted waiting for on-going transactions to finish. %s local transactions and %s remote transactions",
              localTransactions.size(), remoteTransactions.size());
        } else {
          log.debugf(
              "Interrupted waiting for %s on-going transactions to finish.",
              localTransactions.size());
        }
      }
    }

    if (txsOnGoing) {
      log.unfinishedTransactionsRemain(
          localTransactions == null ? 0 : localTransactions.size(),
          remoteTransactions == null ? 0 : remoteTransactions.size());
    } else {
      log.debug("All transactions terminated");
    }
  }
Ejemplo n.º 5
0
 @Override
 public String toString() {
   return "Cache '"
       + name
       + "'@"
       + (config.getCacheMode().isClustered()
           ? getCacheManager().getAddress()
           : Util.hexIdHashCode(this));
 }
Ejemplo n.º 6
0
 /**
  * Returns true if this Fqn is equals or the child of parentFqn. Example usage:
  *
  * <pre>
  * Fqn<String> f1 = Fqn.fromString("/a/b");
  * Fqn<String> f2 = Fqn.fromString("/a/b/c");
  * assertTrue(f1.isChildOrEquals(f2));
  * assertTrue(f1.isChildOrEquals(f1));
  * assertFalse(f2.isChildOrEquals(f1));
  * </pre>
  *
  * @param parentFqn candidate parent to test against
  * @return true if this Fqn is equals or the child of parentFqn.
  */
 public boolean isChildOrEquals(Fqn parentFqn) {
   Object[] parentEl = parentFqn.elements;
   if (parentEl.length > elements.length) {
     return false;
   }
   for (int i = parentEl.length - 1; i >= 0; i--) {
     if (!Util.safeEquals(parentEl[i], elements[i])) return false;
   }
   return true;
 }
Ejemplo n.º 7
0
 protected byte[] returnPossiblePrevValue(Transport transport) {
   if (hasForceReturn(flags)) {
     byte[] bytes = transport.readArray();
     if (log.isTraceEnabled())
       log.tracef("Previous value bytes is: %s", Util.printArray(bytes, false));
     // 0-length response means null
     return bytes.length == 0 ? null : bytes;
   } else {
     return null;
   }
 }
Ejemplo n.º 8
0
 private boolean replace(AdvancedCache<?, ?> cache, K key, V oldValue, V newValue) {
   startAtomic();
   try {
     AtomicMap<K, V> data = getDataInternal(cache);
     V old = data.get(key);
     if (Util.safeEquals(oldValue, old)) {
       data.put(key, newValue);
       return true;
     }
     return false;
   } finally {
     endAtomic();
   }
 }
  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    EventImpl<?, ?> event = (EventImpl<?, ?>) o;

    if (originLocal != event.originLocal) return false;
    if (pre != event.pre) return false;
    if (transactionSuccessful != event.transactionSuccessful) return false;
    if (cache != null ? !cache.equals(event.cache) : event.cache != null) return false;
    if (key != null ? !key.equals(event.key) : event.key != null) return false;
    if (transaction != null ? !transaction.equals(event.transaction) : event.transaction != null)
      return false;
    if (type != event.type) return false;
    if (value != null ? !value.equals(event.value) : event.value != null) return false;
    if (!Util.safeEquals(consistentHashAtStart, event.consistentHashAtStart)) return false;
    if (!Util.safeEquals(consistentHashAtEnd, event.consistentHashAtEnd)) return false;
    if (!Util.safeEquals(membersAtStart, event.membersAtStart)) return false;
    if (!Util.safeEquals(membersAtEnd, event.membersAtEnd)) return false;
    if (newViewId != event.newViewId) return false;

    return true;
  }
Ejemplo n.º 10
0
 /** Returns true if obj is a Fqn with the same elements. */
 @Override
 public boolean equals(Object obj) {
   if (this == obj) {
     return true;
   }
   if (!(obj instanceof Fqn)) {
     return false;
   }
   Fqn other = (Fqn) obj;
   if (elements.length != other.elements.length) return false;
   for (int i = elements.length - 1; i >= 0; i--) {
     if (!Util.safeEquals(elements[i], other.elements[i])) return false;
   }
   return true;
 }
 @Override
 public boolean replace(K key, V oldValue, V newValue) {
   startAtomic();
   try {
     AtomicMap<K, V> data = getDataInternal();
     V old = data.get(key);
     if (Util.safeEquals(oldValue, old)) {
       data.put(key, newValue);
       return true;
     }
     return false;
   } finally {
     endAtomic();
   }
 }
Ejemplo n.º 12
0
 private static ConsistentHash constructConsistentHashInstance(
     Class<? extends ConsistentHash> clazz,
     Hash hashFunction,
     HashSeed hashSeed,
     int numVirtualNodes,
     GroupManager groupManager) {
   ConsistentHash ch = Util.getInstance(clazz);
   if (ch instanceof AbstractWheelConsistentHash) {
     AbstractWheelConsistentHash wch = (AbstractWheelConsistentHash) ch;
     wch.setHashFunction(hashFunction);
     wch.setHashSeed(hashSeed);
     wch.setNumVirtualNodes(numVirtualNodes);
   }
   if (ch instanceof AbstractConsistentHash) {
     AbstractConsistentHash ach = (AbstractConsistentHash) ch;
     if (groupManager != null) ach.setGroupManager(groupManager);
   }
   return ch;
 }
Ejemplo n.º 13
0
 @Override
 public final boolean dumpTo(String filePath) {
   BufferedWriter bufferedWriter = Util.getBufferedWriter(filePath);
   if (bufferedWriter == null) {
     return false;
   }
   try {
     for (Map.Entry<Object, InternalCacheEntry> entry : entries.entrySet()) {
       Util.safeWrite(bufferedWriter, entry.getKey());
       Util.safeWrite(bufferedWriter, "=");
       Util.safeWrite(bufferedWriter, entry.getValue().getValue());
       Util.safeWrite(bufferedWriter, "=");
       Util.safeWrite(bufferedWriter, entry.getValue().getVersion());
       bufferedWriter.newLine();
       bufferedWriter.flush();
     }
     return true;
   } catch (IOException e) {
     return false;
   } finally {
     Util.close(bufferedWriter);
   }
 }
Ejemplo n.º 14
0
 @Override
 public Set<Class<? extends FileReadLockKey>> getTypeClasses() {
   return Util.<Class<? extends FileReadLockKey>>asSet(FileReadLockKey.class);
 }
Ejemplo n.º 15
0
 @Override
 public Set<Class<? extends Map>> getTypeClasses() {
   return Util.<Class<? extends Map>>asSet(HashMap.class, TreeMap.class, FastCopyHashMap.class);
 }
Ejemplo n.º 16
0
 @SuppressWarnings("unchecked")
 @Override
 public Set<Class<? extends RemoveOperation>> getTypeClasses() {
   return Util.<Class<? extends RemoveOperation>>asSet(RemoveOperation.class);
 }
 /**
  * Name of the class implementing Key2StringMapper. The default value is {@link
  * org.infinispan.loaders.keymappers.DefaultTwoWayKey2StringMapper}
  *
  * @see org.infinispan.loaders.keymappers.Key2StringMapper
  */
 public void setKey2StringMapperClass(String className) {
   testImmutability("key2StringMapper");
   key2StringMapper = (Key2StringMapper) Util.getInstance(className);
 }
Ejemplo n.º 18
0
 @SuppressWarnings("unchecked")
 @Override
 public Set<Class<? extends Document>> getTypeClasses() {
   return Util.<Class<? extends Document>>asSet(BasicDocument.class, BasicArray.class);
 }
 @Override
 public Set<Class<? extends DefaultConsistentHash>> getTypeClasses() {
   return Util.<Class<? extends DefaultConsistentHash>>asSet(DefaultConsistentHash.class);
 }
Ejemplo n.º 20
0
 @Override
 public Set<Class<? extends MurmurHash3>> getTypeClasses() {
   return Util.<Class<? extends MurmurHash3>>asSet(MurmurHash3.class);
 }
/**
 * Configures whether global statistics are gathered and reported via JMX for all caches under this
 * cache manager.
 */
public class GlobalJmxStatisticsConfigurationBuilder
    extends AbstractGlobalConfigurationBuilder<GlobalJmxStatisticsConfiguration> {

  private Properties properties = new Properties();
  private String jmxDomain = "org.infinispan";
  private Boolean allowDuplicateDomains = false;
  private String cacheManagerName = "DefaultCacheManager";
  private MBeanServerLookup mBeanServerLookupInstance =
      Util.getInstance(PlatformMBeanServerLookup.class);
  private boolean enabled = false;

  GlobalJmxStatisticsConfigurationBuilder(GlobalConfigurationBuilder globalConfig) {
    super(globalConfig);
  }

  /**
   * Sets properties which are then passed to the MBean Server Lookup implementation specified.
   *
   * @param properties properties to pass to the MBean Server Lookup
   */
  public GlobalJmxStatisticsConfigurationBuilder withProperties(Properties properties) {
    this.properties = properties;
    return this;
  }

  public GlobalJmxStatisticsConfigurationBuilder addProperty(String key, String value) {
    properties.put(key, value);
    return this;
  }

  /**
   * If JMX statistics are enabled then all 'published' JMX objects will appear under this name.
   * This is optional, if not specified an object name will be created for you by default.
   *
   * @param jmxDomain
   */
  public GlobalJmxStatisticsConfigurationBuilder jmxDomain(String jmxDomain) {
    this.jmxDomain = jmxDomain;
    return this;
  }

  /**
   * If true, multiple cache manager instances could be configured under the same configured JMX
   * domain. Each cache manager will in practice use a different JMX domain that has been calculated
   * based on the configured one by adding an incrementing index to it.
   *
   * @param allowDuplicateDomains
   */
  public GlobalJmxStatisticsConfigurationBuilder allowDuplicateDomains(
      Boolean allowDuplicateDomains) {
    this.allowDuplicateDomains = allowDuplicateDomains;
    return this;
  }

  /**
   * If JMX statistics are enabled, this property represents the name of this cache manager. It
   * offers the possibility for clients to provide a user-defined name to the cache manager which
   * later can be used to identify the cache manager within a JMX based management tool amongst
   * other cache managers that might be running under the same JVM.
   *
   * @param cacheManagerName
   */
  public GlobalJmxStatisticsConfigurationBuilder cacheManagerName(String cacheManagerName) {
    this.cacheManagerName = cacheManagerName;
    return this;
  }

  /**
   * Sets the instance of the {@link org.infinispan.jmx.MBeanServerLookup} class to be used to bound
   * JMX MBeans to.
   *
   * @param mBeanServerLookupInstance An instance of {@link org.infinispan.jmx.MBeanServerLookup}
   */
  public GlobalJmxStatisticsConfigurationBuilder mBeanServerLookup(
      MBeanServerLookup mBeanServerLookupInstance) {
    this.mBeanServerLookupInstance = mBeanServerLookupInstance;
    return this;
  }

  public GlobalJmxStatisticsConfigurationBuilder disable() {
    this.enabled = false;
    return this;
  }

  public GlobalJmxStatisticsConfigurationBuilder enable() {
    this.enabled = true;
    return this;
  }

  public GlobalJmxStatisticsConfigurationBuilder enabled(boolean enabled) {
    this.enabled = enabled;
    return this;
  }

  @Override
  void validate() {
    // No-op, no validation required
  }

  @Override
  GlobalJmxStatisticsConfiguration create() {
    return new GlobalJmxStatisticsConfiguration(
        enabled,
        jmxDomain,
        mBeanServerLookupInstance,
        allowDuplicateDomains,
        cacheManagerName,
        TypedProperties.toTypedProperties(properties));
  }

  @Override
  protected GlobalJmxStatisticsConfigurationBuilder read(
      GlobalJmxStatisticsConfiguration template) {
    this.allowDuplicateDomains = template.allowDuplicateDomains();
    this.cacheManagerName = template.cacheManagerName();
    this.enabled = template.enabled();
    this.jmxDomain = template.domain();
    this.mBeanServerLookupInstance = template.mbeanServerLookup();
    this.properties = template.properties();

    return this;
  }

  @Override
  public String toString() {
    return "GlobalJmxStatisticsConfigurationBuilder{"
        + "allowDuplicateDomains="
        + allowDuplicateDomains
        + ", properties="
        + properties
        + ", jmxDomain='"
        + jmxDomain
        + '\''
        + ", cacheManagerName='"
        + cacheManagerName
        + '\''
        + ", mBeanServerLookupInstance="
        + mBeanServerLookupInstance
        + ", enabled="
        + enabled
        + '}';
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    GlobalJmxStatisticsConfigurationBuilder that = (GlobalJmxStatisticsConfigurationBuilder) o;

    if (enabled != that.enabled) return false;
    if (allowDuplicateDomains != null
        ? !allowDuplicateDomains.equals(that.allowDuplicateDomains)
        : that.allowDuplicateDomains != null) return false;
    if (cacheManagerName != null
        ? !cacheManagerName.equals(that.cacheManagerName)
        : that.cacheManagerName != null) return false;
    if (jmxDomain != null ? !jmxDomain.equals(that.jmxDomain) : that.jmxDomain != null)
      return false;
    if (mBeanServerLookupInstance != null
        ? !mBeanServerLookupInstance.equals(that.mBeanServerLookupInstance)
        : that.mBeanServerLookupInstance != null) return false;
    if (properties != null ? !properties.equals(that.properties) : that.properties != null)
      return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = properties != null ? properties.hashCode() : 0;
    result = 31 * result + (jmxDomain != null ? jmxDomain.hashCode() : 0);
    result = 31 * result + (allowDuplicateDomains != null ? allowDuplicateDomains.hashCode() : 0);
    result = 31 * result + (cacheManagerName != null ? cacheManagerName.hashCode() : 0);
    result =
        31 * result
            + (mBeanServerLookupInstance != null ? mBeanServerLookupInstance.hashCode() : 0);
    result = 31 * result + (enabled ? 1 : 0);
    return result;
  }
}
Ejemplo n.º 22
0
 @Override
 public Set<Class<? extends Fqn>> getTypeClasses() {
   return Util.<Class<? extends Fqn>>asSet(Fqn.class);
 }
 /** Try to figure out which TransactionManager to use */
 private static void doLookups() {
   if (lookupFailed) return;
   InitialContext ctx;
   try {
     ctx = new InitialContext();
   } catch (NamingException e) {
     log.error("Failed creating initial JNDI context", e);
     lookupFailed = true;
     return;
   }
   // probe jndi lookups first
   for (String[] knownJNDIManager : knownJNDIManagers) {
     Object jndiObject;
     try {
       if (log.isDebugEnabled())
         log.debug("Trying to lookup TransactionManager for " + knownJNDIManager[1]);
       jndiObject = ctx.lookup(knownJNDIManager[0]);
     } catch (NamingException e) {
       log.debug(
           "Failed to perform a lookup for ["
               + knownJNDIManager[0]
               + " ("
               + knownJNDIManager[1]
               + ")]");
       continue;
     }
     if (jndiObject instanceof TransactionManager) {
       tm = (TransactionManager) jndiObject;
       log.debug("Found TransactionManager for " + knownJNDIManager[1]);
       return;
     }
   }
   // try to find websphere lookups since we came here
   Class clazz;
   try {
     log.debug("Trying WebSphere 5.1: " + WS_FACTORY_CLASS_5_1);
     clazz = Util.loadClassStrict(WS_FACTORY_CLASS_5_1);
     log.debug("Found WebSphere 5.1: " + WS_FACTORY_CLASS_5_1);
   } catch (ClassNotFoundException ex) {
     try {
       log.debug("Trying WebSphere 5.0: " + WS_FACTORY_CLASS_5_0);
       clazz = Util.loadClassStrict(WS_FACTORY_CLASS_5_0);
       log.debug("Found WebSphere 5.0: " + WS_FACTORY_CLASS_5_0);
     } catch (ClassNotFoundException ex2) {
       try {
         log.debug("Trying WebSphere 4: " + WS_FACTORY_CLASS_4);
         clazz = Util.loadClassStrict(WS_FACTORY_CLASS_4);
         log.debug("Found WebSphere 4: " + WS_FACTORY_CLASS_4);
       } catch (ClassNotFoundException ex3) {
         log.debug(
             "Couldn't find any WebSphere TransactionManager factory class, neither for WebSphere version 5.1 nor 5.0 nor 4");
         lookupFailed = true;
         return;
       }
     }
   }
   try {
     Class[] signature = null;
     Object[] args = null;
     Method method = clazz.getMethod("getTransactionManager", signature);
     tm = (TransactionManager) method.invoke(null, args);
   } catch (Exception ex) {
     log.error(
         "Found WebSphere TransactionManager factory class ["
             + clazz.getName()
             + "], but couldn't invoke its static 'getTransactionManager' method",
         ex);
   }
 }
 public TransportConfigurationBuilder defaultTransport() {
   transport(Util.getInstance(DEFAULT_TRANSPORT));
   return this;
 }
 @Override
 public Set<Class<? extends ChunkCacheKey>> getTypeClasses() {
   return Util.<Class<? extends ChunkCacheKey>>asSet(ChunkCacheKey.class);
 }
Ejemplo n.º 26
0
  // This is per CM, so the CL in use should be the CM CL
  private void buildChannel() {
    // in order of preference - we first look for an external JGroups file, then a set of XML
    // properties, and
    // finally the legacy JGroups String properties.
    String cfg;
    if (props != null) {
      if (props.containsKey(CHANNEL_LOOKUP)) {
        String channelLookupClassName = props.getProperty(CHANNEL_LOOKUP);

        try {
          JGroupsChannelLookup lookup =
              (JGroupsChannelLookup)
                  Util.getInstance(channelLookupClassName, configuration.getClassLoader());
          channel = lookup.getJGroupsChannel(props);
          startChannel = lookup.shouldStartAndConnect();
          stopChannel = lookup.shouldStopAndDisconnect();
        } catch (ClassCastException e) {
          log.wrongTypeForJGroupsChannelLookup(channelLookupClassName, e);
          throw new CacheException(e);
        } catch (Exception e) {
          log.errorInstantiatingJGroupsChannelLookup(channelLookupClassName, e);
          throw new CacheException(e);
        }
        if (configuration.isStrictPeerToPeer() && !startChannel) {
          log.warnStrictPeerToPeerWithInjectedChannel();
        }
      }

      if (channel == null && props.containsKey(CONFIGURATION_FILE)) {
        cfg = props.getProperty(CONFIGURATION_FILE);
        try {
          channel =
              new JChannel(
                  FileLookupFactory.newInstance()
                      .lookupFileLocation(cfg, configuration.getClassLoader()));
        } catch (Exception e) {
          log.errorCreatingChannelFromConfigFile(cfg);
          throw new CacheException(e);
        }
      }

      if (channel == null && props.containsKey(CONFIGURATION_XML)) {
        cfg = props.getProperty(CONFIGURATION_XML);
        try {
          channel = new JChannel(XmlConfigHelper.stringToElement(cfg));
        } catch (Exception e) {
          log.errorCreatingChannelFromXML(cfg);
          throw new CacheException(e);
        }
      }

      if (channel == null && props.containsKey(CONFIGURATION_STRING)) {
        cfg = props.getProperty(CONFIGURATION_STRING);
        try {
          channel = new JChannel(cfg);
        } catch (Exception e) {
          log.errorCreatingChannelFromConfigString(cfg);
          throw new CacheException(e);
        }
      }
    }

    if (channel == null) {
      log.unableToUseJGroupsPropertiesProvided(props);
      try {
        channel =
            new JChannel(
                FileLookupFactory.newInstance()
                    .lookupFileLocation(
                        DEFAULT_JGROUPS_CONFIGURATION_FILE, configuration.getClassLoader()));
      } catch (Exception e) {
        throw new CacheException("Unable to start JGroups channel", e);
      }
    }
  }
 @Override
 public Set<Class<? extends UnsuccessfulResponse>> getTypeClasses() {
   return Util.<Class<? extends UnsuccessfulResponse>>asSet(UnsuccessfulResponse.class);
 }
Ejemplo n.º 28
0
 @Override
 public Set<Class<? extends AtomicHashMapDelta>> getTypeClasses() {
   return Util.<Class<? extends AtomicHashMapDelta>>asSet(AtomicHashMapDelta.class);
 }