private static PathAndBytesable<?> createOrUpdate(CuratorFramework curator, String path) throws Exception { if (curator.checkExists().forPath(path) == null) { return curator.create().creatingParentsIfNeeded(); } else { return curator.setData(); } }
/** * Create the parent znode for this job state. */ public void create() throws IOException { try { zk.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT) .withACL(Ids.OPEN_ACL_UNSAFE).forPath(job_trackingroot); } catch (KeeperException.NodeExistsException e) { //root must exist already } catch (Exception e) { throw new IOException("Unable to create parent nodes"); } try { trackingnode = zk.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL) .withACL(Ids.OPEN_ACL_UNSAFE).forPath(makeTrackingZnode(), jobid.getBytes()); } catch (Exception e) { throw new IOException("Unable to create " + makeTrackingZnode()); } } public void delete() throws IOException {
@Override public String persistSequential(final String key, final String value) { try { return client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath(key, value.getBytes(Charsets.UTF_8)); //CHECKSTYLE:OFF } catch (final Exception ex) { //CHECKSTYLE:ON RegExceptionHandler.handleException(ex); } return null; }
public static void main(String[] args) throws Exception { final String remoteAddress = "localhost:2181"; final String groupId = "Sentinel-Demo"; final String dataId = "SYSTEM-CODE-DEMO-FLOW"; final String rule = "[\n" + " {\n" + " \"resource\": \"TestResource\",\n" + " \"controlBehavior\": 0,\n" + " \"count\": 10.0,\n" + " \"grade\": 1,\n" + " \"limitApp\": \"default\",\n" + " \"strategy\": 0\n" + " }\n" + "]"; CuratorFramework zkClient = CuratorFrameworkFactory.newClient(remoteAddress, new ExponentialBackoffRetry(SLEEP_TIME, RETRY_TIMES)); zkClient.start(); String path = getPath(groupId, dataId); Stat stat = zkClient.checkExists().forPath(path); if (stat == null) { zkClient.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, null); } zkClient.setData().forPath(path, rule.getBytes()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } zkClient.close(); }
@Test public void testLeavesBehindTurdlingsThatAlreadyExisted() throws Exception { curator.start(); curator.blockUntilConnected(); Announcer announcer = new Announcer(curator, exec); final byte[] billy = StringUtils.toUtf8("billy"); final String testPath = "/somewhere/test2"; final String parent = ZKPaths.getPathAndNode(testPath).getPath(); curator.create().forPath(parent); final Stat initialStat = curator.checkExists().forPath(parent); announcer.start(); try { Assert.assertEquals(initialStat.getMzxid(), curator.checkExists().forPath(parent).getMzxid()); awaitAnnounce(announcer, testPath, billy, true); Assert.assertEquals(initialStat.getMzxid(), curator.checkExists().forPath(parent).getMzxid()); } finally { announcer.stop(); } Assert.assertEquals(initialStat.getMzxid(), curator.checkExists().forPath(parent).getMzxid()); }
public ZkBasedSnowFlakeIdGenerator(String zooKeeperUrl, String applicationName) { CuratorFramework client = CuratorFrameworkFactory.newClient(zooKeeperUrl, new RetryForever(1000)); client.start(); try { String path = "/EasyTransIdGen/" + applicationName + "/P"; String nodeName = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(path); String sequenceStr = nodeName.replaceAll(path, ""); hostSeq = Long.parseLong(sequenceStr) % (2^SnowFlake.MACHINE_BIT); client.close();//do not need to keep connection, hostSeq will not change } catch (Exception e) { throw new RuntimeException("create Id generator failed",e); } }
CuratorFramework checkRoot = CuratorFrameworkFactory.newClient(zookeepers, new RetryForever(1000)); checkRoot.start(); if (checkRoot.checkExists().forPath(zkMetadataRoot) == null) { checkRoot.create().forPath(zkMetadataRoot); curator = CuratorFrameworkFactory.newClient(zookeepers + zkMetadataRoot, new RetryForever(1000)); curator.start(); if (curator.checkExists().forPath("/" + DEFAULT_SCHEMA) == null) { curator.create().forPath("/" + DEFAULT_SCHEMA);
public synchronized void off(String destination) { if (mode == Mode.LOCAL) { BooleanMutex mutex = LOCAL_LOCK.get(destination); if (mutex != null && mutex.state()) { mutex.set(false); } } else { try { String path = SYN_SWITCH_ZK_NODE + destination; try { curatorClient.getCurator() .create() .creatingParentContainersIfNeeded() .withMode(CreateMode.PERSISTENT) .forPath(path, "off".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { curatorClient.getCurator().setData().forPath(path, "off".getBytes(StandardCharsets.UTF_8)); } } catch (Exception e) { throw new RuntimeException(e); } } }
this.zkClient = CuratorFrameworkFactory.newClient(serverAddr, new ExponentialBackoffRetry(SLEEP_TIME, RETRY_TIMES)); this.zkClient.start(); Stat stat = this.zkClient.checkExists().forPath(this.path); if (stat == null) { this.zkClient.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(this.path, null);
void setUp() throws Exception { testingCluster = new TestingCluster(1); testingCluster.start(); cf = CuratorFrameworkFactory.builder() .connectString(testingCluster.getConnectString()) .retryPolicy(new ExponentialBackoffRetry(1, 10)) .compressionProvider(new PotentiallyGzippedCompressionProvider(false)) .build(); cf.start(); cf.blockUntilConnected(); cf.create().creatingParentsIfNeeded().forPath(basePath); cf.create().creatingParentsIfNeeded().forPath(tasksPath); }
public void updateBrokerStatus(String clusterName, Set<String> brokers) { try { //add cluster node if (zkClient.checkExists().forPath(getClusterPath(clusterName)) == null) { zkClient.create().forPath(getClusterPath(clusterName)); zkClient.create().forPath(getIdsPath(clusterName)); } if (zkClient.checkExists().forPath(getNSPath(clusterName)) != null) { Set brokerSetInZk = fromJsonBytes(zkClient.getData().forPath(getNSPath(clusterName)), Set.class); if (!brokers.equals(brokerSetInZk)) { zkClient.setData().forPath(getNSPath(clusterName), toJsonString(brokers).getBytes()); aliveBrokers.put(clusterName, brokers); } } else { zkClient.create().withMode(CreateMode.EPHEMERAL).forPath(getNSPath(clusterName), toJsonString(brokers).getBytes()); aliveBrokers.put(clusterName, brokers); } } catch (Exception ex) { log.error("update broker status failed, clusterName:" + clusterName + ", brokers:" + brokers, ex); } }
private void ensureZkPaths(CuratorFramework curatorFramework, String[] paths) { for (String s : paths) { try { Stat stat = curatorFramework.checkExists().forPath(s); if (stat == null) { curatorFramework.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT) .forPath(s); } } catch (Exception e) { LOG.info(e.getMessage()); } } }
private void determineLeadership() { ReentrantReadWriteLock.WriteLock lock = this.readWriteLock.writeLock(); lock.lock(); try { List<String> children = this.zooKeeper.getChildren().forPath(this.leaderElectionNode); Collections.sort(children); int idx = children.indexOf(this.nodeId); if (idx == 0) { Stat stat = this.zooKeeper.checkExists().forPath(this.leaderNode); if (stat == null) { this.zooKeeper.create().forPath(this.leaderNode, serializeMetadata(this.localMetadata)); } else { this.zooKeeper.setData().forPath(this.leaderNode, serializeMetadata(this.localMetadata)); } this.isLeader = true; } else { this.isLeader = false; String watchedNode = this.leaderElectionNode + "/" + children.get(idx - 1); this.zooKeeper.checkExists().usingWatcher(new DetermineLeadershipWatcher()).forPath(watchedNode); } findLeader(); } catch (KeeperException exc) { reset(); } catch (Throwable exc) { log.error("Fatal failure.", exc); this.fatalFailure = true; } finally { lock.unlock(); } }
private void createInstanceNodeForInitialization() throws Exception { String parent = String.format("%s/%s/instances", CONSTANTS_ROOT_PATH, CommonUtils.getApplication(this.endpoint)); String path = String.format("%s/%s", parent, this.endpoint); byte[] versionByteArray = ByteUtils.longToByteArray(this.instanceVersion); try { this.curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(path, versionByteArray); } catch (NodeExistsException error) { try { this.instanceLock.lock(); this.instanceInited = false; this.curatorFramework.checkExists().usingWatcher(this).inBackground(this).forPath(path); this.instanceCond.await(this.initializeWaitingSeconds, TimeUnit.SECONDS); if (this.instanceInited == false) { throw error; } } catch (InterruptedException ignore) { // ignore } finally { this.instanceLock.unlock(); } } }
private void createIfNotExists(String path) throws Exception { if (curatorFramework.checkExists().forPath(path) == null) { curatorFramework.create().creatingParentContainersIfNeeded().forPath(path, new byte[0]); } }
private void createRootPath() throws Exception { if (zkClient.checkExists().forPath(getRootPath()) == null) { zkClient.create().forPath(getRootPath()); } }
public static long getLastCachedTid(BigInteger machineId) throws Exception { long oldTid = 0; String timestampPath = String.format("/snowflake/hosts/%s/timestamp", machineId); Stat stat = curator.checkExists().forPath(timestampPath); if (stat == null) { curator.create().creatingParentContainersIfNeeded().forPath(timestampPath); } else { byte[] data = curator.getData().forPath(timestampPath); oldTid = LongCombiner.FIXED_LEN_ENCODER.decode(data); } return oldTid; }
@Test public void verifyZooKeeperToleratesOneNodeDataLoss() throws Exception { try { zk.curatorWithSuperAuth().create().forPath(FOO, FOO_DATA); assertArrayEquals(FOO_DATA, zk.curatorWithSuperAuth().getData().forPath(FOO)); } catch (KeeperException.NodeExistsException ignore) { // ignored } zk.stopPeer(0); zk.resetPeer(0); zk.startPeer(0); zk.stopPeer(1); assertArrayEquals(FOO_DATA, zk.curatorWithSuperAuth().getData().forPath(FOO)); }