/**
   * Reconstructs object on demarshalling.
   *
   * @return Reconstructed object.
   * @throws ObjectStreamException Thrown in case of demarshalling error.
   */
  private Object readResolve() throws ObjectStreamException {
    GridTuple2<GridCacheContext, String> t = stash.get();

    try {
      return t.get1().dataStructures().sequence(t.get2(), 0L, false, false);
    } catch (GridException e) {
      throw U.withCause(new InvalidObjectException(e.getMessage()), e);
    }
  }
  /**
   * Tries to start server with given parameters.
   *
   * @param hostAddr Host on which server should be bound.
   * @param port Port on which server should be bound.
   * @param lsnr Server message listener.
   * @param parser Server message parser.
   * @param sslCtx SSL context in case if SSL is enabled.
   * @param cfg Configuration for other parameters.
   * @return {@code True} if server successfully started, {@code false} if port is used and server
   *     was unable to start.
   */
  private boolean startTcpServer(
      InetAddress hostAddr,
      int port,
      GridNioServerListener<GridClientMessage> lsnr,
      GridNioParser parser,
      @Nullable SSLContext sslCtx,
      GridConfiguration cfg) {
    try {
      GridNioFilter codec = new GridNioCodecFilter(parser, log, false);

      GridNioFilter[] filters;

      if (sslCtx != null) {
        GridNioSslFilter sslFilter = new GridNioSslFilter(sslCtx, log);

        boolean auth = cfg.isRestTcpSslClientAuth();

        sslFilter.wantClientAuth(auth);

        sslFilter.needClientAuth(auth);

        filters = new GridNioFilter[] {codec, sslFilter};
      } else filters = new GridNioFilter[] {codec};

      srv =
          GridNioServer.<GridClientMessage>builder()
              .address(hostAddr)
              .port(port)
              .listener(lsnr)
              .logger(log)
              .selectorCount(cfg.getRestTcpSelectorCount())
              .gridName(ctx.gridName())
              .tcpNoDelay(cfg.isRestTcpNoDelay())
              .directBuffer(cfg.isRestTcpDirectBuffer())
              .byteOrder(ByteOrder.nativeOrder())
              .socketSendBufferSize(cfg.getRestTcpSendBufferSize())
              .socketReceiveBufferSize(cfg.getRestTcpReceiveBufferSize())
              .sendQueueLimit(cfg.getRestTcpSendQueueLimit())
              .filters(filters)
              .build();

      srv.idleTimeout(cfg.getRestIdleTimeout());

      srv.start();

      ctx.ports().registerPort(port, GridPortProtocol.TCP, getClass());

      return true;
    } catch (GridException e) {
      if (log.isDebugEnabled())
        log.debug(
            "Failed to start " + name() + " protocol on port " + port + ": " + e.getMessage());

      return false;
    }
  }
  /**
   * Reconstructs object on demarshalling.
   *
   * @return Reconstructed object.
   * @throws ObjectStreamException Thrown in case of demarshalling error.
   */
  @SuppressWarnings({"ConstantConditions"})
  private Object readResolve() throws ObjectStreamException {
    GridTuple2<GridCacheContext, String> t = stash.get();

    try {
      return t.get1().dataStructures().countDownLatch(t.get2(), 0, false, false);
    } catch (GridException e) {
      throw U.withCause(new InvalidObjectException(e.getMessage()), e);
    }
  }
  /**
   * Checks entry for empty value.
   *
   * @param entry Entry to check.
   * @return {@code True} if entry is empty.
   */
  private boolean empty(GridCacheEntry<K, V> entry) {
    try {
      return entry.peek(F.asList(GLOBAL)) == null;
    } catch (GridException e) {
      U.error(null, e.getMessage(), e);

      assert false : "Should never happen: " + e;

      return false;
    }
  }
  /**
   * Reconstructs object on demarshalling.
   *
   * @return Reconstructed object.
   * @throws ObjectStreamException Thrown in case of demarshalling error.
   */
  @SuppressWarnings("unchecked")
  private Object readResolve() throws ObjectStreamException {
    try {
      GridBiTuple<GridCacheContext, String> t = stash.get();

      return t.get1().dataStructures().atomicReference(t.get2(), null, false);
    } catch (GridException e) {
      throw U.withCause(new InvalidObjectException(e.getMessage()), e);
    } finally {
      stash.remove();
    }
  }
Example #6
0
  /**
   * Checks that the given grid configuration will lead to {@link GridException} upon grid startup.
   *
   * @param cfg Grid configuration to check.
   * @param excMsgSnippet Root cause (assertion) exception message snippet.
   * @param testLoc {@code True} if checking is done for "testLocal" tests.
   */
  private void checkGridStartFails(
      GridConfiguration cfg, CharSequence excMsgSnippet, boolean testLoc) {
    assertNotNull(cfg);
    assertNotNull(excMsgSnippet);

    try {
      G.start(cfg);

      fail("No exception has been thrown.");
    } catch (GridException e) {
      if (testLoc) {
        if ("Failed to start processor: GridProcessorAdapter []".equals(e.getMessage())
            && e.getCause().getMessage().contains(excMsgSnippet)) return; // Expected exception.
      } else if (e.getMessage().contains(excMsgSnippet)) return; // Expected exception.

      error("Caught unexpected exception.", e);

      fail();
    }
  }
  /**
   * Default implementation which will wait for all jobs to complete before calling {@link
   * #reduce(List)} method.
   *
   * <p>If remote job resulted in exception ({@link GridComputeJobResult#getException()} is not
   * {@code null}), then {@link GridComputeJobResultPolicy#FAILOVER} policy will be returned if the
   * exception is instance of {@link GridTopologyException} or {@link
   * GridComputeExecutionRejectedException}, which means that remote node either failed or job
   * execution was rejected before it got a chance to start. In all other cases the exception will
   * be rethrown which will ultimately cause task to fail.
   *
   * @param res Received remote grid executable result.
   * @param rcvd All previously received results.
   * @return Result policy that dictates how to process further upcoming job results.
   * @throws GridException If handling a job result caused an error effectively rejecting a
   *     failover. This exception will be thrown out of {@link GridComputeTaskFuture#get()} method.
   */
  @Override
  public GridComputeJobResultPolicy result(
      GridComputeJobResult res, List<GridComputeJobResult> rcvd) throws GridException {
    GridException e = res.getException();

    // Try to failover if result is failed.
    if (e != null) {
      // Don't failover user's code errors.
      if (e instanceof GridComputeExecutionRejectedException
          || e instanceof GridTopologyException
          ||
          // Failover exception is always wrapped.
          e.hasCause(GridComputeJobFailoverException.class)) return FAILOVER;

      throw new GridException(
          "Remote job threw user exception (override or implement GridComputeTask.result(..) "
              + "method if you would like to have automatic failover for this exception).",
          e);
    }

    // Wait for all job responses.
    return WAIT;
  }
Example #8
0
  public boolean runCase(SimuContext simuCtx) {
    boolean converge = false;
    if (this.xmlGridOpt.isEnableGridRun()) {
      final AclfNetwork aclfNet = simuCtx.getAclfNet();
      Grid grid = GridEnvHelper.getDefaultGrid();
      if (this.contingencyAnalysis) {
        IpssLogger.getLogger().info("Run Grid contingency analysis");

        try {
          GridContingencyAnalysis analysis =
              GridObjectFactory.createGridContingencyAnalysis(
                  simuCtx.getNetType(), simuCtx.getAclfNet(), grid);
          analysis.setLimitRunCase(this.xmlContingency.isLimitRunCases());
          if (analysis.isLimitRunCase())
            analysis.setMaxRunCase(this.xmlContingency.getMaxRunCases());

          LoadflowAlgorithm algo = simuCtx.getLoadflowAlgorithm();
          EditorPluginSpringFactory.getXml2LfAlgorithmMapper()
              .map2Model(this.xmlContingency.getDefaultAclfAlgorithm(), algo);
          analysis.perform(algo, ContingencyAnalysisType.N1);
          // System.out.println(analysis.getResult(IRemoteResult.DisplayType_SecViolation));
          // System.out.println(analysis.getResult(IRemoteResult.DisplayType_SecAssessment));

          IOutputTextDialog dialog =
              UISpringFactory.getOutputTextDialog("Contingency Analysis Info");
          StringBuffer buffer = new StringBuffer();
          buffer.append(analysis.getResult(IRemoteResult.DisplayType_SecViolation));
          buffer.append(analysis.getResult(IRemoteResult.DisplayType_SecAssessment));
          dialog.display(buffer);
        } catch (InterpssException e) {
          EditorPluginSpringFactory.getEditorDialogUtil()
              .showErrMsgDialog("Grid Aclf Error", e.toString());
          return false;
        }
      } else {
        String nodeId = GridEnvHelper.nodeIdLookup(this.xmlGridOpt.getRemoteNodeName());
        DStabSingleJobTask.RemoteNodeId = nodeId;
        GridRunner.MasterNodeId = grid.getLocalNode().getId().toString();
        try {
          RemoteMessageTable result =
              new GridRunner(grid, "InterPSS Grid Aclf Calculation", simuCtx.getLoadflowAlgorithm())
                  .executeSingleJobTask(this.xmlGridOpt.getTimeout());
          String str = result.getSerializedAclfNet();
          AclfNetwork adjNet = (AclfNetwork) SerializeEMFObjectUtil.loadModel(str);
          adjNet.rebuildLookupTable();
          simuCtx.setAclfNet(adjNet);
          converge = adjNet.isLfConverged();
          if (this.xmlCaseData.getAclfAlgorithm().isDisplaySummary()) {
            IOutputTextDialog dialog =
                UISpringFactory.getOutputTextDialog(
                    "Loadflow Analysis Run by Remote " + this.xmlGridOpt.getRemoteNodeName());
            dialog.display(adjNet);
          }
        } catch (GridException e) {
          EditorPluginSpringFactory.getEditorDialogUtil()
              .showErrMsgDialog("Grid Aclf Error", e.toString());
          return false;
        }
      }
      simuCtx.setAclfNet(aclfNet);
    } else {
      if (this.contingencyAnalysis) {
        IpssLogger.getLogger().info("Run contingency analysis");

        ContingencyAnalysis analysis =
            SimuObjectFactory.createContingencyAnalysis(
                SimuCtxType.ACLF_NETWORK, simuCtx.getAclfNet());
        analysis.setLimitRunCase(this.xmlContingency.isLimitRunCases());
        if (analysis.isLimitRunCase()) analysis.setMaxRunCase(this.xmlContingency.getMaxRunCases());

        LoadflowAlgorithm algo = simuCtx.getLoadflowAlgorithm();
        EditorPluginSpringFactory.getXml2LfAlgorithmMapper()
            .map2Model(this.xmlContingency.getDefaultAclfAlgorithm(), algo);
        analysis.analysis(algo, ContingencyAnalysisType.N1);

        IOutputTextDialog dialog = UISpringFactory.getOutputTextDialog("Contingency Analysis Info");
        dialog.display(ContingencyOutFunc.securityMargin(analysis));
      } else converge = runLoadflow(simuCtx.getAclfNet(), simuCtx);
    }
    return converge;
  }