/**
   * Calculates data nodes for replicated caches on unstable topology.
   *
   * @param cctx Cache context for main space.
   * @param extraSpaces Extra spaces.
   * @return Collection of all data nodes owning all the caches or {@code null} for retry.
   */
  private Collection<ClusterNode> replicatedUnstableDataNodes(
      final GridCacheContext<?, ?> cctx, List<String> extraSpaces) {
    assert cctx.isReplicated() : cctx.name() + " must be replicated";

    Set<ClusterNode> nodes = replicatedUnstableDataNodes(cctx);

    if (F.isEmpty(nodes)) return null; // Retry.

    if (!F.isEmpty(extraSpaces)) {
      for (String extraSpace : extraSpaces) {
        GridCacheContext<?, ?> extraCctx = cacheContext(extraSpace);

        if (extraCctx.isLocal()) continue;

        if (!extraCctx.isReplicated())
          throw new CacheException(
              "Queries running on replicated cache should not contain JOINs "
                  + "with tables in partitioned caches [rCache="
                  + cctx.name()
                  + ", pCache="
                  + extraSpace
                  + "]");

        Set<ClusterNode> extraOwners = replicatedUnstableDataNodes(extraCctx);

        if (F.isEmpty(extraOwners)) return null; // Retry.

        nodes.retainAll(extraOwners);

        if (nodes.isEmpty()) return null; // Retry.
      }
    }

    return nodes;
  }
    /**
     * @param topVer Topology version.
     * @param entries Entries.
     */
    FinishLockFuture(Iterable<GridDistributedCacheEntry> entries, AffinityTopologyVersion topVer) {
      assert topVer.compareTo(AffinityTopologyVersion.ZERO) > 0;

      this.topVer = topVer;

      for (GridCacheEntryEx entry : entries) {
        // Either local or near local candidates.
        try {
          Collection<GridCacheMvccCandidate> locs = entry.localCandidates();

          if (!F.isEmpty(locs)) {
            Collection<GridCacheMvccCandidate> cands = new ConcurrentLinkedQueue<>();

            cands.addAll(F.view(locs, versionFilter()));

            if (!F.isEmpty(cands)) pendingLocks.put(entry.txKey(), cands);
          }
        } catch (GridCacheEntryRemovedException ignored) {
          if (exchLog.isDebugEnabled())
            exchLog.debug(
                "Got removed entry when adding it to finish lock future (will ignore): " + entry);
        }
      }

      if (exchLog.isDebugEnabled())
        exchLog.debug("Pending lock set [topVer=" + topVer + ", locks=" + pendingLocks + ']');
    }
  /** Initializes future. */
  @SuppressWarnings({"SimplifiableIfStatement", "IfMayBeConditional"})
  public void finish() {
    boolean sync;

    if (!F.isEmpty(dhtMap) || !F.isEmpty(nearMap)) sync = finish(dhtMap, nearMap);
    else if (!commit && !F.isEmpty(tx.lockTransactionNodes()))
      sync = rollbackLockTransactions(tx.lockTransactionNodes());
    else
      // No backup or near nodes to send commit message to (just complete then).
      sync = false;

    markInitialized();

    if (!sync) onComplete();
  }
  /**
   * @param gridName Grid name.
   * @return Cache configuration.
   * @throws Exception In case of error.
   */
  @SuppressWarnings("unchecked")
  protected CacheConfiguration cacheConfiguration(String gridName) throws Exception {
    CacheConfiguration cfg = defaultCacheConfiguration();

    CacheStore<?, ?> store = cacheStore();

    if (store != null) {
      cfg.setCacheStoreFactory(new TestStoreFactory());
      cfg.setReadThrough(true);
      cfg.setWriteThrough(true);
      cfg.setLoadPreviousValue(true);
    }

    cfg.setSwapEnabled(swapEnabled());
    cfg.setCacheMode(cacheMode());
    cfg.setAtomicityMode(atomicityMode());
    cfg.setWriteSynchronizationMode(writeSynchronization());
    cfg.setNearConfiguration(nearConfiguration());

    Class<?>[] idxTypes = indexedTypes();

    if (!F.isEmpty(idxTypes)) cfg.setIndexedTypes(idxTypes);

    if (cacheMode() == PARTITIONED) cfg.setBackups(1);

    return cfg;
  }
Beispiel #5
0
  /**
   * Adds owned versions to map.
   *
   * @param vers Map of owned versions.
   */
  public void ownedVersions(Map<IgniteTxKey, GridCacheVersion> vers) {
    if (F.isEmpty(vers)) return;

    if (owned == null) owned = new GridLeanMap<>(vers.size());

    owned.putAll(vers);
  }
Beispiel #6
0
  /**
   * @param globalIdMapper ID mapper.
   * @param globalSerializer Serializer.
   * @param typeCfgs Type configurations.
   * @throws BinaryObjectException In case of error.
   */
  private void configure(
      BinaryIdMapper globalIdMapper,
      BinarySerializer globalSerializer,
      Collection<BinaryTypeConfiguration> typeCfgs)
      throws BinaryObjectException {
    TypeDescriptors descs = new TypeDescriptors();

    Map<String, String> affFields = new HashMap<>();

    if (!F.isEmpty(igniteCfg.getCacheKeyConfiguration())) {
      for (CacheKeyConfiguration keyCfg : igniteCfg.getCacheKeyConfiguration())
        affFields.put(keyCfg.getTypeName(), keyCfg.getAffinityKeyFieldName());
    }

    if (typeCfgs != null) {
      for (BinaryTypeConfiguration typeCfg : typeCfgs) {
        String clsName = typeCfg.getTypeName();

        if (clsName == null)
          throw new BinaryObjectException("Class name is required for binary type configuration.");

        BinaryIdMapper idMapper = globalIdMapper;

        if (typeCfg.getIdMapper() != null) idMapper = typeCfg.getIdMapper();

        idMapper = BinaryInternalIdMapper.create(idMapper);

        BinarySerializer serializer = globalSerializer;

        if (typeCfg.getSerializer() != null) serializer = typeCfg.getSerializer();

        if (clsName.endsWith(".*")) {
          String pkgName = clsName.substring(0, clsName.length() - 2);

          for (String clsName0 : classesInPackage(pkgName))
            descs.add(
                clsName0, idMapper, serializer, affFields.get(clsName0), typeCfg.isEnum(), true);
        } else
          descs.add(clsName, idMapper, serializer, affFields.get(clsName), typeCfg.isEnum(), false);
      }
    }

    for (TypeDescriptor desc : descs.descriptors())
      registerUserType(
          desc.clsName, desc.idMapper, desc.serializer, desc.affKeyFieldName, desc.isEnum);

    BinaryInternalIdMapper dfltMapper = BinaryInternalIdMapper.create(globalIdMapper);

    // Put affinity field names for unconfigured types.
    for (Map.Entry<String, String> entry : affFields.entrySet()) {
      String typeName = entry.getKey();

      int typeId = dfltMapper.typeId(typeName);

      affKeyFieldNames.putIfAbsent(typeId, entry.getValue());
    }

    addSystemClassAffinityKey(CollocatedSetItemKey.class);
    addSystemClassAffinityKey(CollocatedQueueItemKey.class);
  }
  /**
   * Callback for backup update response.
   *
   * @param nodeId Backup node ID.
   * @param updateRes Update response.
   */
  public void onResult(UUID nodeId, GridDhtAtomicUpdateResponse updateRes) {
    if (log.isDebugEnabled())
      log.debug(
          "Received DHT atomic update future result [nodeId="
              + nodeId
              + ", updateRes="
              + updateRes
              + ']');

    if (updateRes.error() != null)
      this.updateRes.addFailedKeys(updateRes.failedKeys(), updateRes.error());

    if (!F.isEmpty(updateRes.nearEvicted())) {
      for (KeyCacheObject key : updateRes.nearEvicted()) {
        GridDhtCacheEntry entry = nearReadersEntries.get(key);

        try {
          entry.removeReader(nodeId, updateRes.messageId());
        } catch (GridCacheEntryRemovedException e) {
          if (log.isDebugEnabled())
            log.debug("Entry with evicted reader was removed [entry=" + entry + ", err=" + e + ']');
        }
      }
    }

    registerResponse(nodeId);
  }
  /** {@inheritDoc} */
  @Override
  protected IgniteInternalFuture<Map<K, V>> getAllAsync(
      @Nullable Collection<? extends K> keys,
      boolean forcePrimary,
      boolean skipTx,
      @Nullable UUID subjId,
      String taskName,
      boolean deserializeBinary,
      boolean skipVals,
      boolean canRemap) {
    ctx.checkSecurity(SecurityPermission.CACHE_READ);

    if (F.isEmpty(keys)) return new GridFinishedFuture<>(Collections.<K, V>emptyMap());

    if (keyCheck) validateCacheKeys(keys);

    CacheOperationContext opCtx = ctx.operationContextPerCall();

    subjId = ctx.subjectIdPerCall(subjId, opCtx);

    return loadAsync(
        null,
        ctx.cacheKeysView(keys),
        forcePrimary,
        subjId,
        taskName,
        deserializeBinary,
        skipVals ? null : opCtx != null ? opCtx.expiry() : null,
        skipVals,
        opCtx != null && opCtx.skipStore(),
        canRemap);
  }
  /** {@inheritDoc} */
  @Override
  public final Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid, T arg) {
    assert subgrid != null;
    assert !subgrid.isEmpty();

    Collection<? extends ComputeJob> jobs = split(subgrid.size(), arg);

    if (F.isEmpty(jobs)) throw new IgniteException("Split returned no jobs.");

    Map<ComputeJob, ClusterNode> map = U.newHashMap(jobs.size());

    for (ComputeJob job : jobs) {
      ClusterNode old = map.put(job, balancer.getBalancedNode(job, null));

      if (old != null)
        throw new IgniteException(
            "Failed to map task (same job instance is being mapped more than once) "
                + "[job="
                + job
                + ", task="
                + this
                + ']');
    }

    return map;
  }
  /**
   * @param ctx Kernal context.
   * @param cfg Ignite configuration.
   * @param providers Plugin providers.
   */
  @SuppressWarnings("TypeMayBeWeakened")
  public IgnitePluginProcessor(
      GridKernalContext ctx, IgniteConfiguration cfg, List<PluginProvider> providers) {
    super(ctx);

    ExtensionRegistryImpl registry = new ExtensionRegistryImpl();

    for (PluginProvider provider : providers) {
      GridPluginContext pluginCtx = new GridPluginContext(ctx, cfg);

      if (F.isEmpty(provider.name())) throw new IgniteException("Plugin name can not be empty.");

      if (plugins.containsKey(provider.name()))
        throw new IgniteException("Duplicated plugin name: " + provider.name());

      plugins.put(provider.name(), provider);

      pluginCtxMap.put(provider, pluginCtx);

      provider.initExtensions(pluginCtx, registry);

      if (provider.plugin() == null) throw new IgniteException("Plugin is null.");
    }

    extensions = registry.createExtensionMap();
  }
Beispiel #11
0
  /** @param maps Mappings. */
  void addEntryMapping(@Nullable Collection<GridDistributedTxMapping> maps) {
    if (!F.isEmpty(maps)) {
      for (GridDistributedTxMapping map : maps) {
        ClusterNode n = map.node();

        GridDistributedTxMapping m = mappings.get(n.id());

        if (m == null) {
          mappings.put(m = new GridDistributedTxMapping(n));

          m.near(map.near());

          if (map.explicitLock()) m.markExplicitLock();
        }

        for (IgniteTxEntry entry : map.entries()) m.add(entry);
      }

      if (log.isDebugEnabled())
        log.debug(
            "Added mappings to transaction [locId="
                + cctx.localNodeId()
                + ", mappings="
                + maps
                + ", tx="
                + this
                + ']');
    }
  }
  /**
   * Sends query request.
   *
   * @param fut Distributed future.
   * @param req Request.
   * @param nodes Nodes.
   * @throws IgniteCheckedException In case of error.
   */
  @SuppressWarnings("unchecked")
  private void sendRequest(
      final GridCacheDistributedQueryFuture<?, ?, ?> fut,
      final GridCacheQueryRequest req,
      Collection<ClusterNode> nodes)
      throws IgniteCheckedException {
    assert fut != null;
    assert req != null;
    assert nodes != null;

    final UUID locNodeId = cctx.localNodeId();

    ClusterNode locNode = null;

    Collection<ClusterNode> rmtNodes = null;

    for (ClusterNode n : nodes) {
      if (n.id().equals(locNodeId)) locNode = n;
      else {
        if (rmtNodes == null) rmtNodes = new ArrayList<>(nodes.size());

        rmtNodes.add(n);
      }
    }

    // Request should be sent to remote nodes before the query is processed on the local node.
    // For example, a remote reducer has a state, we should not serialize and then send
    // the reducer changed by the local node.
    if (!F.isEmpty(rmtNodes)) {
      cctx.io()
          .safeSend(
              rmtNodes,
              req,
              cctx.ioPolicy(),
              new P1<ClusterNode>() {
                @Override
                public boolean apply(ClusterNode node) {
                  fut.onNodeLeft(node.id());

                  return !fut.isDone();
                }
              });
    }

    if (locNode != null) {
      cctx.closures()
          .callLocalSafe(
              new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                  req.beforeLocalExecution(cctx);

                  processQueryRequest(locNodeId, req);

                  return null;
                }
              });
    }
  }
  /**
   * Resolve load balancer from string definition.
   *
   * @param balancer Load balancer string definition.
   * @return Resolved load balancer.
   * @throws GridClientException If loading failed.
   */
  private static GridClientLoadBalancer resolveBalancer(String balancer)
      throws GridClientException {
    if (F.isEmpty(balancer) || "random".equals(balancer)) return new GridClientRandomBalancer();

    if ("roundrobin".equals(balancer)) return new GridClientRoundRobinBalancer();

    return newInstance(GridClientLoadBalancer.class, balancer);
  }
  /**
   * Resolve data affinity from string definition.
   *
   * @param affinity Data affinity string definition.
   * @return Resolved data affinity.
   * @throws GridClientException If loading failed.
   */
  private static GridClientDataAffinity resolveAffinity(String affinity)
      throws GridClientException {
    if (F.isEmpty(affinity)) return null;

    if ("partitioned".equals(affinity)) return new GridClientPartitionAffinity();

    return newInstance(GridClientDataAffinity.class, affinity);
  }
    /** @param nodeId Failed node ID. */
    boolean onNodeLeft(UUID nodeId) {
      if (nodeId.equals(m.node().id())) {
        if (log.isDebugEnabled())
          log.debug("Remote node left grid while sending or waiting for reply: " + this);

        if (isSync()) {
          Map<UUID, Collection<UUID>> txNodes = tx.transactionNodes();

          if (txNodes != null) {
            Collection<UUID> backups = txNodes.get(nodeId);

            if (!F.isEmpty(backups)) {
              final CheckRemoteTxMiniFuture mini =
                  new CheckRemoteTxMiniFuture(new HashSet<>(backups));

              add(mini);

              GridDhtTxFinishRequest req = checkCommittedRequest(mini.futureId());

              req.waitRemoteTransactions(true);

              for (UUID backupId : backups) {
                ClusterNode backup = cctx.discovery().node(backupId);

                if (backup != null && WAIT_REMOTE_TXS_SINCE.compareTo(backup.version()) <= 0) {
                  if (backup.isLocal()) {
                    IgniteInternalFuture<?> fut =
                        cctx.tm().remoteTxFinishFuture(tx.nearXidVersion());

                    fut.listen(
                        new CI1<IgniteInternalFuture<?>>() {
                          @Override
                          public void apply(IgniteInternalFuture<?> fut) {
                            mini.onDhtFinishResponse(cctx.localNodeId());
                          }
                        });
                  } else {
                    try {
                      cctx.io().send(backup, req, tx.ioPolicy());
                    } catch (ClusterTopologyCheckedException e) {
                      mini.onNodeLeft(backupId);
                    } catch (IgniteCheckedException e) {
                      mini.onDone(e);
                    }
                  }
                } else mini.onDhtFinishResponse(backupId);
              }
            }
          }
        }

        onDone(tx);

        return true;
      }

      return false;
    }
  /** {@inheritDoc} */
  @SuppressWarnings("deprecation")
  @Override
  public void start() throws IgniteException {
    if (sesFactory == null && F.isEmpty(hibernateCfgPath))
      throw new IgniteException(
          "Either session factory or Hibernate configuration file is required by "
              + getClass().getSimpleName()
              + '.');

    if (!F.isEmpty(hibernateCfgPath)) {
      if (sesFactory == null) {
        try {
          URL url = new URL(hibernateCfgPath);

          sesFactory = new Configuration().configure(url).buildSessionFactory();
        } catch (MalformedURLException ignored) {
          // No-op.
        }

        if (sesFactory == null) {
          File cfgFile = new File(hibernateCfgPath);

          if (cfgFile.exists())
            sesFactory = new Configuration().configure(cfgFile).buildSessionFactory();
        }

        if (sesFactory == null)
          sesFactory = new Configuration().configure(hibernateCfgPath).buildSessionFactory();

        if (sesFactory == null)
          throw new IgniteException(
              "Failed to resolve Hibernate configuration file: " + hibernateCfgPath);

        closeSesOnStop = true;
      } else
        U.warn(
            log,
            "Hibernate configuration file configured in "
                + getClass().getSimpleName()
                + " will be ignored (session factory is already set).");
    }
  }
  /**
   * @param cacheId Cache ID.
   * @return {@code True} if local client has been added.
   */
  public boolean isLocalClientAdded(int cacheId) {
    if (!F.isEmpty(reqs)) {
      for (DynamicCacheChangeRequest req : reqs) {
        if (req.start() && F.eq(req.initiatingNodeId(), cctx.localNodeId())) {
          if (CU.cacheId(req.cacheName()) == cacheId) return true;
        }
      }
    }

    return false;
  }
  /**
   * Checks for explicit events configuration.
   *
   * @param ignite Grid instance.
   * @return {@code true} if all task events explicitly specified in configuration.
   */
  public static boolean checkExplicitTaskMonitoring(Ignite ignite) {
    int[] evts = ignite.configuration().getIncludeEventTypes();

    if (F.isEmpty(evts)) return false;

    for (int evt : VISOR_TASK_EVTS) {
      if (!F.contains(evts, evt)) return false;
    }

    return true;
  }
  /**
   * @param mainSpace Main space.
   * @param allSpaces All spaces.
   * @return List of all extra spaces or {@code null} if none.
   */
  private List<String> extraSpaces(String mainSpace, Set<String> allSpaces) {
    if (F.isEmpty(allSpaces) || (allSpaces.size() == 1 && allSpaces.contains(mainSpace)))
      return null;

    ArrayList<String> res = new ArrayList<>(allSpaces.size());

    for (String space : allSpaces) {
      if (!F.eq(space, mainSpace)) res.add(space);
    }

    return res;
  }
  /**
   * @param cacheId Cache ID to check.
   * @param topVer Topology version.
   * @return {@code True} if cache was added during this exchange.
   */
  public boolean isCacheAdded(int cacheId, AffinityTopologyVersion topVer) {
    if (!F.isEmpty(reqs)) {
      for (DynamicCacheChangeRequest req : reqs) {
        if (req.start() && !req.clientStartOnly()) {
          if (CU.cacheId(req.cacheName()) == cacheId) return true;
        }
      }
    }

    GridCacheContext<?, ?> cacheCtx = cctx.cacheContext(cacheId);

    return cacheCtx != null && F.eq(cacheCtx.startTopologyVersion(), topVer);
  }
  /**
   * Parses HTTP parameters in an appropriate format and return back map of values to predefined
   * list of names.
   *
   * @param req Request.
   * @return Map of parsed parameters.
   */
  @SuppressWarnings({"unchecked"})
  private Map<String, Object> parameters(ServletRequest req) {
    Map<String, String[]> params = req.getParameterMap();

    if (F.isEmpty(params)) return Collections.emptyMap();

    Map<String, Object> map = U.newHashMap(params.size());

    for (Map.Entry<String, String[]> entry : params.entrySet())
      map.put(entry.getKey(), parameter(entry.getValue()));

    return map;
  }
Beispiel #22
0
  /**
   * @param cacheCtx Cache context.
   * @param keys Keys.
   * @param implicit Implicit flag.
   * @param read Read flag.
   * @param accessTtl Access ttl.
   * @param <K> Key type.
   * @param skipStore Skip store flag.
   * @return Future with respond.
   */
  public <K> IgniteInternalFuture<GridCacheReturn> lockAllAsync(
      GridCacheContext cacheCtx,
      final Collection<? extends K> keys,
      boolean implicit,
      boolean read,
      long accessTtl,
      boolean skipStore,
      boolean keepBinary) {
    assert pessimistic();

    try {
      checkValid();
    } catch (IgniteCheckedException e) {
      return new GridFinishedFuture<>(e);
    }

    final GridCacheReturn ret = new GridCacheReturn(localResult(), false);

    if (F.isEmpty(keys)) return new GridFinishedFuture<>(ret);

    init();

    if (log.isDebugEnabled()) log.debug("Before acquiring transaction lock on keys: " + keys);

    IgniteInternalFuture<Boolean> fut =
        cacheCtx
            .colocated()
            .lockAllAsyncInternal(
                keys,
                lockTimeout(),
                this,
                isInvalidate(),
                read,
                /*retval*/ false,
                isolation,
                accessTtl,
                CU.empty0(),
                skipStore,
                keepBinary);

    return new GridEmbeddedFuture<>(
        fut,
        new PLC1<GridCacheReturn>(ret, false) {
          @Override
          protected GridCacheReturn postLock(GridCacheReturn ret) {
            if (log.isDebugEnabled()) log.debug("Acquired transaction lock on keys: " + keys);

            return ret;
          }
        });
  }
Beispiel #23
0
  /**
   * @param exclude Versions to exclude form check.
   * @return {@code True} if lock is empty.
   */
  public boolean isEmpty(GridCacheVersion... exclude) {
    if (locs == null && rmts == null) return true;

    if (locs != null) {
      assert !locs.isEmpty();

      if (F.isEmpty(exclude)) return false;

      for (GridCacheMvccCandidate cand : locs)
        if (!U.containsObjectArray(exclude, cand.version())) return false;
    }

    if (rmts != null) {
      assert !rmts.isEmpty();

      if (F.isEmpty(exclude)) return false;

      for (GridCacheMvccCandidate cand : rmts)
        if (!U.containsObjectArray(exclude, cand.version())) return false;
    }

    return true;
  }
  /**
   * @param cacheId Cache ID to check.
   * @return {@code True} if cache is stopping by this exchange.
   */
  private boolean stopping(int cacheId) {
    boolean stopping = false;

    if (!F.isEmpty(reqs)) {
      for (DynamicCacheChangeRequest req : reqs) {
        if (cacheId == CU.cacheId(req.cacheName())) {
          stopping = req.stop();

          break;
        }
      }
    }

    return stopping;
  }
  /**
   * @param key Key.
   * @param cacheName Cache name.
   * @return Ignite instance which has primary cache for given key.
   */
  protected Ignite primaryNode(Object key, String cacheName) {
    List<Ignite> allGrids = Ignition.allGrids();

    assertFalse("There are no alive nodes.", F.isEmpty(allGrids));

    Ignite ignite = allGrids.get(0);

    Affinity<Object> aff = ignite.affinity(cacheName);

    ClusterNode node = aff.mapKeyToNode(key);

    assertNotNull("There are no cache affinity nodes", node);

    return grid(node);
  }
  /** {@inheritDoc} */
  @Override
  public Collection<ClusterNode> nodes(int p, AffinityTopologyVersion topVer) {
    Collection<ClusterNode> affNodes = cctx.affinity().nodes(p, topVer);

    lock.readLock().lock();

    try {
      assert node2part != null && node2part.valid()
          : "Invalid node-to-partitions map [topVer1="
              + topVer
              + ", topVer2="
              + this.topVer
              + ", cache="
              + cctx.name()
              + ", node2part="
              + node2part
              + ']';

      Collection<ClusterNode> nodes = null;

      Collection<UUID> nodeIds = part2node.get(p);

      if (!F.isEmpty(nodeIds)) {
        Collection<UUID> affIds = new HashSet<>(F.viewReadOnly(affNodes, F.node2id()));

        for (UUID nodeId : nodeIds) {
          if (!affIds.contains(nodeId) && hasState(p, nodeId, OWNING, MOVING, RENTING)) {
            ClusterNode n = cctx.discovery().node(nodeId);

            if (n != null
                && (topVer.topologyVersion() < 0 || n.order() <= topVer.topologyVersion())) {
              if (nodes == null) {
                nodes = new ArrayList<>(affNodes.size() + 2);

                nodes.addAll(affNodes);
              }

              nodes.add(n);
            }
          }
        }
      }

      return nodes != null ? nodes : affNodes;
    } finally {
      lock.readLock().unlock();
    }
  }
  /**
   * @param key Key.
   * @return Near cache for key.
   */
  protected IgniteCache<Integer, Integer> nearCache(Integer key) {
    List<Ignite> allGrids = Ignition.allGrids();

    assertFalse("There are no alive nodes.", F.isEmpty(allGrids));

    Affinity<Integer> aff = allGrids.get(0).affinity(null);

    Collection<ClusterNode> nodes = aff.mapKeyToPrimaryAndBackups(key);

    for (Ignite ignite : allGrids) {
      if (!nodes.contains(ignite.cluster().localNode())) return ignite.cache(null);
    }

    fail();

    return null;
  }
  /** {@inheritDoc} */
  @Override
  public void start() throws IgniteCheckedException {
    IpcSharedMemoryNativeLoader.load(log);

    pid = IpcSharedMemoryUtils.pid();

    if (pid == -1) throw new IpcEndpointBindException("Failed to get PID of the current process.");

    if (size <= 0) throw new IpcEndpointBindException("Space size should be positive: " + size);

    String tokDirPath = this.tokDirPath;

    if (F.isEmpty(tokDirPath)) throw new IpcEndpointBindException("Token directory path is empty.");

    tokDirPath = tokDirPath + '/' + locNodeId.toString() + '-' + IpcSharedMemoryUtils.pid();

    tokDir = U.resolveWorkDirectory(tokDirPath, false);

    if (port <= 0 || port >= 0xffff)
      throw new IpcEndpointBindException("Port value is illegal: " + port);

    try {
      srvSock = new ServerSocket();

      // Always bind to loopback.
      srvSock.bind(new InetSocketAddress("127.0.0.1", port));
    } catch (IOException e) {
      // Although empty socket constructor never throws exception, close it just in case.
      U.closeQuiet(srvSock);

      throw new IpcEndpointBindException(
          "Failed to bind shared memory IPC endpoint (is port already " + "in use?): " + port, e);
    }

    gcWorker = new GcWorker(gridName, "ipc-shmem-gc", log);

    new IgniteThread(gcWorker).start();

    if (log.isInfoEnabled())
      log.info(
          "IPC shared memory server endpoint started [port="
              + port
              + ", tokDir="
              + tokDir.getAbsolutePath()
              + ']');
  }
  /**
   * @param cache Cache.
   * @param keys Entries keys.
   * @param vers Entries versions.
   * @param ttl TTL.
   */
  private void updateTtl(
      GridCacheAdapter<K, V> cache,
      List<KeyCacheObject> keys,
      List<GridCacheVersion> vers,
      long ttl) {
    assert !F.isEmpty(keys);
    assert keys.size() == vers.size();

    int size = keys.size();

    boolean swap = cache.context().isSwapOrOffheapEnabled();

    for (int i = 0; i < size; i++) {
      try {
        GridCacheEntryEx entry = null;

        try {
          while (true) {
            try {
              if (swap) {
                entry = cache.entryEx(keys.get(i));

                entry.unswap(false);
              } else entry = cache.peekEx(keys.get(i));

              if (entry != null) entry.updateTtl(vers.get(i), ttl);

              break;
            } catch (GridCacheEntryRemovedException ignore) {
              // Retry
              if (log.isDebugEnabled()) log.debug("Got removed entry: " + entry);
            } catch (GridDhtInvalidPartitionException e) {
              if (log.isDebugEnabled()) log.debug("Got GridDhtInvalidPartitionException: " + e);

              break;
            }
          }
        } finally {
          if (entry != null) cache.context().evicts().touch(entry, AffinityTopologyVersion.NONE);
        }
      } catch (IgniteCheckedException e) {
        log.error("Failed to unswap entry.", e);
      }
    }
  }
Beispiel #30
0
    /**
     * Get descriptor for method (if any).
     *
     * @param cls Class.
     * @param mthd Method.
     * @return Descriptor or {@code null}.
     */
    @Nullable
    public static IgnoreDescriptor forMethod(Class cls, Method mthd) {
      if (mthd.isAnnotationPresent(IgniteIgnore.class)) {
        IgniteIgnore ignore = mthd.getAnnotation(IgniteIgnore.class);

        String reason = ignore.value();

        if (F.isEmpty(reason))
          throw new IllegalArgumentException(
              "Reason is not set for ignored test [class="
                  + cls.getName()
                  + ", method="
                  + mthd.getName()
                  + ']');

        return new IgnoreDescriptor(reason, ignore.forceFailure());
      } else return null;
    }