예제 #1
0
        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);
        }
        /// <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("路由配置清空完成。");
        }
예제 #3
0
        /// <summary>
        /// 获取子节点列表
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="watcher">监听的watcher</param>
        /// <returns>返回节点列表</returns>
        public static List <string> GetChildrenNode(string path, Watcher watcher = null)
        {
            logger.LogInformation($"GetChildrenNode 开始获取数据:{path}");
            int tryNum = 0;

gotoLable:
            try
            {
                var result = watcher == null
                    ? currentZookeeper.getChildrenAsync(path, false)
                    : currentZookeeper.getChildrenAsync(path, watcher);

                result.Wait();
                logger.LogInformation($"GetChildrenNode 获取到的数据是:{path}----{string.Join(",", result?.Result?.Children?.ToArray())}");
                return(result?.Result?.Children);
            }
            catch (KeeperException.NoNodeException)
            {
                logger.LogError("GrantZookeeperManager.GetChildrenNode.Error,NoNodeException");
            }
            catch (Exception e)
            {
                tryNum += 1;
                if (tryNum < 3)
                {
                    reConnection(e);
                    Thread.Sleep(500);
                    goto gotoLable;
                }
                logger.LogError(e, $"GetChildrenNode 获取数据异常:{path}");
            }

            return(null);
        }
예제 #4
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="path"></param>
 /// <param name="watcher"></param>
 /// <param name="retryOnConnLoss"></param>
 /// <returns>Returns children of the node at the path</returns>
 public async Task <List <string> > getChildren(string path, Watcher watcher, bool retryOnConnLoss)
 {
     if (retryOnConnLoss)
     {
         return(await _zkCmdExecutor.RetryOperation(async() => (await keeper.getChildrenAsync(path, null)).Children));
     }
     else
     {
         return((await keeper.getChildrenAsync(path, watcher)).Children);
     }
 }
예제 #5
0
        public async Task <List <string> > GetSortedChildren(string lockName, ILockInternalsSorter sorter)
        {
            var children = await _zkClient.getChildrenAsync(_basePath);

            children.Children.Sort((x, y) =>
            {
                return(sorter.FixForSorting(x, lockName)
                       .CompareTo(sorter.FixForSorting(y, lockName)));
            });

            return(children.Children);
        }
예제 #6
0
        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());
            }
        }
예제 #7
0
        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();
        }
예제 #8
0
        public async Task testDeleteRecursive()
        {
            ZooKeeper zk = await createClient();

            // making sure setdata works on /
            await zk.setDataAsync("/", "some".UTF8getBytes(), -1);

            await zk.createAsync("/a", "some".UTF8getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

            await zk.createAsync("/a/b", "some".UTF8getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

            await zk.createAsync("/a/b/v", "some".UTF8getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

            await zk.createAsync("/a/b/v/1", "some".UTF8getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

            await zk.createAsync("/a/c", "some".UTF8getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

            await zk.createAsync("/a/c/v", "some".UTF8getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

            IList <string> children = (await zk.getChildrenAsync("/a", false)).Children;

            Assert.assertEquals("2 children - b & c should be present ", children.Count, 2);
            Assert.assertTrue(children.Contains("b"));
            Assert.assertTrue(children.Contains("c"));

            ZKUtil.deleteRecursiveAsync(zk, "/a").GetAwaiter().GetResult();
            Assert.assertNull(await zk.existsAsync("/a", null));
        }
        public async Task <ChildrenResult> GetChildrenAsync(string path, Watcher watcher, bool isSync)
        {
            ReConn();
            if (await _zookeeper.existsAsync(path) == null)
            {
                _logger.LogInformation("path不存在");
                return(null);
            }
            if (isSync)
            {
                _logger.LogInformation("即将进行同步。");
                try
                {
                    _logger.LogInformation("开始同步");
                    await _zookeeper.sync(path);

                    _logger.LogInformation("同步成功");
                }
                catch (Exception ep)
                {
                    _logger.LogError("同步失败。", ep);
                }
            }
            return(await _zookeeper.getChildrenAsync(path, watcher));
        }
예제 #10
0
        private static void ReadVnetThread(object o)
        {
            var input     = o as Tuple <string, IEnumerable <string> >;
            var endpoints = input.Item1;
            var vnets     = input.Item2;

            var zk   = new ZooKeeper((string)endpoints, 10000, null);
            var acls = new List <ACL> {
                new ACL((int)ZooDefs.Perms.ALL, ZooDefs.Ids.ANYONE_ID_UNSAFE),
            };

            foreach (var vnet in vnets)
            {
                ReadInternal(vnet).GetAwaiter().GetResult();
            }

            Interlocked.Increment(ref threadFinished);

            async Task ReadInternal(string vnet)
            {
                var parent   = string.Join("/", vnet, "mappings", "v4ca");
                var children = (await zk.getChildrenAsync(parent)).Children;
                var tasks    = children.Select(child => zk.getDataAsync(string.Join("/", parent, child)));
                await Task.WhenAll(tasks);

                Interlocked.Add(ref nodeCount, children.Count + 1);
            }
        }
예제 #11
0
        public async Task <List <string> > GetChildrenAsync([NotNull] string path)
        {
            ValidateState();
            var childrenResult = await _zk.getChildrenAsync(path, true);

            return(childrenResult.Children);
        }
예제 #12
0
        /**
         * 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
                }
            }
        }
예제 #13
0
            /// <summary>
            /// find if we have been created earler if not create our node
            /// </summary>
            /// <param name="prefix"> the prefix node </param>
            /// <param name="zookeeper"> teh zookeeper client </param>
            /// <param name="dir"> the dir paretn </param>
            /// <exception cref="KeeperException"> </exception>
            private async Task findPrefixInChildren(string prefix, ZooKeeper zookeeper, string dir)
            {
                IList <string> names = (await zookeeper.getChildrenAsync(dir).ConfigureAwait(false)).Children;

                foreach (string name in names)
                {
                    if (name.StartsWith(prefix, StringComparison.Ordinal))
                    {
                        writeLock.Id = name;
                        if (LOG.isDebugEnabled())
                        {
                            LOG.debug("Found id created last time: " + writeLock.Id);
                        }
                        break;
                    }
                }
                if (writeLock.Id == null)
                {
                    writeLock.Id = await zookeeper.createAsync(dir + "/" + prefix, writeLock.data, writeLock.Acl, CreateMode.EPHEMERAL_SEQUENTIAL).ConfigureAwait(false);

                    if (LOG.isDebugEnabled())
                    {
                        LOG.debug("Created id: " + writeLock.Id);
                    }
                }
            }
예제 #14
0
        /// <summary>
        /// BFS Traversal of the system under pathRoot, with the entries in the list, in the
        /// same order as that of the traversal.
        /// <para>
        /// <b>Important:</b> This is <i>not an atomic snapshot</i> of the tree ever, but the
        ///  state as it exists across multiple RPCs from zkClient to the ensemble.
        /// For practical purposes, it is suggested to bring the clients to the ensemble
        /// down (i.e. prevent writes to pathRoot) to 'simulate' a snapshot behavior.
        ///
        /// </para>
        /// </summary>
        /// <param name="zk"> the zookeeper handle </param>
        /// <param name="pathRoot"> The znode path, for which the entire subtree needs to be listed. </param>
        /// <exception cref="KeeperException">  </exception>
        public static async Task <List <string> > listSubTreeBFS(ZooKeeper zk, string pathRoot)
        {
            Queue <string> queue = new Queue <string>();
            List <string>  tree  = new List <string>();

            queue.Enqueue(pathRoot);
            tree.Add(pathRoot);
            while (true)
            {
                string node;
                if (queue.Count == 0)
                {
                    break;
                }
                node = queue.Dequeue();
                IList <string> children = (await zk.getChildrenAsync(node).ConfigureAwait(false)).Children;
                foreach (string child in children)
                {
                    string childPath = node + "/" + child;
                    queue.Enqueue(childPath);
                    tree.Add(childPath);
                }
            }
            return(tree);
        }
예제 #15
0
        //得到node下所有注册的服务节点列表,连接异常的话重试4回
        private ChildrenResult GetChild(ref ZooKeeper zk, string node, Watcher watcher, int runcnt = 0)
        {
            if (zk == null)
            {
                zk = createClientForCall(watcher);
            }
            ChildrenResult children;

            try
            {
                var state = zk.getState();
                if (state != ZooKeeper.States.CONNECTED)
                {
                    zk = createClientForCall(watcher);
                }
                children = zk.getChildrenAsync(node, true).Result;
            }
            catch (AggregateException ex)
            {
                if (runcnt <= 4) //4次机会重发,每次等待2*失败次数的时间
                {
                    runcnt++;
                    Thread.Sleep(1500 * runcnt);
                    children = GetChild(ref zk, node, watcher, runcnt);
                }
                else
                {
                    children = null;
                }
            }
            return(children);
        }
예제 #16
0
        /// <summary>
        /// Returns a Map of the children, ordered by id. </summary>
        /// <param name="watcher"> optional watcher on getChildren() operation. </param>
        /// <returns> map from id to child name for all children </returns>
        private async Task <SortedDictionary <long, string> > getOrderedChildren(Watcher watcher)
        {
            SortedDictionary <long, string> orderedChildren = new SortedDictionary <long, string>();

            List <string> childNames = (await zookeeper.getChildrenAsync(dir, watcher).ConfigureAwait(false)).Children;

            foreach (string childName in childNames)
            {
                try
                {
                    //Check format
                    if (!childName.StartsWith(prefix, StringComparison.Ordinal))
                    {
                        LOG.warn("Found child node with improper name: " + childName);
                        continue;
                    }
                    string suffix  = childName.Substring(prefix.Length);
                    long   childId = long.Parse(suffix);
                    orderedChildren[childId] = childName;
                }
                catch (FormatException e)
                {
                    LOG.warn("Found child node with improper format : " + childName + " " + e, e);
                }
            }

            return(orderedChildren);
        }
예제 #17
0
        private static async Task visitSubTreeDFSHelper(ZooKeeper zk, string path, bool watch, Func <string, Task> visit)
        {
            // we've already validated, therefore if the path is of length 1 it's the root
            bool isRoot = path.Length == 1;

            try
            {
                var childrenResult = await zk.getChildrenAsync(path, watch).ConfigureAwait(false);

                List <string> childrenPaths = childrenResult.Children.Select(child => (isRoot ? path : path + "/") + child).ToList();
                childrenPaths.Sort();

                foreach (string childPath in childrenPaths)
                {
                    await visit(childPath).ConfigureAwait(false);
                }

                foreach (string childPath in childrenPaths)
                {
                    await visitSubTreeDFSHelper(zk, childPath, watch, visit).ConfigureAwait(false);
                }
            }
            catch (KeeperException.NoNodeException)
            {
                // Handle race condition where a node is listed
                // but gets deleted before it can be queried
            }
        }
        private async Task <IEnumerable <(string key, string value)> > GetData(ZooKeeper zk)
        {
            ChildrenResult childrenResult = await zk.getChildrenAsync(_options.Path);

            IEnumerable <Task <IEnumerable <(string key, string value)> > > getAllChildrenTask = childrenResult.Children
                                                                                                 .Select(child => GetData(zk, _options.Path + '/' + child));

            IEnumerable <(string key, string value)>[] result = await Task.WhenAll(getAllChildrenTask);
예제 #19
0
        /// <summary>
        /// Get Live nodes from zookeeper
        /// </summary>
        private async Task <List <string> > GetLiveNodesAsync()
        {
            List <string> result;

            try
            {
                var liveNodesChildren = await zooKeeper.getChildrenAsync($"{LiveNodesZkNode}", this).ConfigureAwait(false);

                result = new List <string>(liveNodesChildren.Children);
            }
            catch (KeeperException)
            {
                result = new List <string>();
            }

            return(result);
        }
예제 #20
0
        public static async Task <List <string> > GetNodeChildren(this ZooKeeper client, string path, Watcher watcher = null)
        {
            __check_path__(path);

            var res = watcher == null ?
                      await client.getChildrenAsync(path, watch : false) :
                      await client.getChildrenAsync(path, watcher);

            if (res.Stat == null)
            {
                throw new Exception("读取子节点状态为空");
            }

            return(res.Children ?? new List <string>()
            {
            });
        }
예제 #21
0
        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();
            }
        }
예제 #22
0
        /**
         * Return the children of the given path sorted by sequence number
         *
         * @param zookeeper the client
         * @param path      the path
         * @return sorted list of children
         * @throws InterruptedException                 thread interruption
         * @throws org.apache.zookeeper.KeeperException zookeeper errors
         */
        public static async Task <List <string> > getSortedChildren(ZooKeeper zookeeper, String path)
        {
            ChildrenResult children = await zookeeper.getChildrenAsync(path, false);

            List <string> sortedList = new List <string>(children.Children);

            sortedList.Sort();
            return(sortedList);
        }
        /// <summary>
        /// 获取指定父节点下的子节点
        /// </summary>
        /// <param name="keeper"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static async Task <IReadOnlyList <string> > GetChildren(this ZooKeeper keeper, ZookeeperPathString path)
        {
            if (await keeper.ExistAsync(path))
            {
                var chid = await keeper.getChildrenAsync(path, true);

                return(chid.Children);
            }
            return(Array.Empty <string>());
        }
예제 #24
0
        private async Task <List <string> > GetChildrenAsync(string path, bool watch = false)
        {
            var childResult = await _zooKeeper.getChildrenAsync(path, watch);

            if (childResult == null)
            {
                return(null);
            }
            return(childResult.Children);
        }
예제 #25
0
        protected override async Task ProcessImpl(WatchedEvent watchedEvent)
        {
            var path = Path;
            Func <ChildrenMonitorWatcher> getWatcher = () => new ChildrenMonitorWatcher(_zooKeeper, path, _action);

            switch (watchedEvent.get_Type())
            {
            //创建之后开始监视下面的子节点情况。
            case Event.EventType.NodeCreated:
                await _zooKeeper.getChildrenAsync(path, getWatcher());

                break;

            //子节点修改则继续监控子节点信息并通知客户端数据变更。
            case Event.EventType.NodeChildrenChanged:
                try
                {
                    var watcher = getWatcher();
                    var result  = await _zooKeeper.getChildrenAsync(path, watcher);

                    var childrens = result.Children.ToArray();
                    _action(_currentData, childrens);
                    watcher.SetCurrentData(childrens);
                }
                catch (KeeperException.NoNodeException)
                {
                    _action(_currentData, new string[0]);
                }
                break;

            //删除之后开始监控自身节点,并通知客户端数据被清空。
            case Event.EventType.NodeDeleted:
            {
                var watcher = getWatcher();
                await _zooKeeper.existsAsync(path, watcher);

                _action(_currentData, new string[0]);
                watcher.SetCurrentData(new string[0]);
            }
            break;
            }
        }
예제 #26
0
        /// <summary>
        ///     Fetch the (user supplied) hostname of the current leader. Note that by the
        ///     time this method returns, state could have changed so do not depend on this
        ///     to be strongly consistent. This method has to read all leader offers from
        ///     ZooKeeper to deterime who the leader is (i.e. there is no caching) so
        ///     consider the performance implications of frequent invocation. If there are
        ///     no leader offers this method returns null.
        /// </summary>
        /// <returns> hostname of the current leader </returns>
        /// <exception cref="KeeperException"> </exception>
        public async Task <string> getLeaderHostName()
        {
            var leaderOffers = await toLeaderOffers((await ZooKeeper.getChildrenAsync(RootNodeName).ConfigureAwait(false)).Children).ConfigureAwait(false);

            if (leaderOffers.Count > 0)
            {
                return(leaderOffers[0].HostName);
            }

            return(null);
        }
예제 #27
0
        public async Task testSequentialNodeNames()
        {
            string path     = "/SEQUENCE";
            string file     = "TEST";
            string filepath = path + "/" + file;

            ZooKeeper zk = await createClient();

            await zk.createAsync(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

            await zk.createAsync(filepath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);

            IList <string> children = (await zk.getChildrenAsync(path, false)).Children;

            Assert.assertEquals(1, children.Count);
            Assert.assertEquals(file + "0000000000", children[0]);

            await zk.createAsync(filepath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);

            children = (await zk.getChildrenAsync(path, false)).Children;
            Assert.assertEquals(2, children.Count);
            Assert.assertTrue("contains child 1", children.Contains(file + "0000000001"));

            await zk.createAsync(filepath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);

            children = (await zk.getChildrenAsync(path, false)).Children;
            Assert.assertEquals(3, children.Count);
            Assert.assertTrue("contains child 2",
                              children.Contains(file + "0000000002"));

            // The pattern is holding so far.  Let's run the counter a bit
            // to be sure it continues to spit out the correct answer
            for (int i = children.Count; i < 105; i++)
            {
                await zk.createAsync(filepath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
            }

            children = (await zk.getChildrenAsync(path, false)).Children;
            Assert.assertTrue("contains child 104",
                              children.Contains(file + "0000000104"));
        }
예제 #28
0
        private bool SetServerConfig(Config.Service service)
        {
            try
            {
                if (_zk == null)
                {
                    _zk = new ZooKeeper(service.ZookeeperConfig.Host, service.ZookeeperConfig.SessionTimeout, this);

                    int count = 0;
                    while (_zk.getState() != ZooKeeper.States.CONNECTED)
                    {
                        if (count++ > 50)
                        {
                            throw new Exception("ZooKeeper 连接失败");
                        }
                        System.Threading.Thread.Sleep(100);
                    }
                }

                _defaultHost = service.Host;
                var children = _zk.getChildrenAsync(service.ZookeeperConfig.NodeParent, this).Result.Children;
                if (children != null && children.Count > 0)
                {
                    service.Host = string.Join(",", children);
                }

                if (!_firstGetConfig) //首次连接,不需要执行更新方法。
                {
                    if (_updateHostDelegate != null)
                    {
                        _updateHostDelegate();
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                ThriftLog.Error(ex.Message + ex.StackTrace);
                return(false);
            }
        }
        /// <summary>
        /// 得到后代节点路径
        /// </summary>
        /// <param name="path">不要使用path等关键字作为路径</param>
        /// <param name="watcher"></param>
        /// <returns></returns>
        public List <string> GetChildren(string path, Watcher watcher = null)
        {
            Task <ChildrenResult> childrenResult = _zooKeeper.getChildrenAsync(path, watcher);

            childrenResult.Wait();
            if (childrenResult.Result != null && childrenResult.Status.ToString().ToLower() == "RanToCompletion".ToLower())
            {
                return(childrenResult.Result.Children);
            }

            return(null);
        }
예제 #30
0
 public List <string> GetServerList()
 {
     try
     {
         //get old Version
         return(_client.getChildrenAsync($"{Root}", true).Result.Children);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
예제 #31
0
 /**
  * Return the children of the given path sorted by sequence number
  *
  * @param zookeeper the client
  * @param path      the path
  * @return sorted list of children
  * @throws InterruptedException                 thread interruption
  * @throws org.apache.zookeeper.KeeperException zookeeper errors
  */
 public static async Task<List<string>> getSortedChildren(ZooKeeper zookeeper, String path)
 {
     ChildrenResult children = await zookeeper.getChildrenAsync(path, false);
     List<string> sortedList = new List<string>(children.Children);
     sortedList.Sort();
     return sortedList;
 }
예제 #32
0
        /// <summary>
        ///     Return the children of the given path sorted by sequence number
        /// </summary>
        /// <param name="zookeeper"> the client </param>
        /// <param name="path">      the path </param>
        /// <returns> sorted list of children </returns>
        /// <exception cref="InterruptedException">                 thread interruption </exception>
        /// <exception cref="org.apache.zookeeper.KeeperException"> zookeeper errors </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public static java.util.List<String> getSortedChildren(org.apache.zookeeper.ZooKeeper zookeeper, String path) throws InterruptedException, org.apache.zookeeper.KeeperException
        public static async Task<IList<string>> getSortedChildren(ZooKeeper zookeeper, string path)
        {
            IList<string> children = (await zookeeper.getChildrenAsync(path, false)).Children;
            var sortedList = new List<string>(children);
            sortedList.Sort();
            return sortedList;
        }
예제 #33
0
        /// <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
                }
            }
        }
예제 #34
0
    /**
     * 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
            }
        }
    }