Пример #1
0
        public async Task DeleteResourceAsync(string group, string resourceName)
        {
            while (true)
            {
                try
                {
                    var childrenRes = await zookeeper.getChildrenAsync($"{zkRootPath}/{group}/resources/{resourceName}");

                    foreach (var child in childrenRes.Children)
                    {
                        await SafeDelete($"{zkRootPath}/{group}/resources/{resourceName}/{child}");
                    }

                    await SafeDelete($"{zkRootPath}/{group}/resources/{resourceName}");

                    return;
                }
                catch (KeeperException.NoNodeException)
                {
                    return;
                }
                catch (KeeperException.ConnectionLossException)
                {
                }
                catch (KeeperException.SessionExpiredException)
                {
                    await EstablishSession();
                }
            }
        }
Пример #2
0
        private async Task LoadNode(org.apache.zookeeper.ZooKeeper zk, Node node)
        {
            var result = await zk.getChildrenAsync(node.Path);

            if (result != null)
            {
                node.NodeState = NodeState.Build(result.Stat);
                foreach (var child in result.Children)
                {
                    var childNode = new Node
                    {
                        Text = child
                    };

                    if (node.Path != "/")
                    {
                        childNode.Path = node.Path + "/" + child;
                    }
                    else
                    {
                        childNode.Path = node.Path + child;
                    }
                    await LoadNode(zk, childNode);

                    if (node.Nodes == null)
                    {
                        node.Nodes = new List <Node>();
                    }
                    node.Nodes.Add(childNode);
                }
            }
        }
        protected static void EnsureChildrenExists(org.apache.zookeeper.ZooKeeper client, string rootNode, string[] children)
        {
            var getChildrenResult = client.getChildrenAsync(rootNode).GetAwaiter().GetResult();

            getChildrenResult.Children.Should().BeEquivalentTo(children);
            //getChildrenResult.EnsureSuccess();
            //getChildrenResult.Status.Should().Be(ZooKeeperStatus.Ok);
            //getChildrenResult.Path.Should().Be(rootNode);
            //getChildrenResult.Payload.Should().BeEquivalentTo(children);
        }
        protected static void EnsureChildrenExistWithCorrectStat(org.apache.zookeeper.ZooKeeper client, string rootNode, string[] children, int nodeVersion = 0, int childVersion = 0)
        {
            var getChildrenWithStatResult = client.getChildrenAsync(rootNode).GetAwaiter().GetResult();

            getChildrenWithStatResult.Children.Should().BeEquivalentTo(children);
            //getChildrenWithStatResult.Path.Should().Be(rootNode);
            //getChildrenWithStatResult.Status.Should().Be(ZooKeeperStatus.Ok);
            //getChildrenWithStatResult.Payload.Item1.Should().BeEquivalentTo(children);
            //getChildrenWithStatResult.Payload.Item2.Version.Should().Be(nodeVersion);
            //getChildrenWithStatResult.Payload.Item2.Cversion.Should().Be(childVersion);
        }
Пример #5
0
        public async Task Lock(string lockNode)
        {
            var node = $"{config.LockPath}/${lockNode}";

            await this.CreatNodeIfNotExist(node);

            var path = $"{config.LockPath}/${lockNode}/${config.Name}-";

            this.nodePath = await zooKeeper.createAsync(
                path,
                this.config.Name.ToBytes(),
                this.acls,
                ZK.CreateMode.EPHEMERAL_SEQUENTIAL);

            var index    = nodePath.GetIndex();
            var children = await zooKeeper.getChildrenAsync(node);

            var childrenIndex = children.Children.Select(p => new { Node = p, Index = p.GetIndex() }).OrderBy(p => p.Index).ToList();

            if (childrenIndex.First().Index == index)
            {
                Console.WriteLine($"{this.config.Name} Begin Lock");
                return;
            }

            var targetNode = string.Empty;

            for (int i = 0; i < childrenIndex.Count; i++)
            {
                if (childrenIndex[i].Index == index)
                {
                    targetNode = childrenIndex[i - 1].Node;
                    break;
                }
            }
            if (string.IsNullOrEmpty(targetNode))
            {
                throw new Exception("Node Get Error");
            }
            var tcs = new TaskCompletionSource <bool>();

            Console.WriteLine($"{this.config.Name} Wait for {node}/{targetNode}");
            var waitNode = await zooKeeper.existsAsync(
                $"{node}/{targetNode}",
                new WaitWatcher($"{node}/{targetNode}", tcs, e => e.get_Type() == EventType.NodeDeleted || e.getState() == KeeperState.Disconnected));

            if (waitNode != null)
            {
                await Task.WhenAny(Task.Delay(Timeout.Infinite), tcs.Task);
            }
            Console.WriteLine($"{this.config.Name} Begin Lock");
            return;
        }
Пример #6
0
        public static async Task DeleteRecursive(org.apache.zookeeper.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) { }
        }
Пример #7
0
        /// <summary>
        /// //
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>

        public async Task <bool> GetLock(string key)
        {
            var node = await _zooKeeper.createAsync($"/PessimisticLockV2/LOCK", Encoding.UTF8.GetBytes("1"),
                                                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);

            var children = await _zooKeeper.getChildrenAsync("/PessimisticLockV2");

            var minNode = children.Children.OrderBy(t => t).First();

            var res = ("/PessimisticLockV2/" + minNode).Equals(node);

            if (res)
            {
                await _zooKeeper.deleteAsync(node);//releaseLock

                return(true);
            }
            return(false);
        }
        public async Task <IActionResult> List()
        {
            var list = new List <Connection>();

            var connResult = await _zooKeeper.getChildrenAsync("/connections");

            foreach (var conn in connResult.Children)
            {
                var connData = await _zooKeeper.getDataAsync($"/connections/{conn}/value");

                var connStr = Encoding.UTF8.GetString(connData.Data);
                var item    = new Connection
                {
                    Id    = conn,
                    Value = connStr
                };
                list.Add(item);
            }

            return(Ok(list));
        }
Пример #9
0
        public async Task RefreshAsync()
        {
            var connDic = new Dictionary <string, string>();

            var isExisted = await _zooKeeper.existsAsync("/connections");

            if (isExisted == null)
            {
                await _zooKeeper.createAsync("/connections", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }

            var connResult = await _zooKeeper.getChildrenAsync("/connections", new ConnectionWatcher(this));

            foreach (var conn in connResult.Children)
            {
                var connData = await _zooKeeper.getDataAsync($"/connections/{conn}/value");

                var connStr = Encoding.UTF8.GetString(connData.Data);
                connDic[conn] = connStr;
            }

            _cache.Set("connections", connDic);
        }
Пример #10
0
        public async Task <ClientsZnode> GetActiveClientsAsync()
        {
            string actionToPerform = "get the list of active clients";

            while (true)
            {
                await BlockUntilConnected(actionToPerform);

                try
                {
                    ChildrenResult childrenResult = await zookeeper.getChildrenAsync(clientsPath);

                    List <string> childrenPaths = childrenResult.Children.Select(x => $"{clientsPath}/{x}").ToList();
                    return(new ClientsZnode {
                        Version = childrenResult.Stat.getVersion(), ClientPaths = childrenPaths
                    });
                }
                catch (KeeperException.NoNodeException e)
                {
                    throw new ZkInvalidOperationException(
                              $"Could not {actionToPerform} as the clients node does not exist.", e);
                }
                catch (KeeperException.ConnectionLossException)
                {
                    // do nothing, the next iteration will try again
                }
                catch (KeeperException.SessionExpiredException e)
                {
                    throw new ZkSessionExpiredException($"Could not {actionToPerform} as the session has expired: ", e);
                }
                catch (Exception e)
                {
                    throw new ZkInvalidOperationException($"Could not {actionToPerform} due to an unexpected error", e);
                }
            }
        }
Пример #11
0
 public async Task <List <string> > GetChildrenAsync(string path, bool watch)
 {
     return((await _zooKeeper.getChildrenAsync(path, watch)).Children);
 }
Пример #12
0
        /// <summary>
        /// 获取锁
        /// </summary>
        /// <param name="millisecondsTimeout">等待时间</param>
        /// <returns></returns>
        public async Task <bool> TryLock(int millisecondsTimeout = 0)
        {
            try
            {
                zooKeeper = new org.apache.zookeeper.ZooKeeper("127.0.0.1", 50000, new MyWatcher());

                //创建锁节点
                if (await zooKeeper.existsAsync("/Locks") == null)
                {
                    await zooKeeper.createAsync("/Locks", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }

                //新建一个临时锁节点
                lockNode = await zooKeeper.createAsync("/Locks/Lock_", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

                //获取锁下所有节点
                var lockNodes = await zooKeeper.getChildrenAsync("/Locks");

                lockNodes.Children.Sort();

                //判断如果创建的节点就是最小节点 返回锁
                if (lockNode.Split("/").Last() == lockNodes.Children[0])
                {
                    return(true);
                }
                else
                {
                    //当前节点的位置
                    var location = lockNodes.Children.FindIndex(n => n == lockNode.Split("/").Last());
                    //获取当前节点 前面一个节点的路径
                    var frontNodePath = lockNodes.Children[location - 1];
                    //在前面一个节点上加上Watcher ,当前面那个节点删除时,会触发Process方法
                    await zooKeeper.getDataAsync("/Locks/" + frontNodePath, myWatcher);

                    //如果时间为0 一直等待下去
                    if (millisecondsTimeout == 0)
                    {
                        myWatcher.AutoResetEvent.WaitOne();
                    }
                    else //如果时间不为0 等待指定时间后,返回结果
                    {
                        var result = myWatcher.AutoResetEvent.WaitOne(millisecondsTimeout);

                        if (result)//如果返回True,说明在指定时间内,前面的节点释放了锁(但是)
                        {
                            //获取锁下所有节点
                            lockNodes = await zooKeeper.getChildrenAsync("/Locks");

                            //判断如果创建的节点就是最小节点 返回锁
                            if (lockNode.Split("/").Last() == lockNodes.Children[0])
                            {
                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        }
                        else
                        {
                            return(false);
                        }
                    }
                }
            }
            catch (KeeperException e)
            {
                await UnLock();

                throw e;
            }
            return(false);
        }