Example #1
0
        public async Task <NodeStatus> GetNodeStatusAsync([NotNull] string path)
        {
            ValidateState();
            var stat = await _zk.existsAsync(path, true);

            return(stat == null ? null : new NodeStatus(stat));
        }
Example #2
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();
        }
Example #3
0
        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();
        }
Example #4
0
        private async Task CreateSubdirectory(ZooKeeper zooKeeper, string path)
        {
            if (await zooKeeper.existsAsync(path) != null)
            {
                return;
            }

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation($"节点{path}不存在,将进行创建。");
            }

            var childrens = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            var nodePath  = "/";

            foreach (var children in childrens)
            {
                nodePath += children;
                if (await zooKeeper.existsAsync(nodePath) == null)
                {
                    await zooKeeper.createAsync(nodePath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }
                nodePath += "/";
            }
        }
Example #5
0
        /// <summary>
        /// 请求一个任务
        /// </summary>
        /// <param name="taskType">任务类型</param>
        /// <param name="taskId">任务ID</param>
        /// <returns>是否请求成功</returns>
        public bool RequireTask(string majorTaskId, string taskId, string serviceId)
        {
            try
            {
                var taskTodoPath = ConstData.TodoTaskPath.Format(majorTaskId, taskId);
                var path         = ConstData.InProgressPath.Format(majorTaskId, taskId);
                // 待办路径不存在,请求任务失败
                if (zkClient.existsAsync(taskTodoPath).GetAwaiter().GetResult() == null)
                {
                    return(false);
                }

                if (zkClient.existsAsync(path).GetAwaiter().GetResult() == null)
                {
                    ensurePath(path);
                    zkClient.createAsync(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL).GetAwaiter().GetResult();
                    return(true);
                }

                return(false);
            }
            catch (KeeperException.NodeExistsException)
            {
                return(false);
            }
        }
Example #6
0
        private string OpenNode(string nodename)
        {
            string result     = "";
            Stat   NodeExists = null;

            while (NodeExists == null)
            {
                try
                {
                    NodeExists = _client.existsAsync(nodename).Result;
                    if (NodeExists == null)
                    {
                        result = _client.createAsync(nodename, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT).Result;
                    }
                    else
                    {
                        result = nodename;
                    }
                }
                catch (Exception ex)
                {
                    if (ex.Message.IndexOf("NodeExistsException") == -1)
                    {
                        throw ex;
                    }
                }
            }
            _client.existsAsync(nodename, true);
            return(result);
        }
Example #7
0
        /// <summary>
        ///     初始化
        /// </summary>
        public void Initialize(string hostName, TcpUri basicCommunicationAddress)
        {
            _basePath = SystemWorker.ConfigurationProxy.GetField("kae-system", "ZooKeeperBasePath", false);
            if (_client.existsAsync(_basePath, false).Result == null)
            {
                try { _client.createAsync(_basePath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT).Wait(); }
                catch (Exception) { }
            }
            //hosting node.
            string hostingPath = Path.Combine(_basePath, "hosting");

            hostingPath = hostingPath.Replace("\\", "/");
            if (_client.existsAsync(hostingPath, false).Result == null)
            {
                try { _client.createAsync(hostingPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT).Wait(); }
                catch (Exception) { }
            }
            //protocols node.
            _protocolPath = Path.Combine(_basePath, "protocols");
            _protocolPath = _protocolPath.Replace("\\", "/");
            if (_client.existsAsync(_protocolPath, false).Result == null)
            {
                try { _client.createAsync(_protocolPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT).Wait(); }
                catch (Exception) { }
            }
            //create resource node.
            string resourcePath = Path.Combine(_basePath, "hosting/", hostName);

            resourcePath = resourcePath.Replace("\\", "/");
            if (_client.existsAsync(resourcePath, false).Result == null)
            {
                try { _client.createAsync(resourcePath, Encoding.UTF8.GetBytes(basicCommunicationAddress.ToString()), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL).Wait(); }
                catch (Exception) { }
            }
        }
Example #8
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();
            }
        }
        /// <summary>
        /// 判断路径是否存在
        /// </summary>
        /// <param name="path"></param>
        /// <param name="watcher"></param>
        /// <returns></returns>
        public Stat Exists(string path, Watcher watcher = null)
        {
            if (watcher == null)
            {
                return(_zk.existsAsync(path).ConfigureAwait(false).GetAwaiter().GetResult());
            }

            return(_zk.existsAsync(path, watcher).ConfigureAwait(false).GetAwaiter().GetResult());
        }
        private async Task AddRootNode()
        {
            var rootNode = await _zookeeper.existsAsync(_nodeName);

            if (rootNode == null)
            {
                //Add application node
                await _zookeeper.createAsync(_nodeName, Encoding.UTF8.GetBytes(_nodeName), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
            _leaderCheckReady = true;
        }
Example #11
0
        //TODO: Func here
        //public Watcher wrapWatcher(final Watcher watcher) {

        /// <summary>
        /// Return the stat of the node of the given path. Return null if no such a
        /// node exists.
        /// If the watch is non-null and the call is successful (no exception is thrown),
        /// a watch will be left on the node with the given path. The watch will be
        /// triggered by a successful operation that creates/delete the node or sets
        /// the data on the node.
        /// </summary>
        /// <param name="path">The node path</param>
        /// <param name="watcher">Explicit watcher</param>
        /// <param name="retryOnConnLoss"></param>
        /// <returns>The stat of the node of the given path; return null if no such a node exists.</returns>
        /// <exception cref="KeeperException">If the server signals an error</exception>.
        public async Task <Stat> exists(string path, Watcher watcher, bool retryOnConnLoss)
        {
            if (retryOnConnLoss)
            {
                return(await _zkCmdExecutor.RetryOperation(async() => await keeper.existsAsync(path, watcher)));
            }
            else
            {
                return(await keeper.existsAsync(path, watcher));
            }
        }
Example #12
0
        public async Task testNullData()
        {
            const string path = "/SIZE";
            ZooKeeper    zk   = await createClient();

            await zk.createAsync(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

            // try sync zk exists
            await zk.existsAsync(path, false);

            Assert.assertTrue(await zk.existsAsync(path, false).WithTimeout(10 * 1000));
        }
        /// <summary>
        /// 判断节点是否存在
        /// </summary>
        /// <param name="path">不要使用path等关键字作为路径</param>
        /// <param name="watcher"></param>
        /// <returns></returns>
        public string ExistsNode(string path, Watcher watcher = null)
        {
            Task <org.apache.zookeeper.data.Stat> stat = _zooKeeper.existsAsync(path, watcher);

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

            return(_fail);
        }
Example #14
0
        /// <summary>
        /// 加锁方法
        /// </summary>
        /// <param name="lockname">锁名称</param>
        /// <returns>{加锁结果 Result ,锁id Id}</returns>
        public LockModel Lock(string lockname)
        {
            lock (_lockerList)
            {
                var node = _lockerList.FirstOrDefault(c => c.Name == lockname);
                if (node != null)
                {
                    return(new LockModel()
                    {
                        Result = LockResult.LockExists, Id = node.Id
                    });
                }
            }

            try
            {
                if (!string.IsNullOrWhiteSpace(_client.createAsync($"/locks/{lockname}", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL).Result))
                {
                    //增加监听
                    var watherResult = _client.existsAsync($"/locks/{lockname}", true).Result;

                    //增加到本地缓存
                    lock (_lockerList)
                    {
                        _lockerList.Add(new ZkLockerWatcher()
                        {
                            Name = lockname, Event = null, Id = watherResult?.getCtime() ?? 0
                        });
                    }

                    return(new LockModel()
                    {
                        Result = LockResult.Success, Id = watherResult.getCtime()
                    });
                }
                else
                {
                    return(new LockModel()
                    {
                        Result = LockResult.Fail, Id = 0
                    });
                }
            }
            catch (Exception)
            {
                return(new LockModel()
                {
                    Result = LockResult.Fail, Id = 0
                });
            }
        }
Example #15
0
        public static async Task <bool> ExistAsync_(this ZooKeeper client, string path, Watcher watcher = null)
        {
            if (watcher == null)
            {
                var res = await client.existsAsync(path, watch : false);

                return(res != null);
            }
            else
            {
                var res = await client.existsAsync(path, watcher);

                return(res != null);
            }
        }
Example #16
0
        private string OpenNode(string nodename)
        {
            string result     = "";
            Stat   NodeExists = null;

            while (NodeExists == null)
            {
                try
                {
                    NodeExists = _client.existsAsync(nodename).Result;
                    if (NodeExists == null)
                    {
                        result = _client.createAsync(nodename, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT).Result;
                    }
                    else
                    {
                        result = nodename;
                    }
                }
                catch (Exception ex)
                {
                    if (ex.HResult != (int)KeeperException.Code.NODEEXISTS)
                    {
                        throw ex;
                    }
                }
            }
            return(result);
        }
Example #17
0
        public async Task testNonExistingOpCode()
        {
            ZooKeeper zk = await createClient();

            const string path = "/m1";

            RequestHeader h = new RequestHeader();

            h.set_Type(888); // This code does not exists
            ExistsRequest request = new ExistsRequest();

            request.setPath(path);
            request.setWatch(false);
            ExistsResponse response = new ExistsResponse();
            ReplyHeader    r        = await zk.cnxn.submitRequest(h, request, response, null);

            Assert.assertEquals(r.getErr(), (int)KeeperException.Code.UNIMPLEMENTED);

            try {
                await zk.existsAsync("/m1", false);

                Assert.fail("The connection should have been closed");
            }
            catch (KeeperException.ConnectionLossException) {
            }
        }
Example #18
0
        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());
            }
        }
Example #19
0
        private async Task becomeReady(LeaderOffer neighborLeaderOffer)
        {
            await dispatchEvent(ElectionEventType.READY_START).ConfigureAwait(false);

            logger.debugFormat("{0} not elected leader. Watching node:{1}", leaderOffer.NodePath,
                               neighborLeaderOffer.NodePath);

            /*
             * Make sure to pass an explicit Watcher because we could be sharing this
             * zooKeeper instance with someone else.
             */
            var stat = await ZooKeeper.existsAsync(neighborLeaderOffer.NodePath, electionWatcher).ConfigureAwait(false);

            if (stat != null)
            {
                logger.debugFormat("We're behind {0} in line and they're alive. Keeping an eye on them.",
                                   neighborLeaderOffer.NodePath);
                state = State.READY;
                await dispatchEvent(ElectionEventType.READY_COMPLETE).ConfigureAwait(false);
            }
            else
            {
                /*
                 * If the stat fails, the node has gone missing between the call to
                 * getChildren() and exists(). We need to try and become the leader.
                 */
                logger.debugFormat("We were behind {0} but it looks like they died. Back to determination.",
                                   neighborLeaderOffer.NodePath);
                await determineElectionStatus().ConfigureAwait(false);
            }
        }
Example #20
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));
        }
Example #21
0
        private void Init()
        {
            try
            {
                connectionResetEvent = new AutoResetEvent(false);

                zk = new ZooKeeper(config, SessionTimeout, this);
                Trace.WriteLine($"ThreadID: {Thread.CurrentThread.ManagedThreadId} zk connect");

                //由于ZK客户端连接服务器是异步的,因此,此处阻塞线程,
                //防止连接还没有建立就调用ZK客户端导致异常;
                connectionResetEvent.WaitOne();
                connectionResetEvent.Dispose();
                connectionResetEvent = null;

                var stat = zk.existsAsync(rootNode, false).Sync();
                if (stat == null)
                {
                    // 创建根节点
                    zk.createAsync(rootNode, EmptyData, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT).Sync();
                }
            }
            catch (KeeperException e)
            {
                throw e;
            }
        }
Example #22
0
         /// <summary>
         /// 判断节点是否存在
         /// </summary>
         /// <param name="path">不要使用path等关键字作为路径</param>
         /// <param name="watcher"></param>
         /// <returns></returns>
         public string ExistsNode(string path, Watcher watcher = null)
 {
     try
     {
         Task <org.apache.zookeeper.data.Stat> stat = _zooKeeper.existsAsync(path, watcher);
         stat.Wait();
         if (stat.Result != null && stat.Status.ToString().ToLower() == "RanToCompletion".ToLower())
         {
             return(_success);
         }
     }
     catch (Exception ex)
     {
         _log.ErrorFormat("判定节点存在与否发生异常:{0},{1}", path, ex.Message + ex.StackTrace);
     }
     return(_fail);
 }
Example #23
0
 public ZkLocker(string lockName, ZkOption option, int lockTimeout = 5000)
 {
     _client = option.SessionId == long.MinValue
         ? new ZooKeeper(option.ConnectionsString, option.SessionTimeout, this, option.CanBeReadOnly)
         : new ZooKeeper(option.ConnectionsString, option.SessionTimeout, this, option.SessionId,
                         option.SessionPassword, option.CanBeReadOnly);
     if (_client.existsAsync("/locks").Result == null)
     {
         _client.createAsync("/locks", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT).Wait();
     }
     if (_client.existsAsync("/locks/" + lockName).Result == null)
     {
         _client.createAsync("/locks/" + lockName, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT).Wait();
     }
     _lockName    = lockName;
     _lockTimeout = lockTimeout;
 }
Example #24
0
        /// <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("路由配置清空完成。");
            }
        }
Example #25
0
        /**
         * Make sure all the nodes in the path are created. NOTE: Unlike File.mkdirs(), Zookeeper doesn't distinguish
         * between directories and files. So, every node in the path is created. The data for each node is an empty blob
         *
         * @param zookeeper    the client
         * @param path         path to ensure
         * @param makeLastNode if true, all nodes are created. If false, only the parent nodes are created
         * @param aclProvider  if not null, the ACL provider to use when creating parent nodes
         * @param asContainers if true, nodes are created as {@link CreateMode#CONTAINER}
         * @throws InterruptedException                 thread interruption
         * @throws org.apache.zookeeper.KeeperException Zookeeper errors
         */
        public static async void mkdirs(ZooKeeper zookeeper,
                                        String path,
                                        bool makeLastNode,
                                        IInternalACLProvider aclProvider,
                                        bool asContainers)
        {
            PathUtils.validatePath(path);

            int pos = 1; // skip first slash, root is guaranteed to exist

            do
            {
                pos = path.IndexOf(PATH_SEPARATOR, pos + 1);

                if (pos == -1)
                {
                    if (makeLastNode)
                    {
                        pos = path.Length;
                    }
                    else
                    {
                        break;
                    }
                }

                String subPath = path.Substring(0, pos);
                if (await zookeeper.existsAsync(subPath, false) == null)
                {
                    try
                    {
                        IList <ACL> acl = null;
                        if (aclProvider != null)
                        {
                            acl = aclProvider.getAclForPath(subPath);
                            if (acl == null)
                            {
                                acl = aclProvider.getDefaultAcl();
                            }
                        }
                        if (acl == null)
                        {
                            acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
                        }
                        await zookeeper.createAsync(subPath,
                                                    new byte[0],
                                                    acl.ToList(),
                                                    getCreateMode(asContainers))
                        .ConfigureAwait(false);
                    }
                    catch (KeeperException.NodeExistsException)
                    {
                        // ignore... someone else has created it since we checked
                    }
                }
            }while (pos < path.Length);
        }
Example #26
0
        protected virtual void CreateRootNodeIfNotExist(string nodeName)
        {
            var stat = zk.existsAsync(nodeName, false).Sync();

            if (stat == null)
            {
                var nodePath = zk.createAsync(nodeName, ZooKeeperDefaults.EmptyData, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT).Sync();
                SafeLog($"create znode {nodePath}");
            }
        }
Example #27
0
        public ZookeeperDistributedLock()
        {
            zk = new ZooKeeper(zooKeeperConnectstring, 60 * 1000, NullWatcher.Instance);

            var stat = zk.existsAsync(lockRoot, true).Run();

            if (stat == null)
            {
                zk.createAsync(lockRoot, EmptyData, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT).Run();
            }
        }
        public Task <DataResult> GetDataAsync(string path, Watcher watcher, bool isSync)
        {
            ReConn();
            if (_zookeeper.existsAsync(path).Result == null)
            {
                _logger.LogDebug("path不存在");
                return(null);
            }
            if (isSync)
            {
                _logger.LogDebug("即将进行同步。");
                var task = Task.Run(async() => {
                    await _zookeeper.sync(path);
                });
                task.Wait();
            }


            return(_zookeeper.getDataAsync(path, watcher));
        }
Example #29
0
            public async Task <bool> execute()
            {
                Stat stat = await zookeeper.existsAsync(path).ConfigureAwait(false);

                if (stat != null)
                {
                    return(true);
                }
                await zookeeper.createAsync(path, data, acl, flags).ConfigureAwait(false);

                return(true);
            }
        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");
        }
Example #31
0
    /**
     * Make sure all the nodes in the path are created. NOTE: Unlike File.mkdirs(), Zookeeper doesn't distinguish
     * between directories and files. So, every node in the path is created. The data for each node is an empty blob
     *
     * @param zookeeper    the client
     * @param path         path to ensure
     * @param makeLastNode if true, all nodes are created. If false, only the parent nodes are created
     * @param aclProvider  if not null, the ACL provider to use when creating parent nodes
     * @param asContainers if true, nodes are created as {@link CreateMode#CONTAINER}
     * @throws InterruptedException                 thread interruption
     * @throws org.apache.zookeeper.KeeperException Zookeeper errors
     */
    public static async void mkdirs(ZooKeeper zookeeper, 
                                String path, 
                                bool makeLastNode, 
                                IInternalACLProvider aclProvider, 
                                bool asContainers)
    {
        PathUtils.validatePath(path);

        int pos = 1; // skip first slash, root is guaranteed to exist
        do
        {
            pos = path.IndexOf(PATH_SEPARATOR, pos + 1);

            if ( pos == -1 )
            {
                if ( makeLastNode )
                {
                    pos = path.Length;
                }
                else
                {
                    break;
                }
            }

            String subPath = path.Substring(0, pos);
            if ( await zookeeper.existsAsync(subPath, false) == null )
            {
                try
                {
                    IList<ACL> acl = null;
                    if ( aclProvider != null )
                    {
                        acl = aclProvider.getAclForPath(subPath);
                        if ( acl == null )
                        {
                            acl = aclProvider.getDefaultAcl();
                        }
                    }
                    if ( acl == null )
                    {
                        acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
                    }
                    await zookeeper.createAsync(subPath,
                                                new byte[0],
                                                acl.ToList(),
                                                getCreateMode(asContainers))
                                    .ConfigureAwait(false);
                }
                catch ( KeeperException.NodeExistsException)
                {
                    // ignore... someone else has created it since we checked
                }
            }

        }
        while ( pos<path.Length );
    }