private static bool ExpectedMonitorResultValues(MonitorResult actual, MonitorResult expected) { return(actual.Actual == expected.Actual && actual.ActualType == expected.ActualType && actual.Expected == expected.Expected && actual.ExpectedType == expected.ExpectedType); }
public void AddMonitorResult(MonitorResult monitorResult) { Guard.NotNull(monitorResult); _monitorRepository.Add(monitorResult); _eventPublisher.DomainModelCreated(monitorResult); }
public static MonitorResult FilterItems(List <MonitoringItem> lstItem, List <Keyword> lstKeyword) { MonitorResult objFilterResult = new MonitorResult(); foreach (MonitoringItem item in lstItem) { foreach (Keyword keyword in lstKeyword) { if (keyword.Search(item) == true) { string exceptWord = keyword.FindExceptWords(item);//제외 단어 찾기 if (exceptWord == "") { objFilterResult.FilteredItems.Add(item); break; } else { //제외 목록에 추가 objFilterResult.ExceptedItems.Add(new ExceptedItem() { Item = item, ExceptWord = exceptWord }); } } } } return(objFilterResult); }
protected override void Update(MonitorResult result) { result.TargetName = TargetAddress; try { var reply = new Ping().Send(TargetAddress); result.Details.Add("IP Status", reply.Status.ToExpandedString()); if (reply.Status == IPStatus.Success) { result.FriendlyMessage = $"Ping: {reply.RoundtripTime}ms"; result.Details.Add(nameof(reply.RoundtripTime).ToExpandedString(), $"{reply.RoundtripTime}ms"); if (reply.RoundtripTime >= ErrorThreshold) { result.TargetState = SeverityState.Error; } else if (reply.RoundtripTime >= WarningThreshold) { result.TargetState = SeverityState.Warning; } } else { result.TargetState = SeverityState.Error; result.FriendlyMessage = "Ping failed."; } } catch (Exception ex) { result.TargetState = SeverityState.Error; result.FriendlyMessage = ex.ToDetailString(); } }
protected override void Update(MonitorResult result) { result.TargetName = $"{_serviceName} on {_machineName}"; result.Details.Add("Service", _serviceName); result.Details.Add("Machine", _machineName); try { var serviceController = new ServiceController(_serviceName, _machineName); var serviceStatus = serviceController.Status; result.Details.Add("Status", serviceStatus.ToExpandedString()); if (ErrorStatuses.Contains(serviceStatus)) { result.TargetState = SeverityState.Error; } else if (WarningStatuses.Contains(serviceStatus)) { result.TargetState = SeverityState.Warning; } result.FriendlyMessage = $"The service is {StateMessageSuffixMap[serviceStatus]}."; } catch (Exception ex) { Log.Error("Failed to update.", ex); result.TargetState = SeverityState.Error; result.FriendlyMessage = ex.ToDetailString(); } }
public void Handle(MonitorResult result) { switch (result.TargetState) { case SeverityState.Normal: Console.ForegroundColor = ConsoleColor.Green; break; case SeverityState.Warning: Console.ForegroundColor = ConsoleColor.Yellow; break; case SeverityState.Error: Console.ForegroundColor = ConsoleColor.Red; break; default: Console.ForegroundColor = ConsoleColor.Blue; break; } Console.WriteLine($"Monitor: {result.SourceType}, Target: {result.TargetName}, State: {result.TargetState}"); if (!string.IsNullOrWhiteSpace(result.FriendlyMessage)) { Console.WriteLine($"\tDetails: {result.FriendlyMessage}"); } }
protected override void Update(MonitorResult result) { result.TargetName = $"{DatabaseName} on {DataSourceName}"; result.Details.Add("Database", DatabaseName); result.Details.Add("Data Source", DataSourceName); try { _connection.Open(); if (!DoesDatabaseExist(_connection)) { result.TargetState = SeverityState.Error; result.FriendlyMessage = "Database was not found."; } } catch (Exception ex) { result.TargetState = SeverityState.Error; result.FriendlyMessage = ex.ToDetailString(); } finally { if (_connection?.State.HasFlag(ConnectionState.Open) ?? false) { _connection.Close(); } } }
protected override void Update(MonitorResult result) { result.TargetName = _address; try { var request = WebRequest.Create(_address); request.Method = "HEAD"; using (var response = request.GetResponse()) { Update(result, response as HttpWebResponse); response.Close(); } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { Update(result, ex.Response as HttpWebResponse); } else { result.TargetState = SeverityState.Error; result.FriendlyMessage = ex.Message; } } catch (Exception ex) { Log.Error("Update failed.", ex); result.TargetState = SeverityState.Error; result.FriendlyMessage = ex.ToDetailString(); } }
protected override void Update(MonitorResult result) { CheckCpu(result); CheckMemory(result); CheckDiskSpace(result); CheckMSMQStorage(result); }
protected override string FormatResult(MonitorResult result) { var slackData = new Dictionary <string, string>(); if (!string.IsNullOrWhiteSpace(Username)) { slackData.Add(MessageConstants.Username, Username); } if (!string.IsNullOrWhiteSpace(Channel)) { slackData.Add(MessageConstants.Channel, Channel); } if (!string.IsNullOrWhiteSpace(Icon)) { slackData.Add(MessageConstants.Icon, Icon); } slackData.Add(MessageConstants.Text, string.Join(Environment.NewLine, new[] { $"Monitor: {result.SourceName}", $"Target: {result.TargetName}", $"State: {result.TargetState}", result.FriendlyMessage })); var serializedMessage = JsonConvert.SerializeObject(slackData); return(serializedMessage); }
private void AddDetail <T>(MonitorResult result, Func <PerformanceCounter> buildCounter, string name, string valueFormatString, Func <float, float> transformValue, Dictionary <SeverityState, T> thresholdCriteria, Func <T, float, bool> compareThreshold) { float?counterValue = null; try { var counter = buildCounter(); counterValue = counter.NextValue(); if (transformValue != null && counterValue.HasValue) { counterValue = transformValue(counterValue.Value); } } catch (Exception) { /* Using N/A for failure output. */ } result.Details.Add(name, string.Format(valueFormatString, counterValue?.ToString() ?? "N/A")); if (!counterValue.HasValue) { return; } result.TargetState = GetThresholdState(result.TargetState, thresholdCriteria, threshold => compareThreshold(threshold, counterValue.Value)); }
public static MonitorResult GET(string strURL) { MonitorResult Res = new MonitorResult() { Data = "", Success = false, Error = "" }; WebResponse objResponse = default(WebResponse); WebRequest objRequest = HttpWebRequest.Create(strURL); objRequest.Method = "GET"; objRequest.ContentType = "application/x-www-form-urlencoded"; try { objResponse = objRequest.GetResponse(); using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())) { Res.Success = true; Res.Data = sr.ReadToEnd(); sr.Close(); } } catch (Exception e){ Res.Success = false; Res.Data = ""; Res.Error = e.Message; } return Res; }
public static void Run(View self, MonitorResult result) { Console.SetBufferSize(Console.WindowWidth, Console.WindowHeight); Console.SetCursorPosition(0, 0); Console.WriteLine($"Process: {result.WindowTitle} ({result.Name}) ({result.ProcessId})"); Console.WriteLine($"Processor %: {result.ProcessorUsagePercent}"); Console.WriteLine($"Memory (MB): {result.MemoryMegabytesWorkingSet} ({result.MemoryBytesWorkingSet / 1024}K)"); Console.WriteLine("Threads: "); var height = Console.WindowHeight - (4 + 4); foreach (var thread in result.Threads) { if (height == 0) { break; } Console.WriteLine($" Thread ID {thread.ThreadId}: Process %: {thread.ProcessorUsagePercent}"); height--; } Console.SetCursorPosition(0, Console.WindowHeight - 3); Console.Write(new String('-', Console.WindowWidth - 1)); Console.SetCursorPosition(0, Console.WindowHeight - 2); Console.Write(new String(' ', Console.WindowWidth - 1)); Console.SetCursorPosition(0, Console.WindowHeight - 2); Console.Write(self.TextArea); Console.SetCursorPosition(0, Console.WindowHeight - 1); Console.Write(new String('-', Console.WindowWidth - 1)); }
public void MonitorResultService_GetAllMonitorResult() { var repo = new Mock <IMonitorResultRepository>(); var collection = (MonitorResult[])null; repo.Setup(r => r.Collection).Returns(() => collection); var srv = new MonitorResultService(repo.Object, null); srv.GetAllMonitorResult().ShouldBeNull(); collection = new MonitorResult[] { }; srv.GetAllMonitorResult().ShouldBeEmpty(); collection = new [] { new MonitorResult { Id = 1 }, new MonitorResult { Id = 2 }, new MonitorResult { Id = 3 }, }; var srvColleciton = srv.GetAllMonitorResult(); srvColleciton.ShouldNotBeEmpty(); srvColleciton.Count().ShouldBe(3); foreach (var c in collection) { srvColleciton.ShouldContain(c); } }
private static void NotifyResultAdded(MonitorResult result) { var resultModel = (Models.Monitor)result; GlobalHost.ConnectionManager .GetHubContext <NotificationHub>() .Clients.All.addMonitorResult(resultModel); }
private void AddDetail <T>(MonitorResult result, Func <PerformanceCounter> buildCounter, string name, string valueFormatString, Dictionary <SeverityState, T> thresholdCriteria, Func <T, float, bool> compareThreshold) { AddDetail(result, buildCounter, name, valueFormatString, x => x, thresholdCriteria, compareThreshold); }
public void Render(MonitorResult result) { var view = this.Views.Find(x => x.Name == this.CurrentView); if (view != null && result != null) { view.Run(this, result); } }
public void Handle(MonitorResult result) { try { _repository.Save(result); } catch (Exception ex) { _log.Error("Failed to record result.", ex); } }
public void ResultHook(MonitorResult result) { var existingResults = _repository.Query <MonitorResult>(); foreach (var currentExistingResult in existingResults.Where(x => x.SourceName == result.SourceName)) { _repository.Delete(currentExistingResult); } _repository.Save(result); NotifyResultAdded(result); }
public async Task <RuntimeResult> MonitorStop_RequestURL() { string profileURL = await _RequestStreamUser(); if (profileURL == null) { return(MonitorResult.FromError($"{Context.Message.Author.Mention}, Please provide a valid Stream URL for me to stop monitoring")); } ILiveBotMonitor monitor = _GetServiceMonitor(profileURL); ILiveBotUser user = await monitor.GetUser(profileURL : profileURL); return(await MonitorStop(user)); }
private void AddDetail <T>(MonitorResult result, Func <PerformanceCounter> buildCounter, string name, string valueFormatString, Func <float, float> transformValue, Dictionary <SeverityState, T> thresholdCriteria, Func <T, float, bool> compareThreshold) { float?counterValue = null; try { var counter = buildCounter(); counterValue = counter.NextValue(); if (transformValue != null && counterValue.HasValue) { counterValue = transformValue(counterValue.Value); } } catch (Exception ex) { result.FriendlyMessage = ex.ToDetailString(); result.TargetState = SeverityState.Error; } var formattedValue = counterValue.HasValue ? string.Format(valueFormatString, counterValue) : string.Format(valueFormatString, "N/A"); result.Details.Add(name, formattedValue); if (!counterValue.HasValue) { return; } if (result.TargetState == SeverityState.Error) { return; } var counterState = GetThresholdState(thresholdCriteria, threshold => compareThreshold(threshold, counterValue.Value)); if ((result.TargetState == SeverityState.Warning && counterState == SeverityState.Error) || (result.TargetState == SeverityState.Normal && counterState == SeverityState.Warning)) { result.TargetState = counterState; result.FriendlyMessage = $"{name} is {formattedValue}"; } }
private void CheckDiskSpace(MonitorResult result) { AddDetail(result, () => new PerformanceCounter { MachineName = _machineName, CategoryName = "LogicalDisk", CounterName = "% Free Space" }, "Disk Space Available", "{0}%", DiskSpaceAvailableSeverity, (threshold, diskAvailable) => threshold <= diskAvailable); }
private void CheckMemory(MonitorResult result) { AddDetail(result, () => new PerformanceCounter { MachineName = _machineName, CategoryName = "Memory", CounterName = "Available MBytes" }, "Memory Available", "{0}MB", MemoryAvailableSeverity, (threshold, memoryAvailable) => threshold <= memoryAvailable); }
public async Task <RuntimeResult> MonitorStop(ILiveBotUser user) { ILiveBotMonitor monitor = _GetServiceMonitor(user); DiscordGuild discordGuild = new DiscordGuild { DiscordId = Context.Guild.Id, Name = Context.Guild.Name, IconUrl = Context.Guild.IconUrl }; await _work.GuildRepository.AddOrUpdateAsync(discordGuild, g => g.DiscordId == Context.Guild.Id); discordGuild = await _work.GuildRepository.SingleOrDefaultAsync(g => g.DiscordId == Context.Guild.Id); StreamUser streamUser = new StreamUser() { ServiceType = user.ServiceType, SourceID = user.Id, Username = user.Username, DisplayName = user.DisplayName, AvatarURL = user.AvatarURL, ProfileURL = user.ProfileURL }; await _work.UserRepository.AddOrUpdateAsync(streamUser, (i => i.ServiceType == user.ServiceType && i.SourceID == user.Id)); streamUser = await _work.UserRepository.SingleOrDefaultAsync(i => i.ServiceType == user.ServiceType && i.SourceID == user.Id); Expression <Func <StreamSubscription, bool> > streamSubscriptionPredicate = (i => i.User == streamUser && i.DiscordGuild == discordGuild ); IEnumerable <StreamSubscription> streamSubscriptions = await _work.SubscriptionRepository.FindAsync(streamSubscriptionPredicate); try { foreach (StreamSubscription streamSubscription in streamSubscriptions) { await _work.SubscriptionRepository.RemoveAsync(streamSubscription.Id); } await ReplyAsync($"{Context.Message.Author.Mention}, I have removed the Subscription for {user.DisplayName}"); return(MonitorResult.FromSuccess()); } catch (Exception e) { Log.Error($"Error running MonitorStop for {Context.Message.Author.Id} {Context.Message.Author.Username}#{Context.Message.Author.Discriminator} GuildID: {Context.Guild.Id} ChannelID: {Context.Channel.Id}\n{e}"); return(MonitorResult.FromSuccess($"{Context.Message.Author.Mention}, I couldn't remove the Subscription for user {user.DisplayName}. Please try again or contact my owner")); } }
private void CheckMSMQStorage(MonitorResult result) { AddDetail(result, () => new PerformanceCounter { MachineName = _machineName, CategoryName = "MSMQ Service", CounterName = "Total bytes in all queues" }, "MSMQ Storage Usage", "{0}MB", value => value / Constants.Units.Kibi / Constants.Units.Kibi, MSMQStorageUsageSeverity, (threshold, storageUsage) => threshold >= storageUsage); }
private static void GetDisplays() { EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, delegate(IntPtr hMonitor, IntPtr hdcMonitor, ref Rect lprcMonitor, IntPtr dwData) { MonitorResult monitorResult = VerifyMonitorCapabilities(hMonitor); if (monitorResult.success) { RecordMonitorBrightness(monitorResult.hMonitor); } return(true); }, IntPtr.Zero); }
private void AddHandler(OnTestContextStepExecutionEndEvent message) { var options = message.TestContextStep.Parameters[0] as AddOptions; var expectedResult = string.Format(AddExpectedResultFormat, options.X, options.Y, options.X + options.Y); var actualResult = _commander.GetElementText("add-result"); var monitorResult = new MonitorResult { Actual = actualResult, Expected = expectedResult, ComparisonTypeCode = ComparisonType.Equality.Code }; _monitorService.AddMonitorResult(monitorResult); }
private void CheckCpu(MonitorResult result) { AddDetail(result, () => new PerformanceCounter { MachineName = _machineName, CategoryName = "Processor", CounterName = "% Processor Time", InstanceName = "_Total" }, "CPU Usage", "{0}%", CpuUsageSeverity, (threshold, cpuUsage) => threshold >= cpuUsage); }
public void Handle(MonitorResult result) { try { var subject = SubjectFormatter.ThrowIfNull(nameof(SubjectFormatter)).Invoke(result); var body = BodyFormatter.ThrowIfNull(nameof(BodyFormatter)).Invoke(result); var message = new MailMessage(_sender, _recipients, subject, body); _smtpClient.Send(message); } catch (Exception ex) { _log.Error("Failed to send email.", ex); } }
protected override void Update(MonitorResult result) { result.TargetName = _queuePath; try { using (var queue = new MessageQueue(_queuePath, QueueAccessMode.Peek)) Update(queue, result); } catch (Exception ex) { Log.Error("Update failed.", ex); result.TargetState = SeverityState.Error; result.FriendlyMessage = ex.ToDetailString(); } }
private async void RunParser() { if (ValidateMonitoringInfo() == true) { LogAction.WriteStatus("start"); foreach (var parsing in LstParsingModule) { LogAction.WriteStatus("downloading data"); List <MonitoringItem> lstAll = await parsing.GetMonitoringList(); //능동적 슬립은 보류 //if (lstAll.Count == 0) //{ // parsing.SetSleepSecond(parsing.GetSleepSecond() + minSleepSecond); //} //else //{ // parsing.SetSleepSecond(Math.Max(minSleepSecond, parsing.GetSleepSecond() / 2)); //} LogAction.WriteStatus($"{parsing.GetParsingTarget()} : success get {lstAll.Count} items"); LogAction.WriteAllItem(lstAll); foreach (var info in LstMonitoringInfo) { MonitorResult filterResult = info.FilterItems(lstAll); LogAction.WriteFilteredItem(filterResult.FilteredItems); LogAction.WriteExceptedItem(filterResult.ExceptedItems); if (filterResult.FilteredItems.Count > 0) { LogAction.WriteStatus($"found {filterResult.FilteredItems.Count} items"); info.SendAlarm(filterResult.FilteredItems); } } } } else { LogAction.WriteStatus("invalid monitoring info"); } LogAction.WriteStatus("finish\r\n===================="); }
public static MonitorResult POST(string strURL, Dictionary<string, string> Data) { MonitorResult Res = new MonitorResult() { Data = "", Success = false, Error = "" }; string postData = ""; WebResponse objResponse = default(WebResponse); WebRequest objRequest = HttpWebRequest.Create(strURL); objRequest.Method = "POST"; objRequest.ContentType = "application/x-www-form-urlencoded"; foreach (KeyValuePair<string, string> V in Data){ postData += V.Key + "=" + HttpUtility.UrlEncode(V.Value) + ";"; } byte[] byteArray = Encoding.UTF8.GetBytes(postData); Stream dataStream = objRequest.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); try{ objResponse = objRequest.GetResponse(); using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())) { Res.Success = true; Res.Data = sr.ReadToEnd(); sr.Close(); } } catch (Exception e){ Res.Success = false; Res.Data = ""; Res.Error = e.Message; } return Res; }
private string compileMonitor(MonitorResult mon, string val) { return val.Replace("{%data%}", mon.Data).Replace("{%error%}", mon.Error).Replace("{%success%}", Convert.ToString(mon.Success)); }
private void ExecAlarm(string AlarmList, MonitorResult Res) { foreach (string A in AlarmList.Split(',')) { Program.Print("RUN>[{0}]...", false, A); Action Act = xmlConfig.Actions[A.ToLower().Trim()]; switch (Act.Type.ToLower()) { case "email": SMTP.send(Act.From, Act.To, compileMonitor(Res, Act.Subject), compileMonitor(Res, Act.Message)); break; case "http": case "http-get": MonitorResult getRes = HTTP.GET(HttpUtility.UrlDecode(Act.To)); break; case "exec": //Not implemented throw new Exception("Exec not implemented."); case "http-post": break; default: throw new Exception("Invalid action type."); } } }
// Method that accepts status from workers and sends to ClientHub public void ReportResult(MonitorResult result) { // Send to relevant client // Some sort of timeout logic here? MonitorQueue.Enqueue(result.Request); }