Beispiel #1
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());
                }
            });
        }
Beispiel #2
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())));
            }
        }
Beispiel #4
0
        public void Test()
        {
            var hub = new NotificationHub();

            hub.Initialise(new AgentInfo());

            Messenger.Publish(NotificationRequest.For("FailureOnly",
                                                      HealthCheckData.For(new PluginDescriptor
            {
                Name = "Test"
            }, "Test").Failed()));
        }
        /// <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());
        }
Beispiel #6
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);
                });
            }
        }
Beispiel #8
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());
        }
        public void Execute()
        {
            var lastRun = Convert.ToInt64(myLastRun.ToString("yyyMMddHHmm"));

            using (var query = SQLiteAdhocCommand.UsingSmartConnection(myConfig.ConnectionString)
                               .WithSql(SQLiteStatement.Create("select s.name, datetime(year || '-' || substr('0' || month, -2,2) || '-' || substr('0' || day, -2,2) || ' ' || substr('0' || hour, -2,2) || ':' || substr('0' || min, -2,2)) [recorded], ")
                                        .Append("ch1_amps_min, ch1_amps_avg, ch1_amps_max, ch1_kw_min, CAST(ch1_kw_avg AS REAL) [ch1_kw_avg], ch1_kw_max")
                                        .Append("from energy_history h join energy_sensor s on h.addr = s.addr")
                                        .Append("where CAST((year || substr('0' || month, -2,2) || substr('0' || day, -2,2) || substr('0' || hour, -2,2) || substr('0' || min, -2,2)) AS INTEGER) > ")
                                        .InsertParameter("@lastrun", lastRun)))
            {
                using (var reader = query.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        // assumes that results are in ascending order
                        myLastRun = Convert.ToDateTime(reader["recorded"]);

                        var sensor = reader["name"].ToString();
                        var data   = HealthCheckData.For(Identity, sensor)
                                     .AddTag(sensor);

                        // report average watts
                        data.ResultCount    = Convert.ToDouble(reader["ch1_kw_avg"]);
                        data.GeneratedOnUtc = myLastRun.ToUniversalTime();
                        data.Properties     = new ResultProperties();

                        Messenger.Publish(data);
                        Logger.Debug("[{0}] Sent reading {1}kw taken {2}",
                                     Identity.Name,
                                     data.ResultCount,
                                     data.GeneratedOnUtc.ToLocalTime());
                    }
                }
            }
        }
Beispiel #11
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())));
            }
        }
Beispiel #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());
                    }
                }
            });
        }