org.apache.curator.framework.recipes.leader.LeaderLatchListener Java Examples

The following examples show how to use org.apache.curator.framework.recipes.leader.LeaderLatchListener. 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: SimpleLeaderManager.java    From mykit-delay with Apache License 2.0 6 votes vote down vote up
public void init() {
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
            .connectString(properties.getServerList())
            .retryPolicy(new ExponentialBackoffRetry(properties.getBaseSleepTimeMilliseconds(),
                    properties.getMaxRetries(),
                    properties.getMaxSleepTimeMilliseconds()))
            .namespace(ServerNode.NAMESPACE);
    framework = builder.build();
    framework.start();
    leaderLatch = new LeaderLatch(framework, ServerNode.LEADERLATCH, serverName, LeaderLatch.CloseMode.NOTIFY_LEADER);
    for (LeaderLatchListener listener : listeners) {
        leaderLatch.addListener(listener);
    }
    LOGGER.info("starting Queue Master Slave Model ...");
    start();
}
 
Example #2
Source File: AgentLeaderElector.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void tryToBeLeader() {
	leaderLatch.addListener(new LeaderLatchListener() {
		@Override
		public void notLeader() {
		}

		@Override
		public void isLeader() {
			try {
				//setting new agent at /jumbune/agent/leader
				agentNode.setStatus(AgentNodeStatus.LEADER);
				curator.setData().forPath(ZKConstants.AGENT_LEADER_PATH, GSON.toJson(agentNode).getBytes());		
                   updateFollowersListOnZk();			
	            CONSOLE_LOGGER.info("Leader event[agent], new leader - " + agentNode);
				LOGGER.debug("Leader event[agent], new leader - " + agentNode);
			} catch (Exception e) {
				LOGGER.error(e.getMessage(), e);
			}
		}
	});
}
 
Example #3
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 #4
Source File: BalancedMetricResolver.java    From timely with Apache License 2.0 6 votes vote down vote up
private void startLeaderLatch(CuratorFramework curatorFramework) {
    try {

        this.leaderLatch = new LeaderLatch(curatorFramework, LEADER_LATCH_PATH);
        this.leaderLatch.start();
        this.leaderLatch.addListener(new LeaderLatchListener() {

            @Override
            public void isLeader() {
                LOG.info("this balancer is the leader");
                isLeader.set(true);
                writeAssignmentsToHdfs();
            }

            @Override
            public void notLeader() {
                LOG.info("this balancer is not the leader");
                isLeader.set(false);
            }
        });
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
}
 
Example #5
Source File: ZookeeperLeaderElector.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private LeaderLatch createNewLeaderLatch(String leaderPath) {
    final LeaderLatch newLeaderLatch = new LeaderLatch(curator, leaderPath, "127.0.0.1");

    newLeaderLatch.addListener(
            new LeaderLatchListener() {
                @Override
                public void isLeader() {
                    announceLeader();
                }

                @Override
                public void notLeader() {
                    leaderActivator.stopBeingLeader();
                }
            }, Executors.newSingleThreadExecutor(new DefaultThreadFactory("LeaderLatchListener-%s")));

    return newLeaderLatch;
}
 
Example #6
Source File: Reaper.java    From xian with Apache License 2.0 6 votes vote down vote up
private void addListenerToLeaderLatch(LeaderLatch leaderLatch)
{

    LeaderLatchListener listener = new LeaderLatchListener()
    {
        @Override
        public void isLeader()
        {
            reapingIsActive.set(true);
            for ( PathHolder holder : activePaths.values() )
            {
                schedule(holder, reapingThresholdMs);
            }
        }

        @Override
        public void notLeader()
        {
            reapingIsActive.set(false);
        }
    };
    leaderLatch.addListener(listener);

    reapingIsActive.set(leaderLatch.hasLeadership());
}
 
Example #7
Source File: SingularityLeaderLatch.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Inject
public SingularityLeaderLatch(
  CuratorFramework curatorFramework,
  Set<LeaderLatchListener> listeners,
  @Named(SingularityMainModule.HTTP_HOST_AND_PORT) HostAndPort httpHostAndPort
)
  throws Exception {
  super(
    checkNotNull(curatorFramework, "curatorFramework is null"),
    LEADER_PATH,
    httpHostAndPort.toString()
  );
  checkNotNull(listeners, "listeners is null");
  for (LeaderLatchListener listener : listeners) {
    addListener(listener);
  }
}
 
Example #8
Source File: SimpleLeaderManager.java    From sdmq with Apache License 2.0 6 votes vote down vote up
public void init() {
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
            .connectString(properties.getServerList())
            .retryPolicy(new ExponentialBackoffRetry(properties.getBaseSleepTimeMilliseconds(),
                    properties.getMaxRetries(),
                    properties.getMaxSleepTimeMilliseconds()))
            .namespace(ServerNode.NAMESPACE);
    framework = builder.build();
    framework.start();
    leaderLatch = new LeaderLatch(framework, ServerNode.LEADERLATCH, serverName, LeaderLatch.CloseMode.NOTIFY_LEADER);
    for (LeaderLatchListener listener : listeners) {
        leaderLatch.addListener(listener);
    }
    LOGGER.info("starting Queue Master Slave Model ...");
    start();
}
 
Example #9
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 #10
Source File: LeaderAutoConfiguration.java    From sdmq with Apache License 2.0 5 votes vote down vote up
@Bean
@Autowired
@ConditionalOnMissingBean
public LeaderLatchListener leaderLatchListenerImpl(RedisQueueImpl redisQueueImpl) {
    LeaderWorkListener listener = new LeaderWorkListener();
    listener.setQueue(redisQueueImpl);
    return listener;
}
 
Example #11
Source File: LeaderAutoConfiguration.java    From sdmq with Apache License 2.0 5 votes vote down vote up
@Bean(name = "simpleLeaderManager", initMethod = "init", destroyMethod = "stop")
@Autowired
@ConditionalOnMissingBean
public LeaderManager leaderManager(LeaderLatchListener leaderLatchListener) {
    SimpleLeaderManager slm = new SimpleLeaderManager();
    slm.setProperties(registryProperties);
    slm.addListener(leaderLatchListener);
    ServerNode.NAMESPACE = registryProperties.getNamespace();
    slm.setServerName(IpUtils.getIp() + ":" + AppEnvContext.getProperty("server.port"));
    return slm;
}
 
Example #12
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 #13
Source File: HeartBeatController.java    From DBus with Apache License 2.0 5 votes vote down vote up
public void start() throws Exception {
    leaderLatch.addListener(new LeaderLatchListener() {
        @Override
        public void isLeader() {
            isLeader = false;
            WorkerCoordinator coordinator = new WorkerCoordinator(zkUtils);
            coordinator.registerWorkerChangeListener();
        }
        @Override
        public void notLeader() {
        }
    });
    leaderLatch.start();
}
 
Example #14
Source File: ClientLeaderLatch.java    From javabase with Apache License 2.0 5 votes vote down vote up
public LeaderLatchListener getLatchListener() {
    return new LeaderLatchListener() {
        @Override
        public void isLeader() {
            log.info(name+" =>  isLeader ");
            doJob();
        }

        @Override
        public void notLeader() {
            log.info(name+" =>relinquishing  notLeader");
        }
    };
}
 
Example #15
Source File: LeaderAutoConfiguration.java    From mykit-delay with Apache License 2.0 5 votes vote down vote up
@Bean(name = "simpleLeaderManager", initMethod = "init", destroyMethod = "stop")
@Autowired
@ConditionalOnMissingBean
public LeaderManager leaderManager(LeaderLatchListener leaderLatchListener) {
    SimpleLeaderManager slm = new SimpleLeaderManager();
    slm.setProperties(registryProperties);
    slm.addListener(leaderLatchListener);
    ServerNode.NAMESPACE = registryProperties.getNamespace();
    slm.setServerName(IpUtils.getIp() + ":" + AppEnvContext.getProperty("server.port"));
    return slm;
}
 
Example #16
Source File: ZookeeperCoordinator.java    From replicator with Apache License 2.0 5 votes vote down vote up
public ZookeeperCoordinator(Map<String, Object> configuration) {
    Object leadershipPath       = configuration.get(Configuration.LEADERSHIP_PATH);
    Object connectionString     = configuration.get(Configuration.CONNECTION_STRING);
    Object retryInitialSleep    = configuration.getOrDefault(Configuration.RETRY_INITIAL_SLEEP, "1000");
    Object retryMaximumAttempts = configuration.getOrDefault(Configuration.RETRY_MAXIMUM_ATTEMPTS, "3");

    Objects.requireNonNull(leadershipPath, String.format("Configuration required: %s", Configuration.LEADERSHIP_PATH));
    Objects.requireNonNull(connectionString, String.format("Configuration required: %s", Configuration.CONNECTION_STRING));

    this.client = CuratorFrameworkFactory.newClient(
            String.join(",",this.getList(connectionString)),
            new ExponentialBackoffRetry(
                    Integer.parseInt(retryInitialSleep.toString()),
                    Integer.parseInt(retryMaximumAttempts.toString())
            )
    );

    this.latch      = new LeaderLatch(this.client, leadershipPath.toString());
    this.running    = new AtomicBoolean();

    this.latch.addListener(new LeaderLatchListener() {
        @Override
        public void isLeader() {
            ZookeeperCoordinator.this.takeLeadership();
        }

        @Override
        public void notLeader() {
            ZookeeperCoordinator.this.loseLeadership();
        }
    });
}
 
Example #17
Source File: ZKLeadershipParticipant.java    From registry with Apache License 2.0 5 votes vote down vote up
private LeaderLatchListener createLeaderLatchListener() {
    return new LeaderLatchListener() {
        @Override
        public void isLeader() {
            LOG.info("This instance with id [{}] acquired leadership", serverUrl);
        }

        @Override
        public void notLeader() {
            LOG.info("This instance with id [{}] lost leadership", serverUrl);
        }
    };
}
 
Example #18
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 #19
Source File: LeaderAutoConfiguration.java    From mykit-delay with Apache License 2.0 5 votes vote down vote up
@Bean
@Autowired
@ConditionalOnMissingBean
public LeaderLatchListener leaderLatchListenerImpl(RedisQueue redisQueue) {
    LeaderWorkListener listener = new LeaderWorkListener();
    listener.setQueue(redisQueue);
    return listener;
}
 
Example #20
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;
}
 
Example #21
Source File: SimpleLeaderManager.java    From sdmq with Apache License 2.0 4 votes vote down vote up
public void addListener(LeaderLatchListener leaderLatchListener) {
    if (!listeners.contains(leaderLatchListener)) {
        listeners.add(leaderLatchListener);
    }

}
 
Example #22
Source File: SimpleLeaderManager.java    From mykit-delay with Apache License 2.0 4 votes vote down vote up
public void addListener(LeaderLatchListener leaderLatchListener) {
    if (!listeners.contains(leaderLatchListener)) {
        listeners.add(leaderLatchListener);
    }

}