public async Task testACLs() { ZooKeeper zk = await createClient(); try { await zk.createAsync("/acltest", new byte[0], ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT); Assert.fail("Should have received an invalid acl error"); } catch (KeeperException.InvalidACLException e) { LOG.info("Test successful, invalid acl received : " + e.Message); } try { List <ACL> testACL = new List <ACL>(); testACL.Add(new ACL((int)(ZooDefs.Perms.ALL | ZooDefs.Perms.ADMIN), ZooDefs.Ids.AUTH_IDS)); testACL.Add(new ACL((int)(ZooDefs.Perms.ALL | ZooDefs.Perms.ADMIN), new Id("ip", "127.0.0.1/8"))); await zk.createAsync("/acltest", new byte[0], testACL, CreateMode.PERSISTENT); Assert.fail("Should have received an invalid acl error"); } catch (KeeperException.InvalidACLException e) { LOG.info("Test successful, invalid acl received : " + e.Message); } zk.addAuthInfo("digest", "ben:passwd".UTF8getBytes()); await zk.createAsync("/acltest", new byte[0], ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT); await zk.closeAsync(); zk = await createClient(); zk.addAuthInfo("digest", "ben:passwd2".UTF8getBytes()); try { await zk.getDataAsync("/acltest", false); Assert.fail("Should have received a permission error"); } catch (KeeperException e) { Assert.assertEquals(KeeperException.Code.NOAUTH, e.getCode()); } zk.addAuthInfo("digest", "ben:passwd".UTF8getBytes()); await zk.getDataAsync("/acltest", false); await zk.setACLAsync("/acltest", ZooDefs.Ids.OPEN_ACL_UNSAFE, -1); await zk.closeAsync(); zk = await createClient(); await zk.getDataAsync("/acltest", false); IList <ACL> acls = (await zk.getACLAsync("/acltest")).Acls; Assert.assertEquals(1, acls.Count); Assert.assertEquals(ZooDefs.Ids.OPEN_ACL_UNSAFE, acls); // The stat parameter should be optional. acls = (await zk.getACLAsync("/acltest")).Acls; Assert.assertEquals(1, acls.Count); Assert.assertEquals(ZooDefs.Ids.OPEN_ACL_UNSAFE, acls); }
private async void MainForm_FormClosing(object sender, FormClosingEventArgs e) { try { var filePath = GetConfigFilePath(); Directory.CreateDirectory(Path.GetDirectoryName(filePath)); Int32.TryParse(textBoxSessionTimeout.Text, out int sessionTimeOut); File.WriteAllText(filePath, Newtonsoft.Json.JsonConvert.SerializeObject(new AppConfig() { Connectstring = textBoxConnectstring.Text, SessionTimeout = sessionTimeOut, })); } catch (Exception ex) { Log(ex.Message); } if (m_zooKeeperClient != null) { try { await m_zooKeeperClient.closeAsync(); } catch (Exception ex) { Log(ex.Message); // 这里记录了也没用^_^ } } }
/// <summary> /// 重新连接zk /// </summary> /// <returns></returns> private async Task Reconnect() { if (!Monitor.TryEnter(_zkEventLock, TimeSpan.FromMilliseconds(_connectionTimeout))) { return; } try { if (_zk != null) { await _zk.closeAsync(); } _zk = Create(_zkServers, _connectionTimeout); Logger.Info("Reconnect"); } catch (Exception ex) { FireSessionEstablishmentErrorEvent(ex); Logger.Error($"Reconnect exception: {ex.ToString()}"); } finally { Monitor.Exit(_zkEventLock); } }
public void Logout() { if (_zk != null) { _zk.closeAsync(); _zk = null; } }
protected virtual void HandleExpired() { SafeLog("Session expired."); zk?.closeAsync().Sync(); Init(); }
/// <summary> /// 断点连接使session过期 /// </summary> /// <returns></returns> public async Task Disconnect() { _lockedAble = false; if (_lockCount == 0) { await _zk.closeAsync(); _zk = new ZooKeeper(_connectionString, _timeOut, null); _lockedAble = true; } }
private void HandleExpired() { try { zk?.closeAsync().Sync(); } catch (KeeperException ex) { throw ex; } Init(); }
internal async void Run() { var data = Encoding.UTF8.GetBytes("test"); ZooKeeper zk = new ZooKeeper("localhost:2181", 50000, NullWatcher.Instance); var zNodeRoot = zk.existsAsync("/").Result.getCversion(); var zNodeA = zk.existsAsync("/a").Result; if (zNodeA == null) { await zk.createAsync("/a", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } var node = zk.existsAsync("/a/1").Result; Task <string> nodetask = null; if (node == null) { nodetask = zk.createAsync("/a/1", data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } nodetask.Wait(); IList <string> children = zk.getChildrenAsync("/a", false).Result.Children; var test2 = zk.getDataAsync("/a", NodeWatcher.Instance).Result; var test3 = zk.setDataAsync("/a", data).Result; var closeEvent = zk.closeAsync(); closeEvent.Wait(); }
private async Task <InternalConnection> InternalConnectAsync(ZooKeeperConnectionInfo connectionInfo) { var watcher = new ConnectionWatcher(connectionInfo.SessionTimeout); var zooKeeper = new ZooKeeper( connectstring: connectionInfo.ConnectionString, sessionTimeout: connectionInfo.SessionTimeout.InMilliseconds, watcher: watcher ); using var timeoutSource = new CancellationTokenSource(connectionInfo.ConnectTimeout.TimeSpan); using var timeoutRegistration = timeoutSource.Token.Register( () => watcher.TaskCompletionSource.TrySetException(new TimeoutException($"Timed out connecting to ZooKeeper after {connectionInfo.ConnectTimeout.InMilliseconds}ms")) ); foreach (var authInfo in connectionInfo.AuthInfo) { zooKeeper.addAuthInfo(authInfo.Scheme, authInfo.Auth.ToArray()); } try { await watcher.TaskCompletionSource.Task.ConfigureAwait(false); return(new InternalConnection(zooKeeper, watcher)); } catch { // on failure, clean up the instance we created try { await zooKeeper.closeAsync().ConfigureAwait(false); } finally { watcher.Dispose(); } throw; } }
public async Task DeleteValue(string path) { var zk = new ZooKeeper("127.0.0.1:2181", 60000, null); await zk.deleteAsync(path); await zk.closeAsync(); }
/// <summary> /// 清除路由,清理连接 /// </summary> /// <param name="serverName">serverName</param> /// <param name="router">router</param> public static void ClearRouter(string serverName, string router) { string path = getRouterPath(serverName) + $"/[{router}]"; logger.LogInformation($"服务退出,清理路由:{path}"); try { var existPath = currentZookeeper.existsAsync(path, false); existPath.Wait(); if (existPath.Result != null) { Delete(path); } if (currentZookeeper != null) { var rst = currentZookeeper.closeAsync(); rst.Wait(); currentZookeeper = null; } } catch (Exception e) { Console.WriteLine(e); // 这里吞掉算了 ,服务要退出了,不管了··· } }
public async Task ChangeValue(string path, string value) { var zk = new ZooKeeper("127.0.0.1:2181", 60000, null); await zk.setDataAsync(path, Encoding.UTF8.GetBytes(value)); await zk.closeAsync(); }
public async Task closeKeeper(ZooKeeper keeper) { if (keeper != null) { await keeper.closeAsync(); } }
public void Dispose() { if (isDisposed) { return; } if (!isDisposed) { if (zooKeeper != null) { zooKeeper.closeAsync().ConfigureAwait(false); } isDisposed = true; } }
private async Task ReConnect() { if (!Monitor.TryEnter(_zkEventLock, Options.ConnectionTimeout)) { return; } try { if (ZooKeeper != null) { try { await ZooKeeper.closeAsync(); } catch { // ignored } } ZooKeeper = CreateZooKeeper(); } finally { Monitor.Exit(_zkEventLock); } }
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(); }
public void Get_Value_From_Node_With_ACL() { string usd = "110"; byte[] auth = Encoding.UTF8.GetBytes("user1:pass1"); var zk = new ZooKeeper("localhost:2181", 3000, null); zk.addAuthInfo("digest", auth); zk.createAsync("/AccountAppAuth", null, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT).GetAwaiter().GetResult(); zk.createAsync("/AccountAppAuth/Rate", null, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT).GetAwaiter().GetResult(); zk.createAsync("/AccountAppAuth/Rate/USD", Encoding.UTF8.GetBytes(usd), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT).GetAwaiter().GetResult(); zk.closeAsync().GetAwaiter().GetResult(); IConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddZookeeper(option => { option.ConnectionString = "localhost:2181"; option.ConnectionTimeout = 10000; option.RootPath = "/AccountAppAuth"; option.SessionTimeout = 30000; option.AddAuthInfo("digest", auth); }); var configuration = builder.Build(); Assert.Equal(usd, configuration["Rate:USD"]); }
public async Task Close() { if (_connection == null) { return; } await _connection.closeAsync().ConfigureAwait(false); }
public async Task AddValue(string path, string value) { var zk = new ZooKeeper("127.0.0.1:2181", 60000, null); await zk.createAsync(path, Encoding.UTF8.GetBytes(value), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); await zk.closeAsync(); }
private async Task CreateZooKeeper() { if (_zooKeeper != null) await _zooKeeper.closeAsync(); _zooKeeper = new ZooKeeper(_configInfo.ConnectionString, (int)_configInfo.SessionTimeout.TotalMilliseconds , new ReconnectionWatcher( () => { _connectionWait.Set(); }, async () => { _connectionWait.Reset(); await CreateZooKeeper(); })); }
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 async Task CloseAsync() { if (_zk != null && _connected) { await _zk.closeAsync(); _connected = false; } }
public void Close(string tempNode) { var task = Task.Run(async() => { requestLockSequence.Remove(tempNode); await _zookeeper.closeAsync(); }); task.Wait(); }
public async void Close(string tempNode) { try { await _zookeeper.closeAsync(); } catch (Exception ep) { _logger.LogError("zookeeper关闭失败。", ep); } }
public async Task testOnlyOneAvailable() { log.debug("START - testOnlyOneAvailable"); var connectionString = Enumerable.Range(0, 9).Select(i => Guid.NewGuid().ToString("N")).ToCommaDelimited() + ",localhost"; var zk = new ZooKeeper(connectionString, CONNECTION_TIMEOUT, NullWatcher.Instance); await zk.existsAsync("/"); await zk.closeAsync(); log.debug("END - testOnlyOneAvailable"); }
/// <summary> /// 关闭连接 /// </summary> /// <returns></returns> public string Close() { Task task = _zooKeeper.closeAsync(); task.Wait(); if (task.Status.ToString().ToLower() == "RanToCompletion".ToLower()) { return(_success); } return(_fail); }
public async Task testMultiRollback() { var zk = await createClient(); await zk.createAsync("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); ZooKeeper epheZk = await createClient(); await epheZk.createAsync("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); List <Op> opList = Arrays.asList(Op.delete("/foo", -1)); try { await multiAsync(zk, opList); Assert.fail("multi delete should failed for not empty directory"); } catch (KeeperException.NotEmptyException) { } var hasBeenDeleted = new HasBeenDeletedWatcher(); await zk.existsAsync("/foo/bar", hasBeenDeleted); await epheZk.closeAsync(); await hasBeenDeleted.triggered.Task; try { await zk.getDataAsync("/foo/bar", false); Assert.fail("ephemeral node should have been deleted"); } catch (KeeperException.NoNodeException) { } await multiAsync(zk, opList); try { await zk.getDataAsync("/foo", false); Assert.fail("persistent node should have been deleted after multi"); } catch (KeeperException.NoNodeException) { } }
private async Task GetSuperHammerTask(string prefix, int count) { for (int current = 0; current < count; current++) { ZooKeeper zk = await createClient(); await zk.createAsync(prefix + current, b, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); await zk.closeAsync(); LOG.warn("created:" + prefix + current); } }
public async Task TestMethod1() { //原来zk客户端不应该作为静态对象,每次new foreach (var i in Com.Range(100)) { var client = new ZooKeeper("localhost:32771", (int)TimeSpan.FromSeconds(5).TotalMilliseconds, this, canBeReadOnly: false); try { //var count = 0; //while (client.getState() != ZooKeeper.States.CONNECTED) //{ // if (++count > 100) { throw new Exception("loss patient to wait for connection"); } // await Task.Delay(10); //} if (await client.existsAsync("/home", false) == null) { var path = await client.createAsync("/home", "".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } var bs = new { id = 2, name = "fas", age = 44, time = DateTime.Now }.ToJson().GetBytes(); await client.setDataAsync("/home", bs); var data = await client.getDataAsync("/home", false); var children = await client.getChildrenAsync("/home"); var t = client.transaction(); //t.delete("/home"); t.setData("/home", $"{DateTime.Now.Ticks}".GetBytes()); var res = await t.commitAsync(); } catch (Exception e) { // } finally { await client.closeAsync(); this.connected = false; } } }
private void internalClose() { try { ZooKeeper zooKeeper = helper?.getZooKeeper(); //Watcher dummyWatcher = new EmptyWatcher(); //zooKeeper.register(dummyWatcher); // clear the default watcher so that no new events get processed by mistake zooKeeper?.closeAsync().Wait(); } catch (Exception) { Thread.CurrentThread.Abort(); } }
/** * Kill the given ZK session * * @param client the client to kill * @param connectString server connection string * @param maxMs max time ms to wait for kill * @throws Exception errors */ public static void kill(ZooKeeper client, String connectString, int maxMs) { // long startTicks = DateTime.Now.Ticks / 1000; // Barrier sessionLostLatch = new Barrier(2); // Watcher sessionLostWatch = new BarrierWatcher(sessionLostLatch); // client.existsAsync("/___CURATOR_KILL_SESSION___" + DateTime.Now.Ticks, // sessionLostWatch) // .Wait(); Barrier connectionLatch = new Barrier(2); Watcher connectionWatcher = new SyncWatcher(connectionLatch); ZooKeeper zk = new ZooKeeper(connectString, maxMs, connectionWatcher, client.getSessionId(), client.getSessionPasswd()); try { if ( !connectionLatch.SignalAndWait(maxMs) ) { throw new Exception("KillSession could not establish duplicate session"); } try { zk.closeAsync().Wait(); } finally { zk = null; } // while ( client.getState() == ZooKeeper.States.CONNECTED // && !sessionLostLatch.SignalAndWait(100) ) // { // long elapsed = (DateTime.Now.Ticks / 1000) - startTicks; // if ( elapsed > maxMs ) // { // throw new Exception("KillSession timed out waiting for session to expire"); // } // } } finally { zk?.closeAsync().Wait(); } }