Beispiel #1
0
  public void statusReport(PrintWriter writer) {

    // Game has ended and graph shut down
    if (gameOverRequest != null) {
      if (gameStartRequest != null) {
        writer.print("[GAME START]: " + gameStartRequest + "\n");
      }

      for (GameRequest request : turnRequests) {
        writer.print("[TURN " + request.getCurrentTurn() + "]: " + request.getStates() + "\n");
      }
      writer.print("[GAME OVER]: " + gameOverRequest.getStates() + "\n");
    } else {
      for (Node node : gameState.getNodesSortedById()) {
        writer.print("Node " + node.getNodeId() + "\n");
        writer.print("  type: " + node.getNodeType() + "\n");
        writer.print("  vp worth: " + node.getVictoryPointWorth() + "\n");
        writer.print("  solders per turn: " + node.getSoldiersGrantedPerTurn() + "\n");
        writer.print("  owner: " + node.getOwner() + "\n");
        writer.print("  soldiers present: " + node.getNumberOfSolders() + "\n");
        writer.print("  inbound neighbouring nodes:  ");
        for (Node neighbour : node.getInboundNeighbours()) {
          writer.print(neighbour.getNodeId() + " ");
        }
        writer.print("\n");
        writer.print("  outbound neighbouring nodes: ");
        for (Node neighbour : node.getOutboundNeighbours()) {
          writer.print(neighbour.getNodeId() + " ");
        }
        writer.print("\n");
      }
    }
  }
    public void map(
        LongWritable lineid, Text nodetxt, OutputCollector<Text, Text> output, Reporter reporter)
        throws IOException {
      Node node = new Node();
      node.fromNodeMsg(nodetxt.toString());

      for (String adj : Node.dirs) {
        node.setCanCompress(adj, false);

        TailInfo next = node.gettail(adj);

        if (next != null /*&& node.getBlackEdges() == null*/) {
          if (next.id.equals(node.getNodeId())) {
            continue;
          }

          reporter.incrCounter("Brush", "remotemark", 1);

          output.collect(
              new Text(next.id), new Text(Node.HASUNIQUEP + "\t" + node.getNodeId() + "\t" + adj));
        }
      }

      output.collect(new Text(node.getNodeId()), new Text(node.toNodeMsg()));

      reporter.incrCounter("Brush", "nodes", 1);
    }
Beispiel #3
0
    public void map(
        LongWritable lineid, Text nodetxt, OutputCollector<Text, Text> output, Reporter reporter)
        throws IOException {
      Node node = new Node();
      node.fromNodeMsg(nodetxt.toString());

      List<String> bubbles = node.getBubbles();
      if (bubbles != null) {
        for (String bubble : bubbles) {
          String[] vals = bubble.split("\\|");
          String minor = vals[0];
          String minord = vals[1];
          String dead = vals[2];
          String newd = vals[3];
          String newid = vals[4];
          String extracov = vals[5];

          output.collect(
              new Text(minor),
              new Text(
                  Node.KILLLINKMSG + "\t" + minord + "\t" + dead + "\t" + newd + "\t" + newid));

          output.collect(new Text(dead), new Text(Node.KILLMSG));
          output.collect(new Text(newid), new Text(Node.EXTRACOV + "\t" + extracov));

          reporter.incrCounter("Contrail", "bubblespopped", 1);
        }

        node.clearBubbles();
      }

      output.collect(new Text(node.getNodeId()), new Text(node.toNodeMsg()));
      reporter.incrCounter("Contrail", "nodes", 1);
    }
Beispiel #4
0
  public boolean handleApplicationUpdateRequest(byte[] data) {
    boolean messageRemoved = false;
    byte nodeId = data[3];
    Node node = getNode(nodeId);
    Node tnode = null;

    if (node != null && !node.isNodeAlive()) {
      node.setNodeAlive(true);
    }
    switch (data[2]) {
      case Defs.UPDATE_STATE_SUC_ID:
        logs.add(String.format("Update SUC Id node %d", SafeCast.toInt(nodeId)));
        sucNodeId = nodeId;
        break;
      case Defs.UPDATE_STATE_DELETE_DONE:
        logs.add(String.format("Remove node %d", SafeCast.toInt(nodeId)));
        removeNode(nodeId);
        break;
      case Defs.UPDATE_STATE_NEW_ID_ASSIGNED:
        logs.add(String.format("Add node %d", SafeCast.toInt(nodeId)));
        addNode(nodeId);
        break;
      case Defs.UPDATE_STATE_ROUTING_PENDING:
        logs.add(String.format("Routing pending node %d", nodeId));
        break;
      case Defs.UPDATE_STATE_NODE_INFO_REQ_FAILED:
        if (queue.getCurrentMsg() != null) {
          logs.add(
              String.format(
                  "Update failed node %d", SafeCast.nodeIdFromMsg(queue.getCurrentMsg())));
          tnode = getNode(SafeCast.nodeIdFromMsg(queue.getCurrentMsg()));
          if (tnode != null) {
            tnode.queryStageRetry(QueryStage.NodeInfo, (byte) 2);
            if (moveMsgToWakeUpQueue(tnode.getNodeId(), true)) {
              messageRemoved = true;
            }
          }
        }
        break;
      case Defs.UPDATE_STATE_NODE_INFO_REQ_DONE:
        logs.add(String.format("Update done node %d", nodeId));
        break;
      case Defs.UPDATE_STATE_NODE_INFO_RECEIVED:
        logs.add(String.format("Update info receive node %d", nodeId));
        if (node != null) {
          node.updateNodeInfo(
              Arrays.copyOfRange(data, 8, data.length), (byte) ((SafeCast.toInt(data[4]) - 3)));
        }
        break;
    }

    if (messageRemoved) {
      queue.removeExpectedAndACK();
    }
    return messageRemoved;
  }
    public void reduce(
        Text key, Iterator<Text> iter, OutputCollector<Text, Text> output, Reporter reporter)
        throws IOException {
      Node node = new Node(key.toString());
      Set<String> f_unique = new HashSet<String>();
      Set<String> r_unique = new HashSet<String>();

      int sawnode = 0;

      while (iter.hasNext()) {
        String msg = iter.next().toString();

        // System.err.println(key.toString() + "\t" + msg);

        String[] vals = msg.split("\t");

        if (vals[0].equals(Node.NODEMSG)) {
          node.parseNodeMsg(vals, 0);
          sawnode++;
        } else if (vals[0].equals(Node.HASUNIQUEP)) {
          if (vals[2].equals("f")) {
            f_unique.add(vals[1]);
          } else if (vals[2].equals("r")) {
            r_unique.add(vals[1]);
          }
        } else {
          throw new IOException("Unknown msgtype: " + msg);
        }
      }

      if (sawnode != 1) {
        throw new IOException(
            "ERROR: Didn't see exactly 1 nodemsg (" + sawnode + ") for " + key.toString());
      }

      for (String adj : Node.dirs) {
        TailInfo next = node.gettail(adj);

        if (next != null) {
          if ((next.dir.equals("f") && r_unique.contains(next.id))
              || (next.dir.equals("r") && f_unique.contains(next.id))) {
            // for path compress
            if (node.getBlackEdges() == null) {
              node.setCanCompress(adj, true);
            }
            reporter.incrCounter("Brush", "compressible", 1);
          }
        }
      }
      // System.err.println(node.getNodeId() + " " + node.toNodeMsg() );
      output.collect(new Text(node.getNodeId()), new Text(node.toNodeMsg()));
    }
Beispiel #6
0
  public void handleGetRoutingInfoResponse(byte[] data) {
    Node node = getNode(SafeCast.nodeIdFromMsg(queue.getCurrentMsg()));
    if (node != null) {
      node.setNeighbors(Arrays.copyOfRange(data, 2, 29));
      logs.add(
          String.format(
              "FUNC_ID_ZW_GET_ROUTING_INFO -- Neighbors of node %d are:", node.getNodeId()));
      boolean neighbors = false;
      for (int i = 0; i < 29; i++) {
        for (int j = 0; j < 8; j++) {
          if ((data[2 + i] & (0x01 << j)) != 0) {
            logs.add(String.format("--- Node %d", (i << 3) + j + 1));
            neighbors = true;
          }
        }
      }

      if (!neighbors) {
        logs.add(String.format("no neighbor on node %d", node.getNodeId()));
      }
    }
  }
Beispiel #7
0
  public void handleSerialAPIGetInitDataResponse(byte[] data) {
    if (!initAllNodes) {
      /* load jika ada settings */
    } else {
      /* driver & setting hilang */
    }

    logs.add("FUNC_ID_SERIAL_API_GET_INIT_DATA");
    primaryController.setInitVersion(data[2]);
    primaryController.setInitCapabilities(data[3]);

    if (data[4] == Defs.NUM_NODE_BITFIELD_BYTES) {
      for (int i = 0; i < Defs.NUM_NODE_BITFIELD_BYTES; ++i) {
        for (int j = 0; j < 8; ++j) {
          byte nodeId = (byte) ((i * 8) + j + 1);
          if ((data[i + 5] & (0x01 << j)) != 0) {
            Node node = getNode(nodeId);
            if (node != null) {
              if (node.getNodeId() == primaryController.getNodeId()) {
                node.setQueryStage(QueryStage.ProtocolInfo);
              }
              if (!initAllNodes) {
                node.setQueryStage(QueryStage.Probe1);
              }
            } else {
              addNode(nodeId);
            }
          } else if (getNode(nodeId) != null) {
            removeNode(nodeId);
          }
        }
      }
    }

    initAllNodes = true;
  }
Beispiel #8
0
  /**
   * Compress this BIN by removing any entries that are deleted. Deleted entries are those that have
   * LN's marked deleted or if the knownDeleted flag is set. Caller is responsible for latching and
   * unlatching this node.
   *
   * @param binRef is used to determine the set of keys to be checked for deletedness, or is null to
   *     check all keys.
   * @param canFetch if false, don't fetch any non-resident children. We don't want some callers of
   *     compress, such as the evictor, to fault in other nodes.
   * @return true if we had to requeue the entry because we were unable to get locks, false if all
   *     entries were processed and therefore any remaining deleted keys in the BINReference must
   *     now be in some other BIN because of a split.
   */
  @Override
  public boolean compress(
      BINReference binRef, boolean canFetch, LocalUtilizationTracker localTracker)
      throws DatabaseException {

    boolean ret = false;
    boolean setNewIdKey = false;
    boolean anyLocksDenied = false;
    DatabaseImpl db = getDatabase();
    EnvironmentImpl envImpl = db.getDbEnvironment();
    BasicLocker lockingTxn = BasicLocker.createBasicLocker(envImpl);

    try {
      for (int i = 0; i < getNEntries(); i++) {

        /*
         * We have to be able to lock the LN before we can compress the
         * entry.  If we can't, then, skip over it.
         *
         * We must lock the LN even if isKnownDeleted is true, because
         * locks protect the aborts. (Aborts may execute multiple
         * operations, where each operation latches and unlatches. It's
         * the LN lock that protects the integrity of the whole
         * multi-step process.)
         *
         * For example, during abort, there may be cases where we have
         * deleted and then added an LN during the same txn.  This
         * means that to undo/abort it, we first delete the LN (leaving
         * knownDeleted set), and then add it back into the tree.  We
         * want to make sure the entry is in the BIN when we do the
         * insert back in.
         */
        boolean deleteEntry = false;
        Node n = null;

        if (binRef == null
            || isEntryPendingDeleted(i)
            || isEntryKnownDeleted(i)
            || binRef.hasDeletedKey(new Key(getKey(i)))) {

          if (canFetch) {
            if (db.isDeferredWriteMode() && getLsn(i) == DbLsn.NULL_LSN) {
              /* Null LSNs are ok in DW. [#15588] */
              n = getTarget(i);
            } else {
              n = fetchTarget(i);
            }
          } else {
            n = getTarget(i);
            if (n == null) {
              /* Punt, we don't know the state of this child. */
              continue;
            }
          }

          if (n == null) {
            /* Cleaner deleted the log file.  Compress this LN. */
            deleteEntry = true;
          } else if (isEntryKnownDeleted(i)) {
            LockResult lockRet = lockingTxn.nonBlockingLock(n.getNodeId(), LockType.READ, db);
            if (lockRet.getLockGrant() == LockGrantType.DENIED) {
              anyLocksDenied = true;
              continue;
            }

            deleteEntry = true;
          } else {
            if (!n.containsDuplicates()) {
              LN ln = (LN) n;
              LockResult lockRet = lockingTxn.nonBlockingLock(ln.getNodeId(), LockType.READ, db);
              if (lockRet.getLockGrant() == LockGrantType.DENIED) {
                anyLocksDenied = true;
                continue;
              }

              if (ln.isDeleted()) {
                deleteEntry = true;
              }
            }
          }

          /* Remove key from BINReference in case we requeue it. */
          if (binRef != null) {
            binRef.removeDeletedKey(new Key(getKey(i)));
          }
        }

        /* At this point, we know we can delete. */
        if (deleteEntry) {
          boolean entryIsIdentifierKey =
              Key.compareKeys(getKey(i), getIdentifierKey(), getKeyComparator()) == 0;
          if (entryIsIdentifierKey) {

            /*
             * We're about to remove the entry with the idKey so
             * the node will need a new idkey.
             */
            setNewIdKey = true;
          }

          /*
           * When deleting a deferred-write LN entry, we count the
           * last logged LSN as obsolete.
           */
          if (localTracker != null && db.isDeferredWriteMode() && n instanceof LN) {
            LN ln = (LN) n;
            long lsn = getLsn(i);
            if (ln.isDirty() && lsn != DbLsn.NULL_LSN) {
              localTracker.countObsoleteNode(lsn, ln.getLogType(), ln.getLastLoggedSize(), db);
            }
          }

          boolean deleteSuccess = deleteEntry(i, true);
          assert deleteSuccess;

          /*
           * Since we're deleting the current entry, bump the current
           * index back down one.
           */
          i--;
        }
      }
    } finally {
      if (lockingTxn != null) {
        lockingTxn.operationEnd();
      }
    }

    if (anyLocksDenied && binRef != null) {
      db.getDbEnvironment().addToCompressorQueue(binRef, false);
      ret = true;
    }

    if (getNEntries() != 0 && setNewIdKey) {
      setIdentifierKey(getKey(0));
    }

    /* This BIN is empty and expendable. */
    if (getNEntries() == 0) {
      setGeneration(0);
    }

    return ret;
  }
Beispiel #9
0
  /*
   * If this search can go further, return the child. If it can't, and you
   * are a possible new parent to this child, return this IN. If the search
   * can't go further and this IN can't be a parent to this child, return
   * null.
   */
  @Override
  protected void descendOnParentSearch(
      SearchResult result,
      boolean targetContainsDuplicates,
      boolean targetIsRoot,
      long targetNodeId,
      Node child,
      boolean requireExactMatch)
      throws DatabaseException {

    if (child.canBeAncestor(targetContainsDuplicates)) {
      if (targetContainsDuplicates && targetIsRoot) {

        /*
         * Don't go further -- the target is a root of a dup tree, so
         * this BIN will have to be the parent.
         */
        long childNid = child.getNodeId();
        ((IN) child).releaseLatch();

        result.keepSearching = false; // stop searching

        if (childNid == targetNodeId) { // set if exact find
          result.exactParentFound = true;
        } else {
          result.exactParentFound = false;
        }

        /*
         * Return a reference to this node unless we need an exact
         * match and this isn't exact.
         */
        if (requireExactMatch && !result.exactParentFound) {
          result.parent = null;
          releaseLatch();
        } else {
          result.parent = this;
        }

      } else {
        /*
         * Go further down into the dup tree.
         */
        releaseLatch();
        result.parent = (IN) child;
      }
    } else {

      /*
       * Our search ends, we didn't find it. If we need an exact match,
       * give up, if we only need a potential match, keep this node
       * latched and return it.
       */
      result.exactParentFound = false;
      result.keepSearching = false;
      if (!requireExactMatch && targetContainsDuplicates) {
        result.parent = this;
      } else {
        releaseLatch();
        result.parent = null;
      }
    }
  }
Beispiel #10
0
  public void handleRemoveNodeFromNetworkRequest(byte[] data) {
    ControllerCmd cci = queue.getCurrentControllerCmd();

    if (cci == null) {
      return;
    }

    ControllerState state = cci.getControllerState();
    switch (data[3]) {
      case Defs.REMOVE_NODE_STATUS_LEARN_READY:
        logs.add("REMOVE_NODE_STATUS_LEARN_READY");
        state = ControllerState.Waiting;
        cci.setControllerCommandNode((byte) 0);
        if (cci != null && cci.getControllerCallback() != null) {
          cci.getControllerCallback().onAction(state, null, null);
        }
        break;
      case Defs.REMOVE_NODE_STATUS_NODE_FOUND:
        logs.add("REMOVE_NODE_STATUS_NODE_FOUND");
        state = ControllerState.InProgress;
        if (cci != null && cci.getControllerCallback() != null) {
          cci.getControllerCallback().onAction(state, null, null);
        }
        break;
      case Defs.REMOVE_NODE_STATUS_REMOVING_SLAVE:
        logs.add("REMOVE_NODE_STATUS_REMOVING_SLAVE --- Node: " + String.valueOf(data[4]));
        cci.setControllerCommandNode(data[4]);
        break;
      case Defs.REMOVE_NODE_STATUS_REMOVING_CONTROLLER:
        logs.add("REMOVE_NODE_STATUS_REMOVING_CONTROLLER --- Node: " + String.valueOf(data[4]));
        // mCurrentControllerCommand.mControllerCommandNode = data[4];
        cci.setControllerCommandNode(data[4]);
        if (data[4] == (byte) 0) {
          if (data[5] >= 3) {
            for (int i = 0; i < Defs.MAX_TOTAL_NODES; i++) {
              Node node = getNode((byte) i);
              synchronized (node) {
                if (node == null || primaryController == null) {
                  continue;
                }
                if (node.getNodeId() == primaryController.getNodeId()) {
                  continue;
                } // Ignore primary controller
                // See if we can match another way
                if (node.getBasicDeviceClassID() == data[6]
                    && node.getGenericDeviceClassID() == data[7]
                    && node.getSpecificDeviceClassID() == data[8]) {
                  if (cci.getControllerCommandNode() != 0) {
                    // TODO: Alternative controller found
                  } else {
                    cci.setControllerCommandNode(node.getNodeId());
                  }
                }
              }
            }
          } else {
            // TODO: error message not enough data
          }
        } else {
          cci.setControllerCommandNode(data[4]);
        }
        break;
      case Defs.REMOVE_NODE_STATUS_DONE:
        logs.add("REMOVE_NODE_STATUS_DONE");
        state = ControllerState.Completed;
        if (cci != null && cci.getControllerCallback() != null) {
          cci.getControllerCallback().onAction(state, null, null);
        }
        if (!cci.isControllerCommandDone()) {
          primaryController.updateControllerState(ControllerState.Completed);
          primaryController.addNodeStop(Defs.FUNC_ID_ZW_REMOVE_NODE_FROM_NETWORK);
          if (cci.getControllerCommandNode() == (byte) 0) {
            if (data[4] != (byte) 0) {
              cci.setControllerCommandNode(data[4]);
            }
          }

          if (cci.getControllerCommandNode() != (byte) 0
              && cci.getControllerCommandNode() != (byte) 0xFF) {
            removeNode(cci.getControllerCommandNode());
          }
        }
        return;
      case Defs.REMOVE_NODE_STATUS_FAILED:
        logs.add("REMOVE_NODE_STATUS_FAILED");
        primaryController.addNodeStop(Defs.FUNC_ID_ZW_REMOVE_NODE_FROM_NETWORK);
        state = ControllerState.Failed;
        if (cci != null && cci.getControllerCallback() != null) {
          cci.getControllerCallback().onAction(state, null, null);
        }
        break;
      default:
        logs.add("No Detected ...");
        break;
    }

    primaryController.updateControllerState(state);
  }