public void FromXml(string content) { XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(content); XmlElement root = xdoc.DocumentElement; UniqueId = root.ReadXmlElementAttr("uniqueId", Guid.NewGuid().ToString()); State = CollectorStateConverter.GetCollectorStateFromText(root.ReadXmlElementAttr("state", "NotAvailable")); try { StateChangedTime = DateTime.Parse(root.ReadXmlElementAttr("stateChangedTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); } catch { } try { Timestamp = DateTime.Parse(root.ReadXmlElementAttr("timeStamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); } catch { } try { CallDurationMS = root.ReadXmlElementAttr("callDurationMS", 0); } catch { } ForAgent = root.ReadXmlElementAttr("forAgent", ""); ForAgentType = root.ReadXmlElementAttr("forAgentType", ""); ForAgentId = root.ReadXmlElementAttr("forAgentId", -1); CurrentValue = root.ReadXmlElementAttr("currentValue", ""); CurrentValueUnit = root.ReadXmlElementAttr("currentValueUnit", ""); PrimaryUIValue = root.ReadXmlElementAttr("primaryUIValue", false); ExecutedOnHostComputer = root.ReadXmlElementAttr("executedOnHostComputer", ""); RanAs = root.ReadXmlElementAttr("ranAs", ""); RepeatCount = root.ReadXmlElementAttr("repeatCount", 0); try { AlertHeader = root.SelectSingleNode("alertHeader").InnerText; } catch { } try { AlertFooter = root.SelectSingleNode("alertFooter").InnerText; } catch { } try { AdditionalAlertText = root.SelectSingleNode("additionalAlertText").InnerText; } catch { } RawDetails = root.SelectSingleNode("rawDetails").InnerText; HtmlDetails = root.SelectSingleNode("htmlDetails").InnerText; XmlNodeList alertNodes = root.SelectNodes("alerts"); AlertsRaised = new List <string>(); foreach (XmlNode alertNode in alertNodes) { if (alertNode.InnerText.Trim().Length > 0) { AlertsRaised.Add(alertNode.InnerText); } } XmlNodeList scriptsRanNodes = root.SelectNodes("scriptsRan"); ScriptsRan = new List <string>(); if (scriptsRanNodes != null) { foreach (XmlNode scriptNode in scriptsRanNodes) { if (scriptNode.InnerText.Trim().Length > 0) { ScriptsRan.Add(scriptNode.InnerText); } } } ChildStates = new List <MonitorState>(); XmlNodeList childStates = root.SelectNodes("childStates/monitorState"); if (childStates != null) { foreach (XmlNode childStateNode in childStates) { MonitorState childState = new MonitorState(); childState.FromXml(childStateNode.OuterXml); ChildStates.Add(childState); } } }
public MonitorState GetState(QuickMon.RemoteCollectorHost entry) { StringBuilder consoleOutPut = new StringBuilder(); MonitorState monitorState = new MonitorState(); /*** For Console debugging **/ consoleOutPut.AppendFormat("{0}: Running collector host: {1}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), entry.Name); try { OperationContext context = OperationContext.Current; System.ServiceModel.Channels.MessageProperties messageProperties = context.IncomingMessageProperties; System.ServiceModel.Channels.RemoteEndpointMessageProperty endpointProperty = messageProperties[System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name] as System.ServiceModel.Channels.RemoteEndpointMessageProperty; consoleOutPut.AppendFormat(" Requested from {0}:{1}\r\n", endpointProperty.Address, endpointProperty.Port); } catch (Exception ex) { consoleOutPut.AppendFormat(" Error getting caller info: {0}\r\n", ex.Message); } consoleOutPut.AppendFormat("{0}\r\n", new string('*', 79)); Console.WriteLine(consoleOutPut.ToString()); consoleOutPut = new StringBuilder(); /*** For Console debugging **/ try { string collectorHostConfig = entry.ToCollectorHostXml(); string tempMonitorPack = "<monitorPack version=\"5.0.0.0\" name=\"\" typeName=\"\" enabled=\"True\" defaultNotifier=\"\" runCorrectiveScripts=\"False\" collectorStateHistorySize=\"1\" pollingFreqSecOverride=\"0\">" + "<collectorHosts>" + collectorHostConfig + "</collectorHosts>\r\n" + "<notifierHosts>\r\n" + "</notifierHosts>\r\n" + "</monitorPack>"; MonitorPack m = new MonitorPack(); m.LoadXml(tempMonitorPack); m.ApplicationUserNameCacheMasterKey = ApplicationUserNameCacheMasterKey; m.ApplicationUserNameCacheFilePath = ApplicationUserNameCacheFilePath; m.BlockedCollectorAgentTypes.AddRange(BlockedCollectorAgentTypes.ToArray()); m.ScriptsRepositoryDirectory = ScriptsRepositoryDirectory; if (m.CollectorHosts.Count == 1) { m.RefreshStates(); //Since there is only one CollectorHost CollectorHost ch = m.CollectorHosts[0]; monitorState = ch.CurrentState; monitorState.RanAs = ch.CurrentState.RanAs; } else { monitorState.CurrentValue = "There was a problem loading the Collector Host config on the remote host!"; monitorState.RawDetails = collectorHostConfig; monitorState.HtmlDetails = collectorHostConfig.EscapeXml(); monitorState.State = CollectorState.Error; } //If hosted in console test app consoleOutPut.AppendFormat("{0}: Results for collector host: {1}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), entry.Name); consoleOutPut.AppendFormat(" State : {0}\r\n", monitorState.State); consoleOutPut.AppendFormat(" Ran as : {0}\r\n", monitorState.RanAs); consoleOutPut.AppendFormat(" Details : {0}\r\n", monitorState.ReadAllRawDetails()); } catch (Exception ex) { consoleOutPut.AppendFormat(" Error: {0}\r\n", ex); monitorState.CurrentValue = ex.Message; monitorState.State = CollectorState.Error; monitorState.RawDetails = ex.ToString(); monitorState.HtmlDetails = ex.ToString().EscapeXml(); } consoleOutPut.AppendLine(new string('*', 79)); Console.WriteLine(consoleOutPut.ToString()); monitorState.ExecutedOnHostComputer = System.Net.Dns.GetHostName(); return(monitorState); }
private void CollectorHostRefreshCurrentState(CollectorHost collectorHost, bool disablePollingOverrides = false, bool forceSingleCollectorUpdate = false) { if (!AbortPolling) { RaiseCollectorHostCalled(collectorHost); try { MonitorState chms = null; collectorHost.RunTimeMasterKey = ""; collectorHost.RunTimeUserNameCacheFile = ""; collectorHost.BlockedCollectorAgentTypes = new List <string>(); collectorHost.BlockedCollectorAgentTypes.AddRange(BlockedCollectorAgentTypes.ToArray()); if (collectorHost.RunAsEnabled && collectorHost.RunAs != null && collectorHost.RunAs.Length > 0) { if (UserNameCacheMasterKey.Length > 0 && System.IO.File.Exists(UserNameCacheFilePath) && QuickMon.Security.CredentialManager.IsAccountPersisted(UserNameCacheFilePath, UserNameCacheMasterKey, collectorHost.RunAs) && QuickMon.Security.CredentialManager.IsAccountDecryptable(UserNameCacheFilePath, UserNameCacheMasterKey, collectorHost.RunAs)) { collectorHost.RunTimeMasterKey = UserNameCacheMasterKey; collectorHost.RunTimeUserNameCacheFile = UserNameCacheFilePath; } else if (ApplicationUserNameCacheMasterKey != null && ApplicationUserNameCacheFilePath != null && ApplicationUserNameCacheMasterKey.Length > 0 && System.IO.File.Exists(ApplicationUserNameCacheFilePath) && QuickMon.Security.CredentialManager.IsAccountPersisted(ApplicationUserNameCacheFilePath, ApplicationUserNameCacheMasterKey, collectorHost.RunAs) && QuickMon.Security.CredentialManager.IsAccountDecryptable(ApplicationUserNameCacheFilePath, ApplicationUserNameCacheMasterKey, collectorHost.RunAs)) { collectorHost.RunTimeMasterKey = ApplicationUserNameCacheMasterKey; collectorHost.RunTimeUserNameCacheFile = ApplicationUserNameCacheFilePath; } } //collectorHost.ApplyConfigVarsNow(ConfigVariables); chms = collectorHost.RefreshCurrentState(disablePollingOverrides); #region Do/Check/Set dependant CollectorHosts if (chms.State == CollectorState.Error && collectorHost.ChildCheckBehaviour != ChildCheckBehaviour.ContinueOnWarningOrError) { SetDependantCollectorHostStates(collectorHost, CollectorState.NotAvailable); } else if (chms.State == CollectorState.Warning && collectorHost.ChildCheckBehaviour == ChildCheckBehaviour.OnlyRunOnSuccess) { SetDependantCollectorHostStates(collectorHost, CollectorState.NotAvailable); } else if (chms.State == CollectorState.Disabled || chms.State == CollectorState.ConfigurationError || !collectorHost.IsEnabledNow()) { SetDependantCollectorHostStates(collectorHost, CollectorState.Disabled); } else { //Remote execute and dependant Collector Hosts if (collectorHost.ForceRemoteExcuteOnChildCollectors) { collectorHost.OverrideForceRemoteExcuteOnChildCollectors = true; SetChildCollectorHostRemoteExecuteDetails(collectorHost, collectorHost.RemoteAgentHostAddress, collectorHost.RemoteAgentHostPort); } //Polling overrides and dependant Collector Hosts if (collectorHost.EnabledPollingOverride) { SetChildCollectorHostPollingOverrides(collectorHost); } #region Loop through dependant CollectorHosts if (ConcurrencyLevel > 1 & !forceSingleCollectorUpdate) { ParallelOptions po = new ParallelOptions() { MaxDegreeOfParallelism = ConcurrencyLevel }; ParallelLoopResult parResult = Parallel.ForEach((from c in CollectorHosts where c.ParentCollectorId == collectorHost.UniqueId select c), po, dependentCollectorHost => CollectorHostRefreshCurrentState(dependentCollectorHost, disablePollingOverrides)); if (!parResult.IsCompleted) { SendNotifierAlert(AlertLevel.Error, DetailLevel.All, "Error querying collectors in parralel"); } } else //use old single threaded way { //Refresh states foreach (CollectorHost dependentCollectorHost in (from c in CollectorHosts where c.ParentCollectorId == collectorHost.UniqueId select c)) { CollectorHostRefreshCurrentState(dependentCollectorHost, disablePollingOverrides); } } #endregion } #endregion LoggingCollectorEvent(string.Format("Collector '{0}' return state '{1}'", collectorHost.Name, collectorHost.CurrentState), collectorHost); } catch (Exception ex) { WriteLogging(string.Format("CollectorHostRefreshCurrentState error: {0}", ex.Message)); if (!ex.Message.Contains("Collection was modified; enumeration operation may not execute")) { RaiseMonitorPackError("Internal error. Collector config was modified while in use!"); } else { RaiseCollectorError(collectorHost, ex.Message); } } } }
private MonitorState GetStateFromLocalCurrentUser() { MonitorState resultMonitorState = new MonitorState() { State = CollectorState.UpdateInProgress, ExecutedOnHostComputer = System.Net.Dns.GetHostName(), RanAs = System.Security.Principal.WindowsIdentity.GetCurrent().Name }; try { //First set blank/NA state foreach (ICollector ca in CollectorAgents) { ca.CurrentState = new MonitorState() { ForAgent = ca.Name, State = CollectorState.UpdateInProgress, RawDetails = "N/A", HtmlDetails = "<p>N/A</p>" }; } int agentId = 0; foreach (ICollector ca in CollectorAgents) { MonitorState caMs; if (BlockedCollectorAgentTypes.Contains(ca.AgentClassName)) { caMs = new MonitorState() { State = CollectorState.Disabled, RawDetails = "This agent is disabled by host process", HtmlDetails = "<p>This agent is disabled by host process</p>" }; } else if (ca.Enabled) { caMs = ca.GetState(); } else { caMs = new MonitorState() { State = CollectorState.Disabled, RawDetails = "This agent is disabled", HtmlDetails = "<p>This agent is disabled</p>" }; //caMs.RanAs = System.Security.Principal.WindowsIdentity.GetCurrent().Name; } caMs.ForAgent = ca.Name; caMs.ForAgentId = agentId; agentId++; resultMonitorState.ChildStates.Add(caMs); //If we only care for the first success and find it don't look further if (AgentCheckSequence == QuickMon.AgentCheckSequence.FirstSuccess && caMs.State == CollectorState.Good) { break; } //If we only care for the first error and find it don't look further else if (AgentCheckSequence == QuickMon.AgentCheckSequence.FirstError && caMs.State == CollectorState.Error) { break; } } } catch (Exception exLocal) { resultMonitorState.State = CollectorState.Error; resultMonitorState.RawDetails = exLocal.ToString(); } //resultMonitorState.ExecutedOnHostComputer = System.Net.Dns.GetHostName(); return(resultMonitorState); }
public MonitorState RefreshCurrentState(bool disablePollingOverrides = false) { MonitorState resultMonitorState = new MonitorState() { State = CollectorState.NotAvailable }; if (AlertHeaderText != null && AlertHeaderText.Trim().Length > 0) { resultMonitorState.AlertHeader = AlertHeaderText; } if (AlertFooterText != null && AlertFooterText.Trim().Length > 0) { resultMonitorState.AlertFooter = AlertFooterText; } RefreshCount++; CurrentPollAborted = false; if (CurrentState.State != CollectorState.ConfigurationError) { if (InServiceWindow) //currently in Service window { if (ServiceWindows.IsInTimeWindow()) //Service window expired { InServiceWindow = false; RaiseEntereringServiceWindow(); } } else if (!ServiceWindows.IsInTimeWindow()) { InServiceWindow = true; RaiseExitingServiceWindow(); } if (!Enabled) { resultMonitorState.State = CollectorState.Disabled; StagnantStateFirstRepeat = false; StagnantStateSecondRepeat = false; StagnantStateThirdRepeat = false; resultMonitorState.RawDetails = "Collector host is disabled."; } else if (InServiceWindow) { resultMonitorState.State = CollectorState.Disabled; StagnantStateFirstRepeat = false; StagnantStateSecondRepeat = false; StagnantStateThirdRepeat = false; resultMonitorState.RawDetails = "Disabled due to 'out of service window' event."; } else if (CollectorAgents == null || CollectorAgents.Count == 0)//like old folder type collector { resultMonitorState.State = CollectorState.None; StagnantStateFirstRepeat = false; StagnantStateSecondRepeat = false; StagnantStateThirdRepeat = false; resultMonitorState.RawDetails = "There are no agents."; } else if (CollectorAgents != null && CollectorAgents.Count == CollectorAgents.Count(ca => !ca.Enabled)) { resultMonitorState.State = CollectorState.Disabled; StagnantStateFirstRepeat = false; StagnantStateSecondRepeat = false; StagnantStateThirdRepeat = false; resultMonitorState.RawDetails = "Disabled because all agents are disabled."; } else if (CurrentState.State != CollectorState.NotAvailable && !disablePollingOverrides && EnabledPollingOverride && !EnablePollFrequencySliding && (LastStateUpdate.AddSeconds(OnlyAllowUpdateOncePerXSec) > DateTime.Now)) { //Not time yet for update CurrentPollAborted = true; resultMonitorState.State = CurrentState.State; resultMonitorState.RawDetails = "Due to polling override (OnlyAllowUpdateOncePerXSec) the previous state is repeated."; RaiseLoggingPollingOverridesTriggeredEvent(string.Format("Polling override of {0} seconds not reached yet", OnlyAllowUpdateOncePerXSec)); } else if (CurrentState.State != CollectorState.NotAvailable && !disablePollingOverrides && EnabledPollingOverride && EnablePollFrequencySliding && ( (StagnantStateThirdRepeat && (LastStateUpdate.AddSeconds(PollSlideFrequencyAfterThirdRepeatSec) > DateTime.Now)) || (!StagnantStateThirdRepeat && StagnantStateSecondRepeat && (LastStateUpdate.AddSeconds(PollSlideFrequencyAfterSecondRepeatSec) > DateTime.Now)) || (!StagnantStateThirdRepeat && !StagnantStateSecondRepeat && StagnantStateFirstRepeat && (LastStateUpdate.AddSeconds(PollSlideFrequencyAfterFirstRepeatSec) > DateTime.Now)) || (!StagnantStateFirstRepeat && !StagnantStateThirdRepeat && !StagnantStateSecondRepeat && (LastStateUpdate.AddSeconds(OnlyAllowUpdateOncePerXSec) > DateTime.Now)) ) ) { //Not time yet for update CurrentPollAborted = true; resultMonitorState.State = CurrentState.State; if (StagnantStateThirdRepeat) { resultMonitorState.RawDetails = "Due to polling override (StagnantStateThirdRepeat) the previous state is repeated."; } else if (StagnantStateSecondRepeat) { resultMonitorState.RawDetails = "Due to polling override (StagnantStateSecondRepeat) the previous state is repeated."; } else if (StagnantStateFirstRepeat) { resultMonitorState.RawDetails = "Due to polling override (StagnantStateFirstRepeat) the previous state is repeated."; } else { resultMonitorState.RawDetails = "Due to polling override (EnablePollFrequencySliding) the previous state is repeated."; } } else { //*********** Call actual collector GetState ********** LastStateCheckAttemptBegin = DateTime.Now; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); //first check if remote host exection is required if (EnableRemoteExecute || (OverrideRemoteAgentHost && !BlockParentOverrideRemoteAgentHostSettings)) { resultMonitorState = GetRemoteState(); } else if (!RunAsEnabled || RunAs == null || RunAs.Length == 0 || RunTimeUserNameCacheFile == null || RunTimeUserNameCacheFile.Length == 0 || RunTimeMasterKey == null || RunTimeMasterKey.Length == 0) { resultMonitorState = GetStateFromLocalCurrentUser(); } else { resultMonitorState = GetStateFromLocal(); } sw.Stop(); resultMonitorState.CallDurationMS = (int)sw.ElapsedMilliseconds; RaiseAllAgentsExecutionTime(sw.ElapsedMilliseconds); #region Calculate summarized state if (resultMonitorState.ChildStates != null && resultMonitorState.ChildStates.Count > 0) { int allCount = resultMonitorState.ChildStates.Count; int disabledCount = (from cs in resultMonitorState.ChildStates where cs.State == CollectorState.Disabled select cs).Count(); int goodCount = (from cs in resultMonitorState.ChildStates where cs.State == CollectorState.Good select cs).Count(); int warningCount = (from cs in resultMonitorState.ChildStates where cs.State == CollectorState.Warning select cs).Count(); int errorCount = (from cs in resultMonitorState.ChildStates where cs.State == CollectorState.Error select cs).Count(); if (allCount == disabledCount) { resultMonitorState.State = CollectorState.Disabled; } else if (AgentCheckSequence == QuickMon.AgentCheckSequence.All) { if (allCount - disabledCount == goodCount) { resultMonitorState.State = CollectorState.Good; } else if (allCount - disabledCount == errorCount) { resultMonitorState.State = CollectorState.Error; } else { resultMonitorState.State = CollectorState.Warning; } } else if (AgentCheckSequence == QuickMon.AgentCheckSequence.FirstSuccess) { if (goodCount > 0) { resultMonitorState.State = CollectorState.Good; } else if (warningCount > 0) { resultMonitorState.State = CollectorState.Warning; } else { resultMonitorState.State = CollectorState.Error; } } else { if (errorCount > 0) { resultMonitorState.State = CollectorState.Error; } else if (warningCount > 0) { resultMonitorState.State = CollectorState.Warning; } else { resultMonitorState.State = CollectorState.Good; } } } #endregion } } else { resultMonitorState.State = CollectorState.ConfigurationError; } //Set current CH state plus raise any alerts if required SetCurrentState(resultMonitorState); return(resultMonitorState); }
public void SetCurrentState(MonitorState newState) { bool raiseAlertNow = false; if (currentState != null) { if (!CurrentPollAborted) { LastStateUpdate = DateTime.Now; } if (FirstStateUpdate < (new DateTime(2000, 1, 1))) { FirstStateUpdate = DateTime.Now; } bool stateChanged = currentState.State != newState.State; if (stateChanged) { LastStateChange = DateTime.Now; StagnantStateFirstRepeat = false; StagnantStateSecondRepeat = false; StagnantStateThirdRepeat = false; if (EnabledPollingOverride && EnablePollFrequencySliding && CurrentState.State != CollectorState.NotAvailable) { RaiseLoggingPollingOverridesTriggeredEvent("Frequency sliding cancelled due to collector state value changed"); } } else if (EnabledPollingOverride && EnablePollFrequencySliding && CurrentState.State != CollectorState.NotAvailable) { if (!StagnantStateFirstRepeat) { StagnantStateFirstRepeat = true; StagnantStateSecondRepeat = false; StagnantStateThirdRepeat = false; RaiseLoggingPollingOverridesTriggeredEvent("Frequency sliding reached 1st stagnant stage"); } else if (!StagnantStateSecondRepeat) { StagnantStateSecondRepeat = true; StagnantStateThirdRepeat = false; RaiseLoggingPollingOverridesTriggeredEvent("Frequency sliding reached 2nd stagnant stage"); } else if (!StagnantStateThirdRepeat) { StagnantStateThirdRepeat = true; RaiseLoggingPollingOverridesTriggeredEvent("Frequency sliding reached 3rd stagnant stage"); } } #region Check if alert should be raised now if (stateChanged) { if (newState.State == CollectorState.Good) { numberOfPollingsInErrWarn = 0; } if (DelayErrWarnAlertForXSec > 0 || DelayErrWarnAlertForXPolls > 0) // alert should be delayed { delayErrWarnAlertTime = DateTime.Now.AddSeconds(DelayErrWarnAlertForXSec); numberOfPollingsInErrWarn = 0; waitAlertTimeErrWarnInMinFlagged = true; } else { raiseAlertNow = true; } } else { if (waitAlertTimeErrWarnInMinFlagged) //waiting for delayed alert { if (DelayErrWarnAlertForXSec > 0 && DateTime.Now > delayErrWarnAlertTime) { raiseAlertNow = true; waitAlertTimeErrWarnInMinFlagged = false; numberOfPollingsInErrWarn = 0; //handle further alerts as if it changed now again LastStateChange = DateTime.Now; } else if (DelayErrWarnAlertForXPolls > 0 && DelayErrWarnAlertForXPolls <= numberOfPollingsInErrWarn) { raiseAlertNow = true; waitAlertTimeErrWarnInMinFlagged = false; numberOfPollingsInErrWarn = 0; //handle further alerts as if it changed now again LastStateChange = DateTime.Now; } else { raiseAlertNow = false; } } else { if ( (RepeatAlertInXMin > 0 && (LastStateChange.AddMinutes(RepeatAlertInXMin) < DateTime.Now)) || (RepeatAlertInXPolls > 0 && RepeatAlertInXPolls <= numberOfPollingsInErrWarn) ) { raiseAlertNow = true; numberOfPollingsInErrWarn = 0; //handle further alerts as if it changed now again LastStateChange = DateTime.Now; } else { raiseAlertNow = false; } } } if (raiseAlertNow) { //only allow repeat alert after specified minutes if (AlertOnceInXMin > 0 && LastAlertTime.AddMinutes(AlertOnceInXMin) > DateTime.Now) { raiseAlertNow = false; //cancel alert } } else { if (newState.State == CollectorState.Warning || newState.State == CollectorState.Error) { numberOfPollingsInErrWarn++; } else { numberOfPollingsInErrWarn = 0; } } #endregion AddStateToHistory(currentState); if (!CorrectiveScriptDisabled) { if (RestorationScriptPath != null && RestorationScriptPath.Trim().Length > 0 && newState.State == CollectorState.Good && stateChanged && (currentState.State == CollectorState.Error || currentState.State == CollectorState.Warning)) { RaiseRunCollectorHostRestorationScript(); } else if (stateChanged || !CorrectiveScriptsOnlyOnStateChange) { if (CorrectiveScriptOnErrorPath != null && CorrectiveScriptOnErrorPath.Trim().Length > 0 && newState.State == CollectorState.Error && RunCollectorHostCorrectiveErrorScript != null) { RaiseRunCollectorHostCorrectiveErrorScript(); } else if (CorrectiveScriptOnWarningPath != null && CorrectiveScriptOnWarningPath.Trim().Length > 0 && newState.State == CollectorState.Warning && RunCollectorHostCorrectiveWarningScript != null) { RaiseRunCollectorHostCorrectiveWarningScript(); } } } } currentState = newState; #region Set Alert texts if (AlertHeaderText != null && AlertHeaderText.Trim().Length > 0) { currentState.AlertHeader = AlertHeaderText; } if (AlertFooterText != null && AlertFooterText.Trim().Length > 0) { currentState.AlertFooter = AlertFooterText; } if (currentState.State == CollectorState.Good && GoodAlertText != null && GoodAlertText.Trim().Length > 0) { currentState.AdditionalAlertText = GoodAlertText; } else if (currentState.State == CollectorState.Warning && WarningAlertText != null && WarningAlertText.Trim().Length > 0) { currentState.AdditionalAlertText = WarningAlertText; } else if (currentState.State == CollectorState.Error && ErrorAlertText != null && ErrorAlertText.Trim().Length > 0) { currentState.AdditionalAlertText = ErrorAlertText; } #endregion RaiseStateUpdated(); #region Raise event for Alert to be handled by Monitorpack if (raiseAlertNow) { LastAlertTime = DateTime.Now; //reset alert time switch (newState.State) { case CollectorState.Good: LastGoodState = newState; GoodStateCount++; RaiseAlertGoodState(); break; case CollectorState.Warning: LastWarningState = newState; WarningStateCount++; RaiseAlertWarningState(); break; case CollectorState.Error: case CollectorState.ConfigurationError: LastErrorState = newState; ErrorStateCount++; RaiseAlertErrorState(); break; default: RaiseNoStateChanged(); break; } } else { RaiseNoStateChanged(); } #endregion }
private void ReadCallback(IAsyncResult result) { try { using (NetworkStream networkStream = clientSocket.GetStream()) { int read = networkStream.EndRead(result); MonitorState packResult = new MonitorState() { State = CollectorState.NotAvailable, RawDetails = "", HtmlDetails = "" }; string data = ""; if (read > 0) { byte[] buffer = result.AsyncState as byte[]; data = Encoding.UTF8.GetString(buffer, 0, read); //do the job with the data here if (data.StartsWith("<monitorPack") && data.EndsWith("</monitorPack>")) { MonitorPack m = new MonitorPack(); StringBuilder plainTextDetails = new StringBuilder(); StringBuilder htmlTextTextDetails = new StringBuilder(); m.RaiseMonitorPackError += m_RaiseMonitorPackError; m.LoadXml(data); RaiseDisplayMonitorPackName(m.Name); packResult.State = m.RefreshStates(); htmlTextTextDetails.AppendLine("<ul>"); foreach (CollectorEntry ce in (from c in m.Collectors where c.CurrentState != null select c)) { if (ce.CurrentState == null) { plainTextDetails.AppendLine(string.Format("\tCollector: {0}, State: N/A", ce.Name)); htmlTextTextDetails.AppendLine(string.Format("<li>Collector: {0}, State: N/A</li>", ce.Name)); } else if (ce.CurrentState.State == CollectorState.Good) { plainTextDetails.AppendLine(string.Format("\tCollector: {0}, State: {1}", ce.Name, ce.CurrentState.State)); htmlTextTextDetails.AppendLine(string.Format("<li>Collector: {0}, State: {1}</li>", ce.Name, ce.CurrentState.State)); } else { plainTextDetails.AppendLine(string.Format("\tCollector: {0}, State: {1}", ce.Name, ce.CurrentState.State)); if (ce.CurrentState.RawDetails != null && ce.CurrentState.RawDetails.Length > 0) { plainTextDetails.AppendLine(string.Format("\t\tDetails: {0}", ce.CurrentState.RawDetails.Replace("\r\n", "\r\n\t\t\t"))); } htmlTextTextDetails.AppendLine(string.Format("<li>Collector: {0}, State: {1}</li>", ce.Name, ce.CurrentState.State)); if (ce.CurrentState.HtmlDetails != null && ce.CurrentState.HtmlDetails.Length > 0) { htmlTextTextDetails.AppendLine(string.Format("<br/>Details: {0}", ce.CurrentState.HtmlDetails)); } } } htmlTextTextDetails.AppendLine("</ul>"); packResult.RawDetails = plainTextDetails.ToString(); packResult.HtmlDetails = htmlTextTextDetails.ToString(); RaiseInfoMessage(string.Format("MonitorPack: '{0}' - state: {1}", m.Name, packResult.State)); m = null; } else { RaiseErrorMessage("Input request data invalid!\r\n" + summarizeErrData(data)); packResult.State = CollectorState.Error; packResult.RawDetails = "Input request data invalid!\r\n" + summarizeErrData(data); packResult.HtmlDetails = "Input request data invalid!\r\n" + summarizeErrData(data.Replace("<", "<").Replace(">", ">")); } //send the data back to client. Byte[] sendBytes = Encoding.UTF8.GetBytes(packResult.ToXml()); networkStream.Write(sendBytes, 0, sendBytes.Length); networkStream.Flush(); } } } catch (Exception ex) { if ((ex is System.IO.IOException && ex.Message.Contains("Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host")) || ex is System.InvalidOperationException && ex.Message.Contains("The operation is not allowed on non-connected sockets")) { RaiseInfoMessage(string.Format("Client {0} disconnecting.", clientNo)); } else { if (clientSocket != null && clientSocket.Client != null && clientSocket.Client.RemoteEndPoint is System.Net.IPEndPoint) { RaiseErrorMessage(string.Format("Error processing request from {0}\r\nError: {1}", ((System.Net.IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString(), ex)); } else { RaiseErrorMessage(string.Format("Error from unknown client: {0}", ex)); } } } }
private void cmdRunTest_Click(object sender, EventArgs e) { string configXml = "<monitorPack version=\"4.0.0\" name=\"Test\" typeName=\"TestType\" enabled=\"True\" " + "defaultNotifier=\"Default notifiers\" runCorrectiveScripts=\"True\" " + "stateHistorySize=\"100\" pollingFreqSecOverride=\"12\">\r\n" + "<configVars />\r\n" + "<collectorHosts>\r\n"; configXml += "<collectorHost uniqueId=\"PingNowhere\" name=\"Ping Nowhere\" enabled=\"True\" expandOnStart=\"True\" dependOnParentId=\"\" " + "agentCheckSequence=\"All\" childCheckBehaviour=\"OnlyRunOnSuccess\" " + "enableRemoteExecute=\"False\" " + "forceRemoteExcuteOnChildCollectors=\"False\" remoteAgentHostAddress=\"\" remoteAgentHostPort=\"48181\" " + "blockParentRemoteAgentHostSettings=\"False\" runLocalOnRemoteHostConnectionFailure=\"True\" >\r\n" + "<collectorAgents>\r\n" + "<collectorAgent type=\"PingCollector\">\r\n" + "<config>\r\n" + "<entries>\r\n" + "<entry pingMethod=\"Ping\" address=\"NowhereSpecific\" />\r\n" + (chkLocalhost.Checked ? "<entry pingMethod=\"Ping\" address=\"localhost\" />\r\n" : "") + "</entries>\r\n" + "</config>\r\n" + "</collectorAgent>\r\n" + "</collectorAgents>\r\n" + "</collectorHost>\r\n"; configXml += "</collectorHosts>" + "<notifierHosts>\r\n"; if (chkEventLog.Checked) { configXml += "<notifierHost name=\"EventLogNotifier\" enabled=\"True\" alertLevel=\"Warning\" detailLevel=\"Detail\" " + "attendedOptionOverride=\"OnlyAttended\">\r\n" + "<notifierAgents>\r\n" + "<notifierAgent type=\"EventLogNotifier\">\r\n" + "<config><eventLog computer=\".\" eventSource=\"QuickMon4\" successEventID=\"0\" warningEventID=\"1\" errorEventID=\"2\" /></config>\r\n" + "</notifierAgent>\r\n" + "</notifierAgents>\r\n" + "</notifierHost>\r\n"; } if (chkLogFile.Checked) { configXml += "<notifierHost name=\"Log file\" enabled=\"True\" alertLevel=\"Info\" detailLevel=\"Detail\" " + "attendedOptionOverride=\"OnlyAttended\">\r\n" + "<notifierAgents>\r\n" + "<notifierAgent type=\"LogFileNotifier\">\r\n" + "<config><logFile path=\"" + txtLogFile.Text + "\" createNewFileSizeKB=\"0\" /></config>\r\n" + "</notifierAgent>\r\n" + "</notifierAgents>\r\n" + "</notifierHost>\r\n"; } if (chkSMTP.Checked) { configXml += "<notifierHost name=\"Email\" enabled=\"True\" alertLevel=\"Info\" detailLevel=\"Detail\" " + "attendedOptionOverride=\"OnlyAttended\">\r\n" + "<notifierAgents>\r\n" + "<notifierAgent name=\"Email\" type=\"SMTPNotifier\">\r\n" + "<config>\r\n" + "<smtp hostServer=\"" + txtSMTPServer.Text + "\" useDefaultCredentials=\"True\" domain=\"\" userName=\"\" password=\"\" " + "fromAddress=\"" + txtEmailAddress.Text + "\" toAddress=\"" + txtEmailAddress.Text + "\" senderAddress=\"" + txtEmailAddress.Text + "\" replyToAddress=\"" + txtEmailAddress.Text + "\" mailPriority=\"0\" useTLS=\"False\" isBodyHtml=\"True\" port=\"25\" subject=\"QuickMon %AlertLevel% - %CollectorName%\" body=\"QuickMon alert raised for <b>'%CollectorName%'</b><br />
<b>Date Time:</b> %DateTime%<br />
<b>Current state:</b> %CurrentState%<br />
<b>Agents:</b> %CollectorAgents%<br />
<b>Details</b><blockquote>%Details%</blockquote>\" />\r\n" + "</config>\r\n" + "</notifierAgent>\r\n" + "</notifierAgents>\r\n" + "</notifierHost>\r\n"; } if (chkAudio.Checked) { configXml += "<notifierHost name=\"AudioNotifier\" enabled=\"True\" alertLevel=\"Warning\" detailLevel=\"Detail\" " + "attendedOptionOverride=\"OnlyAttended\">\r\n" + "<notifierAgents>\r\n" + "<notifierAgent type=\"AudioNotifier\">\r\n" + "<config>\r\n" + "<audioConfig>\r\n" + "<goodState enabled=\"false\" useSystemSounds=\"true\" soundPath=\"\" systemSound=\"1\" soundRepeatCount=\"1\" soundVolumePerc=\"-1\" />\r\n" + "<warningState enabled=\"true\" useSystemSounds=\"true\" soundPath=\"\" systemSound=\"2\" soundRepeatCount=\"1\" soundVolumePerc=\"-1\" />\r\n" + "<errorState enabled=\"true\" useSystemSounds=\"true\" soundPath=\"\" systemSound=\"3\" soundRepeatCount=\"1\" soundVolumePerc=\"-1\" />\r\n" + "</audioConfig>\r\n" + "</config>\r\n" + "</notifierAgent>\r\n" + "</notifierAgents>\r\n" + "</notifierHost>\r\n"; } configXml += "</notifierHosts>\r\n" + "</monitorPack>"; MonitorPack m = new MonitorPack(); m.ConcurrencyLevel = (int)nudConcurency.Value; m.LoadXml(configXml); m.RefreshStates(); txtAlerts.Text = ""; foreach (CollectorHost ch in m.CollectorHosts) { MonitorState ms = ch.CurrentState; txtAlerts.Text += string.Format("Collector host: {0}\r\n", ch.Name); txtAlerts.Text += string.Format("Time: {0}\r\n", ms.Timestamp.ToString("yyyy-MM-dd HH:mm:ss")); txtAlerts.Text += string.Format("Duration: {0}ms\r\n", ms.CallDurationMS); txtAlerts.Text += string.Format("Run on host: {0}\r\n", ms.ExecutedOnHostComputer); txtAlerts.Text += string.Format("State: {0}\r\n{1}\r\n", ms.State, XmlFormattingUtils.NormalizeXML(ms.ReadAllRawDetails('\t'))); txtAlerts.Text += "Alerts\r\n"; foreach (string alert in ms.AlertsRaised) { txtAlerts.Text += "\t" + alert; } } }