示例#1
1
文件: Program.cs 项目: Indifer/Test
        static void Main(string[] args)
        {
             //创建一个Zookeeper实例,第一个参数为目标服务器地址和端口,第二个参数为Session超时时间,第三个为节点变化时的回调方法 
            using (ZooKeeper zk = new ZooKeeper("121.199.25.195:2181", new TimeSpan(0, 0, 0, 50000), new Watcher()))
            {
                var stat = zk.Exists("/root", true);

                //创建一个节点root,数据是mydata,不进行ACL权限控制,节点为永久性的(即客户端shutdown了也不会消失) 
                zk.Create("/root", "mydata".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);

                //在root下面创建一个childone znode,数据为childone,不进行ACL权限控制,节点为永久性的 
                zk.Create("/root/childone", "childone".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
                //取得/root节点下的子节点名称,返回List<String> 
                zk.GetChildren("/root", true);
                //取得/root/childone节点下的数据,返回byte[] 
                zk.GetData("/root/childone", true, null);

                //修改节点/root/childone下的数据,第三个参数为版本,如果是-1,那会无视被修改的数据版本,直接改掉
                zk.SetData("/root/childone", "childonemodify".GetBytes(), -1);
                //删除/root/childone这个节点,第二个参数为版本,-1的话直接删除,无视版本 
                zk.Delete("/root/childone", -1);
            }


        }
            protected override void ProcessImpl(WatchedEvent watchedEvent)
            {
                var path    = Path;
                var watcher = new ChildrenMonitorWatcher(_zooKeeper, path, _action);

                switch (watchedEvent.Type)
                {
                case EventType.NodeCreated:
                case EventType.NodeChildrenChanged:
                    if (_zooKeeper.Exists(path, watcher) != null)
                    {
                        var childrens = _zooKeeper.GetChildren(path, watcher, new Stat());
                        _action(childrens);
                    }
                    else
                    {
                        _action(null);
                    }
                    break;

                case EventType.NodeDeleted:
                    _zooKeeper.Exists(path, watcher);
                    _action(null);
                    break;
                }
            }
        /// <summary>
        ///     Checks whether znode for a given path exists.
        /// </summary>
        /// <param name="path">
        ///     The given path.
        /// </param>
        /// <param name="watch">
        ///     Indicates whether should reinstall watcher in ZooKeeper.
        /// </param>
        /// <returns>
        ///     Result of check
        /// </returns>
        public bool Exists(string path, bool watch)
        {
            Guard.NotNullNorEmpty(path, "path");

            EnsuresNotDisposedAndNotNull();
            return(_zkclient.Exists(path, true) != null);
        }
示例#4
0
 public void UpdateNode(string path, byte[] data)
 {
     if (!string.IsNullOrEmpty(path))
     {
         zk.SetData(path, data, zk.Exists(path, true).Version);
     }
 }
示例#5
0
        public bool AddNode(string nodePath, string nodeValue, ref string message)
        {
            try
            {
                using (ZooKeeper zk = new ZooKeeper(AppSettingsHelper.ZKServer, TimeSpan.FromSeconds(AppSettingsHelper.ZKSessionTimeOut), null))
                {
                    ZooKeeper.WaitUntilConnected(zk);

                    if (zk.Exists(nodePath, false) == null)
                    {
                        zk.Create(nodePath, Encoding.UTF8.GetBytes(nodeValue), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
                        return(true);
                    }
                    else
                    {
                        zk.Exists(nodePath, true);
                        message = string.Format("该节点【{0}】已被别人新增。", nodePath);
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                message = string.Format("JinRi.Fx.Manage:{0}AddNode()方法抛异常:{0}[{1}]{2}。", Environment.NewLine, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.ToString());
                log.Error(message);
                message = string.Format("AddNode()方法抛异常:{0}[{1}]{2}。", Environment.NewLine, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.ToString());
                return(false);
            }
        }
示例#6
0
        public void WaitForLock(string lower)
        {
            Stat stat = ZK.Exists(lower, true);

            //watch lower之前,lower已經被刪了
            if (stat == null)
            {
                GetLock();
            }
        }
示例#7
0
        public void test()
        {
            var stat = zk.Exists("/tasks", this);

            if (stat != null)
            {
                var data = zk.GetData("/tasks", true, stat);
                zk.GetChildren("/tasks", true);
            }
        }
 public Stat GetZookeeperNodeStat(string path)
 {
     if (_zk != null)
     {
         return(_zk.Exists(path, true));
     }
     else
     {
         return(null);
     }
 }
        private static void ASYNC_VerifyZookeeper()
        {
            Stat servicesRoot      = zookeeper.Exists("/typhon/services", false);
            Stat connectionsRoot   = zookeeper.Exists("/typhon/connections", false);
            Stat configurationRoot = zookeeper.Exists("/typhon/configuration", false);

            if (servicesRoot == null || connectionsRoot == null || configurationRoot == null)
            {
                throw new Exception("Expected znode(s) \"/typhon/services\", \"/typhon/configuration\" , and/or \"/typhon/connections\"" +
                                    " were not found! Is this the correct Zookeeper server?");
            }
        }
            public void Process(WatchedEvent @event)
            {
                try
                {
                    if (@event.Type == EventType.None)
                    {
                        return;
                    }

                    if (@event.Type == EventType.NodeCreated)
                    {
                        _zk.GetChildren(@event.Path, this, null);
                        var nodeData = _zk.GetData(@event.Path, this, null);

                        if (_nodeChangecallback != null)
                        {
                            _nodeChangecallback(@event, nodeData);
                        }
                    }
                    else if (@event.Type == EventType.NodeDeleted)
                    {
                        _zk.Exists(@event.Path, this);

                        if (_nodeChangecallback != null)
                        {
                            _nodeChangecallback(@event, null);
                        }
                    }
                    else if (@event.Type == EventType.NodeChildrenChanged)
                    {
                        var chlidrenNode = _zk.GetChildren(@event.Path, this, null);
                        if (_nodeChildrenChangecallback != null)
                        {
                            _nodeChildrenChangecallback(@event, chlidrenNode.ToArray());
                        }
                    }
                    else
                    {
                        var nodeData = _zk.GetData(@event.Path, this, null);
                        if (_nodeChangecallback != null)
                        {
                            _nodeChangecallback(@event, nodeData);
                        }
                    }
                }
                catch (KeeperException.NoNodeException e)
                {
                    _zk.Exists(@event.Path, this);
                    Console.WriteLine("ERROR");
                }
            }
示例#11
0
        public Locker(ZooKeeper zk, string ourPath)
        {
            ZK      = zk;
            OurPath = ourPath;
            var parent = OurPath.Substring(0, OurPath.LastIndexOf('/'));

            if (ZK.Exists(parent, false) == null)
            {
                ZK.Create(parent, "".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
            }
            if (ZK.Exists(OurPath, false) == null)
            {
                OurPath = ZK.Create(OurPath, "".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EphemeralSequential);
            }
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="zk">ZooKeeper</param>
        /// <param name="path">节点路径</param>
        public ZookeeperWatcher(ZooKeeper zk, string path)
        {
            Path      = path;
            ZooKeeper = zk;

            if (zk.Exists(path, false) == null)
            {
                zk.Exists(path, this);
            }
            else
            {
                zk.GetData(path, this, null);
                zk.GetChildren(path, this, null);
            }
        }
示例#13
0
 /// <exception cref="System.IO.IOException"/>
 internal virtual void Init()
 {
     try
     {
         Stat isCurrentInprogressNodeExists = zkc.Exists(currentInprogressNode, false);
         if (isCurrentInprogressNodeExists == null)
         {
             try
             {
                 zkc.Create(currentInprogressNode, null, ZooDefs.Ids.OpenAclUnsafe, CreateMode.Persistent
                            );
             }
             catch (KeeperException.NodeExistsException e)
             {
                 // Node might created by other process at the same time. Ignore it.
                 if (Log.IsDebugEnabled())
                 {
                     Log.Debug(currentInprogressNode + " already created by other process.", e);
                 }
             }
         }
     }
     catch (KeeperException e)
     {
         throw new IOException("Exception accessing Zookeeper", e);
     }
     catch (Exception ie)
     {
         throw new IOException("Interrupted accessing Zookeeper", ie);
     }
 }
示例#14
0
        public List <string> getChildren(string path)
        {
            List <string> list = new List <string>();

            zkWatchCreator.Exists(path, true);

            IEnumerable <string> it = zkWatchCreator.GetChildren(path, false);

            foreach (string s in it)
            {
                //Console.WriteLine(s);
                list.Add(s);
            }

            return(list);
        }
示例#15
0
 /// <exception cref="System.IO.IOException"/>
 internal virtual long Get()
 {
     lock (this)
     {
         try
         {
             currentStat = zkc.Exists(path, false);
             if (currentStat == null)
             {
                 return(0);
             }
             else
             {
                 byte[] bytes = zkc.GetData(path, false, currentStat);
                 BKJournalProtos.MaxTxIdProto.Builder builder = BKJournalProtos.MaxTxIdProto.NewBuilder
                                                                    ();
                 TextFormat.Merge(new string(bytes, Charsets.Utf8), builder);
                 if (!builder.IsInitialized())
                 {
                     throw new IOException("Invalid/Incomplete data in znode");
                 }
                 return(((BKJournalProtos.MaxTxIdProto)builder.Build()).GetTxId());
             }
         }
         catch (KeeperException e)
         {
             throw new IOException("Error reading the max tx id from zk", e);
         }
         catch (Exception ie)
         {
             throw new IOException("Interrupted while reading thr max tx id", ie);
         }
     }
 }
示例#16
0
 /// <summary>
 /// 监控进程
 /// </summary>
 /// <param name="event"></param>
 public override void Process(WatchedEvent @event)
 {
     base.Process(@event);
     switch (@event.Type)
     {
     case EventType.NodeDataChanged:
         var path = @event.Path;
         if (NodeChanged != null && !string.IsNullOrWhiteSpace(path))
         {
             NodeChanged(_builder.GetConfigName(Path.GetFileName(path)));
             try
             {
                 //重新注册监控
                 //这里可能会存在Expired问题
                 var stat = ZooKeeper.Exists(path, true);
                 ZooKeeper.AddTmpChildNode(path, _clientName);
                 //按正常逻辑,最后更新的节点,mtime肯定比目前记录的mtime大,所以这里不进行Math.Max处理
                 _mtime = stat.Mtime;
             }
             catch (Exception)
             {
                 //TODO:可能需要判断Expired
             }
         }
         break;
     }
 }
示例#17
0
        public void waitForLock(String lower)
        {
            zk.Register(new LockerCommon());
            //监听比自己次小的节点
            Stat stat = zk.Exists(root + "/" + lower, true);

            if (stat != null)
            {
                Console.WriteLine($"Waiting for {lower}");
            }
            else
            {
                var t = DateTime.Now;
                Console.WriteLine($"{ourPath}访问资源,时间为{DateTime.Now}");
                //访问共享资源
                IsGetLock();
                //释放锁
                Console.WriteLine($"访问结束{(DateTime.Now - t).TotalMilliseconds}");
                try
                {
                    zk.Delete(ourPath, -1);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                Console.WriteLine($"{ourPath}已被删除,时间为{DateTime.Now}");
                Console.ReadLine();
            }
        }
示例#18
0
            public void OnRoundChildrenChanged(IEnumerable <string> children)
            {
                var seqs = children
                           .Select(p => new KeyValuePair <string, int>(p, PathToSeq(p)))
                           .Where(pair => pair.Value != -1)
                           .OrderBy(pair => pair.Value)
                           .ToArray();

                string toWatch = null;

                for (int i = 0; i < seqs.Length - 1; i++)
                {
                    if (seqs[i + 1].Value == selfSeq)
                    {
                        toWatch = seqs[i].Key;
                        break;
                    }
                }

                if (toWatch == null)
                {
                    Log.Info("nothing to watch , since self is leader");
                    IsLeader = true;
                }
                else
                {
                    Log.Info("watch {0}", toWatch);
                    handle.Exists(roundRoot + '/' + toWatch, this);
                }
            }
示例#19
0
        public bool DeleteNode(string nodePath, ref string message)
        {
            try
            {
                using (ZooKeeper zk = new ZooKeeper(AppSettingsHelper.ZKServer, TimeSpan.FromSeconds(AppSettingsHelper.ZKSessionTimeOut), null))
                {
                    ZooKeeper.WaitUntilConnected(zk);

                    Stat stat = zk.Exists(nodePath, false);
                    if (stat != null)
                    {
                        zk.Delete(nodePath, stat.Version);
                    }
                }
            }
            catch (Exception ex)
            {
                message = string.Format("JinRi.Fx.Manage:{0}DeleteNode()方法抛异常:{0}[{1}]{2}。", Environment.NewLine, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.ToString());
                log.Error(message);
                message = string.Format("DeleteNode()方法抛异常:{0}[{1}]{2}。", Environment.NewLine, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.ToString());
                return(false);
            }

            return(true);
        }
        public void CreateNode()
        {
            var stat = zk.Exists("/configuration", false);

            if (stat == null)
            {
                try
                {
                    // 更具体的权限控制
                    //var aclList = new List<ACL> { new ACL { Perms = 31, Id = Ids.ANYONE_ID_UNSAFE } };

                    var data = zk.Create("/configuration", Encoding.UTF8.GetBytes("mydata"), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
                }
                catch (KeeperException.NodeExistsException ex)
                {
                    // 节点已经存在
                    var exmsg = ex.Message;
                }
                catch (KeeperException.NoNodeException ex)
                {
                    // 创建节点时,其父节点必须要存在,否则会报错
                    throw new Exception("父节点不存在");
                }

                // 其它异常不处理
            }
        }
示例#21
0
        /// <summary>
        /// <![CDATA[Zookeeper使用示例]]>
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //创建一个Zookeeper实例,第一个参数为目标服务器地址和端口,第二个参数为Session超时时间,第三个为节点变化时的回调方法
            using (ZooKeeper zk = new ZooKeeper("10.10.10.19:2181", new TimeSpan(0, 0, 0, 50000), new Watcher()))
            {
                var stat = zk.Exists("/root", true);
                ////创建一个节点root,数据是mydata,不进行ACL权限控制,节点为永久性的(即客户端shutdown了也不会消失)
                //zk.Create("/root", "mydata".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);

                ////在root下面创建一个childone znode,数据为childone,不进行ACL权限控制,节点为永久性的
                //zk.Create("/root/childone", "lichaoqiang.com".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
                //取得/root节点下的子节点名称,返回List<String>
                var listRootChildren = zk.GetChildren("/dubbo", true);
                listRootChildren = zk.GetChildren("/dubbo/com.ty.dao.mapper.ebook.EBookNoteMapper/providers", true);
                //取得/root/childone节点下的数据,返回byte[]
                //byte[] buffer = zk.GetData("/root/childone", true, null);

                //string strData = System.Text.Encoding.UTF8.GetString(buffer);
                //Console.WriteLine(strData);

                //修改节点/root/childone下的数据,第三个参数为版本,如果是-1,那会无视被修改的数据版本,直接改掉
                //zk.SetData("/root/childone", "childonemodify".GetBytes(), -1);
                //删除/root/childone这个节点,第二个参数为版本,-1的话直接删除,无视版本
                //zk.Delete("/root/childone", -1);

                ZooKeeperNet.ClientConnection clientConnection = new ClientConnection("10.10.10.19:2181", new TimeSpan(0, 0, 0, 50000), zk, null);
                clientConnection.Start();
                ZooKeeperNet.ClientConnectionEventConsumer clientConnectionEventConsumer = new ClientConnectionEventConsumer(clientConnection);
                clientConnectionEventConsumer.Start();
            }
            Console.ReadLine();
        }
示例#22
0
        static void Main(string[] args)
        {
            // 创建一个Zookeeper实例,第一个参数为目标服务器地址和端口,第二个参数为Session超时时间,第三个为节点变化时的回调方法
            using (var zk = new ZooKeeper("127.0.0.1:2181", new TimeSpan(0, 0, 0, 50000), new Watcher()))
            {
                var stat = zk.Exists("/root", true);

                // 创建一个节点root,数据是mydata,不进行ACL权限控制,节点为永久性的(即客户端shutdown了也不会消失)
                // zk.Create("/root", "mydata".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);

                // 在root下面创建一个childone znode,数据为childone,不进行ACL权限控制,节点为永久性的
                zk.Create("/root/childone", "childone".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);

                // 取得/root节点下的子节点名称,返回List<String>
                zk.GetChildren("/root", true);

                // 取得/root/childone节点下的数据,返回byte[]
                zk.GetData("/root/childone", true, null);

                // 修改节点/root/childone下的数据,第三个参数为版本,如果是-1,那会无视被修改的数据版本,直接改掉
                zk.SetData("/root/childone", "childonemodify".GetBytes(), -1);

                // 删除/root/childone这个节点,第二个参数为版本,-1的话直接删除,无视版本
                zk.Delete("/root/childone", -1);
            }

            Console.ReadKey();
        }
示例#23
0
 /// <summary>
 /// 设置某个路径的值
 /// </summary>
 /// <param name="path">路径</param>
 /// <param name="value">值</param>
 public void SetData(string path, string value)
 {
     ActionRetryHelper.Retry(() =>
     {
         Stat stat   = ZooKeeper.Exists(path, false);
         byte[] data = value == null ? null : value.GetBytes();
         if (stat == null)
         {
             ZooKeeper.Create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
         }
         else
         {
             ZooKeeper.SetData(path, data, stat.Version);
         }
     }, 3, new TimeSpan(10), () =>
     {
         //exceptionAction
     }, (ex) =>
     {
         //errorHandle
         LogManager.GetLogger().Error(string.Format("DisconfClient.ZooKeeperClient.SetData(path={0},value={1}),ex:{2}", path, value, ex));
     }, () =>
     {
         //retryExceptionAction
         LogManager.GetLogger().Error(string.Format("DisconfClient.ZooKeeperClient.SetData(path={0},value={1}),error", path, value));
     });
 }
示例#24
0
        /// <summary>
        /// 注册监控关系,并返回在注册监控之前变更过的znode完整路径对应的configName
        /// </summary>
        public IEnumerable <string> RegisterWatcher()
        {
            var configs = new HashSet <string>();

            if (_builder != null)
            {
                long mtime  = _mtime;
                var  znodes = _builder.GetAllZnodes();
                foreach (var node in znodes)
                {
                    var path = _builder.GetZkPath(node);
                    try
                    {
                        var stat = ZooKeeper.Exists(path, true);
                        if (stat != null)
                        {
                            if (_mtime > 0 && stat.Mtime > _mtime)
                            {
                                //通过_mtime是否大于0进行判断是第一次还是Expired后重连,只有重连时才需要返回变更过的节点
                                configs.Add(_builder.GetConfigName(node));
                            }
                            ZooKeeper.AddTmpChildNode(path, _clientName);
                            mtime = Math.Max(mtime, stat.Mtime);
                        }
                    }
                    catch (Exception)
                    {
                        //TODO:可能需要判断Expired
                    }
                }
                _mtime = mtime;
            }
            return(configs);
        }
        //static List<Org.Apache.Zookeeper.Data.ACL> CreateAllAccessACLList()
        //{
        //    var list = new List<Org.Apache.Zookeeper.Data.ACL>();

        //    var ZKid = new Org.Apache.Zookeeper.Data.ZKId("world", "anyone");
        //    var acl = new Org.Apache.Zookeeper.Data.ACL(ZooKeeperNet.Perms.ALL, ZKid);

        //    list.Add(acl);

        //    return list;
        //}

        static void Main(string[] args)
        {
            string path = "/zk-book";

            zk = new ZooKeeper("127.0.0.1:2181", new TimeSpan(0, 0, 5), new ZooKeeper_SetData_API_Sync_Usage());
            manualWaitHandler.WaitOne();

            if (zk.Exists(path, false) == null)
            {
                zk.Create(path, "123".GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Ephemeral);
            }
            Console.WriteLine(zk.GetData(path, true, null));

            var stat = zk.SetData(path, "456".GetBytes(), -1);

            Console.WriteLine("{0}, {1}, {2}", stat.Czxid, stat.Mzxid, stat.Version);

            var stat2 = zk.SetData(path, "456".GetBytes(), stat.Version);

            Console.WriteLine("{0}, {1}, {2}", stat2.Czxid, stat2.Mzxid, stat2.Version);

            try
            {
                zk.SetData(path, "456".GetBytes(), stat.Version);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.ToString());
            }

            Console.ReadLine();
        }
        /**
         * Barrier constructor
         *
         * @param address
         * @param root
         * @param size
         */
        public Barrier(ZooKeeper zk, String root, int size, string nodeName)
        {
            _root = root;
            _size = size;

            _nodeName = nodeName;

            _zk = zk;

            // Create barrier node
            if (_zk == null)
            {
                return;
            }

            try
            {
                var s = _zk.Exists(root, false);
                if (s == null)
                {
                    _zk.Create(root, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
                }
            }
            catch (KeeperException e)
            {
                Console.WriteLine("Keeper exception when instantiating queue: " + e);
            }
            catch (Exception e)
            {
                //TODO
            }
        }
        /**
         * Barrier constructor
         *
         * @param address
         * @param root
         * @param size
         */
        public Barrier(ZooKeeper zk, String root, int size, string nodeName)
        {
            _root = root;
            _size = size;

            _nodeName = nodeName;

            _zk = zk;

            // Create barrier node
            if (_zk == null) return;

            try
            {
                var s = _zk.Exists(root, false);
                if (s == null)
                    _zk.Create(root, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
            }
            catch (KeeperException e)
            {
                Console.WriteLine("Keeper exception when instantiating queue: " + e);
            }
            catch (Exception e)
            {
                //TODO
            }
        }
示例#28
0
        public bool GetNodeValue(string nodePath, ref string nodeValue, ref string message)
        {
            nodeValue = string.Empty;

            try
            {
                using (ZooKeeper zk = new ZooKeeper(AppSettingsHelper.ZKServer, TimeSpan.FromSeconds(AppSettingsHelper.ZKSessionTimeOut), null))
                {
                    ZooKeeper.WaitUntilConnected(zk);

                    Stat stat = zk.Exists(nodePath, true);
                    if (stat == null)
                    {
                        message = string.Format("该节点【{0}】已被别人删除。", nodePath);
                        return(false);
                    }

                    byte[] _nodeValue = zk.GetData(nodePath, false, stat);
                    if (_nodeValue != null && _nodeValue.Length > 0)
                    {
                        nodeValue = Encoding.UTF8.GetString(_nodeValue);
                    }
                }
            }
            catch (Exception ex)
            {
                message = string.Format("JinRi.Fx.Manage:{0}GetNodeValue()方法抛异常:{0}[{1}]{2}。", Environment.NewLine, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.ToString());
                log.Error(message);
                message = string.Format("GetNodeValue()方法抛异常:{0}[{1}]{2}。", Environment.NewLine, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.ToString());
                return(false);
            }

            return(true);
        }
            public ZookeeperWatcherWrapper(ZooKeeper zk, string path, Action <WatchedEvent, byte[]> nodeChangecallback, Action <WatchedEvent, string[]> nodeChildrenChangecallback)
            {
                _path = path;
                _nodeChangecallback         = nodeChangecallback;
                _nodeChildrenChangecallback = nodeChildrenChangecallback;
                _zk = zk;

                if (zk.Exists(path, false) == null)
                {
                    zk.Exists(path, this);
                }
                else
                {
                    zk.GetData(path, this, null);
                    zk.GetChildren(path, this, null);
                }
            }
示例#30
0
        private void initTaskMonitor()
        {
            try
            {
                var appName = this.getCurrentTaskAppName();

                mZooKeeper = new ZooKeeper("zk.in.yuncaijing.com:2181", new TimeSpan(0, 0, 10), new MonitorWatcher());

                var appFullPath = "/dubbo";
                var iStat       = mZooKeeper.Exists(appFullPath, true);
                if (iStat == null)
                {
                    mZooKeeper.Create(appFullPath, new byte[] { }, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
                }

                appFullPath = string.Format("/dubbo/com.yuncaijing.monitor.donet.{0}", appName);
                iStat       = mZooKeeper.Exists(appFullPath, true);
                if (iStat == null)
                {
                    mZooKeeper.Create(appFullPath, new byte[] { }, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
                }

                appFullPath = string.Format("/dubbo/com.yuncaijing.monitor.donet.{0}/providers", appName);
                iStat       = mZooKeeper.Exists(appFullPath, true);
                if (iStat == null)
                {
                    mZooKeeper.Create(appFullPath, new byte[] { }, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
                }

                var nodeInfo = new MonitorNodeModel();
                nodeInfo.Create();

                var localUrl = nodeInfo.ToUrl();

                appFullPath = string.Format("/dubbo/com.yuncaijing.monitor.donet.{0}/providers/{1}", appName, localUrl);
                iStat       = mZooKeeper.Exists(appFullPath, true);
                if (iStat == null)
                {
                    mZooKeeper.Create(appFullPath, new byte[] { }, Ids.OPEN_ACL_UNSAFE, CreateMode.Ephemeral);
                }
            }
            catch (Exception ex)
            {
                YunLib.LogWriter.Log(ex.ToString());
            }
        }
 public DataMonitor(ZooKeeper zk, String zPodePath, Watcher chainedWatcher,
     IDataMonitorListener listener)
 {
     _zk = zk;
     _znode = zPodePath;
     _chainedWatcher = chainedWatcher;
     _listener = listener;
     _zk.Exists(_znode, this);
 }
示例#32
0
        /// <summary>
        /// 创建临时节点
        /// </summary>
        /// <param name="zk"></param>
        /// <param name="path"></param>
        /// <param name="data"></param>
        void CreateEphemeralIfNot(ZooKeeper zk, string path, string data)
        {
            var stat = zk.Exists(path, false);

            if (stat == null)
            {
                zk.Create(path, data.GetBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.Ephemeral);
            }
        }
示例#33
0
        public virtual void TestWithConfiguringBKAvailablePath()
        {
            // set Bookie available path in the configuration
            string        bkAvailablePath = BookKeeperJournalManager.BkjmZkLedgersAvailablePathDefault;
            Configuration conf            = new Configuration();

            conf.SetStrings(BookKeeperJournalManager.BkjmZkLedgersAvailablePath, bkAvailablePath
                            );
            NUnit.Framework.Assert.IsNull(bkAvailablePath + " already exists", zkc.Exists(bkAvailablePath
                                                                                          , false));
            NamespaceInfo nsi = NewNSInfo();

            bkjm = new BookKeeperJournalManager(conf, URI.Create("bookkeeper://" + Hostport +
                                                                 "/hdfsjournal-WithBKPath"), nsi);
            bkjm.Format(nsi);
            NUnit.Framework.Assert.IsNotNull("Bookie available path : " + bkAvailablePath + " doesn't exists"
                                             , zkc.Exists(bkAvailablePath, false));
        }
示例#34
0
		public void SessionTermination(){

			var latch = new AutoResetEvent (false);
			var sxl = new AutoResetEvent (false);
			var conlatch = new AutoResetEvent (false);
			var w1 = new CuratorWatcher ((e) => {
				if(e.State == KeeperState.SyncConnected){
					latch.Set();
				}
				else if(e.State == KeeperState.Expired){
					sxl.Set();
				}
			});
			var zookeeper = new ZooKeeper(connectionString,TimeSpan.FromMilliseconds(10000),w1);
			latch.WaitOne (5000);

			using (var zk = new ZooKeeper (connectionString, TimeSpan.FromMilliseconds (2000), new CuratorWatcher ((e) => {
				if (e.State == KeeperState.SyncConnected)
					conlatch.Set ();
			}), zookeeper.SessionId, zookeeper.SesionPassword)) {

				if (!conlatch.WaitOne (5000)) {
					Assert.Fail ();
				} 
			};

			if (!sxl.WaitOne (20000)) {
				Assert.Fail ();
			} 

			try{
				var stat = zookeeper.Exists ("/test", false);
				if (stat == null) {
					System.Diagnostics.Debug.WriteLine ("Node does not exits");

				}
			}
			catch(KeeperException e){

				System.Diagnostics.Debug.WriteLine ("Session Expired");

			}

		}