/**
   * Creates signature for data.
   *
   * @param alg Algorithm.
   * @param prv Provider.
   * @param key Private key.
   * @param data Data.
   * @return Signature.
   * @throws GeneralSecurityException If any exception occurs while signature creation.
   */
  public static byte[] createSignature(String alg, String prv, PrivateKey key, byte[] data)
      throws GeneralSecurityException {
    assert !F.isEmpty(alg);
    assert !F.isEmpty(prv);
    assert key != null;
    assert data != null;

    Signature sign = Signature.getInstance(alg, prv);

    sign.initSign(key);
    sign.update(data);

    return sign.sign();
  }
  /**
   * 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);
  }
  /**
   * @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();
  }
  /**
   * Verifies signature for data.
   *
   * @param alg Algorithm.
   * @param prv Provider.
   * @param key Public key.
   * @param data Data.
   * @param sign Signature.
   * @return {@code true} if signature was verified, {@code false} - otherwise.
   * @throws GeneralSecurityException If any exception occurs while verifying.
   */
  public static boolean verifySignature(
      String alg, String prv, PublicKey key, byte[] data, byte[] sign)
      throws GeneralSecurityException {
    assert !F.isEmpty(alg);
    assert !F.isEmpty(prv);
    assert key != null;
    assert data != null;
    assert sign != null;

    Signature sign0 = Signature.getInstance(alg, prv);

    sign0.initVerify(key);
    sign0.update(data);

    return sign0.verify(sign);
  }
Exemple #5
0
    /**
     * @param id ID.
     * @param name Name.
     * @param age Age.
     * @param orgId Organization ID.
     */
    private Person(int id, String name, int age, int orgId) {
      assert !F.isEmpty(name);
      assert age > 0;
      assert orgId > 0;

      this.id = id;
      this.name = name;
      this.age = age;
      this.orgId = orgId;
    }
Exemple #6
0
  /**
   * @param keys Keys.
   * @param timeout Timeout.
   * @param tx Transaction.
   * @param filter Filter.
   * @return Future.
   */
  public GridFuture<Boolean> lockAllAsync(
      Collection<? extends K> keys,
      long timeout,
      @Nullable GridCacheTxLocalEx<K, V> tx,
      GridPredicate<? super GridCacheEntry<K, V>>[] filter) {
    if (F.isEmpty(keys)) {
      return new GridFinishedFuture<Boolean>(ctx.kernalContext(), true);
    }

    GridLocalLockFuture<K, V> fut =
        new GridLocalLockFuture<K, V>(ctx, keys, tx, this, timeout, filter);

    try {
      for (K key : keys) {
        while (true) {
          GridLocalCacheEntry<K, V> entry = null;

          try {
            entry = entryExx(key);

            if (!ctx.isAll(entry, filter)) {
              fut.onFailed();

              return fut;
            }

            // Removed exception may be thrown here.
            GridCacheMvccCandidate<K> cand = fut.addEntry(entry);

            if (cand == null && fut.isDone()) {
              return fut;
            }

            break;
          } catch (GridCacheEntryRemovedException ignored) {
            if (log().isDebugEnabled()) {
              log().debug("Got removed entry in lockAsync(..) method (will retry): " + entry);
            }
          }
        }
      }

      if (!ctx.mvcc().addFuture(fut))
        fut.onError(new GridException("Duplicate future ID (internal error): " + fut));

      // Must have future added prior to checking locks.
      fut.checkLocks();

      return fut;
    } catch (GridException e) {
      fut.onError(e);

      return fut;
    }
  }
  /** {@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).");
    }
  }
  /**
   * 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;
  }
 /** {@inheritDoc} */
 @Override
 public void stopListenAsync(@Nullable GridInClosure<? super GridFuture<R>>... lsnr) {
   if (F.isEmpty(lsnr))
     synchronized (mux) {
       lsnrs.clear();
     }
   else
     synchronized (mux) {
       lsnrs.removeAll(F.asList(lsnr));
     }
 }
  /**
   * 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;
  }
  /**
   * Checks {@link GridSystemProperties#GG_JETTY_PORT} system property and overrides default
   * connector port if it present. Then initializes {@code port} with the found value.
   *
   * @param con Jetty connector.
   */
  private void override(AbstractNetworkConnector con) {
    String host = System.getProperty(GG_JETTY_HOST);

    if (!F.isEmpty(host)) con.setHost(host);

    int currPort = con.getPort();

    Integer overridePort = Integer.getInteger(GG_JETTY_PORT);

    if (overridePort != null && overridePort != 0) currPort = overridePort;

    con.setPort(currPort);
    port = currPort;
  }
  /** {@inheritDoc} */
  @Override
  public GridFuture<Map<K, V>> getAllAsync(
      @Nullable Collection<? extends K> keys,
      @Nullable GridPredicate<? super GridCacheEntry<K, V>>[] filter) {
    ctx.denyOnFlag(LOCAL);

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

    GridCacheTxLocalAdapter<K, V> tx = ctx.tm().threadLocalTx();

    if (tx != null && !tx.implicit()) return ctx.wrapCloneMap(tx.getAllAsync(keys, filter));

    return loadAsync(keys, false, filter);
  }
Exemple #13
0
  /** @param mappings Mappings. */
  void addEntryMapping(@Nullable Map<UUID, GridDistributedTxMapping<K, V>> mappings) {
    if (!F.isEmpty(mappings)) {
      this.mappings.putAll(mappings);

      if (log.isDebugEnabled())
        log.debug(
            "Added mappings to transaction [locId="
                + cctx.nodeId()
                + ", mappings="
                + mappings
                + ", tx="
                + this
                + ']');
    }
  }
  /**
   * @param ldr Loader.
   * @param nodeId Sender node ID.
   * @param req Request.
   * @return Remote transaction.
   * @throws GridException If failed.
   */
  @Nullable
  public GridNearTxRemote<K, V> startRemoteTx(
      ClassLoader ldr, UUID nodeId, GridDhtTxPrepareRequest<K, V> req) throws GridException {
    if (!F.isEmpty(req.nearWrites())) {
      GridNearTxRemote<K, V> tx =
          new GridNearTxRemote<K, V>(
              ldr,
              nodeId,
              req.nearNodeId(),
              req.threadId(),
              req.version(),
              req.commitVersion(),
              req.concurrency(),
              req.isolation(),
              req.isInvalidate(),
              req.timeout(),
              req.nearWrites(),
              ctx);

      if (!tx.empty()) {
        tx = ctx.tm().onCreated(tx);

        if (tx == null || !ctx.tm().onStarted(tx))
          throw new GridCacheTxRollbackException("Attempt to start a completed transaction: " + tx);

        // Prepare prior to reordering, so the pending locks added
        // in prepare phase will get properly ordered as well.
        tx.prepare();

        // Add remote candidates and reorder completed and uncompleted versions.
        tx.addRemoteCandidates(
            req.candidatesByKey(), req.committedVersions(), req.rolledbackVersions());

        if (req.concurrency() == EVENTUALLY_CONSISTENT) {
          if (log.isDebugEnabled())
            log.debug("Committing transaction during remote prepare: " + tx);

          tx.commit();

          if (log.isDebugEnabled()) log.debug("Committed transaction during remote prepare: " + tx);
        }
      }

      return tx;
    }

    return null;
  }
  /**
   * @param keys Keys to load.
   * @param reload Reload flag.
   * @param filter Filter.
   * @return Loaded values.
   */
  public GridFuture<Map<K, V>> loadAsync(
      @Nullable Collection<? extends K> keys,
      boolean reload,
      @Nullable GridPredicate<? super GridCacheEntry<K, V>>[] filter) {
    if (F.isEmpty(keys))
      return new GridFinishedFuture<Map<K, V>>(ctx.kernalContext(), Collections.<K, V>emptyMap());

    GridNearGetFuture<K, V> fut = new GridNearGetFuture<K, V>(ctx, keys, reload, null, filter);

    // Register future for responses.
    ctx.mvcc().addFuture(fut);

    fut.init();

    return ctx.wrapCloneMap(fut);
  }
  /** {@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()
              + ']');
  }
  /** {@inheritDoc} */
  @Override
  public void prepareMarshal(GridCacheContext<K, V> ctx) throws GridException {
    super.prepareMarshal(ctx);

    if (err != null) errBytes = ctx.marshaller().marshal(err);

    metaDataBytes = marshalCollection(metadata, ctx);
    dataBytes = fields ? marshalFieldsCollection(data, ctx) : marshalCollection(data, ctx);

    if (ctx.deploymentEnabled() && !F.isEmpty(data)) {
      for (Object o : data) {
        if (o instanceof Map.Entry) {
          Map.Entry e = (Map.Entry) o;

          prepareObject(e.getKey(), ctx);
          prepareObject(e.getValue(), ctx);
        }
      }
    }
  }
  /**
   * @param nodeId Sender node ID.
   * @param req Finish transaction message.
   */
  @SuppressWarnings({"CatchGenericClass"})
  private void processFinishRequest(UUID nodeId, GridDistributedTxFinishRequest<K, V> req) {
    assert nodeId != null;
    assert req != null;

    GridReplicatedTxRemote<K, V> tx = ctx.tm().tx(req.version());

    try {
      ClassLoader ldr = ctx.deploy().globalLoader();

      if (req.commit()) {
        // If lock was acquired explicitly.
        if (tx == null) {
          // Create transaction and add entries.
          tx =
              ctx.tm()
                  .onCreated(
                      new GridReplicatedTxRemote<K, V>(
                          ldr,
                          nodeId,
                          req.threadId(),
                          req.version(),
                          req.commitVersion(),
                          PESSIMISTIC,
                          READ_COMMITTED,
                          req.isInvalidate(),
                          /*timeout */ 0,
                          /*read entries*/ null,
                          req.writes(),
                          ctx));

          if (tx == null || !ctx.tm().onStarted(tx))
            throw new GridCacheTxRollbackException(
                "Attempt to start a completed " + "transaction: " + req);
        } else {
          boolean set = tx.commitVersion(req.commitVersion());

          assert set;
        }

        Collection<GridCacheTxEntry<K, V>> writeEntries = req.writes();

        if (!F.isEmpty(writeEntries)) {
          // In OPTIMISTIC mode, we get the values at PREPARE stage.
          assert tx.concurrency() == PESSIMISTIC;

          for (GridCacheTxEntry<K, V> entry : writeEntries) {
            // Unmarshal write entries.
            entry.unmarshal(ctx, ldr);

            if (log.isDebugEnabled())
              log.debug(
                  "Unmarshalled transaction entry from pessimistic transaction [key="
                      + entry.key()
                      + ", value="
                      + entry.value()
                      + ", tx="
                      + tx
                      + ']');

            if (!tx.setWriteValue(entry))
              U.warn(
                  log,
                  "Received entry to commit that was not present in transaction [entry="
                      + entry
                      + ", tx="
                      + tx
                      + ']');
          }
        }

        // Add completed versions.
        tx.doneRemote(req.baseVersion(), req.committedVersions(), req.rolledbackVersions());

        if (tx.pessimistic()) tx.prepare();

        tx.commit();
      } else if (tx != null) {
        tx.doneRemote(req.baseVersion(), req.committedVersions(), req.rolledbackVersions());

        tx.rollback();
      }

      if (req.replyRequired()) {
        GridCacheMessage<K, V> res =
            new GridDistributedTxFinishResponse<K, V>(req.version(), req.futureId());

        try {
          ctx.io().send(nodeId, res);
        } catch (Throwable e) {
          // Double-check.
          if (ctx.discovery().node(nodeId) == null) {
            if (log.isDebugEnabled())
              log.debug(
                  "Node left while sending finish response [nodeId="
                      + nodeId
                      + ", res="
                      + res
                      + ']');
          } else
            U.error(
                log,
                "Failed to send finish response to node [nodeId=" + nodeId + ", res=" + res + ']',
                e);
        }
      }
    } catch (GridCacheTxRollbackException e) {
      if (log.isDebugEnabled())
        log.debug("Attempted to start a completed transaction (will ignore): " + e);
    } catch (Throwable e) {
      U.error(
          log,
          "Failed completing transaction [commit=" + req.commit() + ", tx=" + CU.txString(tx) + ']',
          e);

      if (tx != null) tx.rollback();
    }
  }
 /**
  * Records all undeployed tasks.
  *
  * @param nodeId Left node ID.
  * @param undeployed Undeployed deployments.
  */
 private void recordUndeployed(@Nullable UUID nodeId, Collection<SharedDeployment> undeployed) {
   if (!F.isEmpty(undeployed)) for (SharedDeployment d : undeployed) d.recordUndeployed(nodeId);
 }
  /**
   * Initializes store.
   *
   * @throws GridException If failed to initialize.
   */
  private void init() throws GridException {
    if (initGuard.compareAndSet(false, true)) {
      if (log.isDebugEnabled()) log.debug("Initializing cache store.");

      try {
        if (sesFactory != null)
          // Session factory has been provided - nothing to do.
          return;

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

            sesFactory = new Configuration().configure(url).buildSessionFactory();

            if (log.isDebugEnabled()) log.debug("Configured session factory using URL: " + url);

            // Session factory has been successfully initialized.
            return;
          } catch (MalformedURLException e) {
            if (log.isDebugEnabled())
              log.debug("Caught malformed URL exception: " + e.getMessage());
          }

          // Provided path is not a valid URL. File?
          File cfgFile = new File(hibernateCfgPath);

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

            if (log.isDebugEnabled())
              log.debug("Configured session factory using file: " + hibernateCfgPath);

            // Session factory has been successfully initialized.
            return;
          }

          // Provided path is not a file. Classpath resource?
          sesFactory = new Configuration().configure(hibernateCfgPath).buildSessionFactory();

          if (log.isDebugEnabled())
            log.debug("Configured session factory using classpath resource: " + hibernateCfgPath);
        } else {
          if (hibernateProps == null) {
            U.warn(
                log, "No Hibernate configuration has been provided for store (will use default).");

            hibernateProps = new Properties();

            hibernateProps.setProperty("hibernate.connection.url", DFLT_CONN_URL);
            hibernateProps.setProperty("hibernate.show_sql", DFLT_SHOW_SQL);
            hibernateProps.setProperty("hibernate.hbm2ddl.auto", DFLT_HBM2DDL_AUTO);
          }

          Configuration cfg = new Configuration();

          cfg.setProperties(hibernateProps);

          assert resourceAvailable(MAPPING_RESOURCE);

          cfg.addResource(MAPPING_RESOURCE);

          sesFactory = cfg.buildSessionFactory();

          if (log.isDebugEnabled())
            log.debug("Configured session factory using properties: " + hibernateProps);
        }
      } catch (HibernateException e) {
        throw new GridException("Failed to initialize store.", e);
      } finally {
        initLatch.countDown();
      }
    } else if (initLatch.getCount() > 0) U.await(initLatch);

    if (sesFactory == null) throw new GridException("Cache store was not properly initialized.");
  }