/// <summary>
        /// Executes the health check plugin
        /// </summary>
        protected override void Execute()
        {
            try
            {
                HealthCheck.Execute();
            }
            catch (Exception ex)
            {
                var incidentCorrelationId = Guid.NewGuid();
                var msg = string.Format("Wolfpack Component Failure. IncidentId:={0}; Name:={1}; Details:={2}",
                                        incidentCorrelationId,
                                        HealthCheck.Identity.Name,
                                        ex);

                Logger.Error(msg);

                // Broadcast a failure message
                Messenger.Publish(NotificationRequestBuilder.AlwaysPublish(new HealthCheckData
                {
                    CriticalFailure        = true,
                    CriticalFailureDetails = new CriticalFailureDetails
                    {
                        Id = incidentCorrelationId
                    },
                    GeneratedOnUtc = DateTime.UtcNow,
                    Identity       = HealthCheck.Identity,
                    Info           = ex.Message
                }).Build());
            }
        }
Пример #2
0
        public override void Execute()
        {
            Logger.Debug("HostPingCheck is pinging...");

            _config.Hosts.ForEach(host =>
            {
                using (var pinger = new Ping())
                {
                    var reply = _config.NotificationThreshold.HasValue
                                                              ? pinger.Send(host, (int)_config.NotificationThreshold.Value)
                                                              : pinger.Send(host);

                    var data = HealthCheckData.For(Identity, "Successfully pinged host '{0}'",
                                                   host)
                               .Succeeded()
                               .ResultCountIs(reply.RoundtripTime)
                               .DisplayUnitIs("ms")
                               .AddProperty("host", host)
                               .AddProperty("status", reply.Status.ToString());

                    if (reply.Status != IPStatus.Success)
                    {
                        data.Info = string.Format("Failure ({0}) pinging host {1}", reply.Status, host);
                        data.Failed();
                    }

                    Publish(NotificationRequestBuilder.For(_config.NotificationMode, data,
                                                           BuildKeyWithHostName).Build());
                }
            });
        }
Пример #3
0
        public override void Execute()
        {
            ulong freeBytesAvailable;

            ulong totalNumberOfBytes;
            ulong totalNumberOfFreeBytes;

            var success = GetDiskFreeSpaceEx(_config.Path, out freeBytesAvailable, out totalNumberOfBytes, out totalNumberOfFreeBytes);

            if (!success)
            {
                throw new System.ComponentModel.Win32Exception(string.Format("GetDiskFreeSpaceEx({0}) failed", _config.Path));
            }

            var usedpercentage = 100 - (freeBytesAvailable * 100) / totalNumberOfBytes;

            Logger.Debug(FormatMessage(usedpercentage));

            Publish(NotificationRequestBuilder.For(_config.NotificationMode, HealthCheckData.For(Identity,
                                                                                                 FormatMessage(usedpercentage))
                                                   .Succeeded()
                                                   .ResultCountIs(usedpercentage)
                                                   .DisplayUnitIs("%")
                                                   .AddTag(_config.Path))
                    .Build());
        }
        public override void Execute()
        {
            Logger.Debug("WindowsServiceStartupCheck is checking service startup types...");

            // use the service/current identity to query local or remote
            var wmiScope = new ManagementScope(WmiNamespace, new ConnectionOptions
            {
                Impersonation = ImpersonationLevel.Impersonate
            });

            // set up the query and execute it
            var wmiQuery    = new ObjectQuery("Select * from Win32_Service");
            var wmiSearcher = new ManagementObjectSearcher(wmiScope, wmiQuery);
            var wmiResults  = wmiSearcher.Get();
            var results     = wmiResults.Cast <ManagementObject>();
            var services    = (from service in results
                               select new
            {
                Name = service["Name"].ToString(),
                DisplayName = service["DisplayName"].ToString(),
                StartMode = service["StartMode"].ToString()
            }).ToList();

            // find the services we are interested in that do not have the
            // startup type (startmode) we expect
            var faultedServices = (from service in services
                                   from name in _config.Services
                                   where MatchName(name, service.Name, service.DisplayName) &&
                                   (string.Compare(_config.ExpectedStartupType, service.StartMode,
                                                   StringComparison.OrdinalIgnoreCase) != 0)
                                   select service).ToList();

            faultedServices.ForEach(
                fs =>
            {
                var result = HealthCheckData.For(Identity, string.Format("{0} should be {1} but is {2}",
                                                                         fs.DisplayName, _config.ExpectedStartupType, fs.StartMode))
                             .AddTag(fs.DisplayName)
                             .Failed();

                var request = NotificationRequestBuilder.For(_config.NotificationMode, result,
                                                             nr =>
                {
                    nr.DataKeyGenerator = data => string.Format("{0}>>{1}", data.CheckId, data.Tags);
                }).Build();

                Publish(request);
            });

            // invalid/unknown service names...
            var invalidServices = _config.Services.Where(configService =>
                                                         !services.Any(svc => MatchName(configService, svc.Name, svc.DisplayName))).ToList();

            if (invalidServices.Any())
            {
                throw new InvalidOperationException(string.Format("These services do not exist: {0}",
                                                                  string.Join(",", invalidServices.ToArray())));
            }
        }
Пример #5
0
 public override void Execute()
 {
     Messenger.Publish(NotificationRequestBuilder.AlwaysPublish(new HealthCheckData
     {
         Identity = Identity,
         Result   = true,
         Info     = string.Format("MyCustomSetting:={0}", _config.MyCustomSetting)
     }).Build());
 }
Пример #6
0
        /// <summary>
        /// Override this if you want to alter the publishing behaviour
        /// </summary>
        /// <param name="rowcount"></param>
        /// <param name="duration"></param>
        /// <param name="artifactDescriptor"></param>
        protected virtual void Publish(int rowcount, TimeSpan duration, ArtifactDescriptor artifactDescriptor)
        {
            var data = HealthCheckData.For(Identity, DescribeNotification())
                       .ResultIs(DecideResult(rowcount))
                       .ResultCountIs(rowcount)
                       .SetDuration(duration)
                       .AddProperty("Rowcount", rowcount.ToString(CultureInfo.InvariantCulture))
                       .AddProperty("Criteria", _baseConfig.Query);

            Publish(NotificationRequestBuilder.For(_config.NotificationMode, data)
                    .AssociateArtifact(artifactDescriptor)
                    .Build());
        }
Пример #7
0
        public override void Execute()
        {
            var sample = _counter.NextSample();
            Thread.Sleep(1000);
            var sample2 = _counter.NextSample();
            var value = Math.Round(CounterSampleCalculator.ComputeCounterValue(sample, sample2));

            Publish(NotificationRequestBuilder.For(_config.NotificationMode, HealthCheckData.For(Identity, "Cpu utilisation is {0}%", value)
                .Succeeded()
                .ResultCountIs(value)
                .DisplayUnitIs("%"))
                .Build());

            Logger.Debug("CpuCheck reports {0}%", value);
        }
        public void MarkNotificationsViewedRequest_WithUrlNull_ThrowsArgumentNullException()
        {
            var requestBuilder = new NotificationRequestBuilder();


            var exception =
                Record.Exception(() => NotificationRequestBuilder.MarkNotificationsViewedRequest(null, new List <string>()));

            Assert.NotNull(exception);
            Assert.IsType <ArgumentNullException>(exception);

            var argNullException = (ArgumentNullException)exception;

            Assert.Equal(argNullException.ParamName, "url");
        }
        public void MarkNotificationsViewedRequest_WithIdsNull_ThrowsArgumentNullException()
        {
            var client         = new ImgurClient("123", "1234");
            var requestBuilder = new NotificationRequestBuilder();
            var mockUrl        = $"{client.EndpointUrl}notification";


            var exception = Record.Exception(() => NotificationRequestBuilder.MarkNotificationsViewedRequest(mockUrl, null));

            Assert.NotNull(exception);
            Assert.IsType <ArgumentNullException>(exception);

            var argNullException = (ArgumentNullException)exception;

            Assert.Equal(argNullException.ParamName, "notificationIds");
        }
        public override void Execute()
        {
            for (var i = 0; i < _config.Cycles; i++)
            {
                _config.Values.ToList().ForEach(rv =>
                {
                    Publish(NotificationRequestBuilder.For(_config.NotificationMode,
                                                           HealthCheckData.For(Identity, "Fake Threshold Result")
                                                           .Succeeded()
                                                           .ResultCountIs(rv))
                            .Build());

                    Thread.Sleep(_config.Interval);
                });
            }
        }
        public async Task MarkNotificationsViewedRequest_Equal()
        {
            var client         = new ImgurClient("123", "1234");
            var requestBuilder = new NotificationRequestBuilder();

            var mockUrl = $"{client.EndpointUrl}notifications";
            var ids     = new List <string> {
                "12345", "9867", "45678"
            };

            var request  = NotificationRequestBuilder.MarkNotificationsViewedRequest(mockUrl, ids);
            var expected = "ids=12345%2C9867%2C45678";

            Assert.NotNull(request);
            Assert.Equal(expected, await request.Content.ReadAsStringAsync().ConfigureAwait(false));
            Assert.Equal("https://api.imgur.com/3/notifications", request.RequestUri.ToString());
            Assert.Equal(HttpMethod.Post, request.Method);
        }
Пример #12
0
        /// <summary>
        ///     Marks notifications as viewed.
        ///     OAuth authentication required.
        /// </summary>
        /// <param name="ids">The notification id.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown when a null reference is passed to a method that does not accept it as a
        ///     valid argument.
        /// </exception>
        /// <exception cref="ImgurException">Thrown when an error is found in a response from an Imgur endpoint.</exception>
        /// <exception cref="MashapeException">Thrown when an error is found in a response from a Mashape endpoint.</exception>
        /// <returns></returns>
        public async Task <bool> MarkNotificationsViewedAsync(IEnumerable <string> ids)
        {
            if (ids == null)
            {
                throw new ArgumentNullException(nameof(ids));
            }

            if (ApiClient.OAuth2Token == null)
            {
                throw new ArgumentNullException(nameof(ApiClient.OAuth2Token), OAuth2RequiredExceptionMessage);
            }

            var url = "notification";

            using (var request = NotificationRequestBuilder.MarkNotificationsViewedRequest(url, ids))
            {
                var viewed = await SendRequestAsync <bool>(request).ConfigureAwait(false);

                return(viewed);
            }
        }
Пример #13
0
        public override void Execute()
        {
            var fi   = new DirectoryInfo(FolderLocation.Location);
            var data = HealthCheckData.For(Identity, "Information about folder '{0}'...", FolderLocation.Location)
                       .ResultIs(fi.Exists);

            if (data.Result.GetValueOrDefault(false))
            {
                data.ResultCount = fi.GetFiles().LongLength;
                data.Properties  = new Properties
                {
                    { "CreationTimeUtc", fi.CreationTimeUtc.ToString(CultureInfo.InvariantCulture) },
                    { "LastAccessTimeUtc", fi.LastAccessTimeUtc.ToString(CultureInfo.InvariantCulture) },
                    { "LastWriteTimeUtc", fi.LastWriteTimeUtc.ToString(CultureInfo.InvariantCulture) },
                    { "FileCount", fi.GetFiles().LongLength.ToString(CultureInfo.InvariantCulture) },
                    { "FolderCount", fi.GetDirectories().LongLength.ToString(CultureInfo.InvariantCulture) },
                    { "Attributes", fi.Attributes.ToString() }
                };
            }

            Messenger.Publish(NotificationRequestBuilder.For(_config.NotificationMode, data).Build());
        }
Пример #14
0
        public void Execute()
        {
            ManagementScope wmiScope;

            Logger.Debug("Querying wmi namespace {0}...", WmiNamespace);
            if (!string.IsNullOrEmpty(Config.RemoteUser) && !string.IsNullOrEmpty(Config.RemotePwd))
            {
                wmiScope = new ManagementScope(WmiNamespace, new ConnectionOptions
                {
                    Username = Config.RemoteUser,
                    Password = Config.RemotePwd
                });
            }
            else
            {
                wmiScope = new ManagementScope(WmiNamespace);
            }

            // set up the query and execute it
            var wmiQuery    = new ObjectQuery("Select * from Win32_Process");
            var wmiSearcher = new ManagementObjectSearcher(wmiScope, wmiQuery);
            var wmiResults  = wmiSearcher.Get();
            var processes   = wmiResults.Cast <ManagementObject>();

            var matches = (from process in processes
                           where (string.Compare(process["Name"].ToString(), Config.ProcessName,
                                                 StringComparison.InvariantCultureIgnoreCase) == 0)
                           select process).ToList();

            var data = HealthCheckData.For(Identity, "There are {0} instances of process '{1}' on {2}",
                                           matches.Count(),
                                           Config.ProcessName,
                                           Config.RemoteMachineId)
                       .ResultIs(matches.Any())
                       .ResultCountIs(matches.Count);

            Messenger.Publish(NotificationRequestBuilder.For(Config.NotificationMode, data).Build());
        }
Пример #15
0
        public override void Execute()
        {
            Logger.Debug("WindowsServiceStateCheck is checking service states...");
            var failures = new List <string>();

            _config.Services.ForEach(
                serviceName =>
            {
                try
                {
                    var sc     = new ServiceController(serviceName, Server);
                    var result = HealthCheckData.For(Identity,
                                                     string.Format("{0} is {1}", sc.DisplayName, _config.ExpectedState))
                                 .ResultIs(sc.Status == ExpectedState)
                                 .AddProperty("ExpectedState", ExpectedState.ToString());

                    var request = NotificationRequestBuilder.For(_config.NotificationMode, result,
                                                                 nr =>
                    {
                        nr.DataKeyGenerator = data => string.Format("{0}>>{1}", data.CheckId, serviceName);
                    }).Build();

                    Publish(request);
                }
                catch (InvalidOperationException)
                {
                    failures.Add(serviceName);
                }
            });

            if (failures.Count > 0)
            {
                throw new InvalidOperationException(string.Format("These services do not exist: {0}",
                                                                  string.Join(",", failures.ToArray())));
            }
        }
Пример #16
0
        protected virtual NotificationRequest DoTest()
        {
            string   info;
            var      count = 0;
            DateTime?oldestMessageDated = null;

            var exists = IsDeadLetterRelatedQueue() || MessageQueue.Exists(_config.QueueName);

            if (exists)
            {
                var queue = new MessageQueue(_config.QueueName)
                {
                    MessageReadPropertyFilter = new MessagePropertyFilter
                    {
                        ArrivedTime = true
                    }
                };

                var me      = queue.GetMessageEnumerator2();
                var timeout = new TimeSpan(0, 0, 0);

                while (me.MoveNext(timeout))
                {
                    var msg = me.Current;

                    if (msg == null)
                    {
                        continue;
                    }

                    if (!oldestMessageDated.HasValue)
                    {
                        oldestMessageDated = msg.ArrivedTime;
                    }
                    else if (msg.ArrivedTime < oldestMessageDated)
                    {
                        oldestMessageDated = msg.ArrivedTime;
                    }

                    count++;
                }

                info = string.Format("Queue {0} has {1} messages", _config.QueueName, count);
            }
            else
            {
                info = string.Format("Queue {0} does not exist!", _config.QueueName);
            }

            var props = new Properties
            {
                { "Queue", _config.QueueName },
                { "Count", count.ToString(CultureInfo.InvariantCulture) }
            };

            if (oldestMessageDated.HasValue)
            {
                props.Add("Oldest", oldestMessageDated.Value.ToString(CultureInfo.InvariantCulture));
            }

            var data = new HealthCheckData
            {
                Identity   = Identity,
                Info       = info,
                Result     = exists,
                Properties = props
            };

            if (exists)
            {
                data.ResultCount = count;
            }

            return(NotificationRequestBuilder.For(_config.NotificationMode, data).Build());
        }
Пример #17
0
        public override void Execute()
        {
            Logger.Debug("UrlPingCheck is pinging urls...");
            _config.Urls.ToList().ForEach(
                url =>
            {
                var wc = (HttpWebRequest)WebRequest.Create(url);

                {
                    try
                    {
                        wc.AllowAutoRedirect     = true;
                        wc.UseDefaultCredentials = _config.UseDefaultCredentials;

                        if (!string.IsNullOrWhiteSpace(_config.UserAgentString))
                        {
                            wc.UserAgent = _config.UserAgentString;
                        }

                        if (_config.Headers != null)
                        {
                            foreach (var header in _config.Headers)
                            {
                                if (!HandledAsProtectedHeader(wc, header))
                                {
                                    wc.Headers.Add(header.Key, header.Value);
                                }
                            }
                        }

                        if (_config.IsAjaxCall)
                        {
                            wc.Headers.Add("X-Requested-With", "XMLHttpRequest");
                        }

                        string response;
                        var timer = Stopwatch.StartNew();

                        if (string.IsNullOrWhiteSpace(_config.PostData))
                        {
                            Logger.Debug("Timing ping to '{0}'...", url);

                            wc.Method = "GET";
                            response  = DownloadString(wc);
                        }
                        else
                        {
                            Logger.Debug("Timing ping (POST) to '{0}'...", url);

                            wc.Method      = "POST";
                            wc.ContentType = "application/x-www-form-urlencoded";

                            var streamUp     = wc.GetRequestStream();
                            var dataUp       = Encoding.UTF8.GetBytes(_config.PostData);
                            wc.ContentLength = dataUp.Length;

                            streamUp.Write(dataUp, 0, dataUp.Length);
                            response = DownloadString(wc);
                        }
                        timer.Stop();
                        Logger.Debug("Ping '{0}' = {1}ms", url, timer.ElapsedMilliseconds);

                        var result   = true;
                        var regexMsg = string.Empty;

                        if (!string.IsNullOrWhiteSpace(_config.ContentRegex))
                        {
                            result   = Regex.IsMatch(response, _config.ContentRegex);
                            regexMsg = " - **Failed, Response did not match Regex**";
                        }

                        var sizeInBytes = Encoding.UTF8.GetByteCount(response).ToString(CultureInfo.InvariantCulture);

                        Publish(NotificationRequestBuilder.For(_config.NotificationMode, HealthCheckData.For(Identity,
                                                                                                             "Pinged url '{0}' (Threshold is {1}ms; returned {2}bytes){3}",
                                                                                                             url, _config.NotificationThreshold ?? 0, sizeInBytes, regexMsg)
                                                               .ResultIs(result)
                                                               .DisplayUnitIs("ms")
                                                               .AddProperty("url", url)
                                                               .AddProperty("bytes", sizeInBytes)
                                                               .ResultCountIs(timer.ElapsedMilliseconds), BuildKeyFromUrl)
                                .Build());
                    }
                    catch (WebException wex)
                    {
                        var extraInfo = string.Empty;

                        if (wex.Status == WebExceptionStatus.ProtocolError)
                        {
                            extraInfo = string.Format(", Http state: {0}, '{1}'",
                                                      (int)((HttpWebResponse)wex.Response).StatusCode,
                                                      ((HttpWebResponse)wex.Response).StatusDescription);
                        }

                        Publish(NotificationRequestBuilder.For(_config.NotificationMode, HealthCheckData.For(Identity,
                                                                                                             "Url '{0}' failed with code '{1}'{2}", url, wex.Status, extraInfo)
                                                               .Failed()
                                                               .AddProperty("url", url), BuildKeyFromUrl)
                                .Build());
                    }
                }
            });
        }
Пример #18
0
        public override void Start()
        {
            // start the load process....
            var sessionInfo = new NotificationEventAgentStart
            {
                DiscoveryStarted = DateTime.UtcNow,
                AgentId          = _config.AgentId,
                SiteId           = _config.SiteId,
                Id = _config.InstanceId
            };

            INotificationEventPublisher[] publishers;
            PublisherLoader.Load(out publishers,
                                 p =>
            {
                if (!p.Status.IsHealthy())
                {
                    Logger.Debug(
                        "*** Notification Publisher '{0}' reporting 'unhealthy', disabling it ***",
                        p.FriendlyId);
                    return;
                }

                Messenger.Subscribe(p);
                Logger.Debug("Loaded Notification Publisher '{0}'",
                             p.GetType().Name);
            });

            // load activities...
            IActivityPlugin[] activities;
            if (ActivitiesLoader.Load(out activities))
            {
                activities.ToList().ForEach(
                    a =>
                {
                    if (!a.Status.IsHealthy())
                    {
                        Logger.Debug("*** Activity '{0}' reporting 'unhealthy', skipping it ***",
                                     a.Identity.Name);
                        return;
                    }

                    _plugins.Add(a);
                    Logger.Debug("Loaded Activity '{0}'", a.GetType().Name);
                });
            }

            // load health checks...
            IHealthCheckSchedulerPlugin[] healthChecks;
            ChecksLoader.Load(out healthChecks);
            healthChecks.ToList().ForEach(
                h =>
            {
                if (!h.Status.IsHealthy())
                {
                    Logger.Debug("*** HealthCheck '{0}' reporting 'unhealthy', skipping it ***", h.Identity.Name);
                    return;
                }

                _plugins.Add(h);
                Logger.Debug("Loaded HealthCheck '{0}'", h.Identity.Name);
            });

            // extract check info, attach and publish it to a session message
            sessionInfo.DiscoveryCompleted = DateTime.UtcNow;

            // TODO - add support for publishers
            sessionInfo.Checks = (from healthCheck in healthChecks
                                  where healthCheck.Status.IsHealthy()
                                  select healthCheck.Identity).ToList();
            sessionInfo.UnhealthyChecks = (from healthCheck in healthChecks
                                           where !healthCheck.Status.IsHealthy()
                                           select healthCheck.Identity).ToList();
            sessionInfo.UnhealthyPublishers = (from healthCheck in healthChecks
                                               where !healthCheck.Status.IsHealthy()
                                               select healthCheck.Identity).ToList();
            sessionInfo.Activities = (from activity in activities
                                      where activity.Status.IsHealthy()
                                      select activity.Identity).ToList();
            sessionInfo.UnhealthyActivities = (from activity in activities
                                               where !activity.Status.IsHealthy()
                                               select activity.Identity).ToList();

            Messenger.Publish(NotificationRequestBuilder.AlwaysPublish(sessionInfo).Build());

            // finally start the checks & activities
            base.Start();
        }
Пример #19
0
 protected virtual void Publish(HealthCheckData message)
 {
     Messenger.Publish(NotificationRequestBuilder.For(NotificationMode, message).Build());
 }