public void process(WatchedEvent event) {
      LOGGER.debug(
          "Watcher fired on path: "
              + event.getPath()
              + " state: "
              + event.getState()
              + " type "
              + event.getType());

      latchIfNoChange.countDown();

      // ignore any children except valid children for a queue
      if (keyHandler.hasValidName(ZkUtils.getPathEnd(event.getPath()))) {

        if (highestPriorityChanged == null) {
          highestPriorityChanged = keyHandler.getPriority(event.getPath());
        } else {
          synchronized (highestPriorityChanged) {
            PRIORITY changedPriority = keyHandler.getPriority(event.getPath());
            if (changedPriority != null && changedPriority.compareTo(highestPriorityChanged) < 0) {
              highestPriorityChanged = changedPriority;
            }
          }
        }
      }
    }
 @Override
 public void process(WatchedEvent event) {
   if (event.getType() == EventType.NodeDataChanged) {
     String keyPath = event.getPath();
     String key = keyPath.substring(keyPath.lastIndexOf("/") + 1);
     String value = "";
     try {
       value = pigeonCache.getServiceValue(key);
     } catch (LionException e) {
       logger.error(e.getMessage(), e);
     }
     logger.info("Pigeon Cache Key Change! Key: " + key + " Value: " + value);
     if (pigeonCache.getService().containsKey(key)) {
       List<String[]> hostDetail = pigeonCache.getServiceIpPortWeight(value);
       pigeonCache
           .getServiceChange()
           .onServiceHostChange(this.replaceServiceName(key), hostDetail);
     }
   } else {
     // 重新监听节点信息
     logger.info("Delete The Node " + event.getType() + " " + event.getPath());
     String key = event.getPath().substring(event.getPath().lastIndexOf("/") + 1);
     try {
       pigeonCache.getServiceValue(key);
     } catch (LionException e) {
       logger.error(e.getMessage(), e);
     }
   }
 }
Example #3
0
  @Override
  public void process(WatchedEvent event) {
    if (LOG.isDebugEnabled()) {
      LOG.debug(
          "Received Zookeeper Event, "
              + "type="
              + event.getType()
              + ", "
              + "state="
              + event.getState()
              + ", "
              + "path="
              + event.getPath());
    }

    switch (event.getType()) {
      case None:
        {
          if (event.getState() == KeeperState.SyncConnected) {
            latch.countDown();
          }
        }

      case NodeCreated:
        {
          for (ZkListener listener : this.listeners) {
            listener.nodeCreated(event.getPath());
          }
          break;
        }

      case NodeDeleted:
        {
          for (ZkListener listener : this.listeners) {
            listener.nodeDeleted(event.getPath());
          }
          break;
        }

      case NodeDataChanged:
        {
          for (ZkListener listener : this.listeners) {
            listener.nodeDataChanged(event.getPath());
          }
          break;
        }

      case NodeChildrenChanged:
        {
          for (ZkListener listener : this.listeners) {
            listener.nodeChildrenChanged(event.getPath());
          }
          break;
        }
    }
  }
Example #4
0
 public void process(WatchedEvent event) {
   String path = event.getPath();
   if (event.getType() == Event.EventType.None) {
     // We are are being told that the state of the
     // connection has changed
     switch (event.getState()) {
       case SyncConnected:
         // In this particular example we don't need to do anything
         // here - watches are automatically re-registered with
         // server and any watches triggered while the client was
         // disconnected will be delivered (in order of course)
         break;
       case Expired:
         // It's all over
         dead = true;
         listener.closing(KeeperException.Code.SessionExpired);
         break;
     }
   } else {
     if (path != null && path.equals(znode)) {
       // Something has changed on the node, let's find out
       zk.exists(znode, true, this, null);
     }
   }
   if (chainedWatcher != null) {
     chainedWatcher.process(event);
   }
 }
Example #5
0
 public void process(WatchedEvent event) {
   LOG.info("Event:" + event.getState() + " " + event.getType() + " " + event.getPath());
   if (event.getState() == KeeperState.SyncConnected
       && startSignal != null
       && startSignal.getCount() > 0) {
     startSignal.countDown();
   }
 }
 @Override
 public void process(WatchedEvent watchedEvent) {
   Event.EventType type = watchedEvent.getType();
   LOG.info("Got event " + type + " with path " + watchedEvent.getPath());
   if (type.equals(Event.EventType.NodeDataChanged)) {
     readReplicationStateZnode();
   }
 }
Example #7
0
 @Override
 public void process(WatchedEvent event) {
   if (event.getPath().equals(root + "/start") && event.getType() == Event.EventType.NodeCreated) {
     System.out.println("得到通知");
     super.process(event);
     doAction();
   }
 }
 @Override
 public void process(WatchedEvent event) {
   // Look for a NodeCreate event on /demo
   if (event.getType() == Watcher.Event.EventType.NodeCreated) {
     if (event.getPath().equals(NODE)) {
       _sawDemo = true;
     }
   }
 }
 @Override
 public void process(WatchedEvent event) {
   LOG.debug("Received watched event {} from zookeeper based ledger manager.", event);
   if (Event.EventType.None == event.getType()) {
     if (Event.KeeperState.Expired == event.getState()) {
       LOG.info("ZooKeeper client expired on ledger manager.");
       Set<Long> keySet = new HashSet<Long>(listeners.keySet());
       for (Long lid : keySet) {
         scheduler.submit(new ReadLedgerMetadataTask(lid));
         LOG.info("Re-read ledger metadata for {} after zookeeper session expired.", lid);
       }
     }
     return;
   }
   String path = event.getPath();
   if (null == path) {
     return;
   }
   final long ledgerId;
   try {
     ledgerId = getLedgerId(event.getPath());
   } catch (IOException ioe) {
     LOG.info("Received invalid ledger path {} : ", event.getPath(), ioe);
     return;
   }
   switch (event.getType()) {
     case NodeDeleted:
       Set<LedgerMetadataListener> listenerSet = listeners.remove(ledgerId);
       if (null != listenerSet) {
         LOG.debug("Removed ledger metadata listeners on ledger {} : {}", ledgerId, listenerSet);
       } else {
         LOG.debug(
             "No ledger metadata listeners to remove from ledger {} after it's deleted.",
             ledgerId);
       }
       break;
     case NodeDataChanged:
       new ReadLedgerMetadataTask(ledgerId).run();
       break;
     default:
       LOG.debug("Received event {} on {}.", event.getType(), event.getPath());
       break;
   }
 }
 public void process(WatchedEvent event) {
   if (event.getType() == Event.EventType.NodeChildrenChanged) {
     LOG.debug("Running children changed [" + event.getPath() + "]");
     try {
       getZkRunning();
     } catch (Exception e) {
       e.printStackTrace();
       LOG.error(e);
     }
   } else if (event.getType() == Event.EventType.NodeDeleted) {
     String znodePath = event.getPath();
     LOG.debug("Running znode deleted [" + znodePath + "]");
     try {
       restartServer(znodePath);
     } catch (Exception e) {
       e.printStackTrace();
       LOG.error(e);
     }
   }
 }
Example #11
0
 @Override
 public void process(WatchedEvent event) {
   log.debug("event " + event.getPath() + " " + event.getType() + " " + event.getState());
   if (event.getState() == KeeperState.Expired) {
     log.warn("Trace server lost zookeeper registration at " + event.getPath());
     server.stop();
   } else if (event.getType() == EventType.NodeDeleted) {
     log.warn("Trace server zookeeper entry lost " + event.getPath());
     server.stop();
   }
   if (event.getPath() != null) {
     try {
       if (ZooReaderWriter.getInstance().exists(event.getPath(), this)) return;
     } catch (Exception ex) {
       log.error(ex, ex);
     }
     log.warn("Trace server unable to reset watch on zookeeper registration");
     server.stop();
   }
 }
    @Override
    public void process(WatchedEvent event) {
      boolean needsRefresh = false;
      if (event.getType() == Event.EventType.None
          && event.getState() == Event.KeeperState.SyncConnected) {
        needsRefresh = true;
      } else if (NodeChildrenChanged.equals(event.getType())
          && event.getPath().equals(REPOSITORY_COLLECTION_PATH)) {
        needsRefresh = true;
      } else if (NodeDataChanged.equals(event.getType())
          && event.getPath().startsWith(REPOSITORY_COLLECTION_PATH_SLASH)) {
        needsRefresh = true;
      }

      if (needsRefresh) {
        try {
          refresh();
        } catch (Throwable t) {
          log.error("Repository Model: error handling event from ZooKeeper. Event: " + event, t);
        }
      }
    }
Example #13
0
  @Override
  public void process(WatchedEvent event) {
    if (!asnycConnection && event.getState() == Event.KeeperState.SyncConnected) {
      connectionLock.release(); // 连接成功
    } else if (event.getState() == Event.KeeperState.Disconnected) { // 连接断开
      log.warn("zookeeper 连接断开......");
    } else if (event.getState() == Event.KeeperState.Expired) { // 连接超时
      log.warn("zookeeper session timeout......");
      try {
        zkClient.reconnect();
        process.relisten();
        process.recreate();
      } catch (Exception e) {
        log.error("reconnection to zookeeper error.", e);
      }
    }

    if (event.getType() == Event.EventType.NodeChildrenChanged) { // 子节点变化
      process.clientNodeChanged(event.getPath());
    } else if (event.getType() == Event.EventType.NodeDataChanged) { // 节点数据变化
      process.nodeDataChanged(event.getPath());
    }
  }
Example #14
0
        public void process(WatchedEvent e) {
          log.info(e.getPath());
          // System.out.println(e.getPath() + " " + e.toString());

          if (e.getState() == Watcher.Event.KeeperState.Expired) {

            handleExpired();
          } else if (e.getState() == Watcher.Event.KeeperState.Disconnected) {
            log.warn("ZKDisconnected! {}", e.toString());
          } else if (e.getState() == Watcher.Event.KeeperState.SyncConnected) {
            log.warn("ZKSyncConnected! {}", e.toString());
            ZKClient.this.handleSynConnected();
          }
        }
 public synchronized void process(WatchedEvent event) {
   logger.info(getClass().getName() + event.getPath());
   logger.info(getClass().getName() + event.getType());
   synchronized (mutex) {
     switch (event.getState()) {
       case SyncConnected:
         mutex.notify();
     }
     switch (event.getType()) {
       case NodeCreated:
         mutex.notify();
         break;
     }
   }
 }
Example #16
0
 public void process(WatchedEvent event) {
   // lets either become the leader or watch the new/updated node
   LOG.debug(
       "Watcher fired on path: "
           + event.getPath()
           + " state: "
           + event.getState()
           + " type "
           + event.getType());
   try {
     lock();
   } catch (Exception e) {
     LOG.warn("Failed to acquire lock: " + e, e);
   }
 }
  /** Process the {@link WatchedEvent} for a node which represents an {@link AuthenticationKey} */
  void processChildNode(WatchedEvent event) throws KeeperException, InterruptedException {
    final String path = event.getPath();
    switch (event.getType()) {
      case NodeDeleted:
        // Key expired
        if (null == path) {
          log.error("Got null path for NodeDeleted event");
          return;
        }

        // Pull off the base ZK path and the '/' separator
        String childName = path.substring(baseNode.length() + 1);
        secretManager.removeKey(Integer.parseInt(childName));
        break;
      case None:
        // Not connected, don't care. We'll update when we're reconnected
        break;
      case NodeCreated:
        // New key created
        if (null == path) {
          log.error("Got null path for NodeCreated event");
          return;
        }
        // Get the data and reset the watcher
        AuthenticationKey key = deserializeKey(zk.getData(path, this, null));
        log.debug("Adding AuthenticationKey with keyId {}", key.getKeyId());
        secretManager.addKey(key);
        break;
      case NodeDataChanged:
        // Key changed, could happen on restart after not running Accumulo.
        if (null == path) {
          log.error("Got null path for NodeDataChanged event");
          return;
        }
        // Get the data and reset the watcher
        AuthenticationKey newKey = deserializeKey(zk.getData(path, this, null));
        // Will overwrite the old key if one exists
        secretManager.addKey(newKey);
        break;
      case NodeChildrenChanged:
        // no children for the children..
        log.warn("Unexpected NodeChildrenChanged event for authentication key node {}", path);
        break;
      default:
        log.warn("Unsupported event type: {}", event.getType());
        break;
    }
  }
  @Override
  public void process(WatchedEvent event) {
    if (EventType.None == event.getType()) {
      switch (event.getState()) {
        case Disconnected: // Intentional fall through of case
        case Expired: // ZooReader is handling the Expiration of the original ZooKeeper object for
                      // us
          log.debug("ZooKeeper connection disconnected, clearing secret manager");
          secretManager.removeAllKeys();
          break;
        case SyncConnected:
          log.debug("ZooKeeper reconnected, updating secret manager");
          try {
            updateAuthKeys();
          } catch (KeeperException | InterruptedException e) {
            log.error("Failed to update secret manager after ZooKeeper reconnect");
          }
          break;
        default:
          log.warn("Unhandled: " + event);
      }

      // Nothing more to do for EventType.None
      return;
    }

    String path = event.getPath();
    if (null == path) {
      return;
    }

    if (!path.startsWith(baseNode)) {
      log.info("Ignoring event for path: {}", path);
      return;
    }

    try {
      if (path.equals(baseNode)) {
        processBaseNode(event);
      } else {
        processChildNode(event);
      }
    } catch (KeeperException | InterruptedException e) {
      log.error("Failed to communicate with ZooKeeper", e);
    }
  }
Example #19
0
 @Override
 public void process(WatchedEvent event) {
   Event.EventType eventType = event.getType();
   // None events are ignored
   // If latchEventType is not null, only fire if the type matches
   LOG.info(
       "{} fired on path {} state {} latchEventType {}",
       eventType,
       event.getPath(),
       event.getState(),
       latchEventType);
   if (eventType != Event.EventType.None
       && (latchEventType == null || eventType == latchEventType)) {
     synchronized (lock) {
       this.event = event;
       lock.notifyAll();
     }
   }
 }
 @Override
 public void process(WatchedEvent event) {
   // session events are not change events, and do not remove the watcher
   if (Event.EventType.None.equals(event.getType())) {
     return;
   }
   // If latchEventType is not null, only fire if the type matches
   LOG.debug(
       "{} fired on path {} state {} latchEventType {}",
       event.getType(),
       event.getPath(),
       event.getState(),
       latchEventType);
   if (latchEventType == null || event.getType() == latchEventType) {
     synchronized (lock) {
       this.event = event;
       lock.notifyAll();
     }
   }
 }
Example #21
0
 @Override
 public void process(WatchedEvent event) {
   // TODO Auto-generated method stub
   System.out.println(event);
   if (event.getState().equals(KeeperState.SyncConnected)) {
     if (event.getType() == EventType.None && null == event.getPath()) {
       doSomething(zookeeper);
     } else {
       //				if(event.getType() == EventType.NodeChildrenChanged){
       //					try {
       //						List<String> subList = zookeeper.getChildren("/",
       // false);/*一个watch只能使用一次,如果想再次使用则需要再次注册*/
       //						System.out.println(subList);
       //					} catch (KeeperException e) {
       //						e.printStackTrace();
       //					} catch (InterruptedException e) {
       //						e.printStackTrace();
       //					}
       //				}
     }
   }
 }
 /**
  * Process the {@link WatchedEvent} for the base znode that the {@link AuthenticationKey}s are
  * stored in.
  */
 void processBaseNode(WatchedEvent event) throws KeeperException, InterruptedException {
   switch (event.getType()) {
     case NodeDeleted:
       // The parent node was deleted, no children are possible, remove all keys
       log.debug("Parent ZNode was deleted, removing all AuthenticationKeys");
       secretManager.removeAllKeys();
       break;
     case None:
       // Not connected, don't care
       break;
     case NodeCreated: // intentional fall-through to NodeChildrenChanged
     case NodeChildrenChanged:
       // Process each child, and reset the watcher on the parent node. We know that the node
       // exists
       updateAuthKeys(event.getPath());
       break;
     case NodeDataChanged:
       // The data on the parent changed. We aren't storing anything there so it's a noop
       break;
     default:
       log.warn("Unsupported event type: {}", event.getType());
       break;
   }
 }
Example #23
0
  private void enode_test_2() throws IOException, InterruptedException, KeeperException {
    checkRoot();
    String parentName = testDirOnZK;
    String nodeName = parentName + "/enode_abc";
    ZooKeeper zk = new ZooKeeper(hostPort, 10000, this);
    ZooKeeper zk_1 = new ZooKeeper(hostPort, 10000, this);

    Stat stat = zk_1.exists(parentName, false);
    if (stat == null) {
      try {
        zk.create(parentName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
      } catch (KeeperException ke) {
        fail("Creating node " + parentName + ke.getMessage());
      }
    }

    stat = zk_1.exists(nodeName, false);
    if (stat != null) {

      try {
        zk.delete(nodeName, -1);
      } catch (KeeperException ke) {
        int code = ke.getCode();
        boolean valid =
            code == KeeperException.Code.NoNode || code == KeeperException.Code.NotEmpty;
        if (!valid) {
          fail("Unexpected exception code for delete: " + ke.getMessage());
        }
      }
    }

    List<String> firstGen = zk_1.getChildren(parentName, true);

    try {
      zk.create(nodeName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
    } catch (KeeperException ke) {
      int code = ke.getCode();
      boolean valid = code == KeeperException.Code.NodeExists;
      if (!valid) {
        fail("Unexpected exception code for createin: " + ke.getMessage());
      }
    }

    Thread.sleep(5000);
    WatchedEvent event = events.poll(10, TimeUnit.SECONDS);
    if (event == null) {
      throw new IOException("No event was delivered promptly");
    }
    if (event.getType() != EventType.NodeChildrenChanged
        || !event.getPath().equalsIgnoreCase(parentName)) {
      fail("Unexpected event was delivered: " + event.toString());
    }

    stat = zk_1.exists(nodeName, false);
    if (stat == null) {
      fail("node " + nodeName + " should exist");
    }

    try {
      zk.delete(parentName, -1);
      fail("Should be impossible to delete a non-empty node " + parentName);
    } catch (KeeperException ke) {
      int code = ke.getCode();
      boolean valid = code == KeeperException.Code.NotEmpty;
      if (!valid) {
        fail("Unexpected exception code for delete: " + code);
      }
    }

    try {
      zk.create(nodeName + "/def", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
      fail("Should be impossible to create child off Ephemeral node " + nodeName);
    } catch (KeeperException ke) {
      int code = ke.getCode();
      boolean valid = code == KeeperException.Code.NoChildrenForEphemerals;
      if (!valid) {
        fail("Unexpected exception code for createin: " + code);
      }
    }

    try {
      List<String> children = zk.getChildren(nodeName, false);
      if (children.size() > 0) {
        fail("ephemeral node " + nodeName + " should not have children");
      }
    } catch (KeeperException ke) {
      int code = ke.getCode();
      boolean valid = code == KeeperException.Code.NoNode;
      if (!valid) {
        fail("Unexpected exception code for createin: " + code);
      }
    }
    firstGen = zk_1.getChildren(parentName, true);
    stat = zk_1.exists(nodeName, true);
    if (stat == null) {
      fail("node " + nodeName + " should exist");
    }
    System.out.println("session id of zk: " + zk.getSessionId());
    System.out.println("session id of zk_1: " + zk_1.getSessionId());
    zk.close();

    stat = zk_1.exists("nosuchnode", false);

    event = this.getEvent(10);
    if (event == null) {
      throw new AssertionFailedError("First event was not delivered promptly");
    }
    if (!((event.getType() == EventType.NodeChildrenChanged
            && event.getPath().equalsIgnoreCase(parentName))
        || (event.getType() == EventType.NodeDeleted
            && event.getPath().equalsIgnoreCase(nodeName)))) {
      System.out.print(
          parentName
              + " "
              + EventType.NodeChildrenChanged
              + " "
              + nodeName
              + " "
              + EventType.NodeDeleted);
      fail("Unexpected first event was delivered: " + event.toString());
    }

    event = this.getEvent(10);

    if (event == null) {
      throw new AssertionFailedError("Second event was not delivered promptly");
    }
    if (!((event.getType() == EventType.NodeChildrenChanged
            && event.getPath().equalsIgnoreCase(parentName))
        || (event.getType() == EventType.NodeDeleted
            && event.getPath().equalsIgnoreCase(nodeName)))) {
      System.out.print(
          parentName
              + " "
              + EventType.NodeChildrenChanged
              + " "
              + nodeName
              + " "
              + EventType.NodeDeleted);
      fail("Unexpected second event was delivered: " + event.toString());
    }

    firstGen = zk_1.getChildren(parentName, false);
    stat = zk_1.exists(nodeName, false);
    if (stat != null) {
      fail("node " + nodeName + " should have been deleted");
    }
    if (firstGen.contains(nodeName)) {
      fail("node " + nodeName + " should not be a children");
    }
    deleteZKDir(zk_1, nodeName);
    zk_1.close();
  }
  @Override
  public void process(WatchedEvent event) {
    log.info("已经触发了" + event.getType() + "事件!");
    String event_path = event.getPath();
    ZooKeeper zookeeper = zkmanager.getZookeeper();
    if (event.getType() == Event.EventType.NodeDataChanged) {
      try {
        if (!this.phpClientList.isEmpty()) {
          for (PhpClientDO client : this.phpClientList) {
            String baseConfigPath = client.getChildPath();
            if (baseConfigPath.equals(event_path)) {
              String app_db_name_path = client.getNodePath();
              String db_config_name = client.getDbConfigName();
              List<String> list = new ArrayList<String>();
              byte[] bytes = new byte[0];
              if (zookeeper.exists(baseConfigPath, false) != null) {
                bytes = zookeeper.getData(baseConfigPath, true, null);
              }
              if (zookeeper.exists(app_db_name_path, false) != null) {
                list = zookeeper.getChildren(app_db_name_path, true);
              }
              log.info("NodeDataChanged path is : " + event_path);
              String str = FileUtil.listToString(list, bytes, db_config_name);
              FileUtil.writeFile(client.getGenerateFilePath(), "<?php\n" + str);
            }
          }
        }
      } catch (KeeperException e) {
        log.error(e.getMessage());
      } catch (InterruptedException e) {
        log.error(e.getMessage());
      }
    }
    if (event.getType() == Event.EventType.NodeChildrenChanged) {
      try {
        if (!this.phpClientList.isEmpty()) {
          for (PhpClientDO client : this.phpClientList) {
            String app_db_name_path = client.getNodePath();
            if (app_db_name_path.equals(event_path)) {
              String baseConfigPath = client.getChildPath();
              String db_config_name = client.getDbConfigName();
              List<String> list = new ArrayList<String>();
              byte[] bytes = new byte[0];
              if (zookeeper.exists(baseConfigPath, false) != null) {
                bytes = zookeeper.getData(baseConfigPath, true, null);
              }
              if (zookeeper.exists(app_db_name_path, false) != null) {
                list = zookeeper.getChildren(app_db_name_path, true);
              }
              log.info("NodeChildrenChanged path is : " + event_path);
              String str = FileUtil.listToString(list, bytes, db_config_name);
              FileUtil.writeFile(client.getGenerateFilePath(), "<?php\n" + str);
            }
          }
        }
      } catch (KeeperException e) {
        log.error(e.getMessage());
      } catch (InterruptedException e) {
        log.error(e.getMessage());
      }
    } else if (event.getState() == KeeperState.SyncConnected) {
      log.info("收到ZK连接成功事件!");
    } else if (event.getState() == KeeperState.Expired) {
      log.error("会话超时,等待重新建立ZK连接...");
      try {
        zkmanager.reConnection();

        if (!this.phpClientList.isEmpty()) {
          for (PhpClientDO client : this.phpClientList) {
            if (zookeeper.exists(client.getNodePath(), false) != null) {
              this.zkmanager.getZookeeper().getChildren(client.getNodePath(), true);
            }
            if (zookeeper.exists(client.getChildPath(), false) != null) {
              this.zkmanager.getZookeeper().getData(client.getChildPath(), true, null);
            }
          }
        }
      } catch (Exception e) {
        log.error(e.getMessage());
      }
    }
  }
Example #25
0
    @Override
    public void process(WatchedEvent event) {
      Event.EventType type = event.getType();
      String path = event.getPath();
      System.out.println("Path: " + path + ", Event type:" + type);
      // set watch on workers
      setWatchWorkers();

      switch (type) {
        case NodeDeleted:
          try {
            // Check if node deleted is from /tracker
            if (path.contains(ZK_TRACKER)) {
              String node = zooKeeper.getChildren(ZK_TRACKER, false).get(0);
              // If primary is dead then I become primary
              if (!zooKeeper
                  .getData(Joiner.on("/").join(ZK_TRACKER, node), false, null)
                  .equals("primary")) {
                zooKeeper.setData(Joiner.on("/").join(ZK_TRACKER, node), "primary".getBytes(), -1);
                zooKeeper.setData(
                    ZK_TRACKER,
                    Joiner.on(":")
                        .join(InetAddress.getLocalHost().getHostAddress(), myPort)
                        .getBytes(),
                    -1);
              }
            }
            if (path.contains(ZK_WORKER)) {
              List<String> currJobs = zooKeeper.getChildren(ZK_JOBS, false);
              // /worker/<id>
              String workerId = path.split("/")[2];
              System.out.println("Dead worker id " + workerId);
              for (String job : currJobs) {

                while (true) {
                  String currData =
                      new String(zooKeeper.getData(Joiner.on("/").join(ZK_JOBS, job), false, null));
                  int currVersion =
                      zooKeeper.exists(Joiner.on("/").join(ZK_JOBS, job), false).getVersion();
                  System.out.println("Version curr" + currVersion);

                  // de-serialize
                  WorkerInfo workerInfo = gson.fromJson(currData, WorkerInfo.class);
                  HashMap<String, List<Integer>> newMap = workerInfo.getWorkerInfo();
                  List<Integer> deadWorkerList = newMap.get(workerId);
                  System.out.println("dead worker List" + deadWorkerList);
                  if (deadWorkerList == null) {
                    break;
                  }
                  // remove it from current info as its dead
                  newMap.remove(workerId);

                  List<String> currWorker = zooKeeper.getChildren(ZK_WORKER, false);

                  // Pick a worker ramdomly and assign the task to it by adding to its current task
                  // list
                  int rand = randGen.nextInt(currWorker.size());
                  List<Integer> newWorkerList = newMap.get(currWorker.get(rand));
                  if (newWorkerList == null) newWorkerList = deadWorkerList;
                  else newWorkerList.addAll(deadWorkerList);
                  newMap.put(currWorker.get(rand), newWorkerList);

                  WorkerInfo newWorkerInfo = new WorkerInfo(newMap, job);

                  // serialize
                  String newData = gson.toJson(newWorkerInfo);

                  // setdata on the znode /jobs/<hash>

                  try {
                    if (zooKeeper.setData(
                            Joiner.on("/").join(ZK_JOBS, job), newData.getBytes(), currVersion)
                        != null) {
                      System.out.println(
                          "Update data for " + workerId + " on to " + currWorker.get(rand));
                      break;
                    }
                  } catch (KeeperException e) {
                    // Ignore
                  }
                }
              }
            }

          } catch (Exception e) {
            e.printStackTrace();
          }
          break;
      }
    }
Example #26
0
 @Override
 public void process(WatchedEvent event) throws Exception {
   if (event.getType() == Watcher.Event.EventType.NodeDataChanged) {
     checkRevocableWatcher(event.getPath());
   }
 }