예제 #1
0
 private async Task HandleBrokersChanging(WatchResponse watchResponse)
 {
     if (watchResponse.Events.Count != 0)
     {
         await HandleRepartitioning(_topic);
     }
 }
예제 #2
0
 private async void SetNewElection(WatchResponse watchResponse)
 {
     if (watchResponse.Events.Any(eventS => eventS.Type == Event.Types.EventType.Delete))
     {
         await Election();
     }
 }
예제 #3
0
        /// <summary>
        /// Watches a key according to the specified watch request and
        /// passes the watch response to the method provided.
        /// </summary>
        /// <param name="request">Watch Request containing key to be watched</param>
        /// <param name="method">Method to which watch response should be passed on</param>
        public async void Watch(WatchRequest request, Action <WatchResponse> method)
        {
            try
            {
                using (AsyncDuplexStreamingCall <WatchRequest, WatchResponse> watcher = _watchClient.Watch())
                {
                    Task watcherTask = Task.Run(async() =>
                    {
                        while (await watcher.ResponseStream.MoveNext())
                        {
                            WatchResponse update = watcher.ResponseStream.Current;
                            method(update);
                        }
                    });

                    await watcher.RequestStream.WriteAsync(request);

                    await watcher.RequestStream.CompleteAsync();

                    await watcherTask;
                }
            }
            catch (RpcException)
            {
                // If connection issue, then re-initate the watch
                ResetConnection();
                Watch(request, method);
            }
            catch
            {
                throw;
            }
        }
예제 #4
0
        /// <summary>
        /// Watches a key range according to the specified watch requests and
        /// passes the watch response to the methods provided.
        /// </summary>
        /// <param name="requests">Watch Requests containing keys to be watched</param>
        /// <param name="methods">Methods to which watch response should be passed on</param>
        public async void WatchRange(WatchRequest[] requests, Action <WatchResponse>[] methods, Metadata headers = null)
        {
            using (AsyncDuplexStreamingCall <WatchRequest, WatchResponse> watcher = _balancer.GetConnection().watchClient.Watch(headers))
            {
                Task watcherTask = Task.Run(async() =>
                {
                    while (await watcher.ResponseStream.MoveNext())
                    {
                        WatchResponse update = watcher.ResponseStream.Current;
                        foreach (Action <WatchResponse> method in methods)
                        {
                            method(update);
                        }
                    }
                });

                foreach (WatchRequest request in requests)
                {
                    await watcher.RequestStream.WriteAsync(request);
                }

                await watcher.RequestStream.CompleteAsync();

                await watcherTask;
            }
        }
예제 #5
0
        private void ProcessCanceled(WatchResponse response)
        {
            WatcherImpl watcher = null;

            this.watchers.TryGetValue(response.GetWatchId(), out watcher);
            this.cancelSet.Remove(response.GetWatchId());
            if (watcher == null)
            {
                return;
            }
            string reason = response.GetCancelReason();

            if (string.IsNullOrEmpty(reason))
            {
                watcher.Enqueue(new WatchResponseWithError(new EtcdException(
                                                               ErrorCode.OUT_OF_RANGE,
                                                               "etcdserver: mvcc: required revision is a future revision"))
                                );
            }
            else
            {
                watcher.Enqueue(
                    new WatchResponseWithError(new EtcdException(ErrorCode.FAILED_PRECONDITION, reason)));
            }
        }
예제 #6
0
            public List <WatchEvent> GetLastEvent()
            {
                List <WatchEvent> list = new List <WatchEvent>();
                var watchResponse      = new WatchResponse(stream.ResponseStream.Current);
                var cur = watchResponse.GetEvents();

                if (cur.Count > 0)
                {
                    list.Add(cur[cur.Count - 1]);
                    this.OnNext(stream.ResponseStream.Current);
                }
                while (true)
                {
                    var task = stream.ResponseStream.MoveNext();
                    if (task.Result)
                    {
                        watchResponse = new WatchResponse(stream.ResponseStream.Current);
                        cur           = watchResponse.GetEvents();
                        if (cur.Count > 0)
                        {
                            list.Add(cur[cur.Count - 1]);
                            this.OnNext(stream.ResponseStream.Current);
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                return(list);
            }
        public async Task CorrectExchangeRequestShouldReturnCurrency()
        {
            // Arrange
            //
            var expected = new WatchResponse
            {
                ExchangeRateInfo = new ExchangeRateInfo
                {
                    RequestStatus = new RequestStatus(RequestStatusCode.Ok),
                    ExchangeRate  = (decimal)1.1
                }
            };

            // Act
            //
            var faceSetting = _factory.Services.GetRequiredService <FaceSettings>();
            var url         = $"/api/v2/YAFace?apiToken={faceSetting.AuthSettings.Token}&did=test-device12&bc=USD&tc=DKK";
            var response    = await _client.GetAsync(url);

            // Assert
            //
            response.EnsureSuccessStatusCode();

            var actual = JsonSerializer.Deserialize <WatchResponse>(await response.Content.ReadAsStringAsync());

            Assert.Equal(expected.ExchangeRateInfo.ExchangeRate, actual.ExchangeRateInfo.ExchangeRate);
            Assert.Equal(RequestStatusCode.Ok, actual.ExchangeRateInfo.RequestStatus.StatusCode);
        }
예제 #8
0
        private void ProcessEvents(WatchResponse response)
        {
            WatcherImpl watcher = null;

            this.watchers.TryGetValue(response.GetWatchId(), out watcher);
            if (watcher == null)
            {
                // cancel server side watcher.
                this.CancelWatcher(response.GetWatchId());
                return;
            }

            if (response.GetCompactRevision() != 0)
            {
                watcher.Enqueue(new WatchResponseWithError(
                                    new EtcdException(response.GetCompactRevision())));
                return;
            }

            if (response.GetEventsCount() == 0)
            {
                watcher.SetRevision(response.GetHeader().GetRevision());
                return;
            }
            watcher.Enqueue(new WatchResponseWithError(response));
            //watcher.SetRevision(
            //    response.GetEvents(response.GetEventsCount() - 1)
            //        .GetKv().getModRevision() + 1);
        }
예제 #9
0
 private static void SetNewElection(WatchResponse watchResponse)
 {
     if (watchResponse.Events.Any(eventS => eventS.Type == Event.Types.EventType.Delete))
     {
         NewElection = true;
     }
 }
        //asinhroni prijem iz etcd-a
        public void EtcdNotification(WatchResponse response) //proveri na watch da li se dobija value ili key
        {
            string value = response.Events[0].Kv.Value.ToString();

            string[] s = value.Split('|');
            Notification(Int32.Parse(s[0]), s[1]);
        }
예제 #11
0
        private void watchModelVersion(WatchResponse watchResponse)
        {
            Console.WriteLine("Fire Watch");
            if (watchResponse.Events.Count > 0 && watchResponse.Events[0].Kv != null)
            {
                Console.WriteLine(
                    $"{watchResponse.Events[0].Kv.Key.ToStringUtf8()}:{watchResponse.Events[0].Kv.Value.ToStringUtf8()}");
                var json = watchResponse.Events[0].Kv.Value.ToStringUtf8();
                var maybeModelVersion = deserialize <ModelVersion>(json);
                if (maybeModelVersion.IsSuccess)
                {
                    maybeModelVersion.IfSucc(version =>
                    {
                        lock (model_version_lock)
                        {
                            if (version.TimeStamp != _modelVersion.TimeStamp)
                            {
                                _modelVersion = version;
                            }
                        }

                        filterOutModelVersions();
                    });
                }

                Console.WriteLine("Got new modelversion - {0}", _modelVersion);
            }
        }
예제 #12
0
        /// <summary>
        /// Watches a key range according to the specified watch requests and
        /// passes the minimal watch event data to the methods provided.
        /// </summary>
        /// <param name="requests">Watch Request containing keys to be watched</param>
        /// <param name="methods">Methods to which minimal watch events data should be passed on</param>
        public async void WatchRange(WatchRequest[] requests, Action <WatchEvent[]>[] methods, Metadata headers = null)
        {
            using (AsyncDuplexStreamingCall <WatchRequest, WatchResponse> watcher = _balancer.GetConnection().watchClient.Watch(headers))
            {
                Task watcherTask = Task.Run(async() =>
                {
                    while (await watcher.ResponseStream.MoveNext())
                    {
                        WatchResponse update = watcher.ResponseStream.Current;
                        foreach (Action <WatchEvent[]> method in methods)
                        {
                            method(update.Events.Select(i =>
                            {
                                return(new WatchEvent
                                {
                                    Key = i.Kv.Key.ToStringUtf8(),
                                    Value = i.Kv.Value.ToStringUtf8(),
                                    Type = i.Type
                                });
                            }).ToArray()
                                   );
                        }
                    }
                });

                foreach (WatchRequest request in requests)
                {
                    await watcher.RequestStream.WriteAsync(request);
                }

                await watcher.RequestStream.CompleteAsync();

                await watcherTask;
            }
        }
예제 #13
0
        private void nodesWatch(WatchResponse response)
        {
            if (response.Events.Count == 0)
            {
                Console.WriteLine(response);
            }
            else
            {
                Console.WriteLine(
                    $"{response.Events[0].Kv.Key.ToStringUtf8()}:{response.Events[0].Kv.Value.ToStringUtf8()}");
            }

            foreach (var responseEvent in response.Events)
            {
                if (responseEvent != null && responseEvent.Kv.Key != null)
                {
                    var key = responseEvent.Kv.Key.ToStringUtf8();
                    if (responseEvent.Kv.Value != null)
                    {
                        Result <APIHostPort> value = deserialize <APIHostPort>(responseEvent.Kv.Value.ToStringUtf8());
                        Console.WriteLine("Got new apiHostPort - {0}", value);
                        consumeAndAddApiHostPort(value);
                    }
                }
            }
        }
예제 #14
0
 private async void HandleTopicListWatch(WatchResponse response)
 {
     foreach (var responseEvent in response.Events)
     {
         await HandleElectionForKeyValue(responseEvent.Kv);
     }
 }
        //asinhroni prijem iz etcd-a
        public void EtcdElected(WatchResponse response) //proveri na watch da li se dobija value ili key
        {
            string value = response.Events[0].Kv.Value.ToString();

            IsLeader = value.Equals(myId);
            if (IsLeader)
            {
                ExecuteHistoryRequests();
            }
        }
예제 #16
0
        /// <summary>
        /// Watches a key range according to the specified watch requests and
        /// passes the minimal watch event data to the methods provided.
        /// </summary>
        /// <param name="requests">Watch Request containing keys to be watched</param>
        /// <param name="methods">Methods to which minimal watch events data should be passed on</param>
        public async void WatchRange(WatchRequest[] requests, Action <WatchEvent[]>[] methods, Metadata headers = null)
        {
            bool success    = false;
            int  retryCount = 0;

            while (!success)
            {
                try
                {
                    using (AsyncDuplexStreamingCall <WatchRequest, WatchResponse> watcher = _balancer.GetConnection().watchClient.Watch(headers))
                    {
                        Task watcherTask = Task.Run(async() =>
                        {
                            while (await watcher.ResponseStream.MoveNext())
                            {
                                WatchResponse update = watcher.ResponseStream.Current;
                                foreach (Action <WatchEvent[]> method in methods)
                                {
                                    method(update.Events.Select(i =>
                                    {
                                        return(new WatchEvent
                                        {
                                            Key = i.Kv.Key.ToStringUtf8(),
                                            Value = i.Kv.Value.ToStringUtf8(),
                                            Type = i.Type
                                        });
                                    }).ToArray()
                                           );
                                }
                            }
                        });

                        foreach (WatchRequest request in requests)
                        {
                            await watcher.RequestStream.WriteAsync(request);
                        }

                        await watcher.RequestStream.CompleteAsync();

                        await watcherTask;
                    }
                    success = true;
                }
                catch (RpcException ex) when(ex.StatusCode == StatusCode.Unavailable)
                {
                    retryCount++;
                    if (retryCount >= _balancer._numNodes)
                    {
                        throw ex;
                    }
                }
            }
        }
예제 #17
0
        private async Task WatchCoreAsync(WatchRequest request, Action <WatchResponse> method, Metadata headers = null,
                                          Action <Exception> exceptionHandler = null)
        {
            var success    = false;
            var retryCount = 0;

            while (!success)
            {
                try
                {
                    using (AsyncDuplexStreamingCall <WatchRequest, WatchResponse> watcher =
                               _balancer.GetConnection().watchClient.Watch(headers))
                    {
                        await watcher.RequestStream.WriteAsync(request);

                        await watcher.RequestStream.CompleteAsync();

                        try
                        {
                            while (await watcher.ResponseStream.MoveNext())
                            {
                                WatchResponse update = watcher.ResponseStream.Current;
                                method(update);
                            }
                        }
                        catch (Exception ex)
                        {
                            if (exceptionHandler != null)
                            {
                                exceptionHandler(ex);
                            }
                            else
                            {
                                throw ex;
                            }
                        }

                        ;
                    }

                    success = true;
                }
                catch (RpcException ex) when(ex.StatusCode == StatusCode.Unavailable)
                {
                    retryCount++;
                    if (retryCount >= _balancer._numNodes)
                    {
                        throw ex;
                    }
                }
            }
        }
예제 #18
0
 private static void Print(WatchResponse response)
 {
     if (response.Events.Count == 0)
     {
         Console.WriteLine(response);
     }
     else
     {
         foreach (var responseEvent in response.Events)
         {
             Console.WriteLine($"{responseEvent.Kv.Key.ToStringUtf8()}:{responseEvent.Kv.Value.ToStringUtf8()}");
         }
     }
 }
예제 #19
0
        /// <summary>
        /// Watches a key according to the specified watch requests and
        /// passes the minimal watch event data to the methods provided.
        /// </summary>
        /// <param name="requests">Watch Request containing keys to be watched</param>
        /// <param name="methods">Methods to which minimal watch events data should be passed on</param>
        public async void Watch(WatchRequest[] requests, Action <WatchEvent[]>[] methods)
        {
            try
            {
                using (AsyncDuplexStreamingCall <WatchRequest, WatchResponse> watcher = _watchClient.Watch())
                {
                    Task watcherTask = Task.Run(async() =>
                    {
                        while (await watcher.ResponseStream.MoveNext())
                        {
                            WatchResponse update = watcher.ResponseStream.Current;
                            foreach (Action <WatchEvent[]> method in methods)
                            {
                                method(update.Events.Select(i =>
                                {
                                    return(new WatchEvent
                                    {
                                        Key = i.Kv.Key.ToStringUtf8(),
                                        Value = i.Kv.Value.ToStringUtf8(),
                                        Type = i.Type
                                    });
                                }).ToArray()
                                       );
                            }
                        }
                    });

                    foreach (WatchRequest request in requests)
                    {
                        await watcher.RequestStream.WriteAsync(request);
                    }

                    await watcher.RequestStream.CompleteAsync();

                    await watcherTask;
                }
            }
            catch (RpcException)
            {
                // If connection issue, then re-initate the watch
                ResetConnection();
                Watch(requests, methods);
            }
            catch
            {
                throw;
            }
        }
        public async Task NullRequestShouldReturnEmptyResponse()
        {
            // Arrange
            //
            var expected     = new WatchResponse();
            var expectedJson = JsonSerializer.Serialize(expected);

            // Act
            //
            var faceSetting = _factory.Services.GetRequiredService <FaceSettings>();
            var response    = await _client.GetAsync($"/api/v2/YAFace?apiToken={faceSetting.AuthSettings.Token}");

            // Assert
            //
            response.EnsureSuccessStatusCode(); // Status Code 2xx
            Assert.Equal(expectedJson, await response.Content.ReadAsStringAsync());
        }
예제 #21
0
 public static void watch()
 {
     try
     {
         WatchRequest body = new WatchRequest()
         {
             TopicName = "projects/awolr-213414/topics/awolr",
             LabelIds  = new[] { "INBOX" }
         };
         string userId = "*****@*****.**";
         UsersResource.WatchRequest watchRequest = service.Users.Watch(body, userId);
         WatchResponse test = watchRequest.Execute();
     }
     catch (Exception e)
     {
         Console.WriteLine("cannot initiate watch request " + e);
     }
 }
예제 #22
0
        //private  StreamObserver<WatchRequest> getGrpcWatchStreamObserver() {
        //          lock (this)
        //          {
        //              if (this.grpcWatchStreamObserver == null)
        //              {
        //                  this.grpcWatchStreamObserver = this.stub.Watch(this.createWatchStreamObserver());
        //              }
        //          }
        //  return this.grpcWatchStreamObserver;
        //}

        //private StreamObserver<WatchResponse>CreateWatchStreamObserver() {
        //        return  StreamObserver<WatchResponse>();
        //}

        private void processWatchResponse(WatchResponse watchResponse)
        {
            // prevents grpc on sending watchResponse to a closed watch client.
            //if (this.isClosed()) {
            //  return;
            //}

            //if (watchResponse.getCreated()) {
            //  processCreate(watchResponse);
            //} else if (watchResponse.getCanceled()) {
            //  processCanceled(watchResponse);
            //} else {
            //  processEvents(watchResponse);
            //}
            //  }
            // resume with a delay; avoiding immediate retry on a long connection downtime.
            //Util.addOnFailureLoggingCallback(scheduledExecutorService.schedule(this::resume, 500, TimeUnit.MILLISECONDS),
            //   LOG, "scheduled resume failed");
        }
예제 #23
0
        /// <summary>
        /// Watches a key range according to the specified watch request and
        /// passes the minimal watch event data to the method provided.
        /// </summary>
        /// <param name="request">Watch Request containing key to be watched</param>
        /// <param name="method">Method to which minimal watch events data should be passed on</param>
        public async void WatchRange(WatchRequest request, Action <WatchEvent[]> method)
        {
            try
            {
                using (AsyncDuplexStreamingCall <WatchRequest, WatchResponse> watcher = _watchClient.Watch(_headers))
                {
                    Task watcherTask = Task.Run(async() =>
                    {
                        while (await watcher.ResponseStream.MoveNext())
                        {
                            WatchResponse update = watcher.ResponseStream.Current;
                            method(update.Events.Select(i =>
                            {
                                return(new WatchEvent
                                {
                                    Key = i.Kv.Key.ToStringUtf8(),
                                    Value = i.Kv.Value.ToStringUtf8(),
                                    Type = i.Type
                                });
                            }).ToArray()
                                   );
                        }
                    });

                    await watcher.RequestStream.WriteAsync(request);

                    await watcher.RequestStream.CompleteAsync();

                    await watcherTask;
                }
            }
            catch (RpcException ex) when(ex.Status.Equals(StatusCode.Unavailable))
            {
                // If connection issue, then re-initate the watch
                ResetConnection(ex);
                Watch(request, method);
            }
            catch
            {
                throw;
            }
        }
예제 #24
0
        /// <summary>
        /// Watches a key according to the specified watch request and
        /// passes the watch response to the methods provided.
        /// </summary>
        /// <param name="request">Watch Request containing key to be watched</param>
        /// <param name="methods">Methods to which watch response should be passed on</param>
        public async void Watch(WatchRequest request, Action <WatchResponse>[] methods, Metadata headers = null)
        {
            bool success    = false;
            int  retryCount = 0;

            while (!success)
            {
                try
                {
                    using (AsyncDuplexStreamingCall <WatchRequest, WatchResponse> watcher = _balancer.GetConnection().watchClient.Watch(headers))
                    {
                        Task watcherTask = Task.Run(async() =>
                        {
                            while (await watcher.ResponseStream.MoveNext())
                            {
                                WatchResponse update = watcher.ResponseStream.Current;
                                foreach (Action <WatchResponse> method in methods)
                                {
                                    method(update);
                                }
                            }
                        });

                        await watcher.RequestStream.WriteAsync(request);

                        await watcher.RequestStream.CompleteAsync();

                        await watcherTask;
                    }
                    success = true;
                }
                catch (RpcException ex) when(ex.StatusCode == StatusCode.Unavailable)
                {
                    retryCount++;
                    if (retryCount >= _balancer._numNodes)
                    {
                        throw ex;
                    }
                }
            }
        }
예제 #25
0
        public async Task <WatchResponse> WatchAsync(WatcherParameter parameter)
        {
            var response = new WatchResponse();

            using (var connection = new NpgsqlConnection(parameter.Values["ConnectionString"]))
            {
                try
                {
                    await connection.OpenAsync();

                    response.Successful = true;
                }
                catch (Exception ex)
                {
                    response.ShortMessage = ex.Message;
                    response.FullMessage  = ex.ToString();
                }
            }

            return(response);
        }
        public async Task <WatchResponse> WatchAsync(WatcherParameter parameter)
        {
            var response = new WatchResponse();

            try
            {
                using (var httpClient = new HttpClient())
                {
                    await httpClient.GetAsync(parameter.Values["Url"]);

                    response.Successful = true;
                }
            }
            catch (Exception ex)
            {
                response.ShortMessage = ex.Message;
                response.FullMessage  = ex.ToString();
            }

            return(response);
        }
예제 #27
0
        /// <summary>
        /// Watches a key range according to the specified watch requests and
        /// passes the watch response to the methods provided.
        /// </summary>
        /// <param name="requests">Watch Requests containing keys to be watched</param>
        /// <param name="methods">Methods to which watch response should be passed on</param>
        public async void WatchRange(WatchRequest[] requests, Action <WatchResponse>[] methods)
        {
            try
            {
                using (AsyncDuplexStreamingCall <WatchRequest, WatchResponse> watcher = _watchClient.Watch(_headers))
                {
                    Task watcherTask = Task.Run(async() =>
                    {
                        while (await watcher.ResponseStream.MoveNext())
                        {
                            WatchResponse update = watcher.ResponseStream.Current;
                            foreach (Action <WatchResponse> method in methods)
                            {
                                method(update);
                            }
                        }
                    });

                    foreach (WatchRequest request in requests)
                    {
                        await watcher.RequestStream.WriteAsync(request);
                    }

                    await watcher.RequestStream.CompleteAsync();

                    await watcherTask;
                }
            }
            catch (RpcException ex) when(ex.Status.Equals(StatusCode.Unavailable))
            {
                // If connection issue, then re-initate the watch
                ResetConnection(ex);
                Watch(requests, methods);
            }
            catch
            {
                throw;
            }
        }
예제 #28
0
            public List <WatchEvent> ReadAll()
            {
                List <WatchEvent> list = new List <WatchEvent>();
                var watchResponse      = new WatchResponse(stream.ResponseStream.Current);

                list.AddRange(watchResponse.GetEvents());
                this.OnNext(stream.ResponseStream.Current);
                while (true)
                {
                    var task = stream.ResponseStream.MoveNext();
                    if (task.Result)
                    {
                        watchResponse = new WatchResponse(stream.ResponseStream.Current);
                        list.AddRange(watchResponse.GetEvents());
                        this.OnNext(stream.ResponseStream.Current);
                    }
                    else
                    {
                        break;
                    }
                }
                return(list);
            }
예제 #29
0
        private void ProcessCreate(WatchResponse response)
        {
            WatcherImpl watcher = null;

            this.pendingWatchers.TryDequeue(out watcher);

            this.SendNextWatchCreateRequest();

            if (watcher == null)
            {
                // shouldn't happen
                // may happen due to duplicate watch create responses.
                // LOG.warn("Watch client receives watch create response but find no corresponding watcher");
                return;
            }

            if (watcher.IsClosed())
            {
                return;
            }

            if (response.GetWatchId() == -1)
            {
                watcher.Enqueue(new WatchResponseWithError(
                                    new EtcdException(ErrorCode.INTERNAL, "etcd server failed to create watch id")));
                return;
            }

            if (watcher.GetRevision() == 0)
            {
                watcher.SetRevision(response.GetHeader().GetRevision());
            }

            watcher.SetWatchID(response.GetWatchId());
            this.watchers[watcher.GetWatchID()] = watcher;
        }
예제 #30
0
            private WatchResponse CreateWatchResponseFuture()
            {
                WatchResponse watchResponse = null;

                return(watchResponse = new WatchResponse(stream.ResponseStream.Current));
            }