예제 #1
0
파일: Monitor.cs 프로젝트: Julyuary/MiniML
        private void MonitorTick(object timer, EventArgs e)
        {
            if (state == MonitorState.WaitingForProcess)
            {
                Process targetProcess = Process.GetProcessesByName(targetName).FirstOrDefault();
                bool suspended = false;
                if (targetProcess == null)
                    return;
                if (targetProcess != null && suspendOnHook)
                {
                    targetProcess.Suspend();
                    suspended = true;
                }
                if (ProcessFound != null)
                    ProcessFound(this, new EventArgs());

                if (targetProcess != null && suspended)
                    targetProcess.Resume();
                state = MonitorState.WaitingForProcessClose;
            }
            if (state == MonitorState.WaitingForProcessClose)
            {
                Process targetProcess = Process.GetProcessesByName(targetName).FirstOrDefault();
                if (targetProcess == null && autoRestart)
                {
                    state = MonitorState.WaitingForProcess;
                    ProcessExited(this, new EventArgs());
                }
                else if (targetProcess == null)
                {
                    ProcessExited(this, new EventArgs());
                    Stop();
                }
            }
        }
예제 #2
0
파일: Monitor.cs 프로젝트: Julyuary/MiniML
 /// <summary>
 /// Initiates the monitoring process.
 /// </summary>
 /// <param name="processName">The name of the process that the monitor will look for.</param>
 /// <param name="suspendOnHook">Suspend the process when it's found. Suspension is released after ProcessFound is executed.</param>
 /// <param name="interval">The interval at which the monitor checks for the process.</param>
 /// <param name="autoRestart">If the monitor should automatically restart after reaching it's interval.</param>
 public void Start(string processName, bool suspendOnHook, int interval, bool autoRestart)
 {
     state = MonitorState.WaitingForProcess;
     targetName = processName;
     this.suspendOnHook = suspendOnHook;
     this.autoRestart = autoRestart;
     internalTimer.Interval = interval;
     internalTimer.Start();
 }
 public ChartWorkspaceViewModel()
 {
     _itemValuesDataSource = new ObservableDataSource<SingleItemValueViewModel>();
     DateTime now = DateTime.Now;
     DateFrom = new DateTime(now.Year, now.Month, now.Day, 0,0,0);
     DateTo = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
     MonitorRequestDelay = 1000;
     _monitorState = MonitorState.passive;
 }
예제 #4
0
        private static MonitorState Execute(JsonData[] jsons, MonitorState state)
        {

            foreach (var json in jsons.OrEmpty())
            {
                switch (json.JPath("data", "command")?.ToString())
                {

                }
            }
            return state;
        }
예제 #5
0
 public void doLoadFaceImages(MonitorState.Show newDisplayState)
 {
     print ("popo kakak " + _MonitorStates._Display + " "+ newDisplayState);
     if (newDisplayState == MonitorState.Show.StartLoading){
         StartCoroutine("ReadTextureFromFile",MaximumFaceImages);
         _MonitorStates._Display = MonitorState.Show.Loading;
     }
     if (newDisplayState == MonitorState.Show.FaceAnimation){
         PlayAnimation = true;
         //AnimateFaceFrame();
     }
     if (newDisplayState == MonitorState.Show.Stillframe){
         FaceFramesArray = null;
     }
 }
예제 #6
0
        public void ChangeStateIfPossible(MonitorState targetState)
        {
            if (!IsValidTime())
            {
                // 더 이상 현물 주문이 나갈 수 없는 상태이다.
                return;
            }

            IMonitor_Door next = _monitorDoor.ChangeStateIfPossible(targetState);
            if (next != null)
            {
                logger.Info("Change state {0} -> {1}", _monitorDoor.GetStateString(),
                    next.GetStateString());
                _monitorDoor = next;
            }
        }
예제 #7
0
 public WmpMonitor()
 {
     state = MonitorState.Starting;
     try {
         try {
             player = new RemotedWindowsMediaPlayer();
             player.CreateControl();
             wmp = player.GetOcx() as WindowsMediaPlayer;
             state = MonitorState.Started;
         }
         catch (Exception e) {
             errorMessage = "Error contacting player: " + e.Message;
             state = MonitorState.Error;
             return;
         }
     }
     catch (Exception e) {
         errorMessage = "Error starting monitor: " + e.Message;
         state = MonitorState.Error;
         //throw e;
     }
 }
        /// <summary>
        /// initialisiert Hauptobjekt
        /// </summary>
        public MainControl()
        {
            // Einstellungen initialisieren
            Settings.Initialize();

            // Assembly ermitteln
            Assembly assembly = Assembly.GetAssembly(this.GetType());

            // Protokoll initialisieren
            Logger.Initialize(Tools.GetFileName(assembly), Settings.Instance.LogEnabled,
                              Settings.Instance.LogLevel);

            // Programmversion protokollieren
            Logger.Log.Info("[Info] -> " + Tools.GetFileName(assembly) + " " +
                            Tools.GetFileVersion(assembly));

            // Einstellungen protokollieren
            Logger.Log.Info("[Info] -> MonitorCode: " + Settings.Instance.MonitorCode +
                            ", RefreshInterval: " + Settings.Instance.RefreshInterval +
                            ", ChartHistoryLength: " + Settings.Instance.ChartHistoryLength +
                            ", DeviceCode: " + Settings.Instance.DeviceCode +
                            ", DeviceType: " + Settings.Instance.DeviceType +
                            ", CoachingLevel: " + Settings.Instance.CoachingLevel +
                            ", CoachingPermissionLevel: " + Settings.Instance.CoachingPermissionLevel +
                            ", ScreenMonitoringAllowed: " + Settings.Instance.ScreenMonitoringAllowed +
                            ", AutoStopCoaching: " + Settings.Instance.AutoStopCoaching +
                            ", LogEnabled: " + Settings.Instance.LogEnabled +
                            ", LogLevel: " + Settings.Instance.LogLevel);

            // Monitorparameter initialisieren
            _monitorState     = MonitorState.Disconnected;
            _lastMonitorState = MonitorState.Disconnected;

            // Objektverwaltung initialisieren
            _frontendControl   = new FrontendControl(this);
            _campaignControl   = new CampaignControl(this);
            _conferenceControl = new ConferenceControl(this);
            _siteControl       = new SiteControl(this);
            _deviceControl     = new DeviceControl(this);

            // Schnittstelle zum Dialer initialisieren
            _monitor = new Monitor();
            _monitor.OnAddFrontend += new Monitor.OnAddFrontendEventHandler(
                _monitor_OnAddFrontend);
            _monitor.OnRefreshFrontend += new Monitor.OnRefreshFrontendEventHandler(
                _monitor_OnRefreshFrontend);
            _monitor.OnRemoveFrontend += new Monitor.OnRemoveFrontendEventHandler(
                _monitor_OnRemoveFrontend);
            _monitor.OnAddCampaign += new Monitor.OnAddCampaignEventHandler(
                _monitor_OnAddCampaign);
            _monitor.OnRefreshCampaign += new Monitor.OnRefreshCampaignEventHandler(
                _monitor_OnRefreshCampaign);
            _monitor.OnRemoveCampaign += new Monitor.OnRemoveCampaignEventHandler(
                _monitor_OnRemoveCampaign);
            _monitor.OnAddConference += new Monitor.OnAddConferenceEventHandler(
                _monitor_OnAddConference);
            _monitor.OnRefreshConference += new Monitor.OnRefreshConferenceEventHandler(
                _monitor_OnRefreshConference);
            _monitor.OnRemoveConference += new Monitor.OnRemoveConferenceEventHandler(
                _monitor_OnRemoveConference);
            _monitor.OnDeviceConnected += new Monitor.OnDeviceConnectedEventHandler(
                _monitor_OnDeviceConnected);
            _monitor.OnDeviceDisconnected += new Monitor.OnDeviceDisconnectedEventHandler(
                _monitor_OnDeviceDisconnected);
            _monitor.OnAgentLost += new Monitor.OnAgentLostEventHandler(
                _monitor_OnAgentLost);
            _monitor.OnConnectionLost += new Monitor.OnConnectionLostEventHandler(
                _monitor_OnConnectionLost);

            // Verbindung zum Dialer herstellen
            MonitorConnect();
            MonitorLogonDialer(Settings.Instance.MonitorCode, Settings.Instance.RefreshInterval);
        }
예제 #9
0
파일: Monitor.cs 프로젝트: Julyuary/MiniML
 /// <summary>
 /// Stops the monitor from running.
 /// </summary>
 public void Stop()
 {
     internalTimer.Stop();
     state = MonitorState.Finished;
 }
예제 #10
0
 private static void SetMonitorState(MonitorState state)
 => SendMessage(GetConsoleWindow(), WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)state);
예제 #11
0
        public override MonitorState RefreshState()
        {
            MonitorState returnState = new MonitorState();
            string       lastAction  = "";
            int          errors      = 0;
            int          warnings    = 0;
            int          success     = 0;
            double       totalValue  = 0;

            try
            {
                SqlDatabaseSizeCollectorConfig currentConfig = (SqlDatabaseSizeCollectorConfig)AgentConfig;

                returnState.RawDetails   = string.Format("Running {0} queries", currentConfig.Entries.Count);
                returnState.HtmlDetails  = string.Format("<b>Running {0} queries</b>", currentConfig.Entries.Count);
                returnState.CurrentValue = 0;
                foreach (SqlDatabaseSizeCollectorEntry entry in currentConfig.Entries)
                {
                    long           size         = entry.GetDBSize();
                    CollectorState currentState = entry.GetState(size);
                    totalValue += size;

                    if (currentState == CollectorState.Error)
                    {
                        errors++;
                        returnState.ChildStates.Add(
                            new MonitorState()
                        {
                            State        = CollectorState.Error,
                            ForAgent     = entry.Database,
                            CurrentValue = string.Format("{0} MB", size),
                            RawDetails   = string.Format("(Trigger '{0} MB')", entry.ErrorSizeMB)
                        });
                    }
                    else if (currentState == CollectorState.Warning)
                    {
                        warnings++;
                        returnState.ChildStates.Add(
                            new MonitorState()
                        {
                            State        = CollectorState.Warning,
                            ForAgent     = entry.Database,
                            CurrentValue = string.Format("{0} MB", size),
                            RawDetails   = string.Format("(Trigger '{0} MB')", entry.WarningSizeMB)
                        });
                    }
                    else
                    {
                        success++;
                        returnState.ChildStates.Add(
                            new MonitorState()
                        {
                            State        = CollectorState.Good,
                            ForAgent     = entry.Database,
                            CurrentValue = string.Format("{0} MB", size)
                        });
                    }
                }
                returnState.CurrentValue = totalValue;

                if (errors > 0 && warnings == 0 && success == 0) // any errors
                {
                    returnState.State = CollectorState.Error;
                }
                else if (errors > 0 || warnings > 0) //any warnings
                {
                    returnState.State = CollectorState.Warning;
                }
                else
                {
                    returnState.State = CollectorState.Good;
                }
            }
            catch (Exception ex)
            {
                returnState.RawDetails  = ex.Message;
                returnState.HtmlDetails = string.Format("<p><b>Last action:</b> {0}</p><blockquote>{1}</blockquote>", lastAction, ex.Message);
                returnState.State       = CollectorState.Error;
            }
            return(returnState);
        }
예제 #12
0
        /// <summary>Throws an exception if a deadlock would be caused by the current thread waiting on the specified lock.</summary>
        /// <param name="targetMs">The target lock data.</param>
        private static void ThrowIfDeadlockDetected(MonitorState targetMs)
        {
            // If no thread is holding the target lock, then this won't deadlock...
            if (targetMs.OwningThread == null) return;

            // For the deadlock detection algorithm, we need to know what locks are
            // currently held by which threads as well as which threads are waiting on
            // which locks. We already have this information, but we need it in a tabular
            // form for easier use and better perf.
            Dictionary<Thread, List<MonitorState>> locksHeldByThreads;
            Dictionary<MonitorState, List<Thread>> threadsWaitingOnLocks;
            CreateThreadAndLockTables(out locksHeldByThreads, out threadsWaitingOnLocks);

            // As we iterate over the wait graph, we'll need to store the list of threads still left to examine
            Queue<CycleComponentNode> threadsToFollow = new Queue<CycleComponentNode>(locksHeldByThreads.Count);

            // But rather than just storing the thread, we also store the threads in the cycle that got us to this thread.
            // The top of the stack is the actual thread to be examined.
            threadsToFollow.Enqueue(new CycleComponentNode(Thread.CurrentThread, targetMs, null));

            while (threadsToFollow.Count > 0)
            {
                // Get the next thread to examine
                CycleComponentNode currentChain = threadsToFollow.Dequeue();
                Thread currentThread = currentChain.Thread;

                // If this thread doesn't hold any locks, no point in examining it
                List<MonitorState> locksHeldByThread;
                if (!locksHeldByThreads.TryGetValue(currentThread, out locksHeldByThread)) continue;

                // For each lock it does hold, add to the thread examination list all threads
                // waiting on it.  And for each, see if it completes a cycle that results in
                // a deadlock.
                foreach (MonitorState ms in locksHeldByThread)
                {
                    List<Thread> nextThreads;
                    if (!threadsWaitingOnLocks.TryGetValue(ms, out nextThreads)) continue;
                    foreach (Thread nextThread in nextThreads)
                    {
                        // If any thread waiting on this lock is in the current stack,
                        // it's completng a cycle... deadlock!
                        if (currentChain.ContainsThread(nextThread)) throw new SynchronizationLockException(
                            CreateDeadlockDescription(targetMs, currentChain, locksHeldByThreads));

                        // Clone the stack of threads in the possible cycle and add this to the top,
                        // then queue the stack for examination.
                        threadsToFollow.Enqueue(new CycleComponentNode(nextThread, ms, currentChain));
                    }
                }
            }
        }
예제 #13
0
        public override MonitorState GetCurrentState()
        {
            MonitorState currentState = new MonitorState()
            {
                ForAgent     = Description,
                State        = CollectorState.None,
                CurrentValue = ""
            };

            Renci.SshNet.SshClient sshClient = SSHConnection.GetConnection();

            #region Get Disk infos and states
            List <DiskIOInfoState> diskEntries = new List <DiskIOInfoState>();
            //First see if ANY subentry is for all
            bool addAll = (from NIXDiskIOSubEntry d in SubItems
                           where d.DiskName == "*"
                           select d).Count() > 0;

            if (addAll)
            {
                NIXDiskIOSubEntry alertDef = (from NIXDiskIOSubEntry d in SubItems
                                              where d.DiskName == "*"
                                              select d).FirstOrDefault();
                alertDef.PrimaryUIValue = false;
                foreach (DiskIOInfo di in DiskIOInfo.GetCurrentDiskStats(sshClient, 250))
                {
                    DiskIOInfoState dis = new DiskIOInfoState()
                    {
                        DiskInfo = di, State = CollectorState.NotAvailable, AlertDefinition = alertDef
                    };
                    diskEntries.Add(dis);
                }
            }
            else
            {
                foreach (DiskIOInfo di in DiskIOInfo.GetCurrentDiskStats(sshClient, 250))
                {
                    NIXDiskIOSubEntry alertDef = (from NIXDiskIOSubEntry d in SubItems
                                                  where d.DiskName.ToLower() == di.Name.ToLower()
                                                  select d).FirstOrDefault();

                    if (alertDef != null)
                    {
                        if (!diskEntries.Any(f => f.DiskInfo.Name.ToLower() == di.Name.ToLower()))
                        {
                            DiskIOInfoState dis = new DiskIOInfoState()
                            {
                                DiskInfo = di, State = CollectorState.NotAvailable, AlertDefinition = alertDef
                            };
                            diskEntries.Add(dis);
                        }
                    }
                }
            }
            #endregion

            SSHConnection.CloseConnection();

            int    errors   = 0;
            int    warnings = 0;
            int    success  = 0;
            double average  = 0;
            foreach (DiskIOInfoState dis in diskEntries)
            {
                average += dis.DiskInfo.BytesReadWritePerSec;
                if (dis.DiskInfo.BytesReadWritePerSec >= (dis.AlertDefinition.ErrorValueKB * 1024))
                {
                    dis.State = CollectorState.Error;
                    errors++;
                }
                else if (dis.DiskInfo.BytesReadWritePerSec >= (dis.AlertDefinition.WarningValueKB * 1024))
                {
                    dis.State = CollectorState.Warning;
                    warnings++;
                }
                else
                {
                    dis.State = CollectorState.Good;
                    success++;
                }
                string formatValue = FormatUtils.FormatFileSizePerSec(dis.DiskInfo.BytesReadWritePerSec);
                if (dis.AlertDefinition.PrimaryUIValue)
                {
                    currentState.CurrentValue     = formatValue.Split(' ')[0];
                    currentState.CurrentValueUnit = formatValue.Split(' ')[1];
                }

                MonitorState diskIOState = new MonitorState()
                {
                    ForAgent         = dis.DiskInfo.Name,
                    State            = dis.State,
                    CurrentValue     = formatValue.Split(' ')[0],
                    CurrentValueUnit = formatValue.Split(' ')[1],
                    PrimaryUIValue   = dis.AlertDefinition.PrimaryUIValue
                };
                currentState.ChildStates.Add(diskIOState);
            }
            if (errors > 0 && warnings == 0 && success == 0) // any errors
            {
                currentState.State = CollectorState.Error;
            }
            else if (errors > 0 || warnings > 0) //any warnings
            {
                currentState.State = CollectorState.Warning;
            }
            else
            {
                currentState.State = CollectorState.Good;
            }

            if (currentState.CurrentValue.ToString() == "" && currentState.ChildStates.Count > 0)
            {
                string formatValue = FormatUtils.FormatFileSizePerSec((long)((average / currentState.ChildStates.Count)));
                currentState.CurrentValue     = formatValue.Split(' ')[0];
                currentState.CurrentValueUnit = formatValue.Split(' ')[1];
            }

            return(currentState);
        }
예제 #14
0
    void Update()
    {
        if (FaceMultiSourceManager == null)
        {
            return;
        }

        _MultiManager = FaceMultiSourceManager.GetComponent<FaceMultiSourceManager>();
        if (_MultiManager == null)
        {
            return;
        }

        if (_Monitor == null)
        {
            return;
        }

        _MonitorState = _Monitor.GetComponent<MonitorState>();
        if (_MonitorState == null)
        {
            return;
        }

        // EXPERIMANTAL depth data imlementation

        //		ushort[] depthData = _MultiManager.GetDepthData();
        //		if (depthData == null)
        //		{
        //			return;
        //		}

        //

        //begin body
        Kinect.Body[] BodydataArray = _MultiManager.GetBodyData ();
        if (BodydataArray == null)
        {
            return;
        }

        List<ulong> trackedIds = new List<ulong>();
        foreach(var body in BodydataArray)
        {
            if (body == null)
            {
                continue;
            }

            if(body.IsTracked)
            {
                trackedIds.Add (body.TrackingId);// msaw edit the next lines
                //if (TrackedBody == 0){
                //	TrackedBody = body.TrackingId;
                    //Debug.LogError(body.TrackingId);
                //}
                //msaw end
            }
        }

        List<ulong> knownIds = new List<ulong>(_Bodies.Keys);

        // First delete untracked bodies
        foreach(ulong trackingId in knownIds)
        {
            if(!trackedIds.Contains(trackingId))// msaw edit the next lines
            //if(TrackedBody != trackingId)
                //msaw end
            {
                Destroy(_Bodies[trackingId]);
                _Bodies.Remove(trackingId);
            }
        }
        foreach(var body in BodydataArray)
        {
            if (body == null)
            {
                continue;
            }

            if(body.IsTracked)
            {
                if(!_Bodies.ContainsKey(body.TrackingId)) // msaw edit the next lines
                //if(!_Bodies.ContainsKey(TrackedBody))
                //msaw end
                {
                    _Bodies[body.TrackingId] = CreateBodyObject(body.TrackingId); //msaw edit the next lines
                    //_Bodies[TrackedBody] = CreateBodyObject(TrackedBody);
                    // msaw end
                    _MonitorState._Behavior = MonitorState.AI.Awake;
                    print ("got tracking so awakening....");
                }

                 RefreshBodyObject(body, _Bodies[body.TrackingId]); //msaw edit the next lines
                //RefreshBodyObject(body, _Bodies[TrackedBody]);
                //msaw end
                //SET FACE IS CAUSING AN ERROR SOMETIMES

                SetFace(body, _Bodies[body.TrackingId]); // msaw edit the next lines
                //SetFace(body, _Bodies[TrackedBody]);
                // msaw end
                SetMovingTarget(body);
                //break; // not shure if break helps to only get one body
            }
        }
        //end body

        // if we captured all faceframes play the animation
        //int lastIndex = FaceFramesArray.Length-1;
        //if (FaceFramesArray[lastIndex]!= null){
            //AnimateFaceFrame();
        //}
        doMonitorBehavior();
    }
예제 #15
0
        private void DoMonitorStateChanged(IMonitorSystemContext context, string name, MonitorState state)
        {
            CFuncNode node = mLinkObj as CFuncNode;

            if (node != null)
            {
                IMonitorConfig config = node.ExtConfigObj as IMonitorConfig;
                if (config != null)
                {
                    if (config.SystemContext == context && config.Name.Equals(name))
                    {
                        if (state != MonitorState.None)
                        {
                            IMonitor monitor = config.SystemContext.MonitorManager.GetMonitor(name);
                            if (monitor != null)
                            {
                                this.AlarmManager = monitor.AlarmManager;
                            }
                        }
                        else
                        {
                            this.AlarmManager = null;
                        }

                        if (OnMonitorStateChanged != null)
                        {
                            OnMonitorStateChanged(context, name, state);
                        }
                    }
                }
            }
        }
예제 #16
0
 public void SetPosition(int position)
 {
     if (this.state == MonitorState.Started) {
         try {
             wmp.controls.currentPosition = position;
             // for faster screen updates
             PlayingTrack.Position = position;
         }
         catch (COMException) {
             // application is busy... nothing we can do... just wait, when it will become available again
         }
         catch (Exception e) {
             this.Stop();
             errorMessage = "Error on SetPosition: " + e.Message;
             state = MonitorState.Interrupted;
         }
     }
 }
예제 #17
0
 public void Stop()
 {
     try {
         quit = true;
         wmp = null;
         player = null;
         state = MonitorState.NotStarted;
     }
     catch (COMException) {
         // application is busy... nothing we can do... just wait, when it will become available again
     }
     catch (Exception e) {
         errorMessage = "Error stopping monitor: " + e.Message;
         state = MonitorState.Error;
     }
 }
예제 #18
0
 public void PreviousTrack()
 {
     if (this.state == MonitorState.Started) {
         try {
             if (wmp.controls.currentPosition <= 1) {
                 wmp.controls.previous();
             }
             else {
                 ReplayTrack();
             }
         }
         catch (COMException) {
             // application is busy... nothing we can do... just wait, when it will become available again
         }
         catch (Exception e) {
             this.Stop();
             errorMessage = "Error on PreviousTrack: " + e.Message;
             state = MonitorState.Interrupted;
         }
     }
 }
예제 #19
0
        public MonitorState GetCurrentState()
        {
            RefreshRowCounts();
            MonitorState currentState = new MonitorState()
            {
                ForAgent = Description
            };
            List <Tuple <TableSizeEntry, CollectorState> > states = GetStates();
            long totalValue = 0;
            int  goods      = 0;
            int  warnings   = 0;
            int  errors     = 0;
            int  totalCount = 0;

            foreach (var tableEntryState in states)
            {
                if (tableEntryState.Item1.RowCount > 0)
                {
                    totalValue += tableEntryState.Item1.RowCount;
                }

                MonitorState tableState = new MonitorState()
                {
                    ForAgent         = tableEntryState.Item1.TableName,
                    State            = tableEntryState.Item2,
                    CurrentValue     = tableEntryState.Item1.RowCount,
                    CurrentValueUnit = "row(s)"
                };

                if (tableEntryState.Item2 == CollectorState.Error)
                {
                    tableState.RawDetails = tableEntryState.Item1.RowCount > 0 ? "(Trigger '" + tableEntryState.Item1.ErrorValue.ToString() + "')" : tableEntryState.Item1.ErrorStr;
                    errors++;
                }
                else if (tableEntryState.Item2 == CollectorState.Warning)
                {
                    tableState.RawDetails = string.Format("(Trigger '{0}')", tableEntryState.Item1.WarningValue);
                    warnings++;
                }
                else
                {
                    goods++;
                }
                totalCount++;
                currentState.ChildStates.Add(tableState);
            }
            currentState.CurrentValue     = totalValue;
            currentState.CurrentValueUnit = "row(s)";
            CurrentAgentValue             = totalValue;
            if (totalCount > 0)
            {
                if (errors == totalCount)
                {
                    currentState.State = CollectorState.Error;
                }
                else if (goods == totalCount)
                {
                    currentState.State = CollectorState.Good;
                }
                else
                {
                    currentState.State = CollectorState.Warning;
                }
            }

            return(currentState);
        }
예제 #20
0
 public static void SetMonitorState(MonitorState state)
 {
     SendMessage(0xFFFF, 0x112, 0xF170, (int)state);
 }
예제 #21
0
 /// <inheriteddoc />
 protected override void OnGetInfo(CultureInfo lang,
                                   ref MonitorState state, StringBuilder summary, StringBuilder desc, ref object value, ref DateTimeOffset lastUpdate)
 {
     _PROVIDER(this, lang,
               ref state, summary, desc, ref value, ref lastUpdate);
 }
 private void BroadcastMarketStateChange(MonitorState marketState)
 {
     switch (marketState)
     {
         case MonitorState.Running:
             Clients.All.StartedMonitoring();
             break;
         case MonitorState.Stopped:
             Clients.All.StopedMonitoring();
             break;
         default:
             break;
     }
 }
예제 #23
0
        /// <inheriteddoc />
        protected override void OnGetInfo(CultureInfo lang,
                                          ref MonitorState state, StringBuilder summary, StringBuilder desc, ref object value, ref DateTimeOffset lastUpdate)
        {
            lock (SyncRoot)
            {
                var now = _TIME_PROVIDER(this);

                var lastMonitorUpdate = _lastUpdate;
                var doUpdate = true;
                if (lastMonitorUpdate.HasValue)
                {
                    doUpdate = false;

                    var interval = now - lastMonitorUpdate.Value;
                    if (interval >= _UPDATE_INTERVAL ||
                        _UPDATE_INTERVAL <= TimeSpan.Zero)
                    {
                        doUpdate = true;
                    }
                }

                IMonitorInfo info;
                if (doUpdate)
                {
                    _lastInfo = info = BaseMonitor.GetInfo(lang);
                    _lastUpdate = now;
                }
                else
                {
                    info = _lastInfo;
                }

                if (info == null)
                {
                    return;
                }

                state = info.State;
                summary.Append(info.Summary);
                desc.Append(info.Description);
                value = info.Value;
                lastUpdate = info.LastUpdate;
            }
        }
예제 #24
0
 public static void setMonitorState(MonitorState state)
 {
     //Form frm = new Form();
     SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)state);
     //SendMessage(frm.Handle, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)state);
 }
예제 #25
0
        public override MonitorState GetState()
        {
            MonitorState returnState = new MonitorState()
            {
                State = CollectorState.Good
            };
            StringBuilder plainTextDetails    = new StringBuilder();
            StringBuilder htmlTextTextDetails = new StringBuilder();
            string        lastAction          = "";
            int           errors     = 0;
            int           warnings   = 0;
            int           success    = 0;
            double        totalValue = 0;

            try
            {
                SqlTableSizeCollectorConfig sqlTableSizeConfig = (SqlTableSizeCollectorConfig)AgentConfig;
                plainTextDetails.AppendLine(string.Format("Database table size(s)"));
                htmlTextTextDetails.AppendLine(string.Format("Database table size(s)"));

                foreach (SqlTableSizeCollectorEntry sqlTableSizeEntry in sqlTableSizeConfig.Entries)
                {
                    lastAction = string.Format("Getting table sizes for '{0}\\{1}'", sqlTableSizeEntry.SqlServer, sqlTableSizeEntry.Database);

                    sqlTableSizeEntry.RefreshRowCounts();
                    List <Tuple <TableSizeEntry, CollectorState> > states = sqlTableSizeEntry.GetStates();
                    plainTextDetails.AppendLine(string.Format("\tDatabase {0}", sqlTableSizeEntry));
                    htmlTextTextDetails.AppendLine(string.Format("<b>Database {0}</b>", sqlTableSizeEntry));
                    htmlTextTextDetails.AppendLine("<ul>");
                    foreach (var tableEntryState in states)
                    {
                        if (tableEntryState.Item1.RowCount > 0)
                        {
                            totalValue += tableEntryState.Item1.RowCount;
                        }
                        if (tableEntryState.Item2 == CollectorState.Error)
                        {
                            errors++;
                            if (tableEntryState.Item1.RowCount > 0)
                            {
                                plainTextDetails.AppendLine(string.Format("\t\t{0} - value '{1}' - Error (trigger {2})", tableEntryState.Item1.TableName, tableEntryState.Item1.RowCount, tableEntryState.Item1.ErrorValue));
                                htmlTextTextDetails.AppendLine(string.Format("<li>{0} - Value '{1}' - <b>Error</b> (trigger {2})</li>", tableEntryState.Item1.TableName, tableEntryState.Item1.RowCount, tableEntryState.Item1.ErrorValue));
                            }
                            else
                            {
                                plainTextDetails.AppendLine(string.Format("\t\t{0} - value '{1}' - Error ({2})", tableEntryState.Item1.TableName, tableEntryState.Item1.RowCount, tableEntryState.Item1.ErrorStr));
                                htmlTextTextDetails.AppendLine(string.Format("<li>{0} - Value '{1}' - <b>Error</b> ({2})</li>", tableEntryState.Item1.TableName, tableEntryState.Item1.RowCount, tableEntryState.Item1.ErrorStr));
                            }
                        }
                        else if (tableEntryState.Item2 == CollectorState.Warning)
                        {
                            warnings++;
                            plainTextDetails.AppendLine(string.Format("\t\t{0} - value '{1}' - Warning (trigger {2})", tableEntryState.Item1.TableName, tableEntryState.Item1.RowCount, tableEntryState.Item1.WarningValue));
                            htmlTextTextDetails.AppendLine(string.Format("<li>{0} - Value '{1}' - <b>Warning</b> (trigger {2})</li>", tableEntryState.Item1.TableName, tableEntryState.Item1.RowCount, tableEntryState.Item1.WarningValue));
                        }
                        else
                        {
                            plainTextDetails.AppendLine(string.Format("\t\t{0} - value '{1}'", tableEntryState.Item1.TableName, tableEntryState.Item1.RowCount));
                            htmlTextTextDetails.AppendLine(string.Format("<li>{0} - Value '{1}'</li>", tableEntryState.Item1.TableName, tableEntryState.Item1.RowCount));
                            success++;
                        }
                    }
                    htmlTextTextDetails.AppendLine("</ul>");
                }

                if (errors > 0 && warnings == 0)
                {
                    returnState.State = CollectorState.Error;
                }
                else if (warnings > 0)
                {
                    returnState.State = CollectorState.Warning;
                }
                returnState.RawDetails   = plainTextDetails.ToString().TrimEnd('\r', '\n');
                returnState.HtmlDetails  = htmlTextTextDetails.ToString();
                returnState.CurrentValue = totalValue;
            }
            catch (Exception ex)
            {
                returnState.RawDetails  = string.Format("Last step: '{0}\r\n{1}", lastAction, ex.Message);
                returnState.HtmlDetails = string.Format("<blockquote>Last step: '{0}<br />{1}</blockquote>", lastAction, ex.Message);
                returnState.State       = CollectorState.Error;
            }
            return(returnState);
        }
예제 #26
0
 public virtual void OnMonitorState(string monitorTypeName, MonitorId monitorId, string stateName, bool isEntry, bool?isInHotState)
 {
     MonitorState?.Invoke(monitorTypeName, monitorId, stateName, isEntry, isInHotState);
 }
예제 #27
0
        /// <summary>Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object.</summary>
        /// <param name="monitor">The object on which to acquire the lock.</param>
        /// <param name="millisecondsTimeout">The number of milliseconds to wait for the lock.</param>
        /// <returns>true if the current thread acquires the lock without blocking; otherwise, false.</returns>
        public static bool TryEnter(object monitor, int millisecondsTimeout)
        {
            // Validate arguments
            if (monitor == null) throw new ArgumentNullException("monitor");
            if (millisecondsTimeout < 0 && millisecondsTimeout != Timeout.Infinite) throw new ArgumentOutOfRangeException("millisecondsTimeout");

            //If we're not syncing, don't do anything
            if (m_bNoSync)
                return true;

            //If we're not properly enabled, just do a simple entry
            if (!m_bEnabled)
            {	//If we managed to lock on the object, we need to
                //specify ourself as the owning thread.
                bool bLocked = Monitor.TryEnter(monitor, millisecondsTimeout);
                if (!m_bNoSyncCheck && bLocked)
                    lock (_monitorOwners)
                        _monitorOwners[monitor] = Thread.CurrentThread;
                return bLocked;
            }

            // Keep track of whether we actually acquired the monitor or not
            bool thisThreadOwnsMonitor = false;
            MonitorState ms = null;
            try
            {
                // Register the current thread as waiting on the monitor.
                // Take the global lock before manipulating shared state.  Note that by our lock order,
                // we can take _globalLock while holding an individual monitor, but we *can't* take a
                // monitor while holding _globalLock; otherwise, we'd risk deadlock.
                lock (_globalLock)
                {
                    // Get the internal data for this monitor.  If not data exists, create it.
                    if (!_monitorStates.TryGetValue(monitor, out ms))
                    {
                        _monitorStates[monitor] = ms = new MonitorState(monitor);
                    }

                    // If we already hold this lock, then there's no chance of deadlock by waiting on it,
                    // since monitors are reentrant.  If we don't hold the lock, register our intent to
                    // wait on it and check for deadlock.
                    if (ms.OwningThread != Thread.CurrentThread)
                    {
                        ms.WaitingThreads.Add(Thread.CurrentThread);

                        //Put a little stack trace in too
                        System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(true);
                        System.Diagnostics.StackFrame[] frames = st.GetFrames();
                        string mytrace = string.Format("{0:X}:{1}\r\n", ms.MonitorObject.GetHashCode(), Thread.CurrentThread.ManagedThreadId);

                        foreach (System.Diagnostics.StackFrame sf in frames)
                        {	//Write the frame details
                            mytrace += "\tat " + sf.GetMethod() + " in " + sf.GetFileName() + " : " + sf.GetFileLineNumber();
                            mytrace += "\r\n";
                        }

                        ms.traces[Thread.CurrentThread] = mytrace;

                        ThrowIfDeadlockDetected(ms);
                    }
                }

                // Try to enter the monitor
                thisThreadOwnsMonitor = Monitor.TryEnter(monitor, millisecondsTimeout);

                // At this point we now may own the monitor...
                if (!m_bNoSyncCheck && thisThreadOwnsMonitor)
                    lock (_globalLock)
                        _monitorOwners[monitor] = Thread.CurrentThread;
            }
            finally
            {
                lock (_globalLock)
                {
                    if (ms != null) // This would only be null if an exception occurred at a really weird place
                    {
                        // We're no longer waiting on the monitor, either because something went wrong
                        // in the wait or because we now own the monitor
                        ms.WaitingThreads.Remove(Thread.CurrentThread);

                        // If we did get the monitor, then note that we now own it
                        if (thisThreadOwnsMonitor)
                        {
                            if (ms.OwningThread != Thread.CurrentThread)
                            {
                                ms.OwningThread = Thread.CurrentThread;
                            }
                            else ms.ReentranceCount++;
                        }
                    }
                }
            }

            // Return whether we obtained the monitor or not
            return thisThreadOwnsMonitor;
        }
예제 #28
0
        /// <summary>Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object.</summary>
        /// <param name="monitor">The object on which to acquire the lock.</param>
        /// <param name="millisecondsTimeout">The number of milliseconds to wait for the lock.</param>
        /// <returns>true if the current thread acquires the lock without blocking; otherwise, false.</returns>
        public static bool TryEnter(object monitor, int millisecondsTimeout)
        {               // Validate arguments
            if (monitor == null)
            {
                throw new ArgumentNullException("monitor");
            }
            if (millisecondsTimeout < 0 && millisecondsTimeout != Timeout.Infinite)
            {
                throw new ArgumentOutOfRangeException("millisecondsTimeout");
            }

            //If we're not syncing, don't do anything
            if (m_bNoSync)
            {
                return(true);
            }

            //If we're not properly enabled, just do a simple entry
            if (!m_bEnabled)
            {                   //If we managed to lock on the object, we need to
                                //specify ourself as the owning thread.
                bool bLocked = Monitor.TryEnter(monitor, millisecondsTimeout);
                if (!m_bNoSyncCheck && bLocked)
                {
                    lock (_monitorOwners)
                        _monitorOwners[monitor] = Thread.CurrentThread;
                }
                return(bLocked);
            }

            // Keep track of whether we actually acquired the monitor or not
            bool         thisThreadOwnsMonitor = false;
            MonitorState ms = null;

            try
            {
                // Register the current thread as waiting on the monitor.
                // Take the global lock before manipulating shared state.  Note that by our lock order,
                // we can take _globalLock while holding an individual monitor, but we *can't* take a
                // monitor while holding _globalLock; otherwise, we'd risk deadlock.
                lock (_globalLock)
                {
                    // Get the internal data for this monitor.  If not data exists, create it.
                    if (!_monitorStates.TryGetValue(monitor, out ms))
                    {
                        _monitorStates[monitor] = ms = new MonitorState(monitor);
                    }

                    // If we already hold this lock, then there's no chance of deadlock by waiting on it,
                    // since monitors are reentrant.  If we don't hold the lock, register our intent to
                    // wait on it and check for deadlock.
                    if (ms.OwningThread != Thread.CurrentThread)
                    {
                        ms.WaitingThreads.Add(Thread.CurrentThread);

                        //Put a little stack trace in too
                        System.Diagnostics.StackTrace   st     = new System.Diagnostics.StackTrace(true);
                        System.Diagnostics.StackFrame[] frames = st.GetFrames();
                        string mytrace = string.Format("{0:X}:{1}\r\n", ms.MonitorObject.GetHashCode(), Thread.CurrentThread.ManagedThreadId);

                        foreach (System.Diagnostics.StackFrame sf in frames)
                        {                               //Write the frame details
                            mytrace += "\tat " + sf.GetMethod() + " in " + sf.GetFileName() + " : " + sf.GetFileLineNumber();
                            mytrace += "\r\n";
                        }

                        ms.traces[Thread.CurrentThread] = mytrace;

                        ThrowIfDeadlockDetected(ms);
                    }
                }

                // Try to enter the monitor
                thisThreadOwnsMonitor = Monitor.TryEnter(monitor, millisecondsTimeout);

                // At this point we now may own the monitor...
                if (!m_bNoSyncCheck && thisThreadOwnsMonitor)
                {
                    lock (_globalLock)
                        _monitorOwners[monitor] = Thread.CurrentThread;
                }
            }
            finally
            {
                lock (_globalLock)
                {
                    if (ms != null)                     // This would only be null if an exception occurred at a really weird place
                    {
                        // We're no longer waiting on the monitor, either because something went wrong
                        // in the wait or because we now own the monitor
                        ms.WaitingThreads.Remove(Thread.CurrentThread);

                        // If we did get the monitor, then note that we now own it
                        if (thisThreadOwnsMonitor)
                        {
                            if (ms.OwningThread != Thread.CurrentThread)
                            {
                                ms.OwningThread = Thread.CurrentThread;
                            }
                            else
                            {
                                ms.ReentranceCount++;
                            }
                        }
                    }
                }
            }

            // Return whether we obtained the monitor or not
            return(thisThreadOwnsMonitor);
        }
예제 #29
0
        /// <summary>
        /// Benchmark for client.
        /// </summary>
        /// <param name="state">The command [On|Off|Reset]</param>
        private static void MonitoringControl(MonitorState state)
        {
            switch (state)
            {
                case MonitorState.MonitorOn:
                    if (session != null && session.State == SMSessionState.Opened)
                    {
                        if (protocolMonitor != null)
                        {
                            protocolMonitor.Dispose();
                        }

                        protocolMonitor = new ProtocolMonitor(session);
                        protocolMonitor.Attach();
                    }
                    else
                    {
                        SMLogger.LogError("Session was closed due to error or not opened. Use CONNECT <Uri> to open a new session.");
                    }

                    break;

                case MonitorState.MonitorOff:
                    if (protocolMonitor != null)
                    {
                        protocolMonitor.Dispose();
                        protocolMonitor = null;
                    }

                    break;

                case MonitorState.MonitorReset:
                    if (protocolMonitor != null)
                    {
                        protocolMonitor.Reset();
                    }

                    break;

                default:
                    SMLogger.LogError("CAPTURE-STATS needs [On|Off|Reset].");
                    break;
            }
        }
예제 #30
0
        /// <summary>Throws an exception if a deadlock would be caused by the current thread waiting on the specified lock.</summary>
        /// <param name="targetMs">The target lock data.</param>
        private static void ThrowIfDeadlockDetected(MonitorState targetMs)
        {
            // If no thread is holding the target lock, then this won't deadlock...
            if (targetMs.OwningThread == null)
            {
                return;
            }

            // For the deadlock detection algorithm, we need to know what locks are
            // currently held by which threads as well as which threads are waiting on
            // which locks. We already have this information, but we need it in a tabular
            // form for easier use and better perf.
            Dictionary <Thread, List <MonitorState> > locksHeldByThreads;
            Dictionary <MonitorState, List <Thread> > threadsWaitingOnLocks;

            CreateThreadAndLockTables(out locksHeldByThreads, out threadsWaitingOnLocks);

            // As we iterate over the wait graph, we'll need to store the list of threads still left to examine
            Queue <CycleComponentNode> threadsToFollow = new Queue <CycleComponentNode>(locksHeldByThreads.Count);

            // But rather than just storing the thread, we also store the threads in the cycle that got us to this thread.
            // The top of the stack is the actual thread to be examined.
            threadsToFollow.Enqueue(new CycleComponentNode(Thread.CurrentThread, targetMs, null));

            while (threadsToFollow.Count > 0)
            {
                // Get the next thread to examine
                CycleComponentNode currentChain  = threadsToFollow.Dequeue();
                Thread             currentThread = currentChain.Thread;

                // If this thread doesn't hold any locks, no point in examining it
                List <MonitorState> locksHeldByThread;
                if (!locksHeldByThreads.TryGetValue(currentThread, out locksHeldByThread))
                {
                    continue;
                }

                // For each lock it does hold, add to the thread examination list all threads
                // waiting on it.  And for each, see if it completes a cycle that results in
                // a deadlock.
                foreach (MonitorState ms in locksHeldByThread)
                {
                    List <Thread> nextThreads;
                    if (!threadsWaitingOnLocks.TryGetValue(ms, out nextThreads))
                    {
                        continue;
                    }
                    foreach (Thread nextThread in nextThreads)
                    {
                        // If any thread waiting on this lock is in the current stack,
                        // it's completng a cycle... deadlock!
                        if (currentChain.ContainsThread(nextThread))
                        {
                            throw new SynchronizationLockException(
                                      CreateDeadlockDescription(targetMs, currentChain, locksHeldByThreads));
                        }

                        // Clone the stack of threads in the possible cycle and add this to the top,
                        // then queue the stack for examination.
                        threadsToFollow.Enqueue(new CycleComponentNode(nextThread, ms, currentChain));
                    }
                }
            }
        }
예제 #31
0
        void UpdateVigilance()
        {
            switch (VigilanceMonitorState)
            {
            case MonitorState.Disabled:
                if (VigilanceSystemEnabled)
                {
                    VigilanceMonitorState = MonitorState.StandBy;
                }
                break;

            case MonitorState.StandBy:
                if (!VigilanceSystemEnabled)
                {
                    VigilanceAlarmTimer.Stop();
                    VigilanceMonitorState = MonitorState.Disabled;
                }
                else
                {
                    if (!VigilanceAlarmTimer.Started)
                    {
                        VigilanceAlarmTimer.Start();
                    }

                    if (VigilanceAlarmTimer.Triggered)
                    {
                        VigilanceAlarmTimer.Stop();
                        VigilanceMonitorState = MonitorState.Alarm;
                    }
                }
                break;

            case MonitorState.Alarm:
                if (!VigilanceSystemEnabled)
                {
                    VigilanceEmergencyTimer.Stop();
                    VigilanceMonitorState = MonitorState.Disabled;
                }
                else
                {
                    if (!VigilanceEmergencyTimer.Started)
                    {
                        VigilanceEmergencyTimer.Start();
                    }

                    if (VigilanceEmergencyTimer.Triggered)
                    {
                        VigilanceEmergencyTimer.Stop();
                        VigilanceMonitorState = MonitorState.Emergency;
                    }
                }
                break;

            case MonitorState.Emergency:
                if (!VigilancePenaltyTimer.Started)
                {
                    VigilancePenaltyTimer.Start();
                }

                if (VigilancePenaltyTimer.Triggered && VigilanceReset)
                {
                    VigilanceEmergencyTimer.Stop();
                    VigilanceMonitorState = (VigilanceSystemEnabled ? MonitorState.StandBy : MonitorState.Disabled);
                }
                break;
            }

            if (VigilanceMonitorState >= MonitorState.Alarm)
            {
                if (!AlerterSound())
                {
                    SetVigilanceAlarm(true);
                }
            }
            else
            {
                if (AlerterSound())
                {
                    SetVigilanceAlarm(false);
                }
            }

            SetVigilanceAlarmDisplay(VigilanceMonitorState == MonitorState.Alarm);
            SetVigilanceEmergencyDisplay(VigilanceMonitorState == MonitorState.Emergency);
        }
예제 #32
0
 public CycleComponentNode(Thread thread, MonitorState ms, CycleComponentNode next)
 {
     Thread       = thread;
     MonitorState = ms;
     Next         = next;
 }
예제 #33
0
 private void SetMonitorInState(MonitorState state)
 {
     SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (int)state);
 }
예제 #34
0
        public MonitorState GetCurrentState()
        {
            DirectoryFileInfo directoryFileInfo = GetFileListByFilters();
            string            fullFilePath      = Environment.ExpandEnvironmentVariables(DirectoryPath);
            MonitorState      currentState      = new MonitorState()
            {
                ForAgent = fullFilePath,
                State    = GetState(directoryFileInfo)
            };

            if (!fullFilePath.EndsWith("\\"))
            {
                fullFilePath += "\\";
            }

            if (DirectoryExistOnly && currentState.State != CollectorState.Good)
            {
                currentState.CurrentValue = stateDescription;
            }
            else if (DirectoryExistOnly)
            {
                currentState.CurrentValue = stateDescription;
            }
            else
            {
                currentState.RawDetails = stateDescription;
                if (directoryFileInfo.FileCount == -1)
                {
                    currentState.CurrentValue = stateDescription;
                }
                else
                {
                    if (directoryFileInfo.FileCount > 0)
                    {
                        if (ShowFileCountInOutputValue && ShowFileSizeInOutputValue)
                        {
                            currentState.CurrentValue = string.Format("{0} file(s), {1}", directoryFileInfo.FileCount, FormatUtils.FormatFileSize(directoryFileInfo.TotalFileSize));
                        }
                        else if (ShowFileCountInOutputValue)
                        {
                            currentState.CurrentValue     = directoryFileInfo.FileInfos.Count;
                            currentState.CurrentValueUnit = "file(s)";
                        }
                        else if (ShowFileSizeInOutputValue)
                        {
                            currentState.CurrentValue = FormatUtils.FormatFileSize(directoryFileInfo.TotalFileSize);
                        }
                        else
                        {
                            currentState.CurrentValue = stateDescription;
                        }

                        if (ShowFilenamesInDetails)
                        {
                            int topCount = TopFileNameCountInDetails;
                            if (topCount <= 0)
                            {
                                topCount = directoryFileInfo.FileInfos.Count;
                            }
                            for (int i = 0; i < TopFileNameCountInDetails && i < directoryFileInfo.FileInfos.Count; i++)
                            {
                                FileInfo fi = directoryFileInfo.FileInfos[i];
                                currentState.ChildStates.Add(
                                    new MonitorState()
                                {
                                    ForAgent = fi.FullName.ReplaceCaseInsensitive(fullFilePath, ""),
                                    //ForAgent = fi.Name,
                                    ForAgentType = "FileInfo",
                                    CurrentValue = string.Format("{0},{1}", FormatUtils.FormatFileSize(fi.Length), fi.LastWriteTime.ToString("yyyy-MM-dd HH:mm"))
                                });
                            }
                        }
                    }
                    else
                    {
                        currentState.CurrentValue     = "No";
                        currentState.CurrentValueUnit = "file(s)";
                    }
                }
            }
            CurrentAgentValue = currentState.CurrentValue;
            return(currentState);
        }
 /// <summary>
 /// aktualisiert Monitorstatus
 /// </summary>
 private void RefreshMonitorState()
 {
     _lastMonitorState = _monitorState;
     _monitorState     = _monitor.State;
 }
예제 #36
0
        public override MonitorState GetCurrentState()
        {
            MonitorState currentState = new MonitorState()
            {
                ForAgent     = Description,
                State        = CollectorState.None,
                CurrentValue = ""
            };

            Renci.SshNet.SshClient sshClient = SSHConnection.GetConnection();

            #region Get NIC infos and states
            List <NICInfoState> nicEntries = new List <NICInfoState>();
            //First see if ANY subentry is for all
            bool addAll = (from NIXNICSubEntry d in SubItems
                           where d.NICName == "*"
                           select d).Count() > 0;

            if (addAll)
            {
                NIXNICSubEntry alertDef = (from NIXNICSubEntry d in SubItems
                                           where d.NICName == "*"
                                           select d).FirstOrDefault();
                alertDef.PrimaryUIValue = false;
                foreach (NicInfo di in NicInfo.GetCurrentNicStats(sshClient, MeasuringDelayMS))
                {
                    NICInfoState dis = new NICInfoState()
                    {
                        NICInfo = di, State = CollectorState.NotAvailable, AlertDefinition = alertDef
                    };
                    nicEntries.Add(dis);
                }
            }
            else
            {
                foreach (NicInfo di in NicInfo.GetCurrentNicStats(sshClient, MeasuringDelayMS))
                {
                    NIXNICSubEntry alertDef = (from NIXNICSubEntry d in SubItems
                                               where d.NICName.ToLower() == di.Name.ToLower()
                                               select d).FirstOrDefault();

                    if (alertDef != null)
                    {
                        if (!nicEntries.Any(f => f.NICInfo.Name.ToLower() == di.Name.ToLower()))
                        {
                            NICInfoState dis = new NICInfoState()
                            {
                                NICInfo = di, State = CollectorState.NotAvailable, AlertDefinition = alertDef
                            };
                            nicEntries.Add(dis);
                        }
                    }
                }
            }
            #endregion

            SSHConnection.CloseConnection();

            int    errors   = 0;
            int    warnings = 0;
            int    success  = 0;
            double average  = 0;
            foreach (NICInfoState dis in nicEntries)
            {
                average += dis.NICInfo.RTxBytesPerSec;
                if (dis.NICInfo.RTxBytesPerSec >= dis.AlertDefinition.ErrorValueKB * 1024)
                {
                    dis.State = CollectorState.Error;
                    errors++;
                }
                else if (dis.NICInfo.RTxBytesPerSec >= dis.AlertDefinition.WarningValueKB * 1024)
                {
                    dis.State = CollectorState.Warning;
                    warnings++;
                }
                else
                {
                    dis.State = CollectorState.Good;
                    success++;
                }
                string formatValue = FormatUtils.FormatFileSizePerSec(dis.NICInfo.RTxBytesPerSec);
                if (dis.AlertDefinition.PrimaryUIValue)
                {
                    currentState.CurrentValue     = formatValue.Split(' ')[0]; // (dis.NICInfo.RTxBytesPerSec/1024).ToString("0.00");
                    currentState.CurrentValueUnit = formatValue.Split(' ')[1]; //"kB/s";
                }

                MonitorState diskIOState = new MonitorState()
                {
                    ForAgent         = dis.NICInfo.Name,
                    State            = dis.State,
                    CurrentValue     = formatValue.Split(' ')[0], // (dis.NICInfo.RTxBytesPerSec / 1024).ToString("0.00"),
                    CurrentValueUnit = formatValue.Split(' ')[1], //"kB/s",
                    PrimaryUIValue   = dis.AlertDefinition.PrimaryUIValue
                };
                currentState.ChildStates.Add(diskIOState);
            }
            if (errors > 0 && warnings == 0 && success == 0) // any errors
            {
                currentState.State = CollectorState.Error;
            }
            else if (errors > 0 || warnings > 0) //any warnings
            {
                currentState.State = CollectorState.Warning;
            }
            else
            {
                currentState.State = CollectorState.Good;
            }

            if (currentState.CurrentValue.ToString() == "" && currentState.ChildStates.Count > 0)
            {
                string formatValue = FormatUtils.FormatFileSizePerSec((long)(average / currentState.ChildStates.Count));

                currentState.CurrentValue     = formatValue.Split(' ')[0];            // ((average/1024 )/ currentState.ChildStates.Count).ToString("0.00");
                currentState.CurrentValueUnit = formatValue.Split(' ')[1] + " (avg)"; // "kB/s (avg)";
            }

            return(currentState);
        }
예제 #37
0
        /// <summary>Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object.</summary>
        /// <param name="monitor">The object on which to acquire the lock.</param>
        /// <param name="millisecondsTimeout">The number of milliseconds to wait for the lock.</param>
        /// <returns>true if the current thread acquires the lock without blocking; otherwise, false.</returns>
        public static bool TryEnter(object monitor, int millisecondsTimeout)
        {
            // Validate arguments
            if (monitor == null)
            {
                throw new ArgumentNullException("monitor");
            }
            if (millisecondsTimeout < 0 && millisecondsTimeout != Timeout.Infinite)
            {
                throw new ArgumentOutOfRangeException("millisecondsTimeout");
            }

            // Keep track of whether we actually acquired the monitor or not
            bool         thisThreadOwnsMonitor = false;
            MonitorState ms = null;

            try
            {
                // Register the current thread as waiting on the monitor.
                // Take the global lock before manipulating shared state.  Note that by our lock order,
                // we can take _globalLock while holding an individual monitor, but we *can't* take a
                // monitor while holding _globalLock; otherwise, we'd risk deadlock.
                lock (_globalLock)
                {
                    // Get the internal data for this monitor.  If not data exists, create it.
                    if (!_monitorStates.TryGetValue(monitor, out ms))
                    {
                        _monitorStates[monitor] = ms = new MonitorState(monitor);
                    }

                    // If we already hold this lock, then there's no chance of deadlock by waiting on it,
                    // since monitors are reentrant.  If we don't hold the lock, register our intent to
                    // wait on it and check for deadlock.
                    if (ms.OwningThread != Thread.CurrentThread)
                    {
                        ms.WaitingThreads.Add(Thread.CurrentThread);
                        ThrowIfDeadlockDetected(ms);
                    }
                }

                // Try to enter the monitor
                thisThreadOwnsMonitor = Monitor.TryEnter(monitor, millisecondsTimeout);

                // At this point we now may own the monitor...
            }
            finally
            {
                lock (_globalLock)
                {
                    if (ms != null) // This would only be null if an exception occurred at a really weird place
                    {
                        // We're no longer waiting on the monitor, either because something went wrong
                        // in the wait or because we now own the monitor
                        ms.WaitingThreads.Remove(Thread.CurrentThread);

                        // If we did get the monitor, then note that we now own it
                        if (thisThreadOwnsMonitor)
                        {
                            if (ms.OwningThread != Thread.CurrentThread)
                            {
                                ms.OwningThread = Thread.CurrentThread;
                            }
                            else
                            {
                                ms.ReentranceCount++;
                            }
                        }
                    }
                }
            }

            // Return whether we obtained the monitor or not
            return(thisThreadOwnsMonitor);
        }
예제 #38
0
        public override MonitorState GetState()
        {
            MonitorState  returnState         = new MonitorState();
            StringBuilder plainTextDetails    = new StringBuilder();
            StringBuilder htmlTextTextDetails = new StringBuilder();
            string        lastAction          = "";
            int           errors     = 0;
            int           success    = 0;
            int           warnings   = 0;
            double        totalValue = 0;

            try
            {
                RegistryQueryCollectorConfig config = (RegistryQueryCollectorConfig)AgentConfig;
                plainTextDetails.AppendLine(string.Format("Running {0} registry query(s)", config.Entries.Count));
                htmlTextTextDetails.AppendLine(string.Format("<b>Running {0} registry query(s)</b>", config.Entries.Count));
                htmlTextTextDetails.AppendLine("<ul>");

                foreach (RegistryQueryInstance queryInstance in config.Entries)
                {
                    object value = null;
                    if (queryInstance.UseRemoteServer)
                    {
                        lastAction = string.Format("Running Registry query '{0}' on '{1}'", queryInstance.Name, queryInstance.Server);
                    }
                    else
                    {
                        lastAction = string.Format("Running Registry query '{0}'", queryInstance.Name);
                    }

                    value = queryInstance.GetValue();
                    if (!queryInstance.ReturnValueIsNumber && value.IsNumber())
                    {
                        totalValue += double.Parse(value.ToString());
                    }

                    CollectorState instanceState = queryInstance.EvaluateValue(value);

                    if (instanceState == CollectorState.Error)
                    {
                        errors++;
                        plainTextDetails.AppendLine(string.Format("\t'{0}' - value '{1}' - Error (trigger {2})", queryInstance.Name, FormatUtils.FormatArrayToString(value, "[null]"), queryInstance.ErrorValue));
                        htmlTextTextDetails.AppendLine(string.Format("<li>Machine '{0}' - Value '{1}' - <b>Error</b> (trigger {2})</li>", queryInstance.Name, FormatUtils.FormatArrayToString(value, "[null]"), queryInstance.ErrorValue));
                    }
                    else if (instanceState == CollectorState.Warning)
                    {
                        warnings++;
                        plainTextDetails.AppendLine(string.Format("\t'{0}' - value '{1}' - Warning (trigger {2})", queryInstance.Name, FormatUtils.FormatArrayToString(value, "[null]"), queryInstance.WarningValue));
                        htmlTextTextDetails.AppendLine(string.Format("<li>Machine '{0}' - Value '{1}' - <b>Warning</b> (trigger {2})</li>", queryInstance.Name, FormatUtils.FormatArrayToString(value, "[null]"), queryInstance.WarningValue));
                    }
                    else
                    {
                        success++;
                        plainTextDetails.AppendLine(string.Format("\t'{0}' - value '{1}'", queryInstance.Name, FormatUtils.FormatArrayToString(value)));
                        htmlTextTextDetails.AppendLine(string.Format("<li>Machine '{0}' - Value '{1}'</li>", queryInstance.Name, FormatUtils.FormatArrayToString(value)));
                    }
                }
                htmlTextTextDetails.AppendLine("</ul>");
                if (errors > 0 && warnings == 0)
                {
                    returnState.State = CollectorState.Error;
                }
                else if (warnings > 0)
                {
                    returnState.State = CollectorState.Warning;
                }
                else
                {
                    returnState.State = CollectorState.Good;
                }
                returnState.RawDetails   = plainTextDetails.ToString().TrimEnd('\r', '\n');
                returnState.HtmlDetails  = htmlTextTextDetails.ToString();
                returnState.CurrentValue = totalValue;
            }
            catch (Exception ex)
            {
                returnState.RawDetails  = ex.Message;
                returnState.HtmlDetails = string.Format("<p><b>Last action:</b> {0}</p><blockquote>{1}</blockquote>", lastAction, ex.Message);
                returnState.State       = CollectorState.Error;
            }

            return(returnState);
        }
예제 #39
0
    /// <summary>
    /// Take in what JSON class to use, and create a WWW request based off of
    /// the queries that we were given. At the end, wait (1 - frequency) and then
    /// start the method again recursively
    /// </summary>
    /// <typeparam name="T">What serialized JSON class we want to use</typeparam>
    /// <param name="dataObject">The JSON data object</param>
    /// <returns>A finished WWW request to the given server</returns>
    private IEnumerator MakePostRequest <T>(T dataObject)
    {
        // Set the state to currently running so that we know we are running
        currentState = MonitorState.CurrentlyRunning;

        // Clear the headers, otherwise we will get the same data from the last one:
        headers.Clear();

        // Add in content type to JSON to the HTML headers:
        headers["Content-Type"] = "application/json";

        // Create a web request
        WWW myRequest;

        // Build the query again if the alst one was a success
        if (!_UseLastSuccess)
        {
            _current_Query = BuildQuery();
        }

        // Get the post data that I will be using, since it will always be the same
        _PostData = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(_current_Query);

        // Initalize the WWW request to have our query and proper URL/headers
        myRequest = new WWW(url, _PostData, headers);

        // Yield until the request is done
        yield return(myRequest);

        // If there was an error...
        if (myRequest.error != null)
        {
            if (errorText != null)
            {
                errorText.text = "There was a HTTP request error! Check your Server IP in the options tab!";
            }
            // If we are in the editor, then print the error to the console
#if UNITY_EDITOR
            Debug.Log("Index " + indexName + " The HTTP request text:\n" + myRequest.error);
            Debug.Log("The query was: " + _current_Query);
#endif

            // If there was an error, then stop
            yield break;
        }

        // Create a new data object using the type of JSON that it is
        dataObject = JsonUtility.FromJson <T>(myRequest.text);

        // Call this method so that the more specifc child class can deal with it
        CheckRequestData(dataObject);

        // If our error text is displaying an error when it shoulnd't be...
        if (errorText != null && !string.IsNullOrEmpty(errorText.text))
        {
            // Clear the text to be empty
            errorText.text = "";
        }

        // Wait however long we want to, so that we don't make a crazy amount of requests
        yield return(_waitTime);

        // Change the current state to finished, so that the FSM knows to create another request
        currentState = MonitorState.Finished;
    }
예제 #40
0
        /// <summary>
        /// The start.
        /// </summary>
        /// <exception cref="TimeoutException">
        /// </exception>
        public void Start()
        {
            lock (this._lockObj)
            {
                AppContext.Logger.DebugFormat("Start {0}...", this.GetType());
                DateTime startDate = DateTime.Now;

                // If monitor is still being stopped: Wait for it within a timeout limit
                while (this.State == MonitorState.Stopping && (DateTime.Now - startDate) < this.RequestTimeout)
                {
                    Thread.Sleep(500);
                }

                if (this.State != MonitorState.Stopped)
                {
                    // If the monitor is still not stopped: Throw exception
                    throw new TimeoutException("Could not restart monitor. Timed out waiting for the monitor to stop");
                }

                if (this.MonitorStarting != null)
                {
                    this.MonitorStarting(this);
                }

                this.State = MonitorState.Running;
                if (this._backgroundWorker == null)
                {
                    this._backgroundWorker = new BackgroundWorker();
                    this._backgroundWorker.DoWork += this.backgroundWorker_DoWork;
                    this._backgroundWorker.RunWorkerCompleted += this.backgroundWorker_RunWorkerCompleted;
                }

                // If we can reach here: The background worker should not be doing anything on background
                if (!this._backgroundWorker.IsBusy)
                {
                    this._backgroundWorker.RunWorkerAsync();
                }

                AppContext.Logger.DebugFormat("{0} started", this.GetType());
            }
        }
예제 #41
0
 static void SetMonitorState(MonitorState state) => SendMessage(0xffff, 0x112, 0xf170, (int)state);
예제 #42
0
        /// <summary>
        /// The background worker_ run worker completed.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (this.MonitorStopping != null)
            {
                this.MonitorStopping(this);
            }

            bool noRunningReq = this._pendingQueue.Count == 0 && this._processQueue.Count == 0;
            this.State = noRunningReq ? MonitorState.Stopped : MonitorState.Stopping;
        }
예제 #43
0
 public void PickEmptyMonitor()
 {
     _Monitor = _MonitorList[RigSlot];
     _MonitorState = _Monitor.GetComponent<MonitorState>();
     while (_MonitorState._Display == MonitorState.Show.FaceAnimation){
         if (RigSlot == 0){
             Debug.LogError ("All monitors are taken breaking at Monitor_"+RigSlot);
             // we need an end condition here
             break;
         }
         if (RigSlot == Rig.transform.childCount-1){
             PickEmptyMonitorBackwards = true;
             Debug.LogError ("Changing Slot direction at Monitor_"+RigSlot);
         }
         if (PickEmptyMonitorBackwards){
             RigSlot -= 1;
         }else{
             RigSlot += 1;
         }
         Debug.LogError ("trying to pick Monitor_"+RigSlot);
         PickEmptyMonitor();
     }
 }
 private void AddEvent(MonitorRule monitorRule, MonitorState state)
 {
     var monitorInfo = MonitorInfo.MonitorInfos.FirstOrDefault(m => m.Name == monitorRule.Monitor);
     var value = monitorInfo != null ? monitorInfo.FriendlyName : monitorRule.Monitor;
     var listViewItem = new ListViewItem(state.ToString());
     listViewItem.SubItems.AddRange(new []{monitorRule.Entity,
                                           value, 
                                           DateTime.Now.ToLongTimeString()});
     eventListView.Items.Add(listViewItem);
 }
예제 #45
0
        public override MonitorState RefreshState()
        {
            MonitorState returnState = new MonitorState();
            string       lastAction  = "";
            int          errors      = 0;
            int          warnings    = 0;
            int          success     = 0;

            try
            {
                LinuxProcessCollectorConfig currentConfig = (LinuxProcessCollectorConfig)AgentConfig;
                foreach (LinuxProcessEntry entry in currentConfig.Entries)
                {
                    MonitorState entryState = new MonitorState()
                    {
                        ForAgent = entry.Name + " (" + entry.SSHConnection.ComputerName + ")"
                    };
                    List <ProcessInfoState> pss = entry.GetStates();
                    foreach (ProcessInfoState ps in pss)
                    {
                        string currentValueFormat = "CPU%:" + ps.ProcessInfo.percCPU.ToString("0.00") + ",MEM%:" + ps.ProcessInfo.percMEM.ToString("0.00");
                        if (ps.State == CollectorState.Error)
                        {
                            errors++;
                        }
                        else if (ps.State == CollectorState.Warning)
                        {
                            warnings++;
                        }
                        else
                        {
                            success++;
                        }

                        entryState.ChildStates.Add(
                            new MonitorState()
                        {
                            ForAgent     = ps.ProcessInfo.ProcessName,
                            State        = ps.State,
                            CurrentValue = currentValueFormat
                        });
                    }
                    returnState.ChildStates.Add(entryState);
                }
                returnState.CurrentValue = null;

                if (errors > 0 && warnings == 0 && success == 0) // any errors
                {
                    returnState.State = CollectorState.Error;
                }
                else if (errors > 0 || warnings > 0) //any warnings
                {
                    returnState.State = CollectorState.Warning;
                }
                else
                {
                    returnState.State = CollectorState.Good;
                }
            }
            catch (Exception ex)
            {
                returnState.RawDetails  = ex.Message;
                returnState.HtmlDetails = string.Format("<p><b>Last action:</b> {0}</p><blockquote>{1}</blockquote>", lastAction, ex.Message);
                returnState.State       = CollectorState.Error;
            }
            return(returnState);
        }
예제 #46
0
 public static void SetMonitorState(MonitorState state)
 {
     SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, (int)MonitorState.OFF);
 }
예제 #47
0
        /// <summary>
        /// The stop.
        /// </summary>
        public virtual void Stop()
        {
            lock (this._lockObj)
            {
                AppContext.Logger.DebugFormat("Stopping {0}...", this.GetType());
                this.State = this._backgroundWorker.IsBusy ? MonitorState.Stopping : MonitorState.Stopped;
                if (this._pendingQueue.Count > 0)
                {
                    this._pendingQueue.ToList().ForEach(this.Stop);
                    this._pendingQueue.Clear(true);
                }

                if (this._processQueue.Count > 0)
                {
                    this._processQueue.ToList().ForEach(this.Stop);
                    this._processQueue.Clear(true);
                }

                AppContext.Logger.DebugFormat("{0} stopped", this.GetType());
            }
        }
        public ActionResult <MonitorState> GetMonitor([FromServices] IMonitoringLogic monitoringLogic, MonitorState monitorState)
        {
            monitoringLogic.EnableMonitoring(monitorState.Enabled);

            return(Ok(monitorState));
        }
예제 #49
0
        /// <summary>Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object.</summary>
        /// <param name="monitor">The object on which to acquire the lock.</param>
        /// <param name="millisecondsTimeout">The number of milliseconds to wait for the lock.</param>
        /// <returns>true if the current thread acquires the lock without blocking; otherwise, false.</returns>
        public static bool TryEnter(object monitor, int millisecondsTimeout)
        {
            // Validate arguments
            if (monitor == null) throw new ArgumentNullException("monitor");
            if (millisecondsTimeout < 0 && millisecondsTimeout != Timeout.Infinite) throw new ArgumentOutOfRangeException("millisecondsTimeout");

            // Keep track of whether we actually acquired the monitor or not
            bool thisThreadOwnsMonitor = false;
            MonitorState ms = null;

            try
            {
                // Register the current thread as waiting on the monitor.
                // Take the global lock before manipulating shared state.  Note that by our lock order,
                // we can take _globalLock while holding an individual monitor, but we *can't* take a
                // monitor while holding _globalLock; otherwise, we'd risk deadlock.
                lock (_globalLock)
                {
                    // Get the internal data for this monitor.  If not data exists, create it.
                    if (!_monitorStates.TryGetValue(monitor, out ms))
                    {
                        _monitorStates[monitor] = ms = new MonitorState(monitor);
                    }

                    // If we already hold this lock, then there's no chance of deadlock by waiting on it,
                    // since monitors are reentrant.  If we don't hold the lock, register our intent to
                    // wait on it and check for deadlock.
                    if (ms.OwningThread != Thread.CurrentThread)
                    {
                        ms.WaitingThreads.Add(Thread.CurrentThread);
                        ThrowIfDeadlockDetected(ms);
                    }
                }

                // Try to enter the monitor
                thisThreadOwnsMonitor = Monitor.TryEnter(monitor, millisecondsTimeout);

                // At this point we now may own the monitor...
            }
            finally
            {
                lock (_globalLock)
                {
                    if (ms != null) // This would only be null if an exception occurred at a really weird place
                    {
                        // We're no longer waiting on the monitor, either because something went wrong
                        // in the wait or because we now own the monitor
                        ms.WaitingThreads.Remove(Thread.CurrentThread);

                        // If we did get the monitor, then note that we now own it
                        if (thisThreadOwnsMonitor)
                        {
                            if (ms.OwningThread != Thread.CurrentThread) ms.OwningThread = Thread.CurrentThread;
                            else ms.ReentranceCount++;
                        }
                    }
                }
            }

            // Return whether we obtained the monitor or not
            return thisThreadOwnsMonitor;
        }
예제 #50
0
 private static void SetMonitorInState(IntPtr hwnd_broadcast, MonitorState state)
 {
     //SendMessage((IntPtr)0xFFFF, (uint)0x0112, 0xF170, (int)state);
     SendMessage(hwnd_broadcast, WM_SYSCOMMAND, SC_MONITORPOWER, (int)state);
 }
예제 #51
0
파일: Display.cs 프로젝트: Aproximation/IoT
 public void SetMonitorState(MonitorState state)
 {
     IntPtr xAsIntPtr = new IntPtr(HWND_BROADCAST);
     SendMessage(xAsIntPtr, WM_SYSCOMMAND, SC_MONITORPOWER, 2);//DLL function
 }
예제 #52
0
        //private void cmdEditMachineNames_Click(object sender, EventArgs e)
        //{
        //    CSVEditor csvEditor = new CSVEditor();
        //    csvEditor.Text = "Machine names";
        //    csvEditor.ItemDescription = "Machine";
        //    csvEditor.CSVData = txtMachines.Text;
        //    if (csvEditor.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //    {
        //        txtMachines.Text = csvEditor.CSVData;
        //    }
        //}
        //private void cmdEditColumnNames_Click(object sender, EventArgs e)
        //{
        //    CSVEditor csvEditor = new CSVEditor();
        //    csvEditor.Text = "Column names";
        //    csvEditor.ItemDescription = "Column";
        //    csvEditor.Sorted = false;
        //    csvEditor.CSVData = txtColumnNames.Text;
        //    if (csvEditor.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //    {
        //        txtColumnNames.Text = csvEditor.CSVData;
        //    }
        //}
        private void cmdTestDB_Click(object sender, EventArgs e)
        {
            if (DoValidate())
            {
                string lastStep = "Initialize values";
                try
                {
                    WMIQueryCollectorConfigEntry tmpWMIConfig = new WMIQueryCollectorConfigEntry();

                    string name          = ApplyConfigVarsOnField(txtName.Text);
                    string namespaceName = ApplyConfigVarsOnField(txtNamespace.Text);
                    string machineName   = ApplyConfigVarsOnField(txtMachines.Text);
                    string testScript    = ApplyConfigVarsOnField(txtStateQuery.Text);
                    string successVal    = ApplyConfigVarsOnField(txtSuccess.Text);
                    string warningVal    = ApplyConfigVarsOnField(txtWarning.Text);
                    string errorVal      = ApplyConfigVarsOnField(txtError.Text);

                    tmpWMIConfig.Name        = name;
                    tmpWMIConfig.Namespace   = namespaceName;
                    tmpWMIConfig.Machinename = machineName;
                    tmpWMIConfig.StateQuery  = testScript;

                    tmpWMIConfig.UseRowCountAsValue     = chkUseRowCountAsValue.Checked;
                    tmpWMIConfig.ReturnCheckSequence    = (CollectorAgentReturnValueCheckSequence)cboReturnCheckSequence.SelectedIndex;
                    tmpWMIConfig.GoodValue              = successVal;
                    tmpWMIConfig.GoodResultMatchType    = (CollectorAgentReturnValueCompareMatchType)cboSuccessMatchType.SelectedIndex;
                    tmpWMIConfig.WarningValue           = warningVal;
                    tmpWMIConfig.WarningResultMatchType = (CollectorAgentReturnValueCompareMatchType)cboWarningMatchType.SelectedIndex;
                    tmpWMIConfig.ErrorValue             = errorVal;
                    tmpWMIConfig.ErrorResultMatchType   = (CollectorAgentReturnValueCompareMatchType)cboErrorMatchType.SelectedIndex;
                    tmpWMIConfig.OutputValueUnit        = cboOutputValueUnit.Text;

                    lastStep = "Run GetCurrentState";
                    MonitorState testState = tmpWMIConfig.GetCurrentState();

                    //testing detail query
                    //lastStep = "Testing detail query - Getting column names";
                    //List<DataColumn> columns = tmpWMIConfig.GetDetailQueryColumns();
                    //lastStep = "Testing detail query - Custom column name sequence check";
                    //StringBuilder sbColumns = new StringBuilder();
                    //for (int i = 1; i < columns.Count; i++)
                    //    sbColumns.AppendLine(columns[i].ColumnName);
                    //foreach (string columnName in tmpWMIConfig.ColumnNames)
                    //{
                    //    if ((from c in columns
                    //         where c.ColumnName.ToUpper() == columnName.ToUpper()
                    //         select c).Count() != 1)
                    //    {
                    //        columnWarningText += columnName + ", ";
                    //    }
                    //}
                    //if (chkCopyColumnNames.Checked)
                    //{
                    //    Clipboard.SetText(sbColumns.ToString());
                    //}

                    //lastStep = "Testing detail query";
                    //DataSet ds = tmpWMIConfig.RunDetailQuery();
                    //if (columnWarningText.Length == 0)
                    //    MessageBox.Show(string.Format("{0}!\r\nSummary value return: {1}\r\nDetail row count: {2}\r\nDetail columns: {3}", testState.State, tmpWMIConfig.CurrentAgentValue, ds.Tables[0].Rows.Count, columns.ToCSVString()), "Test", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //else
                    //    MessageBox.Show(string.Format("{0} (with warning)!\r\nSummary value return: {1}\r\nDetail row count: {2}\r\nDetail columns returned: {3}\r\nColumns not found: {4}", testState.State, tmpWMIConfig.CurrentAgentValue, ds.Tables[0].Rows.Count, columns.ToCSVString(), columnWarningText), "Test", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    MessageBox.Show(string.Format("{0}!\r\nValue return: {1}", testState.State, testState.CurrentValue), "Test", MessageBoxButtons.OK,
                                    testState.State == CollectorState.Good ? MessageBoxIcon.Information : testState.State == CollectorState.Warning ? MessageBoxIcon.Warning : MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("Failed!\r\nLast step: {0}\r\n{1}", lastStep, ex.Message), "Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }
예제 #53
0
 private void SetMonitorInState(MonitorState state)
 {
     SendMessage(0xFFFF, 0x112, 0xF170, (int)state);
 }
예제 #54
0
        private void cmdTestDB_Click(object sender, EventArgs e)
        {
            if (DoValidate())
            {
                string lastStep          = "Initialize values";
                string columnWarningText = "";
                try
                {
                    WMIQueryCollectorConfigEntry tmpWMIConfig = new WMIQueryCollectorConfigEntry();
                    tmpWMIConfig.Name        = txtName.Text;
                    tmpWMIConfig.Namespace   = txtNamespace.Text;
                    tmpWMIConfig.Machinename = txtMachines.Text;
                    tmpWMIConfig.StateQuery  = txtStateQuery.Text;

                    //tmpWMIConfig.ReturnValueIsInt = chkIsReturnValueInt.Checked;
                    //tmpWMIConfig.ReturnValueInverted = !chkReturnValueNotInverted.Checked;
                    tmpWMIConfig.UseRowCountAsValue     = chkUseRowCountAsValue.Checked;
                    tmpWMIConfig.ReturnCheckSequence    = (CollectorAgentReturnValueCheckSequence)cboReturnCheckSequence.SelectedIndex;
                    tmpWMIConfig.GoodValue              = txtSuccess.Text;
                    tmpWMIConfig.GoodResultMatchType    = (CollectorAgentReturnValueCompareMatchType)cboSuccessMatchType.SelectedIndex;
                    tmpWMIConfig.WarningValue           = txtWarning.Text;
                    tmpWMIConfig.WarningResultMatchType = (CollectorAgentReturnValueCompareMatchType)cboWarningMatchType.SelectedIndex;
                    tmpWMIConfig.ErrorValue             = txtError.Text;
                    tmpWMIConfig.ErrorResultMatchType   = (CollectorAgentReturnValueCompareMatchType)cboErrorMatchType.SelectedIndex;

                    tmpWMIConfig.DetailQuery     = txtDetailQuery.Text;
                    tmpWMIConfig.ColumnNames     = txtColumnNames.Text.ToListFromCSVString();
                    tmpWMIConfig.OutputValueUnit = cboOutputValueUnit.Text;

                    //tmpWMIConfig.KeyColumn = (int)keyColumnNumericUpDown.Value;

                    lastStep = "Run GetCurrentState";
                    MonitorState testState = tmpWMIConfig.GetCurrentState();



                    //object returnValue = null;

                    //if (tmpWMIConfig.UseRowCountAsValue)
                    //{
                    //    lastStep = "Run summary query (row count as value)";
                    //    returnValue = tmpWMIConfig.RunQueryWithCountResult();
                    //}
                    //else
                    //{
                    //    lastStep = "Run summary query";
                    //    if (returnValue.IsIntegerTypeNumber())
                    //    {
                    //        object currentValue = null;
                    //        currentValue = tmpWMIConfig.RunQueryWithSingleResult();
                    //        if (currentValue.IsNumber())
                    //            returnValue = (decimal)currentValue;
                    //        else
                    //            throw new Exception(string.Format("Return value is not an integer!\r\nValue returned: {0}", returnValue));
                    //    }
                    //    else
                    //        returnValue = tmpWMIConfig.RunQueryWithSingleResult();
                    //}

                    //if (tmpWMIConfig.ReturnValueIsInt)
                    //{
                    //    lastStep = "Test return value is an Integer";
                    //    if (!returnValue.IsIntegerTypeNumber())
                    //        throw new Exception(string.Format("Return value is not an integer!\r\nValue returned: {0}", returnValue));
                    //}
                    //testing detail query
                    lastStep = "Testing detail query - Getting column names";
                    List <DataColumn> columns = tmpWMIConfig.GetDetailQueryColumns();
                    lastStep = "Testing detail query - Custom column name sequence check";
                    StringBuilder sbColumns = new StringBuilder();
                    for (int i = 1; i < columns.Count; i++)
                    {
                        sbColumns.AppendLine(columns[i].ColumnName);
                    }
                    foreach (string columnName in tmpWMIConfig.ColumnNames)
                    {
                        if ((from c in columns
                             where c.ColumnName.ToUpper() == columnName.ToUpper()
                             select c).Count() != 1)
                        {
                            columnWarningText += columnName + ", ";
                        }
                    }
                    if (chkCopyColumnNames.Checked)
                    {
                        Clipboard.SetText(sbColumns.ToString());
                    }

                    lastStep = "Testing detail query";
                    DataSet ds = tmpWMIConfig.RunDetailQuery();
                    if (columnWarningText.Length == 0)
                    {
                        MessageBox.Show(string.Format("{0}!\r\nSummary value return: {1}\r\nDetail row count: {2}\r\nDetail columns: {3}", testState.State, tmpWMIConfig.CurrentAgentValue, ds.Tables[0].Rows.Count, columns.ToCSVString()), "Test", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show(string.Format("{0} (with warning)!\r\nSummary value return: {1}\r\nDetail row count: {2}\r\nDetail columns returned: {3}\r\nColumns not found: {4}", testState.State, tmpWMIConfig.CurrentAgentValue, ds.Tables[0].Rows.Count, columns.ToCSVString(), columnWarningText), "Test", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("Failed!\r\nLast step: {0}\r\n{1}", lastStep, ex.Message), "Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }
예제 #55
0
        /// <summary>Creates a textual description of the deadlock.</summary>
        /// <param name="currentChain">The deadlock cycle.</param>
        /// <param name="locksHeldByThreads">The table containing what locks are held by each thread holding locks.</param>
        /// <returns>The description of the deadlock.</returns>
        private static string CreateDeadlockDescription(
            MonitorState competedState,
            CycleComponentNode currentChain,
            Dictionary<Thread, List<MonitorState>> locksHeldByThreads)
        {
            StringBuilder desc = new StringBuilder();
            for (CycleComponentNode node = currentChain; node != null; node = node.Next)
            {
                desc.AppendFormat("\r\nThread {0} waiting on: {1} ({2:X})\r\nCalling from:\r\n{3}\nwhile holding:\r\n",
                    node.Thread.ManagedThreadId, node.MonitorState.MonitorObject.ToString(),
                    RuntimeHelpers.GetHashCode(node.MonitorState.MonitorObject),
                    node.MonitorState.traces[node.Thread]);

                foreach (MonitorState ms in locksHeldByThreads[node.Thread])
                    desc.AppendFormat("{0} ({1:X})\r\n{2}", ms.MonitorObject.ToString(),
                        RuntimeHelpers.GetHashCode(ms.MonitorObject), ms.traces[node.Thread]);

                desc.AppendLine();
            }
            return desc.ToString();
        }
예제 #56
0
        public override MonitorState GetState()
        {
            MonitorState  returnState         = new MonitorState();
            StringBuilder plainTextDetails    = new StringBuilder();
            StringBuilder htmlTextTextDetails = new StringBuilder();
            string        lastAction          = "";
            int           errors   = 0;
            int           warnings = 0;
            int           success  = 0;

            try
            {
                ServiceStateCollectorConfig currentConfig = (ServiceStateCollectorConfig)AgentConfig;
                foreach (ServiceStateDefinition ssd in currentConfig.Entries)
                {
                    lastAction = "Checking services on " + ssd.MachineName;
                    var serviceStates = ssd.GetServiceStates();
                    lastAction = "Checking service states of " + ssd.MachineName;
                    CollectorState currentState = ssd.GetState(serviceStates);


                    if (currentState == CollectorState.Error)
                    {
                        errors++;
                        plainTextDetails.AppendLine(string.Format("Error: {0}", ssd.MachineName));
                        htmlTextTextDetails.AppendLine(string.Format("<b>Error</b>: {0}", ssd.MachineName));
                    }
                    else if (currentState == CollectorState.Warning)
                    {
                        warnings++;
                        plainTextDetails.AppendLine(string.Format("Warning: {0}", ssd.MachineName));
                        htmlTextTextDetails.AppendLine(string.Format("<i>Warning</i>: {0}", ssd.MachineName));
                    }
                    else
                    {
                        success++;
                        plainTextDetails.AppendLine(string.Format("Success: {0}", ssd.MachineName));
                        htmlTextTextDetails.AppendLine(string.Format("Success: {0}", ssd.MachineName));
                    }
                    foreach (ServiceStateInfo serviceEntry in serviceStates)
                    {
                        plainTextDetails.AppendLine(string.Format("\t{0}: {1}", serviceEntry.DisplayName, serviceEntry.Status));
                        htmlTextTextDetails.AppendLine("<ul>");
                        if (serviceEntry.Status != System.ServiceProcess.ServiceControllerStatus.Running)
                        {
                            htmlTextTextDetails.AppendLine(string.Format("<li>{0}: <b>{1}</b></li>", serviceEntry.DisplayName, serviceEntry.Status));
                        }
                        else
                        {
                            htmlTextTextDetails.AppendLine(string.Format("<li>{0}: {1}</li>", serviceEntry.DisplayName, serviceEntry.Status));
                        }
                        htmlTextTextDetails.AppendLine("</ul>");
                    }
                }
                returnState.RawDetails  = plainTextDetails.ToString().TrimEnd('\r', '\n');
                returnState.HtmlDetails = htmlTextTextDetails.ToString();

                if (errors > 0 && warnings == 0 && success == 0) // all errors
                {
                    returnState.State = CollectorState.Error;
                }
                else if (errors > 0 || warnings > 0) //any error or warnings
                {
                    returnState.State = CollectorState.Warning;
                }
                else
                {
                    returnState.State = CollectorState.Good;
                }
            }
            catch (Exception ex)
            {
                returnState.RawDetails  = ex.Message;
                returnState.HtmlDetails = string.Format("<p><b>Last action:</b> {0}</p><blockquote>{1}</blockquote>", lastAction, ex.Message);
                returnState.State       = CollectorState.Error;
            }

            return(returnState);
        }
예제 #57
0
 public CycleComponentNode(Thread thread, MonitorState ms, CycleComponentNode next)
 {
     Thread = thread;
     MonitorState = ms;
     Next = next;
 }
예제 #58
0
        public MonitorState GetCurrentState()
        {
            string machineName = MachineName;

            CurrentAgentValue = "";
            if (machineName == "." || machineName.ToLower() == "localhost")
            {
                machineName = System.Net.Dns.GetHostName();
            }
            MonitorState machineState = new MonitorState()
            {
                ForAgent = machineName
            };

            try
            {
                List <ServiceStateInfo> serviceStates = GetServiceStates();
                if (serviceStates.Count > 0)
                {
                    machineState.State = GetState(serviceStates);

                    foreach (ServiceStateInfo serviceEntry in serviceStates)
                    {
                        machineState.ChildStates.Add(
                            new MonitorState()
                        {
                            State        = (serviceEntry.Status == System.ServiceProcess.ServiceControllerStatus.Stopped ? CollectorState.Error : serviceEntry.Status == System.ServiceProcess.ServiceControllerStatus.Running ? CollectorState.Good : CollectorState.Warning),
                            ForAgent     = string.Format("{0}", serviceEntry.DisplayName),
                            ForAgentType = "CollectorConfigSubEntry",
                            CurrentValue = serviceEntry.Status.ToString()
                        });
                    }

                    int errors    = machineState.ChildStates.Where(cs => cs.State == CollectorState.Error).Count();
                    int warnings  = machineState.ChildStates.Where(cs => cs.State == CollectorState.Warning).Count();
                    int successes = machineState.ChildStates.Where(cs => cs.State == CollectorState.Good).Count();
                    if (errors > 0 && warnings == 0 && successes == 0)
                    {
                        machineState.CurrentValue = errors.ToString() + " stopped";
                    }
                    else if (errors > 0)
                    {
                        machineState.CurrentValue = errors.ToString() + " stopped," + successes.ToString() + " running";
                    }
                    else
                    {
                        machineState.CurrentValue = successes.ToString() + " running";
                    }
                }
                else
                {
                    machineState.State        = CollectorState.Good;
                    machineState.CurrentValue = "No service(s)";
                }
            }
            catch (Exception ex)
            {
                machineState.State = CollectorState.Error;
                if (ex.Message.Contains("Cannot open Service Control Manager on computer"))
                {
                    machineState.CurrentValue = "Cannot connect!";
                }
                machineState.RawDetails = ex.Message;
            }
            return(machineState);
        }
예제 #59
0
        /// <summary>
        /// Benchmark for client.
        /// </summary>
        /// <param name="state">The command [On|Off|Reset]</param>
        private static void MonitoringControl(MonitorState state)
        {
            switch (state)
            {
                case MonitorState.MonitorOn:
                    if (session != null && session.State == ProtocolSessionState.Opened)
                    {
                        if (protocolMonitor != null)
                        {
                            protocolMonitor.Dispose();
                        }

                        protocolMonitor = new ProtocolMonitor();
                        protocolMonitor.Attach(session);
                    }
                    else
                    {
                        protocolMonitor = new ProtocolMonitor();
                    }

                    break;

                case MonitorState.MonitorOff:
                    if (protocolMonitor != null)
                    {
                        protocolMonitor.Dispose();
                        protocolMonitor = null;
                    }

                    break;

                case MonitorState.MonitorReset:
                    if (protocolMonitor != null)
                    {
                        protocolMonitor.Reset();
                    }

                    break;

                default:
                    Http2Logger.LogError("CAPTURE-STATS needs [On|Off|Reset].");
                    break;
            }
        }
예제 #60
0
        void UpdateSpeedControl()
        {
            var interventionSpeedMpS = CurrentSpeedLimitMpS + Speed.MeterPerSecond.FromKpH(5.0f); // Default margin : 5 km/h

            if (OverspeedMonitor.TriggerOnTrackOverspeed)
            {
                interventionSpeedMpS = CurrentSpeedLimitMpS + OverspeedMonitor.TriggerOnTrackOverspeedMarginMpS;
            }

            SetInterventionSpeedLimitMpS((float)interventionSpeedMpS);

            switch (OverspeedMonitorState)
            {
            case MonitorState.Disabled:
                if (SpeedControlSystemEnabled)
                {
                    OverspeedMonitorState = MonitorState.StandBy;
                }
                break;

            case MonitorState.StandBy:
                if (!SpeedControlSystemEnabled)
                {
                    OverspeedMonitorState = MonitorState.Disabled;
                }
                else
                {
                    if (Overspeed)
                    {
                        OverspeedMonitorState = MonitorState.Alarm;
                    }
                }
                break;

            case MonitorState.Alarm:
                if (!SpeedControlSystemEnabled)
                {
                    OverspeedMonitorState = MonitorState.Disabled;
                }
                else
                {
                    if (!OverspeedEmergencyTimer.Started)
                    {
                        OverspeedEmergencyTimer.Start();
                    }

                    if (!Overspeed)
                    {
                        OverspeedEmergencyTimer.Stop();
                        OverspeedMonitorState = MonitorState.StandBy;
                    }
                    else if (OverspeedEmergencyTimer.Triggered)
                    {
                        OverspeedEmergencyTimer.Stop();
                        OverspeedMonitorState = MonitorState.Emergency;
                    }
                }
                break;

            case MonitorState.Emergency:
                if (!OverspeedPenaltyTimer.Started)
                {
                    OverspeedPenaltyTimer.Start();
                }

                if (OverspeedPenaltyTimer.Triggered && OverspeedReset)
                {
                    OverspeedPenaltyTimer.Stop();
                    OverspeedMonitorState = MonitorState.StandBy;
                }
                break;
            }

            SetOverspeedWarningDisplay(OverspeedMonitorState >= MonitorState.Alarm);
        }