public static NotificationRequestBuilder For(string notificationMode,
                                                     HealthCheckData message,
                                                     Action <NotificationRequest> configurer = null)
        {
            var alert = new NotificationEventHealthCheck
            {
                CheckId                = message.Identity.Name,
                CriticalFailure        = message.CriticalFailure,
                CriticalFailureDetails = message.CriticalFailureDetails,
                Duration               = message.Duration,
                GeneratedOnUtc         = message.GeneratedOnUtc,
                Message                = message.Info,
                NextCheckExpected      = message.NextCheckExpected,
                Properties             = message.Properties,
                Result      = message.Result,
                ResultCount = message.ResultCount,
                DisplayUnit = message.DisplayUnit,
                Tags        = message.Tags
            };

            var builder = For(notificationMode, alert);

            if (configurer != null)
            {
                configurer(builder._request);
            }
            return(builder);
        }
Exemple #2
0
        public void Execute()
        {
            var fi     = new FileInfo(myFileLocation.Location);
            var result = new HealthCheckData
            {
                Identity = Identity,
                Info     = string.Format("Information about file '{0}'...", myFileLocation.Location),
                Result   = fi.Exists
            };

            if (result.Result.GetValueOrDefault(false))
            {
                result.ResultCount = fi.Length;
                result.Properties  = new ResultProperties
                {
                    { "CreationTimeUtc", fi.CreationTimeUtc.ToString() },
                    { "LastAccessTimeUtc", fi.LastAccessTimeUtc.ToString() },
                    { "LastWriteTimeUtc", fi.LastWriteTimeUtc.ToString() },
                    { "Length", fi.Length.ToString() },
                    { "Attributes", fi.Attributes.ToString() }
                };
            }

            Messenger.Publish(result);
        }
        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())));
            }
        }
Exemple #6
0
        public void Execute()
        {
            Logger.Debug("WindowsServiceStartupCheck is checking service startup types...");

            // use the service/current identity to query local or remote
            var wmiScope = new ManagementScope(myWmiNamespace, 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()
            };

            // 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 myConfig.Services
                                   where MatchName(name, service.Name, service.DisplayName) &&
                                   (string.Compare(myConfig.ExpectedStartupType, service.StartMode, true) != 0)
                                   select service).ToList();

            faultedServices.ForEach(fs =>
            {
                var result = new HealthCheckData
                {
                    Identity = Identity,
                    Info     = string.Format("{0} should be {1} but is {2}",
                                             fs.DisplayName, myConfig.ExpectedStartupType, fs.StartMode),
                    Result = false
                };
                Messenger.Publish(result);
            });

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

            if (invalidServices.Count() > 0)
            {
                throw new InvalidOperationException(string.Format("These services do not exist: {0}",
                                                                  string.Join(",", invalidServices.ToArray())));
            }
        }
Exemple #7
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());
        }
        private static HealthCheckOptions Convert(HealthCheckData data)
        {
            if (data == null)
            {
                return(null);
            }

            return(new HealthCheckOptions
            {
                Passive = Convert(data.Passive),
                Active = Convert(data.Active)
            });
        }
Exemple #10
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 #12
0
        private HealthCheckOptions Convert(HealthCheckData data)
        {
            if (data == null)
            {
                return(null);
            }

            return(new HealthCheckOptions
            {
                Enabled = data.Enabled,
                Interval = data.Interval,
                Timeout = data.Timeout,
                Port = data.Port,
                Path = data.Path,
            });
        }
Exemple #13
0
        public void Execute()
        {
            ManagementScope wmiScope;

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

            // 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(), myConfig.ProcessName,
                                          StringComparison.InvariantCultureIgnoreCase) == 0)
                          select process;

            var msg = new HealthCheckData
            {
                Identity = Identity,
                Info     = string.Format("There are {0} instances of process '{1}' on {2}",
                                         matches.Count(),
                                         myConfig.ProcessName,
                                         myConfig.RemoteMachineId),
                Result      = (matches.Count() > 0),
                ResultCount = matches.Count()
            };

            Messenger.Publish(msg);
        }
Exemple #14
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());
        }
        private void AddHealthChecks(IServiceCollection services)
        {
            var hcd = new HealthCheckData();

            hcd.Checks.TryAdd("Health1", new HealthState {
                Status = HealthStatus.Healthy, Description = "Health Check One"
            });
            hcd.Checks.TryAdd("Health2", new HealthState {
                Status = HealthStatus.Healthy, Description = "Health Check Two"
            });
            hcd.Checks.TryAdd("Health3", new HealthState {
                Status = HealthStatus.Healthy, Description = "Health Check Three"
            });

            services.AddSingleton(sp => hcd);

            var checks = services.AddHealthChecks();

            foreach (var check in hcd.Checks)
            {
                checks.AddCheck(check.Key, () => new HealthCheckResult(check.Value.Status, check.Value.Description));
            }
        }
        public void Execute()
        {
            Logger.Debug("WindowsServiceStateCheck is checking service states...");
            var failures = new List <string>();

            myConfig.Services.ForEach(serviceName =>
            {
                try
                {
                    var sc = new ServiceController(serviceName, myServer);

                    if (sc.Status == myExpectedState)
                    {
                        return;
                    }

                    var result = new HealthCheckData
                    {
                        Identity = Identity,
                        Info     = string.Format("{0} should be {1} but is {2}",
                                                 sc.DisplayName, myConfig.ExpectedState, sc.Status),
                        Result = false
                    };
                    Messenger.Publish(result);
                }
                catch (InvalidOperationException)
                {
                    failures.Add(serviceName);
                }
            });
            if (failures.Count > 0)
            {
                throw new InvalidOperationException(string.Format("These services do not exist: {0}",
                                                                  string.Join(",", failures.ToArray())));
            }
        }
        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());
                    }
                }
            }
        }
Exemple #19
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())));
            }
        }
        public void Execute()
        {
            Logger.Debug("UrlPingCheck is pinging urls...");
            myConfig.Urls.ToList().ForEach(url =>
            {
                using (var wc = new WebClient())
                {
                    try
                    {
                        var publish = !myConfig.PublishOnlyIfFailure;
                        var outcome = true;
                        var msg     = string.Format("Successfully pinged url '{0}'", url);

                        var timer = Stopwatch.StartNew();
                        wc.DownloadString(url);
                        timer.Stop();

                        // perform threshold check...
                        if (myConfig.FailIfResponseMillisecondsOver.HasValue &&
                            (myConfig.FailIfResponseMillisecondsOver.Value > 0) &&
                            (timer.ElapsedMilliseconds > myConfig.FailIfResponseMillisecondsOver.Value))
                        {
                            // ok so we set a threshold and it was breached so...
                            publish = true;
                            outcome = false;
                            msg     = string.Format(
                                "Url '{0}' responded too slowly in {1}ms",
                                url, timer.ElapsedMilliseconds);
                        }

                        if (!publish)
                        {
                            return;
                        }

                        var result = new HealthCheckData
                        {
                            Identity    = Identity,
                            Info        = msg,
                            Result      = outcome,
                            ResultCount = timer.ElapsedMilliseconds
                        };
                        Messenger.Publish(result);
                    }
                    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);
                        }

                        var result = new HealthCheckData
                        {
                            Identity = Identity,
                            Info     = string.Format("Url '{0}' failed with code '{1}'{2}",
                                                     url, wex.Status, extraInfo),
                            Result = false
                        };
                        Messenger.Publish(result);
                    }
                }
            });
        }
Exemple #21
0
 IMessenger IMessenger.Publish(HealthCheckData message)
 {
     myMessageBus.Send(message);
     return(this);
 }
Exemple #22
0
 public static IMessenger Publish(HealthCheckData message)
 {
     return(myInstance.Publish(message));
 }
 public static NotificationRequestBuilder AlwaysPublish(HealthCheckData message)
 {
     return(For(String.Empty, message));
 }
Exemple #24
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());
                    }
                }
            });
        }
Exemple #25
0
 public StateController(HealthCheckData data)
 {
     _data = data;
 }
Exemple #26
0
 protected virtual void Publish(HealthCheckData message)
 {
     Messenger.Publish(NotificationRequestBuilder.For(NotificationMode, message).Build());
 }
Exemple #27
0
 public IMessenger Publish(HealthCheckData message)
 {
     Sent.Add(message);
     return(this);
 }
Exemple #28
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());
        }
        protected virtual HealthCheckData DoTest()
        {
            // check it even exists!
            var      count = 0;
            DateTime?oldestMessageDated = null;
            var      exists             = MessageQueue.Exists(myConfig.QueueName);
            string   info;

            if (exists)
            {
                var queue = new MessageQueue(myConfig.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 (!oldestMessageDated.HasValue)
                    {
                        oldestMessageDated = msg.ArrivedTime;
                    }
                    else if (msg.ArrivedTime < oldestMessageDated)
                    {
                        oldestMessageDated = msg.ArrivedTime;
                    }

                    count++;
                }

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

            var props = new ResultProperties
            {
                { "Queue", myConfig.QueueName },
                { "Count", count.ToString() }
            };

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

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

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

            return(result);
        }