/**
   * Change topology.
   *
   * @param parent Grid to execute tasks on.
   * @param add New nodes count.
   * @param rmv Remove nodes count.
   * @param type Type of nodes to manipulate.
   */
  private static void changeTopology(Ignite parent, int add, int rmv, String type) {
    Collection<ComputeTaskFuture<?>> tasks = new ArrayList<>();

    IgniteCompute comp = parent.compute().withAsync();

    // Start nodes in parallel.
    while (add-- > 0) {
      comp.execute(ClientStartNodeTask.class, type);

      tasks.add(comp.future());
    }

    for (ComputeTaskFuture<?> task : tasks) task.get();

    // Stop nodes in sequence.
    while (rmv-- > 0) parent.compute().execute(ClientStopNodeTask.class, type);

    // Wait for node stops.
    // U.sleep(1000);

    Collection<String> gridNames = new ArrayList<>();

    for (Ignite g : G.allGrids()) gridNames.add(g.name());

    parent.log().info(">>> Available grids: " + gridNames);
  }
  /**
   * Start grid with IGFS.
   *
   * @param gridName Grid name.
   * @param igfsName IGFS name
   * @param mode IGFS mode.
   * @param secondaryFs Secondary file system (optional).
   * @param restCfg Rest configuration string (optional).
   * @return Started grid instance.
   * @throws Exception If failed.
   */
  protected Ignite startGridWithIgfs(
      String gridName,
      String igfsName,
      IgfsMode mode,
      @Nullable IgfsSecondaryFileSystem secondaryFs,
      @Nullable IgfsIpcEndpointConfiguration restCfg)
      throws Exception {
    FileSystemConfiguration igfsCfg = new FileSystemConfiguration();

    igfsCfg.setDataCacheName("dataCache");
    igfsCfg.setMetaCacheName("metaCache");
    igfsCfg.setName(igfsName);
    igfsCfg.setBlockSize(IGFS_BLOCK_SIZE);
    igfsCfg.setDefaultMode(mode);
    igfsCfg.setIpcEndpointConfiguration(restCfg);
    igfsCfg.setSecondaryFileSystem(secondaryFs);
    igfsCfg.setPrefetchBlocks(PREFETCH_BLOCKS);
    igfsCfg.setSequentialReadsBeforePrefetch(SEQ_READS_BEFORE_PREFETCH);

    CacheConfiguration dataCacheCfg = defaultCacheConfiguration();

    dataCacheCfg.setName("dataCache");
    dataCacheCfg.setCacheMode(PARTITIONED);
    dataCacheCfg.setNearConfiguration(null);
    dataCacheCfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
    dataCacheCfg.setAffinityMapper(new IgfsGroupDataBlocksKeyMapper(2));
    dataCacheCfg.setBackups(0);
    dataCacheCfg.setAtomicityMode(TRANSACTIONAL);
    dataCacheCfg.setOffHeapMaxMemory(0);

    CacheConfiguration metaCacheCfg = defaultCacheConfiguration();

    metaCacheCfg.setName("metaCache");
    metaCacheCfg.setCacheMode(REPLICATED);
    metaCacheCfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
    metaCacheCfg.setAtomicityMode(TRANSACTIONAL);

    IgniteConfiguration cfg = new IgniteConfiguration();

    cfg.setGridName(gridName);

    TcpDiscoverySpi discoSpi = new TcpDiscoverySpi();

    discoSpi.setIpFinder(new TcpDiscoveryVmIpFinder(true));

    cfg.setDiscoverySpi(discoSpi);
    cfg.setCacheConfiguration(dataCacheCfg, metaCacheCfg);
    cfg.setFileSystemConfiguration(igfsCfg);

    cfg.setLocalHost("127.0.0.1");
    cfg.setConnectorConfiguration(null);

    return G.start(cfg);
  }
  /**
   * Example for start/stop node tasks.
   *
   * @param args Not used.
   */
  public static void main(String[] args) {
    String nodeType = "tcp+ssl";

    // Start initial node = 1
    try (Ignite g = G.start(NODE_CFG.get(nodeType))) {
      // Change topology.
      changeTopology(g, 4, 1, nodeType);
      changeTopology(g, 1, 4, nodeType);

      // Stop node by id = 0
      g.compute().execute(ClientStopNodeTask.class, g.cluster().localNode().id().toString());

      // Wait for node stops.
      // U.sleep(1000);

      assert G.allGrids().isEmpty();
    } catch (Exception e) {
      System.err.println("Uncaught exception: " + e.getMessage());

      e.printStackTrace(System.err);
    }
  }
  /** @throws Exception If failed. */
  @SuppressWarnings({"AssignmentToCatchBlockParameter"})
  public void testCancel() throws Exception {
    Ignite ignite = G.ignite(getTestGridName());

    ignite
        .compute()
        .localDeployTask(GridCancelTestTask.class, GridCancelTestTask.class.getClassLoader());

    ComputeTaskFuture<?> res0 =
        executeAsync(
            ignite.compute().withTimeout(maxJobExecTime * 2),
            GridCancelTestTask.class.getName(),
            null);

    try {
      Object res = res0.get();

      info("Cancel test result: " + res);

      synchronized (mux) {
        // Every execute must be called.
        assert execCnt <= SPLIT_COUNT : "Invalid execute count: " + execCnt;

        // Job returns 1 if was cancelled.
        assert (Integer) res <= SPLIT_COUNT : "Invalid task result: " + res;

        // Should be exactly the same as Jobs number.
        assert cancelCnt <= SPLIT_COUNT : "Invalid cancel count: " + cancelCnt;

        // One per start and one per stop and some that come with heartbeats.
        assert colResolutionCnt > SPLIT_COUNT + 1
            : "Invalid collision resolution count: " + colResolutionCnt;
      }
    } catch (ComputeTaskTimeoutException e) {
      error("Task execution got timed out.", e);
    } catch (Exception e) {
      assert e.getCause() != null;

      if (e.getCause() instanceof IgniteCheckedException) e = (Exception) e.getCause();

      if (e.getCause() instanceof IOException) e = (Exception) e.getCause();

      assert e.getCause() instanceof InterruptedException
          : "Invalid exception cause: " + e.getCause();
    }
  }
  /** {@inheritDoc} */
  @Override
  protected Object executeJob(int gridSize, String type) {
    log.info(">>> Starting new grid node [currGridSize=" + gridSize + ", arg=" + type + "]");

    if (type == null) throw new IllegalArgumentException("Node type to start should be specified.");

    IgniteConfiguration cfg = getConfig(type);

    // Generate unique for this VM grid name.
    String gridName = cfg.getGridName() + " (" + UUID.randomUUID() + ")";

    // Update grid name (required to be unique).
    cfg.setGridName(gridName);

    // Start new node in current VM.
    Ignite g = G.start(cfg);

    log.info(
        ">>> Grid started [nodeId=" + g.cluster().localNode().id() + ", name='" + g.name() + "']");

    return true;
  }
 /** {@inheritDoc} */
 @Override
 protected void afterTestsStopped() throws Exception {
   G.stopAll(true);
 }