Exemplo n.º 1
0
  /**
   * Execute {@code HelloWorld} example on the grid.
   *
   * @param args Command line arguments, none required but if provided first one should point to the
   *     Spring XML configuration file. See {@code "examples/config/"} for configuration file
   *     examples.
   * @throws GridException If example execution failed.
   */
  public static void main(String[] args) throws GridException {
    if (args.length == 0) {
      G.start();
    } else {
      G.start(args[0]);
    }

    try {
      Grid grid = G.grid();

      // Execute Hello World task.
      GridTaskFuture<Integer> fut = grid.execute(GridHelloWorldTask.class, "Hello World");

      // Wait for task completion.
      int phraseLen = fut.get();

      X.println(">>>");
      X.println(">>> Finished executing Grid \"Hello World\" example with custom task.");
      X.println(">>> Total number of characters in the phrase is '" + phraseLen + "'.");
      X.println(">>> You should see print out of 'Hello' on one node and 'World' on another node.");
      X.println(">>> Check all nodes for output (this node is also part of the grid).");
      X.println(">>>");
    } finally {
      G.stop(true);
    }
  }
  /**
   * Executes {@link GridSegmentATask} and {@link GridSegmentBTask} tasks on the grid.
   *
   * @param args Command line arguments, none required or used.
   * @throws GridException If example execution failed.
   */
  public static void main(String[] args) throws GridException {
    AbstractApplicationContext ctx =
        new ClassPathXmlApplicationContext("org/gridgain/examples/multispi/master.xml");

    // Get configuration from Spring.
    GridConfiguration cfg = ctx.getBean("grid.cfg", GridConfiguration.class);

    G.start(cfg);

    try {
      Grid grid = G.grid();

      // Execute task on segment "A".
      GridTaskFuture<Integer> futA = grid.execute(GridSegmentATask.class, null);

      // Execute task on segment "B".
      GridTaskFuture<Integer> futB = grid.execute(GridSegmentBTask.class, null);

      // Wait for task completion.
      futA.get();
      futB.get();

      X.println(">>>");
      X.println(">>> Finished executing Grid \"Multiple Topology\" example with custom tasks.");
      X.println(
          ">>> You should see print out of 'Executing job on node that is from segment A.'"
              + "on node that has attribute \"segment=A\"");
      X.println(
          ">>> and 'Executing job on node that is from segment B.' on node that has "
              + "attribute \"segment=B\"");
      X.println(">>> Check all nodes for output (this node is not a part of the grid).");
      X.println(">>>");
    } finally {
      G.stop(true);
    }
  }
  public void write(List<? extends T> items) throws Exception {

    // Block until expecting <= throttle limit
    while (localState.getExpecting() > throttleLimit) {
      getNextResult();
    }

    if (!items.isEmpty()) {
      logger.debug("Dispatching chunk: " + items);
      ChunkRequest<T> request =
          new ChunkRequest<T>(items, localState.getJobId(), localState.createStepContribution());

      // Create & launch task
      ChunkTask<T> task = new ChunkTask<T>();
      task.setProcessor(chunkProcessor);
      GridTaskFuture<ChunkResponse> future =
          grid.<ChunkRequest<T>, ChunkResponse>execute(task, request);
      futures.add(future);

      localState.expected++;
    }
  }
Exemplo n.º 4
0
  /**
   * Runs all tests belonging to this test suite on the grid.
   *
   * @param result Test result collector.
   */
  @Override
  public void run(TestResult result) {
    if (isDisabled) {
      copy.run(result);
    } else {
      GridTestRouter router = createRouter();

      Grid grid = startGrid();

      try {
        List<GridTaskFuture<?>> futs = new ArrayList<GridTaskFuture<?>>(testCount());

        List<GridJunit3SerializableTest> tests =
            new ArrayList<GridJunit3SerializableTest>(testCount());

        for (int i = 0; i < testCount(); i++) {
          Test junit = testAt(i);

          GridJunit3SerializableTest test;

          if (junit instanceof TestSuite) {
            test = new GridJunit3SerializableTestSuite((TestSuite) junit);
          } else {
            assert junit instanceof TestCase
                : "Test must be either TestSuite or TestCase: " + junit;

            test = new GridJunit3SerializableTestCase((TestCase) junit);
          }

          tests.add(test);

          if (clsLdr == null) {
            clsLdr = U.detectClassLoader(junit.getClass());
          }

          futs.add(
              grid.execute(
                  new GridJunit3Task(junit.getClass(), clsLdr),
                  new GridJunit3Argument(router, test, locTests.contains(test.getName())),
                  timeout));
        }

        for (int i = 0; i < testCount(); i++) {
          GridTaskFuture<?> fut = futs.get(i);

          GridJunit3SerializableTest origTest = tests.get(i);

          try {
            GridJunit3SerializableTest resTest = (GridJunit3SerializableTest) fut.get();

            origTest.setResult(resTest);

            origTest.getTest().run(result);
          } catch (GridException e) {
            handleFail(result, origTest, e);
          }
        }
      } finally {
        stopGrid();
      }
    }
  }
Exemplo n.º 5
0
  /**
   * Aspect implementation which executes grid-enabled methods on remote nodes.
   *
   * @param invoc Method invocation instance provided by JBoss AOP framework.
   * @return Method execution result.
   * @throws Throwable If method execution failed.
   */
  @SuppressWarnings({
    "ProhibitedExceptionDeclared",
    "ProhibitedExceptionThrown",
    "CatchGenericClass",
    "unchecked"
  })
  @Bind(
      pointcut = "execution(* *->@org.gridgain.grid.gridify.Gridify(..))",
      cflow = "org.gridgain.grid.gridify.aop.jboss.GridifyJbossAspect.CFLOW_STACK")
  public Object gridify(MethodInvocation invoc) throws Throwable {
    Method mtd = invoc.getMethod();

    Gridify ann = mtd.getAnnotation(Gridify.class);

    assert ann != null : "Intercepted method does not have gridify annotation.";

    // Since annotations in Java don't allow 'null' as default value
    // we have accept an empty string and convert it here.
    // NOTE: there's unintended behavior when user specifies an empty
    // string as intended grid name.
    // NOTE: the 'ann.gridName() == null' check is added to mitigate
    // annotation bugs in some scripting languages (e.g. Groovy).
    String gridName = F.isEmpty(ann.gridName()) ? null : ann.gridName();

    if (G.state(gridName) != STARTED) {
      throw new GridException("Grid is not locally started: " + gridName);
    }

    // Initialize defaults.
    GridifyArgument arg =
        new GridifyArgumentAdapter(
            mtd.getDeclaringClass(),
            mtd.getName(),
            mtd.getParameterTypes(),
            invoc.getArguments(),
            invoc.getTargetObject());

    if (!ann.interceptor().equals(GridifyInterceptor.class)) {
      // Check interceptor first.
      if (!ann.interceptor().newInstance().isGridify(ann, arg)) {
        return invoc.invokeNext();
      }
    }

    if (!ann.taskClass().equals(GridifyDefaultTask.class) && ann.taskName().length() > 0) {
      throw new GridException(
          "Gridify annotation must specify either Gridify.taskName() or "
              + "Gridify.taskClass(), but not both: "
              + ann);
    }

    try {
      Grid grid = G.grid(gridName);

      // If task class was specified.
      if (!ann.taskClass().equals(GridifyDefaultTask.class)) {
        return grid.execute(
                (Class<? extends GridTask<GridifyArgument, Object>>) ann.taskClass(),
                arg,
                ann.timeout())
            .get();
      }

      // If task name was not specified.
      if (ann.taskName().length() == 0) {
        return grid.execute(
                new GridifyDefaultTask(invoc.getActualMethod().getDeclaringClass()),
                arg,
                ann.timeout())
            .get();
      }

      // If task name was specified.
      return grid.execute(ann.taskName(), arg, ann.timeout()).get();
    } catch (Throwable e) {
      for (Class<?> ex : invoc.getMethod().getExceptionTypes()) {
        // Descend all levels down.
        Throwable cause = e.getCause();

        while (cause != null) {
          if (ex.isAssignableFrom(cause.getClass())) {
            throw cause;
          }

          cause = cause.getCause();
        }

        if (ex.isAssignableFrom(e.getClass())) {
          throw e;
        }
      }

      throw new GridifyRuntimeException("Undeclared exception thrown: " + e.getMessage(), e);
    }
  }