Ejemplo n.º 1
0
    private IEnumerator SetRandomDestination()
    {
        State = KeeperState.ConstructingPath;
        Vector3?randomDestination = null;
        int     grace             = 0;

        while (!randomDestination.HasValue)
        {
            var        area        = Mathf.Clamp(RandomDestinationArea - grace, Transform.localScale.magnitude, Mathf.Infinity);
            var        randomPoint = Random.insideUnitSphere * area + Transform.position;
            NavMeshHit hit;
            NavMesh.SamplePosition(randomPoint, out hit, area, 1);
            var path = new NavMeshPath();
            navAgent.CalculatePath(hit.position, path);
            if (path.status == NavMeshPathStatus.PathComplete)
            {
                randomDestination = hit.position;
            }
            grace += (int)Transform.localScale.magnitude;

            yield return(null);
        }

        currentDestination = randomDestination.Value;
        navAgent.SetDestination(randomDestination.Value);
        _state = State = KeeperState.Stalking;
    }
Ejemplo n.º 2
0
        public bool WaitForKeeperState(KeeperState keeperState, TimeSpan timeOut)
        {
            if (_zookeeperEventThread != null && Thread.CurrentThread == _zookeeperEventThread)
            {
                throw new Exception("Must not be done in the zookeeper event thread.");
            }

            LOG.Info("Waiting for keeper state " + keeperState);
            try
            {
                bool stillWaiting = true;
                while (_currentState != keeperState)
                {
                    if (!stillWaiting)
                    {
                        return(false);
                    }
                    stillWaiting = _stateChangedCondition.WaitOne(timeOut);
                    // Throw an exception in the case authorization fails
                }
                LOG.Debug("State is " + _currentState);
                return(true);
            }
            catch (ThreadInterruptedException e)
            {
                throw new ZKInterruptedException(e);
            }
            finally
            {
            }
        }
        public bool WaitForKeeperState(KeeperState keeperState, TimeSpan timeout)
        {
            if (_zookeeperEventThread != null && Thread.CurrentThread == _zookeeperEventThread)
            {
                throw new Exception("Must not be done in the zookeeper event thread.");
            }

            Logger.Debug("Waiting for keeper state " + keeperState);
            this.AcquireEventLock();
            try
            {
                bool stillWaiting = true;
                while (CurrentState != keeperState)
                {
                    if (!stillWaiting)
                    {
                        return(false);
                    }

                    stillWaiting = EventLock.StateChangedCondition.Await(timeout);
                }

                Logger.Debug("State is " + CurrentState);
                return(true);
            }
            catch (ThreadInterruptedException e)
            {
                throw new ZkInterruptedException(e);
            }
            finally
            {
                EventLock.Unlock();
            }
        }
Ejemplo n.º 4
0
 //MethodImpl(MethodImplOptions.Synchronized)]
 private void SetCurrentState(KeeperState state)
 {
     lock (this)
     {
         _currentState = state;
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="state"></param>
        /// <param name="type"></param>
        /// <param name="clientPath"></param>
        /// <returns></returns>
        public IEnumerable <IWatcher> Materialize(KeeperState state, EventType type, string clientPath)
        {
            HashSet <IWatcher> result = new HashSet <IWatcher>();

            switch (type)
            {
            case EventType.None:
                result.Add(defaultWatcher);
                foreach (var ws in dataWatches.Values)
                {
                    result.UnionWith(ws);
                }
                foreach (var ws in existWatches.Values)
                {
                    result.UnionWith(ws);
                }
                foreach (var ws in childWatches.Values)
                {
                    result.UnionWith(ws);
                }

                // clear the watches if auto watch reset is not enabled
                if (ClientConnection.DisableAutoWatchReset &&
                    state != KeeperState.SyncConnected)
                {
                    dataWatches.Clear();
                    existWatches.Clear();
                    childWatches.Clear();
                }
                return(result);

            case EventType.NodeDataChanged:
            case EventType.NodeCreated:
                AddTo(dataWatches.GetAndRemove(clientPath), result);
                AddTo(existWatches.GetAndRemove(clientPath), result);
                break;

            case EventType.NodeChildrenChanged:
                AddTo(childWatches.GetAndRemove(clientPath), result);
                break;

            case EventType.NodeDeleted:
                AddTo(dataWatches.GetAndRemove(clientPath), result);
                //XXX This shouldn't be needed, but just in case
                HashSet <IWatcher> list = existWatches.GetAndRemove(clientPath);
                if (list != null)
                {
                    AddTo(existWatches.GetAndRemove(clientPath), result);
                    log.Warn("We are triggering an exists watch for delete! Shouldn't happen!");
                }
                AddTo(childWatches.GetAndRemove(clientPath), result);
                break;

            default:
                var msg = new StringBuilder("Unhandled watch event type ").Append(type).Append(" with state ").Append(state).Append(" on path ").Append(clientPath).ToString();
                log.Error(msg);
                throw new InvalidOperationException(msg);
            }
            return(result);
        }
Ejemplo n.º 6
0
 public void HandleStateChanged(KeeperState state)
 {
     if (state == KeeperState.Expired)
     {
         expiredEvents++;
     }
 }
Ejemplo n.º 7
0
        /// <summary>
        ///     Waits untill ZooKeeper connection is established
        /// </summary>
        /// <param name="connectionTimeout">
        ///     The connection timeout.
        /// </param>
        /// <returns>
        ///     Status
        /// </returns>
        public bool WaitUntilConnected(int connectionTimeout)
        {
            Guard.Greater(connectionTimeout, 0, "connectionTimeout");

            EnsuresNotDisposed();
            if (eventWorker != null && eventWorker == Thread.CurrentThread)
            {
                throw new InvalidOperationException("Must not be done in the ZooKeeper event thread.");
            }

            Logger.Debug("Waiting for keeper state: " + KeeperState.SyncConnected + " time out: " +
                         connectionTimeout); //.SyncConnected);

            var stillWaiting = true;

            lock (stateChangedLock)
            {
                currentState = connection.ClientState;
                if (currentState == KeeperState.SyncConnected)
                {
                    return(true);
                }
                Logger.DebugFormat("Current state:{0} in the lib:{1}", currentState,
                                   connection.GetInternalZKClient().State);

                var stopWatch = Stopwatch.StartNew();
                while (currentState != KeeperState.SyncConnected)
                {
                    if (!stillWaiting)
                    {
                        return(false);
                    }

                    stillWaiting = Monitor.Wait(stateChangedLock, connectionTimeout);
                    Logger.DebugFormat("Current state:{0} in the lib:{1}", currentState,
                                       connection.GetInternalZKClient().State);
                    currentState = connection.ClientState;
                    if (currentState == KeeperState.SyncConnected)
                    {
                        return(true);
                    }
                    if (stopWatch.Elapsed.TotalMilliseconds > connectionTimeout)
                    {
                        break;
                    }
                    Thread.Sleep(1000);
                }

                Logger.DebugFormat("Current state:{0} in the lib:{1}", currentState,
                                   connection.GetInternalZKClient().State);
                currentState = connection.ClientState;
                if (currentState == KeeperState.SyncConnected)
                {
                    return(true);
                }
                return(false);
            }
        }
Ejemplo n.º 8
0
        public IEnumerable<IWatcher> Materialize(KeeperState state, EventType type, string clientPath)
        {
            HashSet<IWatcher> result = new HashSet<IWatcher>();

            switch (type) {
                case EventType.None:
                    result.Add(defaultWatcher);
                    foreach (var ws in dataWatches.Values) {
                        result.UnionWith(ws);
                    }
                    foreach (var ws in existWatches.Values) {
                        result.UnionWith(ws);
                    }
                    foreach(var ws in childWatches.Values) {
                        result.UnionWith(ws);
                    }

                    // clear the watches if auto watch reset is not enabled
                    if (ClientConnection.DisableAutoWatchReset &&
                        state != KeeperState.SyncConnected)
                    {
                        dataWatches.Clear();
                        existWatches.Clear();
                        childWatches.Clear();
                    }

                    return result;
                case EventType.NodeDataChanged:
                case EventType.NodeCreated:
                        AddTo(dataWatches.GetAndRemove(clientPath), result);
                        AddTo(existWatches.GetAndRemove(clientPath), result);
                    break;
                case EventType.NodeChildrenChanged:
                        AddTo(childWatches.GetAndRemove(clientPath), result);
                    break;
                case EventType.NodeDeleted:
                        AddTo(dataWatches.GetAndRemove(clientPath), result);
                    // XXX This shouldn't be needed, but just in case
                        HashSet<IWatcher> list = existWatches.GetAndRemove(clientPath);
                        if (list != null) {
                            AddTo(existWatches.GetAndRemove(clientPath), result);
                            #if !NET_CORE
                            LOG.Warn("We are triggering an exists watch for delete! Shouldn't happen!");
                            #endif
                        }
                        AddTo(childWatches.GetAndRemove(clientPath), result);
                    break;
                default:
                    var msg = new StringBuilder("Unhandled watch event type ").Append(type).Append(" with state ").Append(state).Append(" on path ").Append(clientPath).ToString();
                    #if !NET_CORE
                    LOG.Error(msg);
                    #endif
                    throw new InvalidOperationException(msg);
            }

            return result;
        }
Ejemplo n.º 9
0
 private void FireStateChangedEvent(KeeperState state)
 {
     foreach (var listener in _stateListeners)
     {
         Action <ZooKeeperEvent> handler = e => listener.OnStateChanged(state);
         var description = string.Format("KeeperState changed to {0}, send to {1}", state, listener);
         var @event      = new ZooKeeperEvent(description, handler);
         _eventExecutor.Add(@event);
     }
 }
 private void FireStateChangedEvent(KeeperState state)
 {
     foreach (var s in this._stateListener)
     {
         var stateListener = s;
         _eventThread.Send(new ZkEvent("State changed to " + state + " sent to " + stateListener)
         {
             RunAction = () => stateListener.HandleStateChanged(state)
         });
     }
 }
Ejemplo n.º 11
0
 public override void OnStateChanged(KeeperState state)
 {
     System.Console.WriteLine("Zookeeper connection state changed to {0}", state);
     if (state == KeeperState.Disconnected)
     {
         this.DisconnectedHandle();
     }
     else if (state == KeeperState.SyncConnected)
     {
         this.ConnectedHandle();
     }
 }
Ejemplo n.º 12
0
 private void FireStateChangedEvent(KeeperState state)
 {
     foreach (IZKStateListener stateListener in _stateListener)
     {
         _eventTask.Send(new ZKTask.ZKEvent("State changed to " + Convert.ToString(state) + " sent to " + nameof(stateListener))
         {
             Run = () =>
             {
                 stateListener.HandleStateChanged(state);
             }
         });
     }
 }
Ejemplo n.º 13
0
        private bool CheckState(KeeperState state, bool wasConnected)
        {
            bool isConnected = wasConnected;
            bool checkNewConnectionString = true;

            switch (state)
            {
            default:
            case KeeperState.Disconnected:
            {
                isConnected = false;
                break;
            }

            case KeeperState.SyncConnected:

            {
                isConnected = true;
                break;
            }

//			case KeeperState.AuthFailed:
//				{
//					isConnected = false;
//					log.error("Authentication failed");
//					break;
//				}

            case KeeperState.Expired:
            {
                isConnected = false;
                checkNewConnectionString = false;
                HandleExpiredSession();
                break;
            }

//			case KeeperState.SaslAuthenticated:
//				{
//					// NOP
//					break;
//				}
            }

            if (checkNewConnectionString && zooKeeper.HasNewConnectionString())
            {
                HandleNewConnectionString();
            }

            return(isConnected);
        }
        public void QueueEvent(WatchedEvent @event)
        {
            if (@event.Type == EventType.None && sessionState == @event.State)
            {
                return;
            }

            sessionState = @event.State;

            // materialize the watchers based on the event
            var pair = new ClientConnection.WatcherSetEventPair(conn.watcher.Materialize(@event.State, @event.Type, @event.Path), @event);

            // queue the pair (watch set & event) for later processing
            AppendToQueue(pair);
        }
Ejemplo n.º 15
0
 private void FireStateChangedEvent(KeeperState state)
 {
     foreach (var stateListener in _stateListeners)
     {
         _eventTask.Send(new ZKTask.ZKEvent($"State changed to {Convert.ToString(state)} sent to {(stateListener)}")
         {
             Run = async() =>
             {
                 if (stateListener.StateChangedHandler != null)
                 {
                     await stateListener.StateChangedHandler(state);
                 }
             }
         });
     }
 }
Ejemplo n.º 16
0
 private void FireStateChangedEvent(KeeperState state)
 {
     foreach (var stateListener in _stateListeners)
     {
         _eventTask.Send(new ZKTask.ZKEvent()
         {
             Run = async() =>
             {
                 if (stateListener.StateChangedHandler != null)
                 {
                     await stateListener.StateChangedHandler(state);
                 }
             }
         });
     }
 }
Ejemplo n.º 17
0
        public void ProcessResult(int rc, String path, Object ctx, KeeperState stat)
        {
            bool exists;

            switch ((KeeperException.Code)rc)
            {
            case KeeperException.Code.OK:
                exists = true;
                break;

            case KeeperException.Code.NONODE:
                exists = false;
                break;

            case KeeperException.Code.SESSIONEXPIRED:
            case KeeperException.Code.NOAUTH:
                dead = true;
                listener.Closing(rc);
                return;

            default:
                // Retry errors
                zk.Exists(znode, true);
                return;
            }

            byte[] b = null;
            if (exists)
            {
                try
                {
                    b = zk.GetData(znode, false, null);
                }
                catch (KeeperException e)
                {
                    // We don't need to worry about recovering now. The watch
                    // callbacks will kick off any exception handling
                    Console.WriteLine(e.ToString());
                }
            }
            if ((b == null && b != prevData) ||
                (b != null && !Array.Equals(prevData, b)))
            {
                listener.Exists(b);
                prevData = b;
            }
        }
Ejemplo n.º 18
0
        public bool WaitForKeeperState(KeeperState keeperState, TimeSpan timeOut)
        {
            LOG.Info($"Waiting for keeper state {Convert.ToString(keeperState)}");
            bool stillWaiting = true;

            while (_currentState != keeperState)
            {
                if (!stillWaiting)
                {
                    return(false);
                }
                stillWaiting = _stateChangedCondition.WaitOne(timeOut);
                // Throw an exception in the case authorization fails
            }
            LOG.Debug($"State is {Convert.ToString(_currentState)}");
            return(true);
        }
Ejemplo n.º 19
0
 private bool WaitUntilKeeperState(KeeperState keeperState)
 {
     lock (WAIT_KEEPER_STATE_LOCK)
     {
         var elapsed = 0;
         while (_connectionState.Value != keeperState)
         {
             Thread.Sleep(1000);
             elapsed += 1000;
             if (elapsed >= _connectTimeoutMs)
             {
                 return(false);
             }
         }
         return(true);
     }
 }
Ejemplo n.º 20
0
        private void ProcessZkConnectEvent(KeeperState state)
        {
            if (state == KeeperState.SyncConnected)
            {
                _isDisconnected = false;
            }

            if (state == KeeperState.Disconnected)
            {
                _isDisconnected = true;
            }

            if (state == KeeperState.Expired)
            {
                _isDisconnected = true;
                _zkElectionClient.Reconnect();
            }
        }
        public void QueueEvent(WatchedEvent @event)
        {
            if (@event.Type == EventType.None && sessionState == @event.State)
            {
                return;
            }

            if (waitingEvents.IsAddingCompleted)
            {
                throw new InvalidOperationException("consumer has been disposed");
            }

            sessionState = @event.State;

            // materialize the watchers based on the event
            var pair = new ClientConnection.WatcherSetEventPair(conn.watcher.Materialize(@event.State, @event.Type, @event.Path), @event);

            // queue the pair (watch set & event) for later processing
            waitingEvents.Add(pair);
        }
Ejemplo n.º 22
0
        public void Process(WatchedEvent wEvent)
        {
            string path = wEvent.Path.ToString();

            log("zooWatcher.Process Called");
            log("path: " + path);

            if (wEvent.GetType().Equals(EventType.None))
            {
                // We are are being told that the state of the connection has changed
                switch (wEvent.State)
                {
                case KeeperState.SyncConnected:
                    // In this particular example we don't need to do anything
                    // here - watches are automatically re-registered with
                    // server and any watches triggered while the client was
                    // disconnected will be delivered (in order of course)
                    break;

                case KeeperState.Expired:
                    // It's all over
                    // dead = true;
                    // listener.closing(KeeperException.Code.SessionExpired);
                    break;
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(path))
                {
                    OnChange(new CollectionChangeEventArgs(path));
                }
            }
            KeeperState state   = wEvent.State;
            EventType   eType   = wEvent.Type;
            string      ewPath  = wEvent.Wrapper.Path;
            int         ewState = wEvent.Wrapper.State;
            int         ewType  = wEvent.Wrapper.Type;
        }
Ejemplo n.º 23
0
    private IEnumerator SetRandomDestination()
    {
        State = KeeperState.ConstructingPath;
        Vector3? randomDestination = null;
        int grace = 0;

        while (!randomDestination.HasValue)
        {
            var area = Mathf.Clamp(RandomDestinationArea - grace, Transform.localScale.magnitude, Mathf.Infinity);
            var randomPoint = Random.insideUnitSphere * area + Transform.position;
            NavMeshHit hit;
            NavMesh.SamplePosition(randomPoint, out hit, area, 1);
            var path = new NavMeshPath();
            navAgent.CalculatePath(hit.position, path);
            if (path.status == NavMeshPathStatus.PathComplete) randomDestination = hit.position;
            grace += (int)Transform.localScale.magnitude;

            yield return null;
        }

        currentDestination = randomDestination.Value;
        navAgent.SetDestination(randomDestination.Value);
        _state = State = KeeperState.Stalking;
    }
Ejemplo n.º 24
0
        public HashSet <IWatcher> Materialize(KeeperState state, EventType type, string clientPath)
        {
            HashSet <IWatcher> result = new HashSet <IWatcher>();

            switch (type)
            {
            case EventType.None:
                result.Add(defaultWatcher);
                foreach (var ws in dataWatches.Values)
                {
                    result.UnionWith(ws);
                }
                foreach (var ws in existWatches.Values)
                {
                    result.UnionWith(ws);
                }
                foreach (var ws in childWatches.Values)
                {
                    result.UnionWith(ws);
                }

                // clear the watches if auto watch reset is not enabled
                if (ClientConnection.disableAutoWatchReset &&
                    state != KeeperState.SyncConnected)
                {
                    lock (dataWatches) {
                        dataWatches.Clear();
                    }
                    lock (existWatches) {
                        existWatches.Clear();
                    }
                    lock (childWatches) {
                        childWatches.Clear();
                    }
                }

                return(result);

            case EventType.NodeDataChanged:
            case EventType.NodeCreated:
                lock (dataWatches) {
                    AddTo(dataWatches.GetAndRemove(clientPath), result);
                }
                lock (existWatches) {
                    AddTo(existWatches.GetAndRemove(clientPath), result);
                }
                break;

            case EventType.NodeChildrenChanged:
                lock (childWatches) {
                    AddTo(childWatches.GetAndRemove(clientPath), result);
                }
                break;

            case EventType.NodeDeleted:
                lock (dataWatches) {
                    AddTo(dataWatches.GetAndRemove(clientPath), result);
                }
                // XXX This shouldn't be needed, but just in case
                lock (existWatches) {
                    HashSet <IWatcher> list = existWatches.GetAndRemove(clientPath);
                    if (list != null)
                    {
                        AddTo(existWatches.GetAndRemove(clientPath), result);
                        LOG.Warn("We are triggering an exists watch for delete! Shouldn't happen!");
                    }
                }
                lock (childWatches) {
                    AddTo(childWatches.GetAndRemove(clientPath), result);
                }
                break;

            default:
                var msg = string.Format("Unhandled watch event type {0} with state {1} on path {2}", type, state, clientPath);
                LOG.Error(msg);
                throw new InvalidOperationException(msg);
            }

            return(result);
        }
Ejemplo n.º 25
0
    private void Update()
    {
        State = Vector3.Distance(Transform.position, drone.Transform.position) < PursuitRange ? KeeperState.Pursuiting : KeeperState.Stalking;

        distortion.LookAt(drone.transform);
    }
Ejemplo n.º 26
0
 public WatchedEvent(WatcherEvent eventMessage)
 {
     state = (KeeperState)Enum.ToObject(typeof(KeeperState), eventMessage.State);
     type  = (EventType)Enum.ToObject(typeof(EventType), eventMessage.Type);
     path  = eventMessage.Path;
 }
Ejemplo n.º 27
0
 private void SetCurrentState(KeeperState state)
 {
     _currentState = state;
 }
Ejemplo n.º 28
0
 public void HandleStateChanged(KeeperState state)
 {
 }
Ejemplo n.º 29
0
 public WatchedEvent(KeeperState state, EventType type, string path)
 {
     this.state = state;
     this.type  = type;
     this.path  = path;
 }
Ejemplo n.º 30
0
 /// <summary>
 /// 状态改变的回调函数
 /// </summary>
 /// <param name="state"></param>
 public void HandleStateChanged(KeeperState state)
 {
     stateChangedEvent(state);
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ZooKeeperStateChangedEventArgs"/> class.
 /// </summary>
 /// <param name="state">
 /// The current ZooKeeper state.
 /// </param>
 public ZooKeeperStateChangedEventArgs(KeeperState state)
     : base("State changed to " + state)
 {
     this.State = state;
 }
Ejemplo n.º 32
0
 public void HandleStateChanged(KeeperState state)
 {
     // do nothing, since zkclient will do reconnect for us.
 }
Ejemplo n.º 33
0
    // fetches phrases from server
    // we pull double the limit
    private IEnumerator FetchCoroutine()
    {
        keeperState = KeeperState.Fetching;
        isFetchedReady = false;

        // prepare the pre-queue list with needed filters
        IDictionary<string, object> fetchInfo = new Dictionary<string, object>
        {
            { "requestLimit", PHRASE_REQUEST_LIMIT }
        };

        var fetchTask = ParseCloud.CallFunctionAsync<IList<ParsePhrase>> ("FetchPhrases", fetchInfo);

        while (!fetchTask.IsCompleted) yield return null;

        if (fetchTask.IsFaulted || fetchTask.IsCanceled)
        {
            using (IEnumerator<System.Exception> enumerator = fetchTask.Exception.InnerExceptions.GetEnumerator())
            {
                if (enumerator.MoveNext ())
                {
                    ParseException exception = (ParseException)enumerator.Current;
                    errorInfo = new ErrorInfo(ErrorType.ParseException, exception.Code);
                }
                else
                {
                    errorInfo = new ErrorInfo(ErrorType.ParseInternal);
                }
            }

            keeperState = KeeperState.Error;
            yield break;
        }
        else
        {
            IList<ParsePhrase> result = fetchTask.Result;
            if(result != null)
            {
                foreach(ParsePhrase phrase in result)
                {
                    phraseCollection.Add (new Phrase() { CorrectMessage = phrase.CorrectMessage });
                }
            }
            else
            {
                errorInfo = new ErrorInfo(ErrorType.ParseInternal);
                keeperState = KeeperState.Error;
                yield break;
            }
        }

        keeperState = KeeperState.Neutral;
        isFetchedReady = true;
        fetchCoroutine = null;
    }
Ejemplo n.º 34
0
    private void Update()
    {
        State = Vector3.Distance(Transform.position, drone.Transform.position) < PursuitRange ? KeeperState.Pursuiting : KeeperState.Stalking;

        distortion.LookAt(drone.transform);
    }
Ejemplo n.º 35
0
 public WatchedEvent(KeeperState state, EventType type, string path)
 {
     this.state = state;
     this.type = type;
     this.path = path;
 }
Ejemplo n.º 36
0
 public WatchedEvent(WatcherEvent eventMessage)
 {
     state = (KeeperState)Enum.ToObject(typeof(KeeperState), eventMessage.State);
     type = (EventType)Enum.ToObject(typeof (EventType), eventMessage.Type);
     path = eventMessage.Path;
 }
Ejemplo n.º 37
0
 /// <summary>
 /// new
 /// </summary>
 /// <param name="type"></param>
 /// <param name="state"></param>
 /// <param name="path"></param>
 public WatchedEvent(EventType type, KeeperState state, string path)
 {
     this.Type  = type;
     this.State = state;
     this.Path  = path;
 }
Ejemplo n.º 38
0
 private void Start()
 {
     State = KeeperState.Stalking;
 }
        public void QueueEvent(WatchedEvent @event)
        {
            if (@event.Type == EventType.None && sessionState == @event.State) return;

            if (waitingEvents.IsAddingCompleted)
                throw new InvalidOperationException("consumer has been disposed");

            sessionState = @event.State;

            // materialize the watchers based on the event
            var pair = new ClientConnection.WatcherSetEventPair(conn.watcher.Materialize(@event.State, @event.Type,@event.Path), @event);
            // queue the pair (watch set & event) for later processing
            waitingEvents.Add(pair);
        }
Ejemplo n.º 40
0
        public HashSet<IWatcher> Materialize(KeeperState state, EventType type, string clientPath)
        {
            HashSet<IWatcher> result = new HashSet<IWatcher>();

            switch (type) {
                case EventType.None:
                    result.Add(defaultWatcher);
                    foreach (var ws in dataWatches.Values) {
                        result.UnionWith(ws);
                    }
                    foreach (var ws in existWatches.Values) {
                        result.UnionWith(ws);
                    }
                    foreach(var ws in childWatches.Values) {
                        result.UnionWith(ws);
                    }

                    // clear the watches if auto watch reset is not enabled
                    if (ClientConnection.disableAutoWatchReset &&
                        state != KeeperState.SyncConnected)
                    {
                        lock(dataWatches) {
                            dataWatches.Clear();
                        }
                        lock(existWatches) {
                            existWatches.Clear();
                        }
                        lock(childWatches) {
                            childWatches.Clear();
                        }
                    }

                    return result;
                case EventType.NodeDataChanged:
                case EventType.NodeCreated:
                    lock (dataWatches) {
                        AddTo(dataWatches.GetAndRemove(clientPath), result);
                    }
                    lock (existWatches) {
                        AddTo(existWatches.GetAndRemove(clientPath), result);
                    }
                    break;
                case EventType.NodeChildrenChanged:
                    lock (childWatches) {
                        AddTo(childWatches.GetAndRemove(clientPath), result);
                    }
                    break;
                case EventType.NodeDeleted:
                    lock (dataWatches) {
                        AddTo(dataWatches.GetAndRemove(clientPath), result);
                    }
                    // XXX This shouldn't be needed, but just in case
                    lock (existWatches) {
                        HashSet<IWatcher> list = existWatches.GetAndRemove(clientPath);
                        if (list != null) {
                            AddTo(existWatches.GetAndRemove(clientPath), result);
                            LOG.Warn("We are triggering an exists watch for delete! Shouldn't happen!");
                        }
                    }
                    lock (childWatches) {
                        AddTo(childWatches.GetAndRemove(clientPath), result);
                    }
                    break;
                default:
                    var msg = string.Format("Unhandled watch event type {0} with state {1} on path {2}", type, state, clientPath);
                    LOG.Error(msg);
                    throw new InvalidOperationException(msg);
            }

            return result;
        }
Ejemplo n.º 41
0
 /// <summary>
 /// new
 /// </summary>
 /// <param name="type"></param>
 /// <param name="state"></param>
 /// <param name="path"></param>
 public WatchedEvent(EventType type, KeeperState state, string path)
 {
     this.Type = type;
     this.State = state;
     this.Path = path;
 }
        public void QueueEvent(WatchedEvent @event)
        {
            if (@event.Type == EventType.None && sessionState == @event.State) return;

            sessionState = @event.State;

            // materialize the watchers based on the event
            var pair = new ClientConnection.WatcherSetEventPair(conn.watcher.Materialize(@event.State, @event.Type,@event.Path), @event);
            // queue the pair (watch set & event) for later processing
            AppendToQueue(pair);
        }
Ejemplo n.º 43
0
 private void Start()
 {
     State = KeeperState.Stalking;
 }
Ejemplo n.º 44
0
		private bool CheckState(KeeperState state, bool wasConnected)
		{
			bool isConnected = wasConnected;
			bool checkNewConnectionString = true;
			switch ( state )
			{
			default:
			case KeeperState.Disconnected:
				{
					isConnected = false;
					break;
				}

			case KeeperState.SyncConnected:

				{
					isConnected = true;
					break;
				}

//			case KeeperState.AuthFailed:
//				{
//					isConnected = false;
//					log.error("Authentication failed");
//					break;
//				}

			case KeeperState.Expired:
				{
					isConnected = false;
					checkNewConnectionString = false;
					HandleExpiredSession();
					break;
				}

//			case KeeperState.SaslAuthenticated:
//				{
//					// NOP
//					break;
//				}
			}

			if ( checkNewConnectionString && zooKeeper.HasNewConnectionString() )
			{
				HandleNewConnectionString();
			}

			return isConnected;
		}