Java Code Examples for org.apache.curator.framework.recipes.leader.LeaderLatch#start()

The following examples show how to use org.apache.curator.framework.recipes.leader.LeaderLatch#start() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StartupRunner.java    From liteflow with Apache License 2.0 6 votes vote down vote up
@Override
public void run(String... strings) throws Exception {
    LeaderLatch leaderLatch = new LeaderLatch(client, path);
    leaderLatch.addListener(new LeaderLatchListener() {
        @Override
        public void isLeader() {
            MasterInfo.setIsMaster(true);
            refreshLeaderIp();
            scheduler.start();
        }

        @Override
        public void notLeader() {
            MasterInfo.setIsMaster(false);
            scheduler.stop();
            EventQueue.clear();
        }
    });
    leaderLatch.start();
}
 
Example 2
Source File: DefaultLeaderElector.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@Override
public void elect() throws Exception {
	
	zkClient.createContainers(ctx.getLeaderElectionZKPath());
	
	latch = new LeaderLatch(zkClient, ctx.getLeaderElectionZKPath(), ctx.getLeaderElectionID());
	latch.addListener(new LeaderLatchListener() {

		@Override
		public void notLeader() {
		}

		@Override
		public void isLeader() {
		}
	});

	latch.start();
	logger.info("[elect]{}", ctx);
}
 
Example 3
Source File: BaragonServiceTestBase.java    From Baragon with Apache License 2.0 6 votes vote down vote up
protected void startAgent(String baseUrl, String group) {
  try {
    BaragonAgentMetadata agentMetadata = new BaragonAgentMetadata(
        baseUrl,
        UUID.randomUUID().toString(),
        Optional.absent(),
        null,
        Optional.absent(),
        null,
        true);
    LeaderLatch leaderLatch = loadBalancerDatastore.createLeaderLatch(group, agentMetadata);
    String id = leaderLatch.getId();
    leaderLatch.start();
    activeLeaderLatch.add(leaderLatch);
    while (leaderLatch.getParticipants().stream().map(Participant::getId).noneMatch(id::equals)) {
      Thread.sleep(5);
    }
  } catch (Throwable t) {
    throw new RuntimeException(t);
  }
}
 
Example 4
Source File: StateKeeper.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public synchronized void registerLeaderLatch() throws Exception {
    if (zkClient.checkExists().forPath(getLeaderPath()) == null) {
        zkClient.create().forPath(getLeaderPath());
    }
    leaderLatch = new LeaderLatch(zkClient, getLeaderPath(), hostName);
    leaderLatch.start();

    log.info("leaderLatch start");
}
 
Example 5
Source File: StateKeeper.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public synchronized void registerLeaderLatch() throws Exception {
    if (zkClient.checkExists().forPath(getLeaderPath()) == null) {
        zkClient.create().forPath(getLeaderPath());
    }
    leaderLatch = new LeaderLatch(zkClient, getLeaderPath(), hostName);
    leaderLatch.start();

    log.info("leaderLatch start");
}
 
Example 6
Source File: ZooKeeperMasterSelectorImpl.java    From EasyTransaction with Apache License 2.0 5 votes vote down vote up
private void init(){
	CuratorFramework client = CuratorFrameworkFactory.newClient(zooKeeperUrl, new RetryForever(1000));
	leaderLatch = new LeaderLatch(client, "/EasyTransMasterSelector"+"/" + applicationName);
	try {
		client.start();
		leaderLatch.start();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 7
Source File: LeaderElectHandler.java    From DBus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("resource")
@Override
public void process() {
    try {
        CuratorFramework _curator = CuratorContainer.getInstance().getCurator();
        ZkVo conf = HeartBeatConfigContainer.getInstance().getZkConf();
        CuratorContainer.getInstance().createZkNode(conf.getLeaderPath());

        // 获取进程ID和服务器hostName
        final BrokerInfoVo brokerInfo = new BrokerInfoVo();
        String name = ManagementFactory.getRuntimeMXBean().getName();
        String[] pidAndHostName = StringUtils.split(name, "@");
        brokerInfo.setPid(pidAndHostName[0]);
        brokerInfo.setHostName(pidAndHostName[1]);
        brokerInfo.setIp(InetAddress.getLocalHost().getHostAddress());
        LeaderLatch ll = new LeaderLatch(_curator, conf.getLeaderPath(), JsonUtil.toJson(brokerInfo));

        ll.addListener(new LeaderLatchListener() {
            @Override
            public void notLeader() {
                LoggerFactory.getLogger().error("本机现在切换到非leader状态,准备终止当前进程PID:{}", brokerInfo.getPid());
                System.exit(-1);
            }

            @Override
            public void isLeader() {
                LoggerFactory.getLogger().info("本机现在切换到leader状态.");
            }
        });

        ll.start();
        ll.await();
    } catch (Exception e) {
        throw new RuntimeException("选举leader时发生错误!", e);
    }
}
 
Example 8
Source File: ZkHaGuard.java    From fountain with Apache License 2.0 5 votes vote down vote up
/**
 * 阻塞式的初始化和Zookeeper的连接,这个方法在一个容器生命周期中只允许允许一次。
 * <p/>
 * 和zookeeper之间的连接遵循每实例一个ZkClientProvider的方式,这样当实例内部有多个同步线程的时候,
 * 可以共享一个ZkClientProvider,状态都是一致的,避免有些线程是leader,有些是standby的情况。
 * <p/>
 * 改方法是全异步的,如果zookeeper连接不上,也会返回。但是一般上层应用拿不到leader latch,不会成为leader。
 * 而且<code>apache.zookeeper.ClientCnxn</code>包的日志会打印如下:
 * <pre>
 *     Unable to read additional data from server sessionid 0x0, likely server has closed socket, closing socket
 *     connection and attempting reconnect
 * </pre>
 * 参数<code>name</code>标示同步线程的名称,默认的话只有一个可以初始化好和zk的连接,其他的都不再重复初始化了。
 */
@Override
public void init(String name) {
    if (!state.compareAndSet(State.LATENT, State.STARTED)) {
        logger.debug("ZkHaGuard can only be initialized once because LeaderLatch should be singleton");
        return;
    }

    if (zkClientProvider == null) {
        throw new IllegalStateException("ZkClientProvider should not be null");
    }
    logger.info("LeaderLatch will start soon by " + name);
    zkClientProvider.init();
    leaderLatch = new LeaderLatch(zkClientProvider.provideClient(), latchPath, NetUtils.getLocalHostIP());
    leaderLatch.addListener(new LeaderLatchListener() {
        @Override
        public void isLeader() {
            logger.info("This instance is leader");
        }

        @Override
        public void notLeader() {
            logger.warn("This instance is NOT leader");
        }
    });
    try {
        leaderLatch.start();
    } catch (Exception e) {
        throw new RuntimeException("Leader latch init failed", e);
    }
    logger.info("LeaderLatch starts by " + name + " asynchronously");
}
 
Example 9
Source File: ClusterSyncManager.java    From Decision with Apache License 2.0 5 votes vote down vote up
public void start() throws Exception {
    client.start();
    client.getZookeeperClient().blockUntilConnectedOrTimedOut();
    leaderLatch = new LeaderLatch(client, latchpath, id);

    ClusterSyncManagerLeaderListener listener = new ClusterSyncManagerLeaderListener(failOverTask, getNode());
    leaderLatch.addListener(listener);

    leaderLatch.start();
}
 
Example 10
Source File: LeaderService.java    From curator-extensions with Apache License 2.0 5 votes vote down vote up
private synchronized LeaderLatch startLeaderLatch() throws InterruptedException {
    LeaderLatch latch = _latch; // Read the volatile once
    // Assert not started already.  initLeaderLatch() and closeLeaderLatch() leave the latch in the latent state.
    checkState(latch.getState() == LeaderLatch.State.LATENT);
    try {
        latch.start();
    } catch (InterruptedException ie) {
        throw ie;
    } catch (Throwable t) {
        LOG.error("Exception attempting to acquire leadership: {}", getId(), t);
    }
    return latch;
}
 
Example 11
Source File: LeadershipManager.java    From Decision with Apache License 2.0 4 votes vote down vote up
public void start() throws Exception {
    client.start();
    client.getZookeeperClient().blockUntilConnectedOrTimedOut();
    leaderLatch = new LeaderLatch(client, latchpath, id);
    leaderLatch.start();
}
 
Example 12
Source File: OracleServer.java    From fluo with Apache License 2.0 4 votes vote down vote up
public synchronized void start() throws Exception {
  if (started) {
    throw new IllegalStateException();
  }

  curatorFramework = CuratorUtil.newAppCurator(env.getConfiguration());
  curatorFramework.getConnectionStateListenable().addListener(cnxnListener);
  curatorFramework.start();

  while (!cnxnListener.isConnected()) {
    UtilWaitThread.sleep(200);
  }

  final InetSocketAddress addr = startServer();

  String leaderId = HostUtil.getHostName() + ":" + addr.getPort();
  leaderLatch = new LeaderLatch(curatorFramework, ZookeeperPath.ORACLE_SERVER, leaderId);
  log.info("Leader ID = " + leaderId);
  execService = Executors.newSingleThreadExecutor(new FluoThreadFactory("Oracle Server Worker"));
  leaderLatch.addListener(new LeaderLatchListener() {
    @Override
    public void notLeader() {
      isLeader = false;

      if (started) {
        // if we stopped the server manually, we shouldn't halt
        Halt.halt("Oracle has lost leadership unexpectedly and is now halting.");
      }
    }

    @Override
    public void isLeader() {
      assumeLeadership();
    }
  }, execService);
  leaderLatch.start();

  pathChildrenCache = new PathChildrenCache(curatorFramework, oraclePath, true);
  pathChildrenCache.getListenable().addListener(this);
  pathChildrenCache.start();

  while (!cnxnListener.isConnected()) {
    UtilWaitThread.sleep(200);
  }

  log.info("Listening " + addr);

  started = true;
}