コード例 #1
0
  private void handleStateChange(ConnectionState newState) {
    switch (newState) {
      default:
        {
          // NOP
          break;
        }

      case RECONNECTED:
        {
          try {
            reset();
          } catch (Exception e) {
            log.error("Could not reset leader latch", e);
            setLeadership(false);
          }
          break;
        }

      case SUSPENDED:
      case LOST:
        {
          setLeadership(false);
          break;
        }
    }
  }
コード例 #2
0
  /**
   * Add this instance to the leadership election and attempt to acquire leadership.
   *
   * @throws Exception errors
   */
  public void start() throws Exception {
    Preconditions.checkState(
        state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once");

    client.getConnectionStateListenable().addListener(listener);
    reset();
  }
コード例 #3
0
  private void checkLeadership(List<String> children) throws Exception {
    final String localOurPath = ourPath.get();
    List<String> sortedChildren = LockInternals.getSortedChildren(LOCK_NAME, sorter, children);
    int ourIndex =
        (localOurPath != null) ? sortedChildren.indexOf(ZKPaths.getNodeFromPath(localOurPath)) : -1;
    if (ourIndex < 0) {
      log.error("Can't find our node. Resetting. Index: " + ourIndex);
      reset();
    } else if (ourIndex == 0) {
      setLeadership(true);
    } else {
      String watchPath = sortedChildren.get(ourIndex - 1);
      Watcher watcher =
          new Watcher() {
            @Override
            public void process(WatchedEvent event) {
              if ((state.get() == State.STARTED)
                  && (event.getType() == Event.EventType.NodeDeleted)
                  && (localOurPath != null)) {
                try {
                  getChildren();
                } catch (Exception ex) {
                  log.error("An error occurred checking the leadership.", ex);
                }
              }
            }
          };

      BackgroundCallback callback =
          new BackgroundCallback() {
            @Override
            public void processResult(CuratorFramework client, CuratorEvent event)
                throws Exception {
              if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) {
                // previous node is gone - reset
                reset();
              }
            }
          };
      client
          .checkExists()
          .usingWatcher(watcher)
          .inBackground(callback)
          .forPath(ZKPaths.makePath(latchPath, watchPath));
    }
  }