private async Task EnsureSendHealthUpdateAsync(HealthUpdate update)
        {
            while (!_cancelationTokenSource.IsCancellationRequested)
            {
                try
                {
                    await SendHealthUpdateAsync(update);

                    _retryInterval = null;
                    return;
                }
                catch (Exception e) when(!_cancelationTokenSource.IsCancellationRequested)
                {
                    BackOffPlan backOffPlan = await _backOffStategy.GetCurrent(_retryInterval, _cancelationTokenSource.Token);

                    if (backOffPlan.ShouldLog)
                    {
                        _logger.Error("Unable to send health update", e);
                    }

                    _retryInterval = backOffPlan.RetryInterval;

                    if (_retryInterval.HasValue)
                    {
                        await SafeDelay(_retryInterval.Value);
                    }
                }
            }
        }
Ejemplo n.º 2
0
 public void ClearDelegates()
 {
     PlayerHealthUpdateCall = null;
     EnemyHealthUpdateCall  = null;
     CombatEndVictoryCall   = null;
     CombatEndDefeatCall    = null;
 }
Ejemplo n.º 3
0
        public async Task Notifier_should_send_current_health_to_the_API()
        {
            var endpointId     = Guid.NewGuid();
            var expectedHealth = new EndpointHealth(HealthStatus.Offline, new Dictionary <string, string> {
                { "key", "value" }
            });
            HealthUpdate lastCaptured = null;
            var          countdown    = new AsyncCountdown("update", 5);

            SetupHealthCheckInterval(TimeSpan.FromMilliseconds(1));
            SetupEndpointRegistration(endpointId);

            _mockClient.Setup(c => c.SendHealthUpdateAsync(endpointId, AuthenticationToken, It.IsAny <HealthUpdate>(), It.IsAny <CancellationToken>()))
            .Returns((Guid id, string authToken, HealthUpdate upd, CancellationToken token) => _awaitableFactory
                     .Execute(() => lastCaptured = upd)
                     .WithCountdown(countdown)
                     .RunAsync());

            using (CreateNotifier(token => Task.FromResult(expectedHealth)))
                await countdown.WaitAsync(TestMaxTime);

            Assert.NotNull(lastCaptured);
            Assert.Equal(expectedHealth.Status, lastCaptured.Status);
            Assert.Equal(expectedHealth.Details, lastCaptured.Details);
            Assert.True(lastCaptured.CheckTimeUtc > DateTime.UtcNow.AddMinutes(-1) && lastCaptured.CheckTimeUtc < DateTime.UtcNow.AddMinutes(1));
        }
Ejemplo n.º 4
0
        private void SendUpdate()
        {
            /* construct the update object so send */
            HealthUpdate dt = new HealthUpdate();

            //get the machine name
            dt.Name = Environment.MachineName;

            //get the cpu info
            var cpu = getCPUCounter();

            if (cpu != null)
            {
                dt.CPU = (float)cpu;
            }

            //get the ram info
            var ram = getAvailableRAM();

            if (!float.IsNaN(ram))
            {
                dt.RAM = (decimal)ram;
            }

            //get hard disk space
            DriveInfo cDrive = DriveInfo.GetDrives()[0];//1st disk only

            dt.DISK = (float)cDrive.AvailableFreeSpace / 10000000000;

            //now transmit it to the server
            Transmit(dt);
        }
 private static bool AssertHealth(EndpointHealth actual, HealthUpdate expected)
 {
     Assert.Equal(expected.CheckTimeUtc, actual.CheckTimeUtc);
     Assert.Equal(expected.ResponseTime, actual.ResponseTime);
     Assert.Equal(expected.Status, actual.Status);
     Assert.Equal(expected.Details, actual.Details);
     return(true);
 }
 public void GetPendingUpdatesTest()
 {
     using (MemberRepository MR = new MemberRepository())
     {
         HealthUpdate update = MR.GetPendingUpdatesAsync(3).Result;
         Assert.AreEqual(false, update.IsProfileActive);
     }
 }
Ejemplo n.º 7
0
        public void GetPendingUpdatesTest()
        {
            MemberService MS = new MemberService();

            HealthUpdate update = MS.CheckPendingUpdates("4", DateTime.Now.AddDays(-20).ToString(), DateTime.Now.Ticks.ToString()).Result;

            Assert.AreEqual(false, update.IsProfileActive);
        }
Ejemplo n.º 8
0
        public IHttpActionResult Post([FromBody] HealthUpdate anUpdate)
        {
            anUpdate.TimeStamp = DateTime.Now;
            //var db = GHModel.HealthUpdate.
            _context.HealthUpdates.Add(anUpdate);

            _context.SaveChanges();

            return(Ok(anUpdate));
        }
Ejemplo n.º 9
0
        public static async Task <HealthUpdate> GetSystemHealthAsync()
        {
            HealthUpdate objHealth = null;

            if (IsDataNetworkAvailable && IsRegisteredUser)
            {
                objHealth = await MembershipServiceWrapper.CheckPendingUpdates(CurrentProfile.ProfileId, CurrentProfile.LastSynced.HasValue?CurrentProfile.LastSynced.Value : DateTime.MinValue);
            }
            return(objHealth);
        }
Ejemplo n.º 10
0
        void UpdateSubscribers()
        {
            var message = new HealthUpdate();

            _healthSagas
            .Select(x => new HealthInformation(x.CorrelationId, x.ControlUri, x.DataUri, x.LastHeartbeat, x.CurrentState.Name))
            .Each(x => message.Information.Add(x));

            _log.Debug("Publishing HealthUpdate");
            _bus.Publish(message);
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Take damage from opponent's weapon
 /// </summary>
 /// <param name="amount">damage amount</param>
 public void TakeDamage(int amount)
 {
     if (currentHealth > 0)
     {
         currentHealth -= amount;
         HealthUpdate?.Invoke(currentHealth);
         if (currentHealth <= 0)
         {
             OnDie();
         }
     }
 }
Ejemplo n.º 12
0
 public void OnHealthUpdate(HealthUpdate package)
 {
     _stateHandler.EntityManager.HealthUpdate(
         package.ObjectId,
         package.TimeStamp,
         package.HealthChange,
         package.NewHealthValue,
         package.EffectType,
         package.EffectOrigin,
         package.CauserId,
         package.CausingSpellType
         );
 }
        private async Task SendHealthUpdateAsync(HealthUpdate update)
        {
            var endpointId = _endpointId ?? (_endpointId = await RegisterEndpointAsync()).Value;

            try
            {
                await _client.SendHealthUpdateAsync(endpointId, _definition.Password, update, _cancelationTokenSource.Token);
            }
            catch (EndpointNotFoundException)
            {
                _endpointId = null;
            }
        }
        public void PostEndpointHealth_should_return_NotFound_status_for_unknown_endpoint()
        {
            var endpointId = Guid.NewGuid();
            var update     = new HealthUpdate {
                CheckTimeUtc = _utcNow, Status = EndpointStatus.Offline, ResponseTime = TimeSpan.FromSeconds(5), Details = new Dictionary <string, string> {
                    { "a", "b" }
                }
            };

            _endpointRegistry.Setup(r => r.UpdateHealth(endpointId, It.IsAny <EndpointHealth>())).Returns(false);
            AuthorizeWithId(endpointId);
            Assert.IsType <NotFoundResult>(_controller.PostEndpointHealth(endpointId, update));
        }
        public void PostEndpointHealth_should_update_health()
        {
            var endpointId = Guid.NewGuid();
            var update     = new HealthUpdate {
                CheckTimeUtc = _utcNow, Status = EndpointStatus.Offline, ResponseTime = TimeSpan.FromSeconds(5), Details = new Dictionary <string, string> {
                    { "a", "b" }
                }
            };

            _endpointRegistry.Setup(r => r.UpdateHealth(endpointId, It.IsAny <EndpointHealth>())).Returns(true);
            AuthorizeWithId(endpointId);
            Assert.IsType <OkResult>(_controller.PostEndpointHealth(endpointId, update));

            _endpointRegistry.Verify(r => r.UpdateHealth(endpointId, It.Is <EndpointHealth>(h => AssertHealth(h, update))), Times.Once);
        }
Ejemplo n.º 16
0
        /// <summary>Transmit the HealthUpdate to the central server</summary>
        /// <param name="hu">The HealthUpdate to send.</param>
        private void Transmit(HealthUpdate hu)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            httpWebRequest.ContentType = "text/json";
            httpWebRequest.Method      = "POST";

            var json = new JavaScriptSerializer().Serialize(hu);

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
            }
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        }
        public IHttpActionResult PostEndpointHealth(Guid id, [FromBody] HealthUpdate health, DateTimeOffset?clientCurrentTime = null)
        {
            if (_endpointRegistry.GetById(id) != null)
            {
                RequestContext.Authorize(id);
            }

            health.ValidateModel();
            var clockDifference = GetServerToClientTimeDifference(clientCurrentTime);

            if (!_endpointRegistry.UpdateHealth(id, health.ToEndpointHealth(clockDifference)))
            {
                return(NotFound());
            }

            return(Ok());
        }
Ejemplo n.º 18
0
    private void RefreshHealth(HealthUpdate ignored)
    {
        heartbeatList.Items.Clear();

        foreach (HealthInformation information in ignored.Information)
        {
            var items = new[]
            {
                information.Uri.ToString(),
                                   information.State
                //information.FirstDetectedAt.Value.ToString("hh:mm:ss"),
                //information.LastDetectedAt.Value.ToString("hh:mm:ss")
            };
            var lvi = new ListViewItem(items);
            heartbeatList.Items.Add(lvi);
        }
    }
Ejemplo n.º 19
0
        public async Task <HealthUpdate> GetPendingUpdatesAsync(long ProfileID)
        {
            return(await _sqlAzureExecutionStrategy.ExecuteAsync <HealthUpdate>(async() =>
            {
                HealthUpdate pendingUpdate = new HealthUpdate();

                pendingUpdate.IsGroupModified = false;
                pendingUpdate.IsProfileActive = false;

                Profile updatedProfile = null;
                GroupMembership updatedGroup = null;

                List <Task> tasks = new List <Task>();

                Task <Profile> profileTask = _guardianContext.Profiles
                                             .Where(w => w.ProfileID == ProfileID)
                                             .AsNoTracking().FirstOrDefaultAsync();

                Task <GroupMembership> groupTask = _guardianContext.GroupMemberships
                                                   .Where(w => w.ProfileID == ProfileID)
                                                   .AsNoTracking().FirstOrDefaultAsync();

                tasks.Add(profileTask);
                tasks.Add(groupTask);
                Task.WaitAll(tasks.ToArray());

                updatedProfile = profileTask.Result;
                updatedGroup = groupTask.Result;

                if (updatedProfile != null)
                {
                    pendingUpdate.IsProfileActive = updatedProfile.IsValid;
                }

                if (updatedGroup != null)
                {
                    pendingUpdate.IsGroupModified = true;
                }

                return pendingUpdate;
            }, CancellationToken.None));
        }
Ejemplo n.º 20
0
        private async Task EnsureSendHealthUpdateAsync(HealthUpdate update)
        {
            int repeats = 1;

            while (!_cancelationTokenSource.IsCancellationRequested)
            {
                try
                {
                    await SendHealthUpdateAsync(update);

                    return;
                }
                catch (Exception e) when(!_cancelationTokenSource.IsCancellationRequested)
                {
                    _logger.Error("Unable to send health update", e);
                    await SafeDelay(TimeSpan.FromSeconds(Math.Min(MaxRepeatDelayInSecs, repeats)));

                    repeats *= 2;
                }
            }
        }
        public void PostEndpointHealth_should_update_health_and_adjust_check_time_with_clientServer_time_difference()
        {
            var endpointId = Guid.NewGuid();
            var update     = new HealthUpdate {
                CheckTimeUtc = _utcNow, Status = EndpointStatus.Offline, ResponseTime = TimeSpan.FromSeconds(5), Details = new Dictionary <string, string> {
                    { "a", "b" }
                }
            };
            var timeDifference = TimeSpan.FromMinutes(5);

            var expected = new HealthUpdate
            {
                CheckTimeUtc = update.CheckTimeUtc - timeDifference,
                Details      = update.Details,
                ResponseTime = update.ResponseTime,
                Status       = update.Status
            };

            _endpointRegistry.Setup(r => r.UpdateHealth(endpointId, It.IsAny <EndpointHealth>())).Returns(true);
            AuthorizeWithId(endpointId);
            Assert.IsType <OkResult>(_controller.PostEndpointHealth(endpointId, update, _utcNow + timeDifference));
            _endpointRegistry.Verify(r => r.UpdateHealth(endpointId, It.Is <EndpointHealth>(h => AssertHealth(h, expected))), Times.Once);
        }
Ejemplo n.º 22
0
        public async Task Notifier_should_send_faulty_health_to_the_API_if_provided_health_method_throws()
        {
            var          endpointId   = Guid.NewGuid();
            HealthUpdate lastCaptured = null;
            var          countdown    = new AsyncCountdown("update", 5);

            SetupHealthCheckInterval(TimeSpan.FromMilliseconds(1));
            SetupEndpointRegistration(endpointId);

            _mockClient.Setup(c => c.SendHealthUpdateAsync(endpointId, AuthenticationToken, It.IsAny <HealthUpdate>(), It.IsAny <CancellationToken>()))
            .Returns((Guid id, string authToken, HealthUpdate upd, CancellationToken token) => _awaitableFactory
                     .Execute(() => lastCaptured = upd)
                     .WithCountdown(countdown)
                     .RunAsync());

            using (CreateNotifier(async token => { await Task.Delay(50, token); throw new InvalidOperationException("some reason"); }))
                await countdown.WaitAsync(TestMaxTime);

            Assert.NotNull(lastCaptured);
            Assert.Equal(HealthStatus.Faulty, lastCaptured.Status);
            Assert.Equal("Unable to collect health information", lastCaptured.Details["reason"]);
            Assert.True(lastCaptured.Details["exception"].StartsWith("System.InvalidOperationException: some reason"));
            Assert.True(lastCaptured.CheckTimeUtc > DateTime.UtcNow.AddMinutes(-1) && lastCaptured.CheckTimeUtc < DateTime.UtcNow.AddMinutes(1));
        }
Ejemplo n.º 23
0
 public void updateHealth(HealthUpdate u)
 {
     playerHPText.text = u.Health.ToString();
 }
Ejemplo n.º 24
0
 public async Task SendHealthUpdateAsync(Guid endpointId, string authenticationToken, HealthUpdate update, CancellationToken cancellationToken)
 {
     _logger.Info($"Sending health update: {update.Status}");
     using (var client = new HttpClient())
     {
         Authorize(client, endpointId, authenticationToken);
         var result = await PostAsync(client, $"/api/endpoints/{endpointId}/health?clientCurrentTime={DateTimeOffset.UtcNow.ToString("u", CultureInfo.InvariantCulture)}", update, cancellationToken);
         if (result.StatusCode == HttpStatusCode.NotFound)
             throw new EndpointNotFoundException();
         result.EnsureSuccessStatusCode();
     }
 }
Ejemplo n.º 25
0
        public void Consume(HealthUpdate message)
        {
            Action <IEnumerable <HealthInformation> > method = RefreshHealthView;

            BeginInvoke(method, new object[] { message.Information });
        }
Ejemplo n.º 26
0
    private void HeartBeatRefreshNeeded(HealthUpdate message)
    {
        ThreadSafeUpdate2 tsu = RefreshHealth;

        BeginInvoke(tsu, new object[] { message });
    }
Ejemplo n.º 27
0
 public void Consume(HealthUpdate message)
 {
     HeartBeatRefreshNeeded(message);
 }