Example #1
0
        public static void TestWindsorInstaller(TestContext context)
        {
            IWindsorContainer container = new WindsorContainer();

            container.Install(new HipChatClientInstaller());
            defaultClient       = container.Resolve <HipChatClient>("ChatClient");
            defaultClient.From += defaultClient.GetHashCode().ToString();
            defaultClient.SendMessage("TestWindsorInstaller");
        }
        public static void SendMessage(this ICakeContext context, string authToken, string roomId, string senderName, string message)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var client = new HipChatClient(authToken, roomId, senderName);

            client.SendMessage(message);
        }
        public void Run(IIntegrationResult result)
        {
            var displayDuration = false;
            var duration        = TimeSpan.Zero;

            if (result.EndTime != DateTime.MinValue)
            {
                duration        = result.EndTime - result.StartTime;
                displayDuration = true;
            }
            var link = String.Format(@"<a href=""{0}"">{1}</a>", result.ProjectUrl, result.Status);

            var message = new StringBuilder();

            message.Append(result.ProjectName);
            message.Append(" ");

            if (String.IsNullOrEmpty(Message))
            {
                message.Append("build complete");
            }
            else
            {
                message.Append(Message);
            }

            message.Append(" ");

            if (displayDuration)
            {
                message.AppendFormat("(duration {0})", duration);
            }

            message.Append(". ");

            if (!HideResult)
            {
                message.AppendFormat("Result: {0}.", link);
            }

            var notify = result.Succeeded;
            var color  = result.Succeeded ? HipChatClient.BackgroundColor.green : HipChatClient.BackgroundColor.red;

            if (HideResult)
            {
                color = HipChatClient.BackgroundColor.yellow;
            }

            var client = new HipChatClient(AuthToken, RoomId, From);

            client.SendMessage(message.ToString(), color, notify);
        }
        public SendHipChatMessageResponse Invoke(SendHipChatMessageRequest request)
        {
            if (request.HipChatAuthToken.IsNotNullOrEmpty() && request.HipChatRoomId > 0)
            {
                if (request.Colour.HasValue)
                {
                    HipChatClient.SendMessage(request.HipChatAuthToken, request.HipChatRoomId, "Errordite", request.Message, request.Colour.Value);
                }
                else
                {
                    HipChatClient.SendMessage(request.HipChatAuthToken, request.HipChatRoomId, "Errordite", request.Message);
                }
            }

            return(new SendHipChatMessageResponse());
        }
Example #5
0
        public static void Main()
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var pulseBotConfigurationSection = (PulseConfigurationSection)config.GetSection("pulseBot");

            var alertingMetrics = pulseBotConfigurationSection.Alerts
                                  .Select(x => new AlertingMetric
            {
                IPAddress              = x.Host.IPAddress,
                PingInterval           = x.Host.PingInterval,
                PingTimeout            = x.Host.PingTimeout,
                PingHipChatFailCount   = x.Host.PingHipChatFailCount,
                PingPagerDutyFailCount = x.Host.PingPagerDutyFailCount,
                HipChatApiKey          = x.HipChat.HipChatApiKey,
                HipChatRoomName        = x.HipChat.HipChatRoomName,
                LastPagerDutyAlert     = null,
                PagerDutyServiceAPIKey = x.PagerDuty.GenericServiceApiKey,
                PagerDutyMessage       = x.PagerDuty.MessageOnAlert
            })
                                  .ToList();

            foreach (var hipChatSink in alertingMetrics.Select(x => new { x.HipChatApiKey, x.HipChatRoomName }).Distinct())
            {
                HipChatClient.SendMessage(hipChatSink.HipChatApiKey, hipChatSink.HipChatRoomName, "PulseBot", "PulseBot has started", true, HipChatClient.BackgroundColor.purple);
            }

            Parallel.ForEach(alertingMetrics, alertingMetric =>
            {
                var consecutiveFailCount = 0;

                while (true)
                {
                    try
                    {
                        if (alertingMetric.PingInterval.HasValue)
                        {
                            using (var pingSender = new Ping())
                            {
                                var options = new PingOptions
                                {
                                    DontFragment = true
                                };

                                // Create a buffer of 32 bytes of data to be transmitted.
                                var buffer = Encoding.ASCII.GetBytes(PingData);
                                try
                                {
                                    var reply = pingSender.Send(IPAddress.Parse(alertingMetric.IPAddress), alertingMetric.PingTimeout ?? 10000, buffer, options);
                                    if (reply != null && reply.Status != IPStatus.Success)
                                    {
                                        Console.WriteLine("\r\n{0:yyyy-MM-dd-HH:mm:ss} - {1}: PING FAILURE", DateTime.Now, alertingMetric.PagerDutyMessage);
                                        consecutiveFailCount++;

                                        if (alertingMetric.PingHipChatFailCount.HasValue &&
                                            consecutiveFailCount == alertingMetric.PingHipChatFailCount.Value)
                                        {
                                            HipChatClient.SendMessage(alertingMetric.HipChatApiKey, alertingMetric.HipChatRoomName, "PulseBot", alertingMetric.PagerDutyMessage, true, HipChatClient.BackgroundColor.red);
                                        }

                                        if (alertingMetric.PingPagerDutyFailCount.HasValue &&
                                            (consecutiveFailCount == alertingMetric.PingPagerDutyFailCount.Value || (alertingMetric.LastPagerDutyAlert.HasValue && (DateTime.Now - alertingMetric.LastPagerDutyAlert.Value).TotalMinutes > 60)))
                                        {
                                            Console.WriteLine("\r\nAlerting PagerDuty for {0} after {1} failures!", alertingMetric.PagerDutyMessage,
                                                              consecutiveFailCount);
                                            //PostPagerDutyAlert(alertingMetric.PagerDutyServiceAPIKey, alertingMetric.PagerDutyMessage, consecutiveFailCount);
                                            alertingMetric.LastPagerDutyAlert = DateTime.Now;
                                        }
                                    }
                                    else if (reply != null && reply.Status == IPStatus.Success)
                                    {
                                        consecutiveFailCount = 0;
                                        Console.Write(".");
                                    }
                                }
                                catch (PingException)
                                {
                                    Console.WriteLine("\r\n{0:yyyy-MM-dd-HH:mm:ss} - {1}: PING FAILURE", DateTime.Now, alertingMetric.PagerDutyMessage);
                                    consecutiveFailCount++;
                                }
                            }
                        }

                        System.Threading.Thread.Sleep(alertingMetric.PingInterval.Value * 1000);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("\r\n{0}", ex.ToString());
                    }
                }
            });
        }
        private void SendMessageToHipchat(string message)
        {
            var client = new HipChatClient(this.AuthToken, this.RoomId, this.SenderName);

            client.SendMessage(message, this.BackgroundColor);
        }
Example #7
0
        public static void Main()
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var canaryRelicConfigurationSection = (CanaryConfigurationSection)config.GetSection("canaryRelic");

            var alertingMetrics = canaryRelicConfigurationSection.Alerts.Select(x => new AlertingMetric
            {
                Name                   = x.Name,
                AccountID              = x.NewRelic.NewRelicAccountId,
                ApplicationID          = x.NewRelic.NewRelicApplicationId,
                FieldName              = x.NewRelic.NewRelicMetricFieldName,
                HipChatApiKey          = x.HipChat.HipChatApiKey,
                HipChatRoomName        = x.HipChat.HipChatRoomName,
                LastPagerDutyAlert     = null,
                MinAverage             = x.MinimumMetricAverage,
                MaxAverage             = x.MaximumMetricAverage,
                MetricName             = x.NewRelic.NewRelicMetricName,
                NewRelicAPIKey         = x.NewRelic.NewRelicApiKey,
                PagerDutyServiceAPIKey = x.PagerDuty == null ? null : x.PagerDuty.GenericServiceApiKey,
                PagerDutyMessage       = x.PagerDuty == null ? null : x.PagerDuty.MessageOnAlert
            })
                                  .ToList();

            foreach (var hipChatSink in alertingMetrics.Select(x => new { x.HipChatApiKey, x.HipChatRoomName }).Distinct())
            {
                HipChatClient.SendMessage(hipChatSink.HipChatApiKey, hipChatSink.HipChatRoomName, "CanaryBot", "CanaryBot has started", true, HipChatClient.BackgroundColor.purple);
            }

            while (true)
            {
                try
                {
                    foreach (var alertingMetric in alertingMetrics)
                    {
                        var startDate = DateTime.UtcNow.AddMinutes(-5).ToString("yyyy-MM-ddTHH:mm:ss") + "Z";
                        var endDate   = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss") + "Z";

                        var url = string.Format(
                            @"https://api.newrelic.com/api/v1/accounts/{0}/applications/{1}/data.xml?metrics[]={2}&field={3}&begin={4}&end={5}",
                            alertingMetric.AccountID,
                            alertingMetric.ApplicationID,
                            alertingMetric.MetricName,
                            alertingMetric.FieldName,
                            startDate,
                            endDate);

                        string data;
                        using (var request = new WebClient())
                        {
                            request.Headers.Add("x-api-key", alertingMetric.NewRelicAPIKey);
                            data = request.DownloadString(url);
                        }

                        var urlCount = string.Format(
                            @"https://api.newrelic.com/api/v1/accounts/{0}/applications/{1}/data.xml?metrics[]={2}&field={3}&begin={4}&end={5}",
                            alertingMetric.AccountID,
                            alertingMetric.ApplicationID,
                            alertingMetric.MetricName,
                            "call_count",
                            startDate,
                            endDate);

                        string dataCount;
                        using (var requestCount = new WebClient())
                        {
                            requestCount.Headers.Add("x-api-key", alertingMetric.NewRelicAPIKey);
                            dataCount = requestCount.DownloadString(urlCount);
                        }

                        var xml = new XmlDocument();
                        xml.LoadXml(data);
                        var nodes = xml.SelectNodes("metrics/metric/field");

                        var xmlCount = new XmlDocument();
                        xmlCount.LoadXml(dataCount);
                        var nodesCount = xmlCount.SelectNodes("metrics/metric/field");

                        if (nodes != null && nodesCount != null && nodes.Count == nodesCount.Count)
                        {
                            var sumMetric   = 0F;
                            var countMetric = 0F;

                            for (var i = 0; i < nodes.Count; i++)
                            {
                                var node      = nodes[i];
                                var nodeCount = nodesCount[i];

                                if ((float.Parse(nodeCount.InnerText) > 1 && alertingMetric.FieldName == "average_value") ||
                                    alertingMetric.FieldName != "average_value")
                                {
                                    sumMetric += float.Parse(node.InnerText);
                                    countMetric++;
                                }
                            }

                            //if (countMetric < 3)
                            //	continue;

                            var avgMetric = sumMetric / countMetric;
                            if (float.IsNaN(avgMetric))
                            {
                                avgMetric = 0;
                            }

                            Console.WriteLine("{0:yyyy-MM-dd-HH:mm:ss} - {1}: {2:N3} average over {3} minutes", DateTime.Now, alertingMetric.Name, avgMetric, countMetric);

                            if (avgMetric > alertingMetric.MaxAverage || avgMetric < alertingMetric.MinAverage)
                            {
                                Console.WriteLine("Alerting HipChat for {0}!", alertingMetric.Name);
                                HipChatClient.SendMessage(alertingMetric.HipChatApiKey, alertingMetric.HipChatRoomName, "CanaryBot", alertingMetric.Name, true, HipChatClient.BackgroundColor.red);
                            }

                            if ((avgMetric > alertingMetric.MaxAverage || avgMetric < alertingMetric.MinAverage) &&
                                (alertingMetric.LastPagerDutyAlert == null || (DateTime.Now - alertingMetric.LastPagerDutyAlert.Value).TotalMinutes > 60) &&
                                !string.IsNullOrWhiteSpace(alertingMetric.PagerDutyServiceAPIKey))
                            {
                                Console.WriteLine("Alerting PagerDuty for {0}!", alertingMetric.Name);
                                PostPagerDutyAlert(alertingMetric.PagerDutyServiceAPIKey, alertingMetric.PagerDutyMessage, avgMetric);
                                alertingMetric.LastPagerDutyAlert = DateTime.Now;
                            }
                        }
                    }
                    System.Threading.Thread.Sleep(29000);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    System.Threading.Thread.Sleep(15000);
                }
            }
        }