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());
                }
            });
        }
        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())));
            }
        }
        /// <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());
        }
Exemple #5
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 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);
                });
            }
        }
Exemple #7
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());
        }
        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());
        }
Exemple #9
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())));
            }
        }
Exemple #10
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());
        }
Exemple #11
0
 protected virtual void Publish(HealthCheckData message)
 {
     Messenger.Publish(NotificationRequestBuilder.For(NotificationMode, message).Build());
 }
Exemple #12
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());
                    }
                }
            });
        }