/** @throws Exception If failed. */
  public void testDisabledRest() throws Exception {
    restEnabled = false;

    final Grid g = startGrid("disabled-rest");

    try {
      Thread.sleep(2 * TOP_REFRESH_FREQ);

      // As long as we have round robin load balancer this will cause every node to be queried.
      for (int i = 0; i < NODES_CNT + 1; i++)
        assertEquals(NODES_CNT + 1, client.compute().refreshTopology(false, false).size());

      final GridClientData data = client.data(PARTITIONED_CACHE_NAME);

      // Check rest-disabled node is unavailable.
      try {
        String affKey;

        do {
          affKey = UUID.randomUUID().toString();
        } while (!data.affinity(affKey).equals(g.localNode().id()));

        data.put(affKey, "asdf");

        assertEquals("asdf", cache(0, PARTITIONED_CACHE_NAME).get(affKey));
      } catch (GridServerUnreachableException e) {
        // Thrown for direct client-node connections.
        assertTrue(
            "Unexpected exception message: " + e.getMessage(),
            e.getMessage()
                .startsWith("No available endpoints to connect (is rest enabled for this node?)"));
      } catch (GridClientException e) {
        // Thrown for routed client-router-node connections.
        String msg = e.getMessage();

        assertTrue(
            "Unexpected exception message: " + msg,
            protocol() == GridClientProtocol.TCP
                ? msg.contains("No available endpoints to connect (is rest enabled for this node?)")
                : // TCP router.
                msg.startsWith(
                    "No available nodes on the router for destination node ID")); // HTTP router.
      }

      // Check rest-enabled nodes are available.
      String affKey;

      do {
        affKey = UUID.randomUUID().toString();
      } while (data.affinity(affKey).equals(g.localNode().id()));

      data.put(affKey, "fdsa");

      assertEquals("fdsa", cache(0, PARTITIONED_CACHE_NAME).get(affKey));
    } finally {
      restEnabled = true;

      G.stop(g.name(), true);
    }
  }
  /** @throws Exception If failed. */
  public void testInvalidateFlag() throws Exception {
    GridEx g0 = grid(0);

    GridCache<String, String> cache = g0.cache(PARTITIONED_CACHE_NAME);

    String key = null;

    for (int i = 0; i < 10_000; i++) {
      if (!cache.affinity().isPrimaryOrBackup(g0.localNode(), String.valueOf(i))) {
        key = String.valueOf(i);

        break;
      }
    }

    assertNotNull(key);

    cache.put(key, key); // Create entry in near cache, it is invalidated if INVALIDATE flag is set.

    assertNotNull(cache.peek(key));

    GridClientData d = client.data(PARTITIONED_CACHE_NAME);

    d.flagsOn(GridClientCacheFlag.INVALIDATE).put(key, "zzz");

    for (Grid g : G.allGrids()) {
      cache = g.cache(PARTITIONED_CACHE_NAME);

      if (cache.affinity().isPrimaryOrBackup(g.localNode(), key))
        assertEquals("zzz", cache.peek(key));
      else assertNull(cache.peek(key));
    }
  }
  /** @throws Exception If failed. */
  public void testProjectionRun() throws Exception {
    GridClientCompute dflt = client.compute();

    Collection<? extends GridClientNode> nodes = dflt.nodes();

    assertEquals(NODES_CNT, nodes.size());

    for (int i = 0; i < NODES_CNT; i++) {
      Grid g = grid(i);

      assert g != null;

      GridClientNode clientNode = dflt.node(g.localNode().id());

      assertNotNull("Client node for " + g.localNode().id() + " was not found", clientNode);

      GridClientCompute prj = dflt.projection(clientNode);

      String res = prj.execute(TestTask.class.getName(), null);

      assertNotNull(res);

      assertEquals(g.localNode().id().toString(), res);
    }
  }
  /**
   * Ensure that {@link GridComputeJobMasterLeaveAware} callback is invoked on job which is
   * initiated by master and is currently running on it.
   *
   * @throws Exception If failed.
   */
  public void testLocalJobOnMaster() throws Exception {
    invokeLatch = new CountDownLatch(1);
    jobLatch = new CountDownLatch(1);

    Grid g = startGrid(0);

    g.compute().execute(new TestTask(1), null);

    jobLatch.await();

    // Count down the latch in a separate thread.
    new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  U.sleep(500);
                } catch (GridInterruptedException ignore) {
                  // No-op.
                }

                latch.countDown();
              }
            })
        .start();

    stopGrid(0, true);

    latch.countDown();

    assert invokeLatch.await(5000, MILLISECONDS);
  }
  /** @throws Exception If failed. */
  public void testTopologyListener() throws Exception {
    final Collection<UUID> added = new ArrayList<>(1);
    final Collection<UUID> rmvd = new ArrayList<>(1);

    final CountDownLatch addedLatch = new CountDownLatch(1);
    final CountDownLatch rmvLatch = new CountDownLatch(1);

    assertEquals(NODES_CNT, client.compute().refreshTopology(false, false).size());

    GridClientTopologyListener lsnr =
        new GridClientTopologyListener() {
          @Override
          public void onNodeAdded(GridClientNode node) {
            added.add(node.nodeId());

            addedLatch.countDown();
          }

          @Override
          public void onNodeRemoved(GridClientNode node) {
            rmvd.add(node.nodeId());

            rmvLatch.countDown();
          }
        };

    client.addTopologyListener(lsnr);

    try {
      Grid g = startGrid(NODES_CNT + 1);

      UUID id = g.localNode().id();

      assertTrue(addedLatch.await(2 * TOP_REFRESH_FREQ, MILLISECONDS));

      assertEquals(1, added.size());
      assertEquals(id, F.first(added));

      stopGrid(NODES_CNT + 1);

      assertTrue(rmvLatch.await(2 * TOP_REFRESH_FREQ, MILLISECONDS));

      assertEquals(1, rmvd.size());
      assertEquals(id, F.first(rmvd));
    } finally {
      client.removeTopologyListener(lsnr);

      stopGrid(NODES_CNT + 1);
    }
  }
    /** {@inheritDoc} */
    @Override
    protected Collection<? extends GridComputeJob> split(int gridSize, Object arg)
        throws GridException {
      Collection<GridComputeJobAdapter> jobs = new ArrayList<>(gridSize);

      this.gridSize = gridSize;

      final String locNodeId = grid.localNode().id().toString();

      for (int i = 0; i < gridSize; i++) {
        jobs.add(
            new GridComputeJobAdapter() {
              @SuppressWarnings("OverlyStrongTypeCast")
              @Override
              public Object execute() {
                try {
                  Thread.sleep(1000);
                } catch (InterruptedException ignored) {
                  Thread.currentThread().interrupt();
                }

                return new GridBiTuple<>(locNodeId, 1);
              }
            });
      }

      return jobs;
    }
  /**
   * Sends optional message. If message is {@code null} - it's no-op.
   *
   * @param nodeId ID of the node to send message to.
   * @param respMsg Message to send.
   * @throws GridException Thrown in case of any errors.
   */
  private void send(UUID nodeId, @Nullable Object respMsg) throws GridException {
    assert nodeId != null;

    if (respMsg != null) {
      GridNode node = grid.node(nodeId);

      if (node != null) grid.forNode(node).message().send(null, respMsg); // Can still fail.
      else
        throw new GridException(
            "Failed to send message since destination node has "
                + "left topology (ignoring) [nodeId="
                + nodeId
                + ", respMsg="
                + respMsg
                + ']');
    }
  }
  /**
   * Executes example.
   *
   * @param args Command line arguments, none required.
   * @throws GridException If example execution failed.
   */
  public static void main(String[] args) throws Exception {
    Timer timer = new Timer("priceBars");

    // Start grid.
    final Grid g = GridGain.start("examples/config/example-streamer.xml");

    System.out.println();
    System.out.println(">>> Streaming price bars example started.");

    try {
      TimerTask task = scheduleQuery(g, timer);

      streamData(g);

      // Force one more run to get final results.
      task.run();

      timer.cancel();

      // Reset all streamers on all nodes to make sure that
      // consecutive executions start from scratch.
      g.compute()
          .broadcast(
              new Runnable() {
                @Override
                public void run() {
                  if (!ExamplesUtils.hasStreamer(g, "priceBars"))
                    System.err.println(
                        "Default streamer not found (is example-streamer.xml "
                            + "configuration used on all nodes?)");
                  else {
                    GridStreamer streamer = g.streamer("priceBars");

                    System.out.println("Clearing bars from streamer.");

                    streamer.reset();
                  }
                }
              })
          .get();
    } finally {
      GridGain.stop(true);
    }
  }
  /**
   * Streams random prices into the system.
   *
   * @param g Grid.
   * @throws GridException If failed.
   */
  private static void streamData(final Grid g) throws GridException {
    GridStreamer streamer = g.streamer("priceBars");

    for (int i = 0; i < CNT; i++) {
      for (int j = 0; j < INSTRUMENTS.length; j++) {
        // Use gaussian distribution to ensure that
        // numbers closer to 0 have higher probability.
        double price = round2(INITIAL_PRICES[j] + RAND.nextGaussian());

        Quote quote = new Quote(INSTRUMENTS[j], price);

        streamer.addEvent(quote);
      }
    }
  }
  /** @throws Exception If failed. */
  public void testAffinityExecute() throws Exception {
    GridClientCompute dflt = client.compute();

    GridClientData data = client.data(PARTITIONED_CACHE_NAME);

    Collection<? extends GridClientNode> nodes = dflt.nodes();

    assertEquals(NODES_CNT, nodes.size());

    for (int i = 0; i < NODES_CNT; i++) {
      Grid g = grid(i);

      assert g != null;

      int affinityKey = -1;

      for (int key = 0; key < 10000; key++) {
        if (g.localNode().id().equals(data.affinity(key))) {
          affinityKey = key;

          break;
        }
      }

      if (affinityKey == -1)
        throw new Exception("Unable to found key for which node is primary: " + g.localNode().id());

      GridClientNode clientNode = dflt.node(g.localNode().id());

      assertNotNull("Client node for " + g.localNode().id() + " was not found", clientNode);

      String res =
          dflt.affinityExecute(TestTask.class.getName(), PARTITIONED_CACHE_NAME, affinityKey, null);

      assertNotNull(res);

      assertEquals(g.localNode().id().toString(), res);
    }
  }
Example #11
0
  /** {@inheritDoc} */
  @Nullable
  @Override
  public final Map<? extends GridComputeJob, GridNode> map(
      List<GridNode> subgrid, @Nullable GridGgfsTaskArgs<T> args) throws GridException {
    assert grid != null;
    assert args != null;

    GridGgfs ggfs = grid.ggfs(args.ggfsName());
    GridGgfsProcessorAdapter ggfsProc = ((GridKernal) grid).context().ggfs();

    Map<GridComputeJob, GridNode> splitMap = new HashMap<>();

    Map<UUID, GridNode> nodes = mapSubgrid(subgrid);

    for (GridGgfsPath path : args.paths()) {
      GridGgfsFile file = ggfs.info(path);

      if (file == null) {
        if (args.skipNonExistentFiles()) continue;
        else
          throw new GridException("Failed to process GGFS file because it doesn't exist: " + path);
      }

      Collection<GridGgfsBlockLocation> aff =
          ggfs.affinity(path, 0, file.length(), args.maxRangeLength());

      long totalLen = 0;

      for (GridGgfsBlockLocation loc : aff) {
        GridNode node = null;

        for (UUID nodeId : loc.nodeIds()) {
          node = nodes.get(nodeId);

          if (node != null) break;
        }

        if (node == null)
          throw new GridException(
              "Failed to find any of block affinity nodes in subgrid [loc="
                  + loc
                  + ", subgrid="
                  + subgrid
                  + ']');

        GridGgfsJob job =
            createJob(path, new GridGgfsFileRange(file.path(), loc.start(), loc.length()), args);

        if (job != null) {
          GridComputeJob jobImpl =
              ggfsProc.createJob(
                  job, ggfs.name(), file.path(), loc.start(), loc.length(), args.recordResolver());

          splitMap.put(jobImpl, node);
        }

        totalLen += loc.length();
      }

      assert totalLen == file.length();
    }

    return splitMap;
  }