Ejemplo n.º 1
0
 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);
 }
Ejemplo n.º 2
0
        public void AddMonitorResult(MonitorResult monitorResult)
        {
            Guard.NotNull(monitorResult);

            _monitorRepository.Add(monitorResult);
            _eventPublisher.DomainModelCreated(monitorResult);
        }
Ejemplo n.º 3
0
        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);
        }
Ejemplo n.º 4
0
        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();
            }
        }
Ejemplo n.º 5
0
        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();
            }
        }
Ejemplo n.º 6
0
        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}");
            }
        }
Ejemplo n.º 7
0
        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();
                }
            }
        }
Ejemplo n.º 8
0
        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();
            }
        }
Ejemplo n.º 9
0
 protected override void Update(MonitorResult result)
 {
     CheckCpu(result);
     CheckMemory(result);
     CheckDiskSpace(result);
     CheckMSMQStorage(result);
 }
Ejemplo n.º 10
0
        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);
        }
Ejemplo n.º 11
0
        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));
        }
Ejemplo n.º 12
0
    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;
    }
Ejemplo n.º 13
0
        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));
        }
Ejemplo n.º 14
0
        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);
            }
        }
Ejemplo n.º 15
0
        private static void NotifyResultAdded(MonitorResult result)
        {
            var resultModel = (Models.Monitor)result;

            GlobalHost.ConnectionManager
            .GetHubContext <NotificationHub>()
            .Clients.All.addMonitorResult(resultModel);
        }
Ejemplo n.º 16
0
 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);
 }
Ejemplo n.º 17
0
        public void Render(MonitorResult result)
        {
            var view = this.Views.Find(x => x.Name == this.CurrentView);

            if (view != null && result != null)
            {
                view.Run(this, result);
            }
        }
Ejemplo n.º 18
0
 public void Handle(MonitorResult result)
 {
     try
     {
         _repository.Save(result);
     }
     catch (Exception ex)
     {
         _log.Error("Failed to record result.", ex);
     }
 }
Ejemplo n.º 19
0
        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);
        }
Ejemplo n.º 20
0
        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));
        }
Ejemplo n.º 21
0
        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}";
            }
        }
Ejemplo n.º 22
0
 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);
 }
Ejemplo n.º 23
0
 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);
 }
Ejemplo n.º 24
0
        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"));
            }
        }
Ejemplo n.º 25
0
 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);
 }
Ejemplo n.º 26
0
        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);
        }
Ejemplo n.º 27
0
        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);
        }
Ejemplo n.º 28
0
 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);
 }
Ejemplo n.º 29
0
        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);
            }
        }
Ejemplo n.º 30
0
        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();
            }
        }
Ejemplo n.º 31
0
        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====================");
        }
Ejemplo n.º 32
0
    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;
    }
Ejemplo n.º 33
0
 private string compileMonitor(MonitorResult mon, string val)
 {
     return val.Replace("{%data%}", mon.Data).Replace("{%error%}", mon.Error).Replace("{%success%}", Convert.ToString(mon.Success));
 }
Ejemplo n.º 34
0
    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.");
            }
        }
    }
Ejemplo n.º 35
0
 // 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);
 }