/// <summary> /// 清空所有的服务路由。 /// </summary> /// <returns>一个任务。</returns> public override async Task ClearAsync() { if (_logger.IsEnabled(LogLevel.Information)) _logger.LogInformation("准备清空所有路由配置。"); var path = _configInfo.RoutePath; var childrens = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); var index = 0; while (childrens.Any()) { var nodePath = "/" + string.Join("/", childrens); if (await _zooKeeper.existsAsync(nodePath) != null) { var result = await _zooKeeper.getChildrenAsync(nodePath); if (result?.Children != null) { foreach (var child in result.Children) { var childPath = $"{nodePath}/{child}"; if (_logger.IsEnabled(LogLevel.Debug)) _logger.LogDebug($"准备删除:{childPath}。"); await _zooKeeper.deleteAsync(childPath); } } if (_logger.IsEnabled(LogLevel.Debug)) _logger.LogDebug($"准备删除:{nodePath}。"); await _zooKeeper.deleteAsync(nodePath); } index++; childrens = childrens.Take(childrens.Length - index).ToArray(); } if (_logger.IsEnabled(LogLevel.Information)) _logger.LogInformation("路由配置清空完成。"); }
/// <summary> /// 完成一个任务 /// </summary> /// <param name="taskType"></param> /// <param name="taskId"></param> /// <returns></returns> public void FinishTask(string majorTaskId, string taskId) { var todoPath = ConstData.TodoTaskPath.Format(majorTaskId, taskId); var inprogressPath = ConstData.InProgressPath.Format(majorTaskId, taskId); zkClient.deleteAsync(todoPath); zkClient.deleteAsync(inprogressPath); }
public void Dispose() { var zk = new ZooKeeper("localhost:2181", 3000, null); if (zk.existsAsync("/AccountApp").GetAwaiter().GetResult() != null) { zk.deleteAsync("/AccountApp/Rate/USD").GetAwaiter().GetResult(); zk.deleteAsync("/AccountApp/Rate").GetAwaiter().GetResult(); zk.deleteAsync("/AccountApp").GetAwaiter().GetResult(); } byte[] auth = Encoding.UTF8.GetBytes("user1:pass1"); zk.addAuthInfo("digest", auth); if (zk.existsAsync("/AccountAppAuth").GetAwaiter().GetResult() != null) { zk.deleteAsync("/AccountAppAuth/Rate/USD").GetAwaiter().GetResult(); zk.deleteAsync("/AccountAppAuth/Rate").GetAwaiter().GetResult(); zk.deleteAsync("/AccountAppAuth").GetAwaiter().GetResult(); } if (zk.existsAsync("/AccountAppAuth2").GetAwaiter().GetResult() != null) { zk.deleteAsync("/AccountAppAuth2/Rate/USD").GetAwaiter().GetResult(); zk.deleteAsync("/AccountAppAuth2/Rate").GetAwaiter().GetResult(); zk.deleteAsync("/AccountAppAuth2").GetAwaiter().GetResult(); } zk.closeAsync().GetAwaiter().GetResult(); }
private async Task DeleteOurPathAsync(string ourPath) { try { await _zkClient.deleteAsync(ourPath); } catch (KeeperException.NoNodeException e) { // 忽略-已删除(可能已过期会话等) } }
public async Task delete(string path, int version, bool retryOnConnLoss) { if (retryOnConnLoss) { await _zkCmdExecutor.RetryOperation(async() => { await keeper.deleteAsync(path, version); }); } else { await keeper.deleteAsync(path, version); } }
/** * Recursively deletes children of a node. * * @param zookeeper the client * @param path path of the node to delete * @param deleteSelf flag that indicates that the node should also get deleted * @throws InterruptedException * @throws KeeperException */ public static async void deleteChildren(ZooKeeper zookeeper, String path, bool deleteSelf) { PathUtils.validatePath(path); ChildrenResult children = await zookeeper.getChildrenAsync(path, null); foreach (String child in children.Children) { String fullPath = makePath(path, child); deleteChildren(zookeeper, fullPath, true); } if (deleteSelf) { try { await zookeeper.deleteAsync(path, -1); } catch (KeeperException.NotEmptyException) { //someone has created a new child since we checked ... delete again. deleteChildren(zookeeper, path, true); } catch (KeeperException.NoNodeException) { // ignore... someone else has deleted the node it since we checked } } }
/// <summary> /// 删除节点,只有永久节点需要删除 /// </summary> /// <param name="path">要删除的节点</param> public static void Delete(string path) { var rst = currentZookeeper.deleteAsync(path); rst.Wait(); logger.LogWarning($"删除zk节点{path}"); }
public async Task DeleteValue(string path) { var zk = new ZooKeeper("127.0.0.1:2181", 60000, null); await zk.deleteAsync(path); await zk.closeAsync(); }
public async Task testSync() { LOG.info("Starting ZK:" + DateTime.Now); ZooKeeper zk = await createClient(); LOG.info("Beginning test:" + DateTime.Now); for (var i = 0; i < 100; i++) { await zk.createAsync("/test" + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } await zk.sync("/test"); for (var i = 0; i < 100; i++) { await zk.deleteAsync("/test" + i, 0); } for (var i = 0; i < 100; i++) { await zk.getChildrenAsync("/", false); } for (var i = 0; i < 100; i++) { await zk.getChildrenAsync("/", false); } LOG.info("Submitted all operations:" + DateTime.Now); }
public async Task testWatcherCorrectness() { ZooKeeper zk = null; MyWatcher watcher = new MyWatcher(); zk = await createClient(watcher); string[] names = new string[10]; for (int i = 0; i < names.Length; i++) { string name = await zk.createAsync("/tc-", "initialvalue".UTF8getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); names[i] = name; Stat stat = (await zk.getDataAsync(name, watcher)).Stat; await zk.setDataAsync(name, "new".UTF8getBytes(), stat.getVersion()); stat = await zk.existsAsync(name, watcher); await zk.deleteAsync(name, stat.getVersion()); } for (int i = 0; i < names.Length; i++) { string name = names[i]; WatchedEvent @event = watcher.events.poll(10 * 1000); Assert.assertEquals(name, @event.getPath()); Assert.assertEquals(Watcher.Event.EventType.NodeDataChanged, @event.get_Type()); Assert.assertEquals(Watcher.Event.KeeperState.SyncConnected, @event.getState()); @event = watcher.events.poll(10 * 1000); Assert.assertEquals(name, @event.getPath()); Assert.assertEquals(Watcher.Event.EventType.NodeDeleted, @event.get_Type()); Assert.assertEquals(Watcher.Event.KeeperState.SyncConnected, @event.getState()); } }
/// <summary> /// Stops all election services, revokes any outstanding leader offers, and /// disconnects from ZooKeeper. /// </summary> public async Task stop() { using (await lockable.LockAsync().ConfigureAwait(false)) { state = State.STOP; await dispatchEvent(ElectionEventType.STOP_START).ConfigureAwait(false); logger.info("Stopping leader election support"); if (leaderOffer != null) { KeeperException ke = null; try { await ZooKeeper.deleteAsync(leaderOffer.NodePath).ConfigureAwait(false); logger.debugFormat("Removed leader offer {0}", leaderOffer.NodePath); } catch (KeeperException e) { ke = e; } if (ke != null) { await becomeFailed(ke).ConfigureAwait(false); } } await dispatchEvent(ElectionEventType.STOP_COMPLETE).ConfigureAwait(false); } }
public void DeleteNode(string path, String tempNode) { if (!string.IsNullOrEmpty(tempNode)) { requestLockSequence.Remove(tempNode); } ReConn(); if (_zookeeper.existsAsync(path).Result == null) { _logger.LogDebug("path不存在"); return; } var task = Task.Run(async() => { _logger.LogDebug("删除node:{0}", path); await _zookeeper.deleteAsync(path); }); task.Wait(); var sequencePath = requestLockSequence.Where(w => path == w).FirstOrDefault(); if (sequencePath != null) { requestLockSequence.Remove(sequencePath); } }
private async void buttonDelete_Click(object sender, EventArgs e) { var selectedNode = treeViewNodes.SelectedNode; if (selectedNode != null) { if (MessageBox.Show($"Are You Sure To Delete {selectedNode.Text}?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes) { try { await m_zooKeeperClient.deleteAsync(selectedNode.Name); SelecteNode(selectedNode.Parent.Name); selectedNode.Parent?.Nodes.Remove(selectedNode); Log($"Deleted {selectedNode.Name}."); } catch (KeeperException ex) { Log($"{ex.Message} {selectedNode.Name}"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } } } else { MessageBox.Show("No Node Selected.", "Info"); } }
static async Task Test() { var output = string.Empty; ZooKeeper zk = null; try { //创建一个Zookeeper实例,第一个参数为目标服务器地址和端口,第二个参数为Session超时时间,第三个为节点变化时的回调方法 ZooKeeper.LogToFile = false; ZooKeeper.LogToTrace = true; zk = new ZooKeeper("127.0.0.1:2181", 10 * 1000, NullWatcher.Instance); var stat = await zk.existsAsync("/root", true); if (stat == null) { //创建一个节点root,数据是mydata,不进行ACL权限控制,节点为永久性的(即客户端shutdown了也不会消失) output = await zk.createAsync("/root", "mydata".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); Trace.WriteLine($"output"); } stat = await zk.existsAsync("/root/childone", true); if (stat == null) { //在root下面创建一个childone znode,数据为childone,不进行ACL权限控制,节点为永久性的 output = await zk.createAsync("/root/childone", "childone".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); Trace.WriteLine($"output"); } //取得/root节点下的子节点名称,返回List<String> var subNodes = await zk.getChildrenAsync("/root", true); Trace.WriteLine($"SubNodes: {(string.Join(",", subNodes.Children))}"); //取得/root/childone节点下的数据,返回byte[] var data = await zk.getDataAsync("/root/childone", true); Trace.WriteLine($"/root/childone Data: {Encoding.UTF8.GetString(data.Data)}"); //修改节点/root/childone下的数据,第三个参数为版本,如果是-1,那会无视被修改的数据版本,直接改掉 await zk.setDataAsync("/root/childone", "childonemodify".GetBytes(), -1); //删除/root/childone这个节点,第二个参数为版本,-1的话直接删除,无视版本 await zk.deleteAsync("/root/childone", -1); } catch (Exception ex) { Trace.WriteLine(ex.StackTrace); } finally { await zk.closeAsync(); } }
public override void tearDown() { if (zooKeeper != null) { zooKeeper.deleteAsync(testRootNode + Thread.CurrentThread.ManagedThreadId).Wait(); } base.tearDown(); }
public async Task testDeleteWithChildren() { ZooKeeper zk = await createClient(); await zk.createAsync("/parent", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); await zk.createAsync("/parent/child", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); try { await zk.deleteAsync("/parent", -1); Assert.fail("Should have received a not equals message"); } catch (KeeperException e) { Assert.assertEquals(KeeperException.Code.NOTEMPTY, e.getCode()); } await zk.deleteAsync("/parent/child", -1); await zk.deleteAsync("/parent", -1); }
/// <summary> /// 删除节点,删除节点的子节点个数必须为0,否则请先删除子节点 /// </summary> /// <param name="path">不要使用path等关键字作为路径</param> /// <returns></returns> public string DeleteNode(string path) { Task task = _zooKeeper.deleteAsync(path); task.Wait(); if (task.Status.ToString().ToLower() == "RanToCompletion".ToLower()) { return(_success); } return(_fail); }
static async Task DeleteRecursive(ZooKeeper zk, string path = "", string key = "") { var correctedPath = path + "/" + key; var a = await zk.getChildrenAsync(correctedPath); var d = await zk.getDataAsync(correctedPath); foreach (var child in a.Children) { await DeleteRecursive(zk, correctedPath == "/"? "" : correctedPath, child); } await zk.deleteAsync(correctedPath); }
private async Task DeleteLease(string leasePath) { try { await _zkClient.deleteAsync(leasePath); } catch (KeeperException.NoNodeException) { } catch (Exception) { throw; } }
public UnLockResult UnLock(string lockname) { lock (_lockerList) { if (_lockerList.Count(c => lockname == c.Name) == 0) { return(UnLockResult.NotExists); } } try { _client.deleteAsync($"/locks/{lockname}").Wait(); return(UnLockResult.Success); } catch (Exception) { //throw; } return(UnLockResult.Fail); }
public void UnLock() { try { Trace.WriteLine("zk unlock " + currentNode); zk.deleteAsync(currentNode, AnyVersion).Sync(); currentNode = null; preWaitNode = null; } catch (KeeperException e) { throw e; } }
static async Task DeleteRecursive(ZooKeeper zk, string path = "", string key = "") { try { var correctedPath = path + "/" + key; var a = await zk.getChildrenAsync(correctedPath); foreach (var child in a.Children) { await DeleteRecursive(zk, correctedPath == "/"? "" : correctedPath, child); } await zk.deleteAsync(correctedPath); } catch (KeeperException.NoNodeException) { } }
public string removeAsync(string node, Watcher watcher) { ZooKeeper zk = createClient(watcher); if (zk.existsAsync(node, null).Result != null) { zk.deleteAsync(node); return("ok"); } else { return("notexists"); } }
public void Delete(string ServiceName) { try { _client.deleteAsync($"/ZooDiscovery/{ServiceName}").Wait(); } catch (Exception ex) { if (ex.HResult != (int)KeeperException.Code.NONODE) { throw ex; } } }
/// <summary> /// Attempts to remove the head of the queue and return it. </summary> /// <returns> The former head of the queue </returns> /// <exception cref="InvalidOperationException"> </exception> /// <exception cref="KeeperException"> </exception> public async Task <byte[]> remove() { // Same as for element. Should refactor this. while (true) { SortedDictionary <long, string> orderedChildren; try { orderedChildren = await getOrderedChildren(null).ConfigureAwait(false); } catch (KeeperException.NoNodeException) { throw new InvalidOperationException(); } if (orderedChildren.Count == 0) { throw new InvalidOperationException(); } foreach (string headNode in orderedChildren.Values) { string path = dir + "/" + headNode; try { byte[] data = (await zookeeper.getDataAsync(path).ConfigureAwait(false)).Data; await zookeeper.deleteAsync(path).ConfigureAwait(false); return(data); } catch (KeeperException.NoNodeException) { // Another client deleted the node first. } } } }
public void testSync() { try { LOG.info("Starting ZK:" + (DateTime.Now)); countFinished = new ManualResetEventSlim(false); opsCount = limit; ZooKeeper zk = createClient(); LOG.info("Beginning test:" + (DateTime.Now)); for (int i = 0; i < 100; i++) { zk.createAsync("/test" + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT). ContinueWith(processResult); } zk.sync("/test").ContinueWith(processResult); for (int i = 0; i < 100; i++) { zk.deleteAsync("/test" + i, 0).ContinueWith(processResult); } for (int i = 0; i < 100; i++) { zk.getChildrenAsync("/", new NullWatcher()).ContinueWith(processResult); } for (int i = 0; i < 100; i++) { zk.getChildrenAsync("/", new NullWatcher()).ContinueWith(processResult); } LOG.info("Submitted all operations:" + (DateTime.Now)); if (!countFinished.Wait(10000)) { Thread.MemoryBarrier(); Assert.fail("Haven't received all confirmations" + opsCount); } for (int i = 0; i < limit; i++) { lock (results) { Assert.assertEquals(0, results[i]); } } } catch (IOException e) { Console.WriteLine(e.ToString()); } }
public async Task <bool> Unlock(string resourceName, string fenceToken) { try { var lockName = $"/consumer/lock-{resourceName.Replace(@"/", "_")}"; await _zooKeeper.deleteAsync(lockName); return(true); } catch (System.Exception ex) { _logger.LogError(ex, "UnlockFailed"); } return(false); }
/// <summary> /// 删除节点,删除节点的子节点个数必须为0,否则请先删除子节点 /// </summary> /// <param name="path">不要使用path等关键字作为路径</param> /// <returns></returns> public string DeleteNode(string path) { try { Task task = _zooKeeper.deleteAsync(path); task.Wait(); if (task.Status.ToString().ToLower() == "RanToCompletion".ToLower()) { return(_success); } } catch (Exception ex) { _log.ErrorFormat("删除节点发生异常:{0},{1}", path, ex.Message + ex.StackTrace); } return(_fail); }
public async Task <bool> DeleteAsync(string path) { try { await RetryUntilConnected(async() => { await _zk.deleteAsync(path); return(await Task.FromResult(true)); }); } catch (KeeperException.NoNodeException e) { return(await Task.FromResult(false)); } return(await Task.FromResult(true)); }
public async Task <bool> DeregisterAsync() { try { if (await ZooKeeper.existsAsync($"{Root}/{ZooKeeperRegisterServiceConfiguration.Name}/{ZooKeeperRegisterServiceConfiguration.Id}") == null) { return(true); } await ZooKeeper.deleteAsync($"{Root}/{ZooKeeperRegisterServiceConfiguration.Name}/{ZooKeeperRegisterServiceConfiguration.Id}"); return(true); } catch (Exception e) { Logger.LogError(e, e.Message); throw; } }
/// <summary> /// Recursively deletes children of a node. /// </summary> /// <param name="zookeeper"> the client </param> /// <param name="path"> path of the node to delete </param> /// <param name="deleteSelf"> flag that indicates that the node should also get deleted </param> /// <exception cref="InterruptedException"> </exception> /// <exception cref="KeeperException"> </exception> //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public static void deleteChildren(org.apache.zookeeper.ZooKeeper zookeeper, String path, boolean deleteSelf) throws InterruptedException, org.apache.zookeeper.KeeperException public static async Task deleteChildren(ZooKeeper zookeeper, string path, bool deleteSelf) { PathUtils.validatePath(path); IList<string> children = (await zookeeper.getChildrenAsync(path, null)).Children; foreach (var child in children) { var fullPath = makePath(path, child); await deleteChildren(zookeeper, fullPath, true); } if (deleteSelf) { try { await zookeeper.deleteAsync(path, -1); } catch (KeeperException.NotEmptyException) { //someone has created a new child since we checked ... delete again. await deleteChildren(zookeeper, path, true); } catch (KeeperException.NoNodeException) { // ignore... someone else has deleted the node it since we checked } } }
/** * Recursively deletes children of a node. * * @param zookeeper the client * @param path path of the node to delete * @param deleteSelf flag that indicates that the node should also get deleted * @throws InterruptedException * @throws KeeperException */ public static async void deleteChildren(ZooKeeper zookeeper, String path, bool deleteSelf) { PathUtils.validatePath(path); ChildrenResult children = await zookeeper.getChildrenAsync(path, null); foreach( String child in children.Children ) { String fullPath = makePath(path, child); deleteChildren(zookeeper, fullPath, true); } if ( deleteSelf ) { try { await zookeeper.deleteAsync(path, -1); } catch ( KeeperException.NotEmptyException ) { //someone has created a new child since we checked ... delete again. deleteChildren(zookeeper, path, true); } catch ( KeeperException.NoNodeException ) { // ignore... someone else has deleted the node it since we checked } } }