Beispiel #1
0
        public override MonitorStates GetState()
        {
            MonitorStates    returnState = MonitorStates.Good;
            CollectorMessage details     = new CollectorMessage();

            LastDetailMsg.HtmlText  = "";
            LastDetailMsg.PlainText = "Getting Ports and Orchestration states and counts";
            LastError    = 0;
            LastErrorMsg = "";
            try
            {
                LastDetailMsg.PlainText = "Getting Receive Location count";
                int receiveLocationCount = BizTalkGroup.AllReceiveLocations ? BizTalkGroup.GetTotalReceiveLocationCount() : BizTalkGroup.ReceiveLocations.Count;
                LastDetailMsg.PlainText = "Getting Disabled Receive Location count";
                int receiveLocationsDisabled = BizTalkGroup.AllReceiveLocations ? BizTalkGroup.GetDisabledReceiveLocationCount(new List <string>()) : BizTalkGroup.GetDisabledReceiveLocationCount(BizTalkGroup.ReceiveLocations);
                //Now check send ports
                LastDetailMsg.PlainText = "Getting Send Port count";
                int sendPortCount = BizTalkGroup.AllSendPorts ? BizTalkGroup.GetTotalSendPortCount() : BizTalkGroup.SendPorts.Count;
                LastDetailMsg.PlainText = "Getting Stopped Send Port count";
                int sendPortStoppedCount = BizTalkGroup.AllSendPorts ? BizTalkGroup.GetStoppedSendPortCount(new List <string>()) : BizTalkGroup.GetStoppedSendPortCount(BizTalkGroup.SendPorts);
                //Now check orchestrations
                LastDetailMsg.PlainText = "Getting Orchestration count";
                int orchestrationCount = BizTalkGroup.AllOrchestrations ? BizTalkGroup.GetTotalOrchestrationCount() : BizTalkGroup.Orchestrations.Count;
                LastDetailMsg.PlainText = "Getting Stopped Orchestration count";
                int orchestrationStoppedCount = BizTalkGroup.AllOrchestrations ? BizTalkGroup.GetStoppedOrchestrationCount(new List <string>()) : BizTalkGroup.GetStoppedOrchestrationCount(BizTalkGroup.Orchestrations);

                if (receiveLocationsDisabled == -1 || sendPortStoppedCount == -1 || orchestrationStoppedCount == -1)
                {
                    returnState       = MonitorStates.Error;
                    details.PlainText = "An error occured trying to query the BizTalk Management database!";
                    details.HtmlText  = "<blockquote>An error occured trying to query the BizTalk Management database!</blockquote>";
                }
                else
                {
                    if ((receiveLocationsDisabled >= receiveLocationCount && (receiveLocationCount > 0)) ||
                        (sendPortStoppedCount >= sendPortCount && (sendPortCount > 0)) ||
                        (orchestrationStoppedCount >= orchestrationCount && (orchestrationCount > 0)))
                    {
                        returnState = MonitorStates.Error;
                    }
                    else if (receiveLocationsDisabled > 0 || sendPortStoppedCount > 0 || orchestrationStoppedCount > 0)
                    {
                        returnState = MonitorStates.Warning;
                    }
                    details.PlainText = "Getting summary of current states";
                    details           = GetSummaryOfDisabledOrStopped();
                }
                LastDetailMsg = details;
            }
            catch (Exception ex)
            {
                LastError               = 1;
                LastErrorMsg            = ex.Message;
                LastDetailMsg.PlainText = string.Format("Last step: {0}\r\n{1}", LastDetailMsg.PlainText, ex.Message);
                LastDetailMsg.HtmlText  = string.Format("<blockquote>Last step: {0}<br />{1}</blockquote>", LastDetailMsg.PlainText, ex.Message);

                returnState = MonitorStates.Error;
            }
            return(returnState);
        }
Beispiel #2
0
        internal CollectorMessage GetLastXDetails()
        {
            CollectorMessage collectorMessage = new CollectorMessage();
            //List<string> suspendedInstanceList = new List<string>();
            StringBuilder            sbText             = new StringBuilder();
            StringBuilder            sbHtml             = new StringBuilder();
            List <SuspendedInstance> suspendedInstances = new List <SuspendedInstance>();

            if (ShowLastXDetails > 0)
            {
                foreach (string connString in GetMsgBoxConnStrs())
                {
                    foreach (string suspendedQueue in GetHostInstanceSuspendedQs(connString))
                    {
                        string hostName = suspendedQueue.Substring(0, suspendedQueue.Length - 11);
                        if (Hosts.Count == 0 || Hosts.Contains(hostName))
                        {
                            suspendedInstances.AddRange(GetHostSuspendedInstancesLastX(connString, suspendedQueue));
                        }
                    }
                }
            }
            foreach (SuspendedInstance suspendedItem in (from s in suspendedInstances
                                                         orderby s.SuspendTime descending
                                                         select s).Take(ShowLastXDetails))
            {
                sbText.AppendLine(suspendedItem.ToString());
                sbHtml.AppendLine(suspendedItem.ToString(true));
            }
            collectorMessage.PlainText = sbText.ToString();
            collectorMessage.HtmlText  = sbHtml.ToString();
            return(collectorMessage);
        }
Beispiel #3
0
        private void LogCorrectiveScriptAction(CollectorEntry collector, bool error)
        {
            CollectorMessage details = new CollectorMessage();

            details.PlainText = string.Format("Due to an alert raised on the collector '{0}' the following corrective script was executed: '{1}'",
                                              collector.Name, error ? collector.CorrectiveScriptOnErrorPath : collector.CorrectiveScriptOnWarningPath);
            //details.LastValue = collector.LastMonitorDetails.LastValue;
            Stopwatch sw = new Stopwatch();

            sw.Start();
            foreach (NotifierEntry notifierEntry in (from n in Notifiers
                                                     where n.Enabled &&
                                                     (
                                                         ((int)n.AlertLevel <= (int)AlertLevel.Warning && !error) ||
                                                         ((int)n.AlertLevel <= (int)AlertLevel.Error && error)
                                                     ) &&
                                                     (n.AlertForCollectors.Count == 0 || n.AlertForCollectors.Contains(collector.Name))
                                                     select n))
            {
                try
                {
                    PCRaiseNotifiersCalled();
                    notifierEntry.Notifier.RecordMessage(error ? AlertLevel.Error : AlertLevel.Warning, collector.CollectorRegistrationName, collector.Name, collector.LastMonitorState, collector.CurrentState, details);
                }
                catch (Exception ex)
                {
                    RaiseRaiseNotifierError(notifierEntry, ex.ToString());
                }
            }
            sw.Stop();
            PCSetNotifiersSendTime(sw.ElapsedMilliseconds);
        }
Beispiel #4
0
        public override void RecordMessage(AlertLevel alertLevel, string collectorType, string category, MonitorStates oldState, MonitorStates newState, CollectorMessage collectorMessage)
        {
            string lastStep = "";

            try
            {
                //eventLogWriteMutex.WaitOne();
                if (eventLogNotifierConfig.MachineName.Length == 0)
                {
                    throw new Exception("Computer name not specified!");
                }
                if (eventLogNotifierConfig.EventSource.Length == 0)
                {
                    throw new Exception("Event source not specified!");
                }
                string currentEventSource = eventLogNotifierConfig.EventSource
                                            .Replace("%CollectorName%", category)
                                            .Replace("%CollectorType%", collectorType);

                lastStep = "Test if source exists";
                if (!EventLog.SourceExists(currentEventSource))
                {
                    lastStep = "Attempt to create event source " + currentEventSource;
                    EventSourceCreationData escd = new EventSourceCreationData(currentEventSource, "Application");
                    escd.MachineName = eventLogNotifierConfig.MachineName;
                    EventLog.CreateEventSource(escd);
                }
                lastStep = "Opening event log on " + eventLogNotifierConfig.MachineName;
                EventLog          outputLog         = new EventLog("Application", eventLogNotifierConfig.MachineName, currentEventSource);
                EventLogEntryType eventLogEntryType = (alertLevel == AlertLevel.Info || alertLevel == AlertLevel.Debug) ?  EventLogEntryType.Information :
                                                      alertLevel == AlertLevel.Warning ? EventLogEntryType.Warning :EventLogEntryType.Error;

                lastStep = "Generate output stream";
                string outputStr = string.Format("Time: {0}\r\nAlert level: {1}\r\nCollector: {2}\r\nCategory: {3}\r\nOld state: {4}\r\nCurrent state: {5}\r\nDetails: {6}",
                                                 DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                                 Enum.GetName(typeof(AlertLevel), alertLevel),
                                                 collectorType,
                                                 category,
                                                 Enum.GetName(typeof(MonitorStates), oldState),
                                                 Enum.GetName(typeof(MonitorStates), newState),
                                                 collectorMessage.PlainText);

                lastStep = "Write the event log entry";
                outputLog.WriteEntry(outputStr, eventLogEntryType);
            }
            catch (Exception ex)
            {
                throw new Exception("Error recording message in Event log notifier\r\nLast step: " + lastStep, ex);
            }
            finally
            {
                //eventLogWriteMutex.ReleaseMutex();
            }
        }
Beispiel #5
0
        public override void RecordMessage(AlertLevel alertLevel, string collectorType, string category, MonitorStates oldState, MonitorStates newState, CollectorMessage collectorMessage)
        {
            string lastStep = "";

            try
            {
                smtpWriteMutex.WaitOne();
                if (mailSettings.HostServer.Length == 0)
                {
                    throw new Exception("SMTP host server not specified!");
                }
                lastStep = "Setting up SMTP client details";
                using (SmtpClient smtpClient = new SmtpClient())
                {
                    smtpClient.Host = mailSettings.HostServer;
                    smtpClient.UseDefaultCredentials = mailSettings.UseDefaultCredentials;
                    smtpClient.Port = mailSettings.Port;

                    if (!mailSettings.UseDefaultCredentials)
                    {
                        lastStep = "Setting up non default credentials";
                        System.Net.NetworkCredential cr = new System.Net.NetworkCredential();
                        cr.Domain              = mailSettings.Domain;
                        cr.UserName            = mailSettings.UserName;
                        cr.Password            = mailSettings.Password;
                        smtpClient.Credentials = cr;
                    }
                    if (mailSettings.UseTLS)
                    {
                        smtpClient.EnableSsl = true;
                    }
                    MailMessage mailMessage = new MailMessage(mailSettings.FromAddress, mailSettings.ToAddress);

                    lastStep = "Setting up mail body";
                    string body = mailSettings.Body
                                  .Replace("%Details%", mailSettings.IsBodyHtml ? collectorMessage.HtmlText : collectorMessage.PlainText)
                                  .Replace("%DateTime%", DateTime.Now.ToString("F"))
                                  .Replace("%AlertLevel%", alertLevel.ToString())
                                  .Replace("%PreviousState%", oldState.ToString())
                                  .Replace("%CurrentState%", newState.ToString())
                                  .Replace("%CollectorName%", category)
                                  .Replace("%CollectorType%", collectorType);

                    string subject = mailSettings.Subject
                                     .Replace("%DateTime%", DateTime.Now.ToString("F"))
                                     .Replace("%AlertLevel%", alertLevel.ToString())
                                     .Replace("%PreviousState%", oldState.ToString())
                                     .Replace("%CurrentState%", newState.ToString())
                                     .Replace("%CollectorName%", category)
                                     .Replace("%CollectorType%", collectorType);

                    mailMessage.Priority = (MailPriority)mailSettings.MailPriority;
                    if (mailSettings.SenderAddress.Length > 0)
                    {
                        mailMessage.Sender = new MailAddress(mailSettings.SenderAddress);
                    }
                    if (mailSettings.ReplyToAddress.Length > 0)
                    {
                        mailMessage.ReplyToList.Add(mailSettings.ReplyToAddress);
                    }

                    mailMessage.Body       = body;
                    mailMessage.IsBodyHtml = mailSettings.IsBodyHtml;

                    mailMessage.Subject = subject;
                    lastStep            = "Sending SMTP mail";
                    smtpClient.Send(mailMessage);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error recording message in SMTP notifier\r\nLast step: " + lastStep, ex);
            }
            finally
            {
                smtpWriteMutex.ReleaseMutex();
            }
        }
Beispiel #6
0
        public override void RecordMessage(AlertLevel alertLevel, string collectorType, string category, MonitorStates oldState, MonitorStates newState, CollectorMessage collectorMessage)
        {
            string lastStep = "";

            try
            {
                //rssWriteMutex.WaitOne();
                if (rssDocument == null)
                {
                    LoadRSSDocument();
                }
                string lineTitle = rssConfig.LineTitle
                                   .Replace("%DateTime%", DateTime.Now.ToString("F"))
                                   .Replace("%AlertLevel%", alertLevel.ToString())
                                   .Replace("%PreviousState%", oldState.ToString())
                                   .Replace("%CurrentState%", newState.ToString())
                                   .Replace("%CollectorName%", category)
                                   .Replace("%CollectorType%", collectorType);
                string lineCategory = rssConfig.LineCategory
                                      .Replace("%DateTime%", DateTime.Now.ToString("F"))
                                      .Replace("%AlertLevel%", alertLevel.ToString())
                                      .Replace("%PreviousState%", oldState.ToString())
                                      .Replace("%CurrentState%", newState.ToString())
                                      .Replace("%CollectorName%", category)
                                      .Replace("%CollectorType%", collectorType);
                string lineDetails = rssConfig.LineDescription
                                     .Replace("%Details%", collectorMessage.HtmlText)
                                     .Replace("%DateTime%", DateTime.Now.ToString("F"))
                                     .Replace("%AlertLevel%", alertLevel.ToString())
                                     .Replace("%PreviousState%", oldState.ToString())
                                     .Replace("%CurrentState%", newState.ToString())
                                     .Replace("%CollectorName%", category)
                                     .Replace("%CollectorType%", collectorType);

                rssDocument.Lines.Add(
                    new InMemoryRSSDocumentLine()
                {
                    Title   = lineTitle,
                    PubDate = DateTime.Now,
                    //GUID = Guid.NewGuid().ToString(),
                    Category    = lineCategory,
                    Description = lineDetails     //.Replace("\r\n", "<br/>")
                }
                    );
                rssDocument.SaveRssDocument();
            }
            catch (Exception ex)
            {
                throw new Exception("Error recording message in rss notifier\r\nLast step: " + lastStep, ex);
            }
            finally
            {
                //rssWriteMutex.ReleaseMutex();
            }
        }
Beispiel #7
0
 public abstract void RecordMessage(AlertLevel alertLevel, string collectorType, string category, MonitorStates oldState, MonitorStates newState, CollectorMessage collectorMessage);
Beispiel #8
0
        public override void RecordMessage(AlertLevel alertLevel, string collectorType, string collectorName, MonitorStates oldState, MonitorStates newState, CollectorMessage collectorMessage)
        {
            string             lastStep           = "";
            PerformanceCounter thePCValueInstance = null;

            try
            {
                //pcCategoryCreationMutex.WaitOne();
                if (!PerformanceCounterCategory.Exists(category)) //Does performance counter category exists?
                {
                    CounterCreationDataCollection ccdc = new CounterCreationDataCollection(
                        new CounterCreationData[]
                    {
                        new CounterCreationData("Value", "Raw Value", PerformanceCounterType.NumberOfItems32)
                    }
                        );
                    PerformanceCounterCategory.Create(category, category, PerformanceCounterCategoryType.MultiInstance, ccdc);
                    System.Threading.Thread.Sleep(500); //give moment for internal stuff to do creation of PC
                }
                //pcCategoryCreationMutex.ReleaseMutex();
            }
            catch (Exception ex)
            {
                //pcCategoryCreationMutex.ReleaseMutex();
                throw new Exception(string.Format("An error occured trying to create the performance counter category  '{0}'", category), ex);
            }
            try
            {
                if (collectorName != null && collectorName.Length > 0)
                {
                    //Zero any disabled collector values
                    if (collectorMessage != null && newState == MonitorStates.Disabled)
                    {
                        collectorMessage.LastValue = 0;
                    }
                    lastStep           = "Retrieving performance counter from cache";
                    thePCValueInstance = (from pc in perfCounterCache
                                          where pc.InstanceName == collectorName
                                          select pc).FirstOrDefault();
                    if (thePCValueInstance == null)
                    {
                        lastStep           = "Creating 'Value' performance counter for " + collectorName;
                        thePCValueInstance = new PerformanceCounter(category, "Value", collectorName, false);
                        perfCounterCache.Add(thePCValueInstance);
                    }

                    lastStep = "Reading last value";
                    if (collectorMessage != null && collectorMessage.LastValue != null && collectorMessage.LastValue.IsNumber())
                    {
                        long   theValue = 0;
                        double tmpValue = double.Parse(collectorMessage.LastValue.ToString());
                        theValue = (long)tmpValue;
                        lastStep = "Setting performance counter value for " + collectorName;
                        try
                        {
                            thePCValueInstance.BeginInit();
                            thePCValueInstance.RawValue = theValue;
                        }
                        finally
                        {
                            thePCValueInstance.EndInit();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error recording message in log file notifier '{0}'\r\nLast step: " + lastStep, ex);
            }
        }
Beispiel #9
0
        private void SendNotifierAlert(AlertLevel alertLevel, DetailLevel detailLevel,
                                       string collectorType, string collectorName, MonitorStates oldState, MonitorStates currentState, CollectorMessage details)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            foreach (NotifierEntry notifierEntry in (from n in Notifiers
                                                     where n.Enabled && (int)n.AlertLevel <= (int)alertLevel &&
                                                     (detailLevel == DetailLevel.All || detailLevel == n.DetailLevel) &&
                                                     (n.AlertForCollectors.Count == 0 || n.AlertForCollectors.Contains(collectorName))
                                                     select n))
            {
                try
                {
                    PCRaiseNotifiersCalled();
                    notifierEntry.Notifier.RecordMessage(alertLevel, collectorType, collectorName, oldState, currentState, details);
                }
                catch (Exception ex)
                {
                    RaiseRaiseNotifierError(notifierEntry, ex.ToString());
                }
            }
            sw.Stop();
            PCSetNotifiersSendTime(sw.ElapsedMilliseconds);
        }
Beispiel #10
0
 private void RaiseStateChanged(AlertLevel alertLevel, string collectorType, string collectorName, MonitorStates oldState, MonitorStates currentState, CollectorMessage details)
 {
     try
     {
         if (StateChanged != null)
         {
             StateChanged(alertLevel, collectorType, collectorName, oldState, currentState, details);
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Trace.WriteLine(string.Format("Error in RaiseStateChanged: {0}", ex.Message));
     }
 }
Beispiel #11
0
        //private Mutex sqlWriteMutex = new Mutex();
        #endregion

        public override void RecordMessage(AlertLevel alertLevel, string collectorType, string category, MonitorStates oldState, MonitorStates newState, CollectorMessage collectorMessage)
        {
            string lastStep = "";

            try
            {
                //sqlWriteMutex.WaitOne();
                if (connStr.Length == 0)
                {
                    lastStep = "Setting up connection string";
                    connStr  = dbSettings.GetConnectionString();
                }
                lastStep = "Opening connection";
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    conn.Open();
                    lastStep = "Inserting test message into database";

                    string alertParamName         = dbSettings.AlertFieldName.Replace("'", "''").Replace("@", "");
                    string collectorTypeParamName = dbSettings.CollectorTypeFieldName.Replace("'", "''").Replace("@", "");
                    string categoryParamName      = dbSettings.CategoryFieldName.Replace("'", "''").Replace("@", "");
                    string previousStateParamName = dbSettings.PreviousStateFieldName.Replace("'", "''").Replace("@", "");
                    string currentStateParamName  = dbSettings.CurrentStateFieldName.Replace("'", "''").Replace("@", "");
                    string detailsParamName       = dbSettings.DetailsFieldName.Replace("'", "''").Replace("@", "");

                    string sql = dbSettings.UseSP ? dbSettings.CmndValue :
                                 string.Format("Insert {0} ({1}, {2}, {3}, {4}, {5}, {6}) values(@{1}, @{2}, @{3}, @{4}, @{5}, @{6})",
                                               dbSettings.CmndValue,
                                               dbSettings.AlertFieldName,
                                               collectorTypeParamName,
                                               categoryParamName,
                                               previousStateParamName,
                                               currentStateParamName,
                                               detailsParamName);
                    using (SqlCommand cmnd = new SqlCommand(sql, conn))
                    {
                        SqlParameter[] paramArr = new SqlParameter[]
                        {
                            new SqlParameter("@" + alertParamName, (byte)alertLevel),
                            new SqlParameter("@" + collectorTypeParamName, collectorType),
                            new SqlParameter("@" + categoryParamName, category),
                            new SqlParameter("@" + previousStateParamName, (byte)oldState),
                            new SqlParameter("@" + currentStateParamName, (byte)newState),
                            new SqlParameter("@" + detailsParamName, FormatUtils.N(collectorMessage.PlainText, "No details available"))
                        };
                        cmnd.Parameters.AddRange(paramArr);
                        if (dbSettings.UseSP)
                        {
                            cmnd.CommandType = CommandType.StoredProcedure;
                        }
                        else
                        {
                            cmnd.CommandType = CommandType.Text;
                        }
                        cmnd.CommandTimeout = dbSettings.CmndTimeOut;
                        cmnd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error recording message in Database notifier\r\nLast step: " + lastStep, ex);
            }
            finally
            {
                //sqlWriteMutex.ReleaseMutex();
            }
        }
Beispiel #12
0
        public override void RecordMessage(AlertLevel alertLevel, string collectorType, string category, MonitorStates oldState, MonitorStates newState, CollectorMessage collectorMessage)
        {
            string lastStep = "";

            try
            {
                if (createNewFileSizeKB > 0)
                {
                    lastStep = "Checking if log file exists";
                    FileInfo fi = new FileInfo(outputPath);
                    if (fi.Exists)
                    {
                        lastStep = "Checking log file size";
                        if (fi.Length > createNewFileSizeKB * 1024)
                        {
                            lastStep = "Create new log file";
                            CreateBackupFile(outputPath, 1);
                        }
                    }
                }

                lastStep = "Append text to log file";
                File.AppendAllText(outputPath,
                                   string.Format("Time: {0}\r\nAlert level: {1}\r\nCollector: {2}\r\nCategory: {3}\r\nOld state: {4}\r\nCurrent state: {5}\r\nDetails: {6}",
                                                 DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                                 Enum.GetName(typeof(AlertLevel), alertLevel),
                                                 collectorType,
                                                 category,
                                                 Enum.GetName(typeof(MonitorStates), oldState),
                                                 Enum.GetName(typeof(MonitorStates), newState),
                                                 collectorMessage.PlainText + "\r\n" + new string('-', 79) + "\r\n"
                                                 ));
            }
            catch (Exception ex)
            {
                throw new Exception("Error recording message in log file notifier '{0}'\r\nLast step: " + lastStep, ex);
            }
        }
Beispiel #13
0
 public void AppendCollectorMessage(CollectorMessage appendedOne)
 {
     PlainText += appendedOne.PlainText;
     htmlText  += appendedOne.htmlText;
 }