Ejemplo n.º 1
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());
            }
        }
Ejemplo n.º 2
0
        public override Task process(WatchedEvent e)
        {
            var path  = e.getPath();
            var state = e.getState();

            Console.WriteLine($"{Name} recieve: Path-{path}     State-{e.getState()}    Type-{e.get_Type()}");
            return(Task.FromResult(0));
        }
Ejemplo n.º 3
0
        public override async Task process(WatchedEvent watchedEvent)
        {
            var event_type = watchedEvent.get_Type();
            var zk_status  = watchedEvent.getState();
            var path       = watchedEvent.getPath();

            if (watchedEvent.getState() != Event.KeeperState.SyncConnected || watchedEvent.getPath() != Path)
            {
                $"{watchedEvent.ToJson()}".AddBusinessInfoLog();
                return;
            }

            await ProcessImpl(watchedEvent);

            /*
             *           switch (zk_status)
             * {
             *  case Event.KeeperState.AuthFailed:
             *      Console.WriteLine(nameof(Event.KeeperState.AuthFailed));
             *      break;
             *  case Event.KeeperState.ConnectedReadOnly:
             *      Console.WriteLine(nameof(Event.KeeperState.ConnectedReadOnly));
             *      break;
             *  case Event.KeeperState.Disconnected:
             *      Console.WriteLine(nameof(Event.KeeperState.Disconnected));
             *      this.ReConnect();
             *      break;
             *  case Event.KeeperState.Expired:
             *      Console.WriteLine(nameof(Event.KeeperState.Expired));
             *      this.ReConnect();
             *      break;
             *  case Event.KeeperState.SyncConnected:
             *      break;
             *  default:
             *      break;
             * }
             *
             * switch (event_type)
             * {
             *  case Event.EventType.NodeChildrenChanged:
             *      //注册节点发生改变
             *      await this.NodeChildrenChanged(path);
             *      break;
             *  case Event.EventType.NodeCreated:
             *      break;
             *  case Event.EventType.NodeDataChanged:
             *      break;
             *  case Event.EventType.NodeDeleted:
             *      break;
             *  case Event.EventType.None:
             *      break;
             *  default:
             *      break;
             * }
             */
        }
 public override Task process(WatchedEvent @event)
 {
     _logger.LogDebug("watch激发,回掉状态:{0}", @event.getState().ToString());
     if (@event.getState() == KeeperState.SyncConnected ||
         @event.getState() == KeeperState.ConnectedReadOnly)
     {
         _logger.LogDebug("释放阻塞");
         _autoResetEvent.Set();
     }
     return(Task.FromResult(0));
 }
Ejemplo n.º 5
0
 public override Task process(WatchedEvent @event)
 {
     if (@event != null)
     {
         if (@event.getState() == Event.KeeperState.Disconnected || @event.getState() == Event.KeeperState.Expired)
         {
             return(new Task(() => zkClient.InitClientConnection()));
         }
     }
     return(new Task(() => {
     }));
 }
Ejemplo n.º 6
0
        public override async Task process(WatchedEvent watchedEvent)
        {
            Console.WriteLine("WatchedEvent:" + watchedEvent.getState().ToString() + ":" + watchedEvent.get_Type().ToString());
            if (watchedEvent.getState() == KeeperState.Expired)
            {
                ThriftLog.Info("重新注册zk");
                await _zk.closeAsync();

                _zk = null;
                Start();
            }
            return;
        }
Ejemplo n.º 7
0
        // very important that this method does not throw any exceptions as it is called from the zookeeper library
        public override async Task process(WatchedEvent @event)
        {
            if (this.coordinatorToken.IsCancellationRequested || this.ignoreWatches)
                return;

            if (@event.getPath() != null)
                this.logger.Info(this.clientId, $"Coordinator - KEEPER EVENT {@event.getState()} - {@event.get_Type()} - {@event.getPath()}");
            else
                this.logger.Info(this.clientId, $"Coordinator - KEEPER EVENT {@event.getState()} - {@event.get_Type()}");

            switch (@event.getState())
            {
                case Event.KeeperState.Expired:
                    this.events.Add(CoordinatorEvent.SessionExpired);
                    break;
                case Event.KeeperState.Disconnected:
                    if (!this.disconnectedTimer.IsRunning)
                        this.disconnectedTimer.Start();
                    break;
                case Event.KeeperState.ConnectedReadOnly:
                case Event.KeeperState.SyncConnected:
                    if (this.disconnectedTimer.IsRunning)
                        this.disconnectedTimer.Reset();

                    if (@event.getPath() != null)
                    {
                        if (@event.get_Type() == Event.EventType.NodeDataChanged)
                        {
                            if (@event.getPath().EndsWith("epoch"))
                                this.events.Add(CoordinatorEvent.NoLongerCoordinator);
                        }
                        else if (@event.get_Type() == Event.EventType.NodeChildrenChanged)
                        {
                            if (@event.getPath().EndsWith("resources"))
                                this.events.Add(CoordinatorEvent.RebalancingTriggered);
                            else if (@event.getPath().EndsWith("clients"))
                                this.events.Add(CoordinatorEvent.RebalancingTriggered);
                        }
                    }

                    break;
                default:
                    this.logger.Error(this.clientId,
                        $"Coordinator - Currently this library does not support ZooKeeper state {@event.getState()}");
                    this.events.Add(CoordinatorEvent.PotentialInconsistentState);
                    break;
            }

            await Task.Yield();
        }
Ejemplo n.º 8
0
            public override Task process(WatchedEvent @event)
            {
                var state = @event.getState();

                if (state == Event.KeeperState.SyncConnected)
                {
                    if (_tcs.TrySetResult(default))
Ejemplo n.º 9
0
            public async override Task process(WatchedEvent @event)
            {
                await base.process(@event);

                if (@event.getState() == Event.KeeperState.SyncConnected)
                {
                    if (latch != null)
                    {
                        latch.Set();
                    }
                }

                if (@event.get_Type() == Event.EventType.None)
                {
                    return;
                }
                try
                {
                    events.Add(@event);
                }
                catch (ThreadInterruptedException)
                {
                    Assert.assertTrue("interruption unexpected", false);
                }
            }
Ejemplo n.º 10
0
 public override async Task process(WatchedEvent @event)
 {
     if (@event.getState() == Event.KeeperState.SyncConnected)
     {
         this.connected = true;
     }
     if (@event.getState() == Event.KeeperState.Disconnected)
     {
         this.connected = false;
     }
     if (@event.getState() == Event.KeeperState.Expired)
     {
         this.connected = false;
     }
     await Task.FromResult(1);
 }
Ejemplo n.º 11
0
        public override Task process(WatchedEvent @event)
        {
            if (LOG_EVENTS)
            {
                log.Debug("ConnectState watcher: " + @event);
            }

            if (@event.get_Type() == Watcher.Event.EventType.None)
            {
                bool wasConnected   = _isConnected.get();
                bool newIsConnected = checkState(@event.getState(), wasConnected);
                if (newIsConnected != wasConnected)
                {
                    _isConnected.set(newIsConnected);
                    Volatile.Write(ref connectionStartMs, CurrentMillis);
                }
            }

            foreach (Watcher parentWatcher in parentWatchers)
            {
                TimeTrace timeTrace = new TimeTrace("connection-state-parent-process", tracer.Get());
                parentWatcher.process(@event);
                timeTrace.commit();
            }
            return(Task.FromResult <object>(null));
        }
Ejemplo n.º 12
0
        public override Task process(WatchedEvent @event)
        {
            _state = @event.getState().ToString();
            _type  = @event.get_Type();
            _path  = @event.getPath();
            switch (_type)
            {
            case Event.EventType.NodeCreated:
                HandleCreate();
                break;

            case Event.EventType.NodeDeleted:
                HandleDelete();
                break;

            case Event.EventType.NodeDataChanged:
                HandleDataChange();
                break;

            case Event.EventType.NodeChildrenChanged:
                HandleChildrenChange();
                break;

            default:
                HandleNone();
                break;
            }
            return(CompletedTask);
        }
Ejemplo n.º 13
0
        public ZookeeperEvent(WatchedEvent @event)
        {
            switch (@event.getState())
            {
            case Watcher.Event.KeeperState.AuthFailed: State = EventState.AuthFailed; break;

            case Watcher.Event.KeeperState.ConnectedReadOnly: State = EventState.ConnectedReadOnly; break;

            case Watcher.Event.KeeperState.Disconnected: State = EventState.Disconnected; break;

            case Watcher.Event.KeeperState.Expired: State = EventState.Expired; break;

            case Watcher.Event.KeeperState.SyncConnected: State = EventState.SyncConnected; break;
            }

            switch (@event.get_Type())
            {
            case Watcher.Event.EventType.NodeChildrenChanged: Type = EventType.NodeChildrenChanged; break;

            case Watcher.Event.EventType.NodeCreated: Type = EventType.NodeCreated; break;

            case Watcher.Event.EventType.NodeDataChanged: Type = EventType.NodeDataChanged; break;

            case Watcher.Event.EventType.NodeDeleted: Type = EventType.NodeDeleted; break;

            case Watcher.Event.EventType.None: Type = EventType.None; break;
            }

            Path = @event.getPath();
        }
Ejemplo n.º 14
0
        public override async Task process(WatchedEvent @event)
        {
            if (_isDisposed)
            {
                return;
            }
            var stateChanged = @event.getPath() == null;
            var dataChanged  = @event.get_Type() == Event.EventType.NodeChildrenChanged ||
                               @event.get_Type() == Event.EventType.NodeCreated ||
                               @event.get_Type() == Event.EventType.NodeDeleted ||
                               @event.get_Type() == Event.EventType.NodeDataChanged;

            if (stateChanged)
            {
                await ProcessStateChange(@event);
            }
            else if (dataChanged)
            {
                await ProcessDataOrChildChange(@event);
            }
            else if (@event.getState() == Event.KeeperState.Expired)
            {
                // If the session expired we have to signal all conditions, because watches might have been removed and
                // there is no guarantee that those
                // We also have to notify all listeners that something might have changed
                Logger.Info("session过期");
                await FireAllEvents();
            }
        }
        private Task OnStateChanged(WatchedEvent arg)
        {
            switch (arg.getState())
            {
            case Watcher.Event.KeeperState.Disconnected:
                _connectedEvent.Reset();
                break;

            case Watcher.Event.KeeperState.SyncConnected:
                _connectedEvent.Set();
                return(LoadAsync());

            case Watcher.Event.KeeperState.AuthFailed:
                //todo:throw custom exception.
                throw new Exception("connect to zookeeper auth failed");

            case Watcher.Event.KeeperState.ConnectedReadOnly:
                //we won't connect readonly when instantiate zookeeper.
                break;

            case Watcher.Event.KeeperState.Expired:
                _connectedEvent.Reset();
                _zooKeeper = _zooKeeperFactory.CreateZooKeeper(_option.ConnectionString, _option.SessionTimeout, out _watcher);
                break;

            default:
                break;
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 16
0
 public override Task process(WatchedEvent @event)
 {
     _logger.LogInformation("watch激发,回掉状态:{0}", @event.getState().ToString());
     if (@event.getState() == KeeperState.SyncConnected ||
         @event.getState() == KeeperState.ConnectedReadOnly)
     {
         _logger.LogInformation("释放连接阻塞");
         _autoResetEvent.Set();
     }
     else
     {
         _logger.LogInformation("连接断开,释放分布式锁阻塞");
         _mutex.Set();
     }
     return(Task.FromResult(0));
 }
        public override async Task process(WatchedEvent @event)
        {
            switch (@event.get_Type())
            {
            case EventType.NodeDeleted:
                //Node deleted, clear the leader so it'll recheck
                _isLeader.Clear();
                break;

            case EventType.None:
                switch (@event.getState())
                {
                case KeeperState.SyncConnected:
                    //When connected add the root node
                    await AddRootNode();

                    break;

                case KeeperState.Disconnected:
                    //When disconnected, reconnect and recheck leader
                    _isLeader.Clear();
                    await Connect();

                    break;
                }
                break;
            }
        }
Ejemplo n.º 18
0
        public override async Task process(WatchedEvent watchedEvent)
        {
            Console.WriteLine("WatchedEvent:" + watchedEvent.getState().ToString() + ":" + watchedEvent.get_Type().ToString());
            if (watchedEvent.getState() == KeeperState.Expired)
            {
                ThriftLog.Info(" 重新连接zk");
                await _zk.closeAsync();

                _zk            = null;
                _serviceConfig = GetServiceConfig();
                return;
            }

            try
            {
                if (watchedEvent.get_Type() == EventType.NodeChildrenChanged)
                {
                    var data = await _zk.getChildrenAsync(_serviceConfig.ZookeeperConfig.NodeParent, this);

                    var children = data.Children;

                    if (children != null && children.Count > 0)
                    {
                        _serviceConfig.Host = string.Join(",", children);
                    }
                    else
                    {
                        _serviceConfig.Host = _defaultHost;
                    }

                    if (_updateHostDelegate != null)
                    {
                        _updateHostDelegate();
                    }
                }
            }
            catch (Exception ex)
            {
                ThriftLog.Error(ex.Message + ex.StackTrace);
                _zk            = null;
                _serviceConfig = GetServiceConfig();
                ThriftLog.Info(" 重新连接zk2");
            }

            return;
        }
Ejemplo n.º 19
0
        public override Task process(WatchedEvent @event)
        {
            var state = @event.getState();
            var type  = @event.get_Type();

            return(Task.CompletedTask);
            // nada
        }
Ejemplo n.º 20
0
 public override Task process(WatchedEvent @event)
 {
     if (@event.getState() == Watcher.Event.KeeperState.SyncConnected)
     {
         Barrier.SignalAndWait(1);
     }
     return(Task.FromResult <object>(null));
 }
Ejemplo n.º 21
0
 public override async Task process(WatchedEvent watchedEvent)
 {
     if (watchedEvent.getState() != Event.KeeperState.SyncConnected || watchedEvent.getPath() != Path)
     {
         return;
     }
     await ProcessImpl(watchedEvent);
 }
Ejemplo n.º 22
0
 public override async Task process(WatchedEvent @event)
 {
     _logger.LogDebug($"{@event.getPath()}|{@event.get_Type()}|{@event.getState()}");
     if (onWatch != null)
     {
         await onWatch(@event);
     }
 }
Ejemplo n.º 23
0
        public override async Task process(WatchedEvent watchedEvent)
        {
            var status = watchedEvent.getState();

            await this._status_changed.Invoke(status);

            await Task.FromResult(1);
        }
Ejemplo n.º 24
0
 public override Task process(WatchedEvent @event)
 {
     if (@event.getState() == Event.KeeperState.Disconnected)
     {
         latch.TrySetResult(true);
     }
     return(CompletedTask);
 }
Ejemplo n.º 25
0
 public override Task process(WatchedEvent @event)
 {
     if (@event.getState() == Event.KeeperState.Expired)
     {
         Console.WriteLine("Session expired event received");
         Barrier.SignalAndWait(0);
     }
     return(Task.FromResult <object>(null));
 }
Ejemplo n.º 26
0
 public override Task process(WatchedEvent @event)
 {
     if (@event.getState() == Event.KeeperState.Expired)
     {
         Console.WriteLine("Session expired event received");
         Barrier.SignalAndWait(0);
     }
     return Task.FromResult<object>(null);
 }
Ejemplo n.º 27
0
        public override Task process(WatchedEvent @event)
        {
            Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] Status: {@event.getState()}, Type: {@event.get_Type()}, Path: {@event.getPath()}");
            if (@event.getState() == Event.KeeperState.Expired)
            {
                if (_startTask?.IsCompleted == true)
                {
                    _startTask = Start();
                }
            }

            switch (@event.get_Type())
            {
            case Event.EventType.NodeChildrenChanged:
                break;
            }
            return(Task.FromResult <object>(null));
        }
Ejemplo n.º 28
0
        public override async Task process(WatchedEvent @event)
        {
            var state = @event.getState();
            var path  = @event.getPath();
            var type  = @event.get_Type();

            OnChange?.Invoke(path, state, type);
            await Task.CompletedTask;
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 处理zk状态变更
        /// </summary>
        /// <param name="event"></param>
        /// <returns></returns>
        private async Task ProcessStateChange(WatchedEvent @event)
        {
            SetCurrentState(@event.getState());
            //触发注册的StateChange事件
            FireStateChangedEvent(@event.getState());

            if (@event.getState() == Event.KeeperState.Expired)
            {
                Task.Run(async() => await Reconnect().ConfigureAwait(false))
                .ConfigureAwait(false).GetAwaiter().GetResult();

                FireNewSessionEvent();
            }

            _stateChangEvent.Set();

            await Task.FromResult(0);
        }
            public override Task process(WatchedEvent @event)
            {
                if (@event.getState() == Event.KeeperState.SyncConnected)
                {
                    SyncConnectedEvent?.Invoke();
                }

                return(Task.CompletedTask);
            }
Ejemplo n.º 31
0
        private void ProcessStateChanged(WatchedEvent @event)
        {
            this._currentState = @event.getState();

            this.HandleStateChanged(this._currentState);
            if (@event.getState() != Event.KeeperState.Expired)
            {
                return;
            }
            try
            {
                this.ReConnect(true);
            }
            catch (Exception e)
            {
                _logHandler.Error("Process state changed event error", e);
                this.HandleEstablishmentError(e);
            }
        }
Ejemplo n.º 32
0
 public override Task process(WatchedEvent watchedEvent)
 {
     string unfixForNs = _curatorFrameworkImpl.unfixForNamespace(watchedEvent.getPath());
     ICuratorEvent @event = new CuratorEventImpl(_curatorFrameworkImpl,
                                                 CuratorEventType.WATCHED,
                                                 (int) watchedEvent.getState(),
                                                 unfixForNs,
                                                 null,
                                                 null,
                                                 null,
                                                 null,
                                                 null,
                                                 watchedEvent,
                                                 null);
     processEvent(@event);
     return Task.FromResult<object>(null);
 }
Ejemplo n.º 33
0
 internal NamespaceWatchedEvent(CuratorFrameworkImpl client, WatchedEvent @event)
     : base(@event.get_Type(), @event.getState(), client.unfixForNamespace(@event.getPath()))
 {
 }
Ejemplo n.º 34
0
        public override Task process(WatchedEvent @event)
        {
            if (LOG_EVENTS)
            {
                log.Debug("ConnectState watcher: " + @event);
            }

            if ( @event.get_Type() == Watcher.Event.EventType.None )
            {
                bool wasConnected = _isConnected.get();
                bool newIsConnected = checkState(@event.getState(), wasConnected);
                if ( newIsConnected != wasConnected )
                {
                    _isConnected.set(newIsConnected);
                    Volatile.Write(ref connectionStartMs, CurrentMillis);
                }
            }

            foreach ( Watcher parentWatcher in parentWatchers )
            {
                TimeTrace timeTrace = new TimeTrace("connection-state-parent-process", tracer.Get());
                parentWatcher.process(@event);
                timeTrace.commit();
            }
            return Task.FromResult<object>(null);
        }
Ejemplo n.º 35
0
        public override Task process(WatchedEvent @event)
        {
            if (LOG_EVENTS)
            {
                log.debug("ConnectState watcher: " + @event);
            }

            if (@event.get_Type() == Event.EventType.None)
            {
                bool wasConnected = isConnected_Renamed.get();
                var newIsConnected = checkState(@event.getState(), wasConnected);
                if (newIsConnected != wasConnected)
                {
                    isConnected_Renamed.set(newIsConnected);
                    connectionStartMs.Value = TimeHelper.ElapsedMiliseconds;
                }
            }

            foreach (var parentWatcher in parentWatchers)
            {
                var timeTrace = new TimeTrace("connection-state-parent-process", tracer.get());
                parentWatcher.process(@event);
                timeTrace.commit();
            }
        }
Ejemplo n.º 36
0
		public override Task process(WatchedEvent @event)
		{
			Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] Status: {@event.getState()}, Type: {@event.get_Type()}, Path: {@event.getPath()}");
			if (@event.getState() == Event.KeeperState.Expired)
			{
				if (_startTask?.IsCompleted == true)
					_startTask = Start();
			}

			switch (@event.get_Type())
			{
				case Event.EventType.NodeChildrenChanged:
					break;
			}
			return Task.FromResult<object>(null);
		}
Ejemplo n.º 37
0
            /// <summary>Processes the specified event.</summary>
            /// <param name="watchedEvent">The event.</param>
            /// <returns></returns>
            public override async Task process(WatchedEvent watchedEvent)
            {
                if (watchedEvent.getState() == Event.KeeperState.SyncConnected)
                {
                    _connectioned();
                }
                else
                {
                    _disconnect();
                }
#if NET45||NET451
                await Task.FromResult(1);
#else
                await Task.CompletedTask;
#endif
            }
Ejemplo n.º 38
0
 public override async Task process(WatchedEvent watchedEvent)
 {
     if (watchedEvent.getState() != Event.KeeperState.SyncConnected || watchedEvent.getPath() != Path)
         return;
     await ProcessImpl(watchedEvent);
 }
Ejemplo n.º 39
0
 public override Task process(WatchedEvent @event)
 {
     if ( @event.getState() == Watcher.Event.KeeperState.SyncConnected )
     {
         Barrier.SignalAndWait(1);
     }
     return Task.FromResult<object>(null);
 }