Ejemplo n.º 1
0
        public WatcherResult Watch()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ProcessName))
                {
                    throw new MissingArgumentException(ProcessWatcherArgs.ProcessName);
                }

                var processes = System.Diagnostics.Process.GetProcessesByName(ProcessName);
                var process   = processes.FirstOrDefault(e => !e.HasExited);

                if (!NotifyOnlyOnFirstOccurrence)
                {
                    _lastStatus = null;
                }

                if (WatchForStopped)
                {
                    if (process == null && (
                            // First Time after service started
                            !_lastStatus.HasValue
                            // Or process was previously running
                            || _lastStatus.Value))
                    {
                        _lastStatus = false;
                        return(WatcherResult.Succeed(
                                   ArgumentCollection.New()
                                   .WithArgument(ProcessWatcherResultArgs.ProcessName, ProcessName)
                                   ));
                    }

                    _lastStatus = process != null;
                    return(WatcherResult.NotFound);
                }

                if (process != null && (
                        // First Time after service started
                        !_lastStatus.HasValue
                        // Or process was previously stopped
                        || !_lastStatus.Value)
                    )
                {
                    _lastStatus = true;
                    return(WatcherResult.Succeed(
                               ArgumentCollection.New()
                               .WithArgument(ProcessWatcherResultArgs.ProcessName, process.ProcessName)
                               .WithArgument(ProcessWatcherResultArgs.ProcessId, process.Id)
                               ));
                }

                _lastStatus = process != null;
                return(WatcherResult.NotFound);
            }
            catch (Exception exception)
            {
                LoggingService.Error(exception);
                return(WatcherResult.NotFound.WithException(exception));
            }
        }
Ejemplo n.º 2
0
        public WatcherResult Watch()
        {
            try
            {
                var usage = Counter.NextValue();

                // LoggingService.Debug($"Last Usage: {_lastUsage}, Current Usage: {usage}, Target {TargetMaximumUsage}");
                if (usage > TargetMaximumUsage && CanNotify())
                {
                    // Notify only for the first occurrence when exceeding the target maximum
                    if (_lastUsage < TargetMaximumUsage
                        // Current usage is greater than previous notification usage
                        || _lastNotificationUsage < usage)
                    {
                        _lastUsage             = usage;
                        _lastNotificationUsage = usage;
                        _lastNotificationTime  = DateTime.Now;
                        return(WatcherResult.Succeed(ArgumentCollection.New()
                                                     .WithArgument(UsageWatcherResultArgs.Usage, usage.ToString("F"))
                                                     ));
                    }
                }

                _lastUsage = usage;

                return(WatcherResult.NotFound);
            }
            catch (Exception exception)
            {
                LoggingService.Error(exception);
                return(WatcherResult.NotFound);
            }
        }
Ejemplo n.º 3
0
        public void CreateResultSucceedInstanceTest()
        {
            var watcherResult = WatcherResult.Succeed(ArgumentCollection.New());

            Assert.IsNotNull(watcherResult);
            Assert.IsTrue(watcherResult.Result);
        }
Ejemplo n.º 4
0
        public virtual WatcherResult Watch()
        {
            try
            {
                LoggingService.Trace("Watching.");
                if (DataManager == null)
                {
                    LoggingService.Debug("Creating new instance of Plugin Data Manager.");
                    DataManager = new PluginDataManager(this.Id);
                    LoggingService.Debug("Setting Data File.");
                    DataManager.SetDataFile();
                }

                var plannedExecutionTime = DataManager.GetPlannedExecutionTime();
                LoggingService.Trace("Planned Execution Time: {0}", plannedExecutionTime.ToString("G"));
                if (DateTime.Compare(DateTime.Now, plannedExecutionTime) >= 0)
                {
                    LoggingService.Debug("Time Reached");
                    var nextExecutionTime = GetNextExecutionTime();
                    LoggingService.Debug("Saving Next Execution Time: {0}", nextExecutionTime.ToString("G"));
                    DataManager.SaveNextExecutionTime(nextExecutionTime);
                    return(WatcherResult.Succeed(ArgumentCollection.New()));
                }

                LoggingService.Trace("Time Not Reached Yet!");
                return(WatcherResult.NotFound);
            }
            catch (Exception exception)
            {
                LoggingService.Error(exception);
                return(WatcherResult.NotFound);
            }
        }
Ejemplo n.º 5
0
        public WatcherResult Watch()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Host))
                {
                    throw new Exception($"{nameof(Host)} not set");
                }

                bool?oldStatus = _lastStatus;
                bool status;
                try
                {
                    using (var ping = new Ping())
                    {
                        PingReply pingReply = ping.Send(Host);
                        status = (pingReply != null && pingReply.Status == IPStatus.Success);
                    }
                }
                catch (PingException pingException)
                {
                    LoggingService.Error(pingException);
                    LoggingService.Error($"Exception HResult = {pingException.HResult}");
                    status = false;
                }

                bool notify = false;

                if (!_lastStatus.HasValue || status != _lastStatus.Value)
                {
                    _lastStatus = status;
                    if (AnyStatus)
                    {
                        notify = true;
                    }
                    else if (status == Reachable)
                    {
                        notify = true;
                    }
                }

                if (!notify)
                {
                    return(WatcherResult.NotFound);
                }
                _lastStatus = status;
                var statusString = status ? "Reachable" : "Unreachable";
                return(WatcherResult.Succeed(ArgumentCollection.New()
                                             .WithArgument(PingStatusWatcherResultArgs.Host, this.Host)
                                             .WithArgument(PingStatusWatcherResultArgs.IsReachable, status))
                       .WithArgument(PingStatusWatcherResultArgs.ResultMessage, $"Host {Host} is {statusString}"));
            }
            catch (Exception exception)
            {
                LoggingService.Error(exception);
                return(WatcherResult.NotFound);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 阻塞监视锁方法
        /// </summary>
        /// <param name="lockname">锁名称</param>
        /// <param name="timeout">阻塞超时时间</param>
        /// <returns>{监视结果 Result ,锁id Id}</returns>
        public WatchLockModel WatchLock(string lockname, long timeout)
        {
            EventWaitHandle handle   = null;
            WatcherResult   zooevent = WatcherResult.TimeOuit;
            long            Id       = 0;

            lock (_lockerList)
            {
                var node = _lockerList.FirstOrDefault(c => c.Name == lockname);
                if (node == null)
                {
                    return(new WatchLockModel()
                    {
                        Id = 0, Result = WatcherResult.NotExists
                    });
                }
                node.Event = node.Event ?? new ManualResetEvent(false);
                handle     = node.Event;
                zooevent   = node.ZooEvent;
                Id         = node.Id;
            }

            var action = WaitHandle.WaitAny(new WaitHandle[] { handle }, TimeSpan.FromMilliseconds(timeout));

            if (action == WaitHandle.WaitTimeout)
            {
                return(new WatchLockModel()
                {
                    Id = Id, Result = WatcherResult.TimeOuit
                });
            }
            else
            {
                if (zooevent == WatcherResult.Disconnected)
                {
                    return(new WatchLockModel()
                    {
                        Id = Id, Result = WatcherResult.Disconnected
                    });
                }
                else if (zooevent == WatcherResult.UnLocked)
                {
                    return(new WatchLockModel()
                    {
                        Id = Id, Result = WatcherResult.UnLocked
                    });
                }
                else
                {
                    return(new WatchLockModel()
                    {
                        Id = Id, Result = zooevent
                    });
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// This method exports a single item.
        /// </summary>
        /// <remarks>TODO: Standards Compliance Handling?</remarks>
        private void ExportResult(WatcherResult watcherResult)
        {
            WatcherEngine.ProgressDialog.UpdateProgress("Verifying work item type...");

            // Verify the work item type exists in the project (e.g., "Bug")
            if (_adapter.Project.WorkItemTypes.Contains(_adapter.Configuration.ExportMap.Type) == false)
            {
                String s = String.Format("Required work item \"{0}\" does not exist in the work item template.", _adapter.Configuration.ExportMap.Type);
                Trace.TraceError(s);
                throw new WatcherException(s); // TODO: Message box title: Error
            }

            // Create an instance of the work item
            WatcherEngine.ProgressDialog.UpdateProgress(String.Format("Creating work item \"{0}\"...", watcherResult.Title));
            WorkItem workItem = new WorkItem(_adapter.Project.WorkItemTypes[_adapter.Configuration.ExportMap.Type]);

#if DEBUG
            Debug.WriteLine(String.Format("Work item \"{0}\" fields:", workItem.Title));
            foreach (Field field in workItem.Fields)
            {
                Debug.WriteLine(String.Format("\tRequired: {0}; Reference Name: {1}", field.IsRequired, field.ReferenceName));
            }
#endif

            // Ensure fields required by the work item template have been defined in the XML map
            try { ValidateWorkItemFields(workItem); }
            catch (WatcherException ex)
            {
                String s = String.Format("Unable to validate work item fields:\r\n\r\n{0}", ex.Message);
                Trace.TraceError(s);
                throw new WatcherException(s, ex); // TODO: Message box title: Error
            }

            // Map the Watcher result information to the TFS template (including SDL fields)
            try { PopulateWorkItem(workItem, watcherResult); }
            catch (WatcherException ex)
            {
                String s = String.Format("Unable to populate work item fields:\r\n\r\n{0}", ex.Message);
                Trace.TraceError(s);
                throw new WatcherException(s, ex); // TODO: Message box title: Error
            }

            WatcherEngine.ProgressDialog.UpdateProgress("Saving work item...");

            // Save the new work item
            // TODO: Allow the user to continue on non-fatal failures
            try { workItem.Save(); }
            catch (ValidationException ex)
            {
                String s = String.Format("Unable to save the work item template:\r\n\r\n{0}", ex.Message);
                Trace.TraceError(s);
                throw new WatcherException(s, ex);  // TODO: Message box title: Error
            }
        }
Ejemplo n.º 8
0
        public void CreateResultSucceedWithArgumentFailsOnGettingWrongTypeTest()
        {
            var argumentKey   = "key";
            var argumentValue = "vale";
            var watcherResult = WatcherResult.Succeed(ArgumentCollection.New().WithArgument(argumentKey, argumentValue));

            Assert.IsNotNull(watcherResult);
            Assert.IsTrue(watcherResult.Result);
            Assert.IsNotNull(watcherResult.WatchingArguments);
            Assert.IsTrue(watcherResult.WatchingArguments.Any());
            Assert.AreEqual(1, watcherResult.WatchingArguments.Count);
            Assert.IsTrue(watcherResult.WatchingArguments.HasArgument(argumentKey));
            watcherResult.WatchingArguments.GetValue <int>(argumentKey);
        }
Ejemplo n.º 9
0
        public void CreateResultSucceedWithArgumentInstanceTest()
        {
            var argumentKey   = "key";
            var argumentValue = "vale";
            var watcherResult = WatcherResult.Succeed(ArgumentCollection.New().WithArgument(argumentKey, argumentValue));

            Assert.IsNotNull(watcherResult);
            Assert.IsTrue(watcherResult.Result);
            Assert.IsNotNull(watcherResult.WatchingArguments);
            Assert.IsTrue(watcherResult.WatchingArguments.Any());
            Assert.AreEqual(1, watcherResult.WatchingArguments.Count);
            Assert.IsTrue(watcherResult.WatchingArguments.HasArgument(argumentKey));
            Assert.IsNotNull(watcherResult.WatchingArguments[argumentKey]);
            Assert.IsNotNull(watcherResult.WatchingArguments.GetValue <string>(argumentKey));
            Assert.AreEqual(argumentValue, watcherResult.WatchingArguments[argumentKey]);
            Assert.AreEqual(argumentValue, watcherResult.WatchingArguments.GetValue <string>(argumentKey));
        }
Ejemplo n.º 10
0
        public WatcherResult Watch()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ServiceName))
                {
                    throw new Exception("ServiceName is incorrect ! NULL or EMPTY");
                }

                var status = WinServiceUtilities.GetServiceStatus(ServiceName);

                bool notify = false;

                if (!_serviceStatus.HasValue || status != _serviceStatus.Value)
                {
                    _serviceStatus = status;
                    if (AnyStatus)
                    {
                        notify = true;
                    }
                    else if ((int)status == Status)
                    {
                        notify = true;
                    }
                }

                if (!notify)
                {
                    return(WatcherResult.NotFound);
                }
                _serviceStatus = status;
                return(WatcherResult.Succeed(ArgumentCollection.New()
                                             .WithArgument(WinServiceWatcherResultArgs.ServiceName, ServiceName)
                                             .WithArgument(WinServiceWatcherResultArgs.Status, status.ToString("G"))));
            }
            catch (Exception exception)
            {
                LoggingService.Error(exception);
                return(WatcherResult.NotFound
                       .WithException(exception));
            }
        }
Ejemplo n.º 11
0
        public WatcherResult Watch()
        {
            try
            {
                var files = Select();
                if (files.Any())
                {
                    return(WatcherResult.Succeed(ArgumentCollection.New()
                                                 .WithArgument(FtpWatcherResultArgs.RemoteFilesCollection, files)
                                                 ));
                }

                return(WatcherResult.NotFound);
            }
            catch (Exception exception)
            {
                LoggingService.Error(exception);
                return(WatcherResult.NotFound.WithException(exception));
            }
        }
Ejemplo n.º 12
0
        public WatcherResult Watch()
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Url))
                {
                    throw new Exception("Url not set");
                }

                HttpStatusCode?oldStatusCode = _lastStatusCode;
                HttpStatusCode status;
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        status = response.StatusCode;
                    }
                }
                catch (WebException webException)
                {
                    if (webException.Response != null && webException.Response is HttpWebResponse response)
                    {
                        status = response.StatusCode;
                    }
                    else
                    {
                        throw;
                    }
                }

                bool notify = false;

                if (!_lastStatusCode.HasValue || status != _lastStatusCode.Value)
                {
                    _lastStatusCode = status;
                    if (AnyStatus)
                    {
                        notify = true;
                    }
                    else if ((int)status == StatusCode)
                    {
                        notify = true;
                    }
                }

                if (!notify)
                {
                    return(WatcherResult.NotFound);
                }
                _lastStatusCode = status;
                string resultMessage = oldStatusCode.HasValue
                    ? $"Response from Url {Url} has changed from {oldStatusCode} ({(int) oldStatusCode}) to {status} ({(int) status})"
                    : $"Response from Url {Url} is {status} ({(int) status})";
                return(WatcherResult.Succeed(ArgumentCollection.New()
                                             .WithArgument(UrlStatusWatcherResultArgs.Url, this.Url)
                                             .WithArgument(UrlStatusWatcherResultArgs.StatusCodeName, status.ToString("G")))
                       .WithArgument(UrlStatusWatcherResultArgs.StatusCodeValue, (int)status)
                       .WithArgument(UrlStatusWatcherResultArgs.ResultMessage, resultMessage));
            }
            catch (Exception exception)
            {
                LoggingService.Error(exception);
                return(WatcherResult.NotFound);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// This method saves the collection of Watcher findings to the Team Foundation Server specified in the UI.
        /// </summary>
        /// <param name="watcherResults">Collection of Watcher findings to export.</param>
        /// <returns>This method always returns null for Team Foundation Server exports.</returns>
        public override Stream SaveResult(WatcherResultCollection watcherResults)
        {
            Trace.TraceInformation("Exporting {0} items...", watcherResults.Count);

            // Create an instance of the Watcher Result to Team Foundation Work Item adapter
            _adapter = TeamFoundationAdapter.Create(_configurationPanel.servername, _configurationPanel.projectname);

            Trace.TraceInformation("Connecting to Team Foundation Server...");
            WatcherEngine.ProgressDialog.UpdateProgress("Connecting to Team Foundation Server...");

            // Attempt to connect to the Team Foundation Server specified in the configuration panel
            try { _adapter.Connect(); }
            catch (WatcherException ex)
            {
                Trace.TraceError("Unable to connect to Team Foundation Server \"{0}\": {1}", _adapter.ServerName, ex.Message);
                throw;
            }

            Trace.TraceInformation("Opening the project...");
            WatcherEngine.ProgressDialog.UpdateProgress("Opening the project...");

            // Attempt to open the Team Foundation Project specified in the configuration panel
            try { _adapter.OpenProject(); }
            catch (WatcherException ex)
            {
                Trace.TraceError("Unable to connect to Team Foundation Server \"{0}\": {1}", _adapter.ServerName, ex.Message);
                throw;
            }

            // TODO: collect results and throw with error
            // Enumerate and export the results
            for (int ndx = 0; ndx < watcherResults.Count;)
            {
                // Reset the progress bar for each finding exported
                WatcherEngine.ProgressDialog.ProgressValue = 10;

                // Determine the current finding
                WatcherResult watcherResult = watcherResults[ndx];

                // Export the current finding
                try { ExportResult(watcherResult); }
                catch (WatcherException ex)
                {
                    DialogResult dlgResult = MessageBox.Show(ex.Message, "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Warning);
                    switch (dlgResult)
                    {
                    case DialogResult.Abort:
                        Trace.TraceInformation("User has aborted the export.");
                        WatcherException e = new WatcherException(ex.Message);
                        e.Data["UserAbortedOperation"] = true;      // Prevent an additional dialog from appearing when the exception is
                        throw e;                                    // rethrown to abort the operation.

                    case DialogResult.Retry:
                        Trace.TraceInformation("User is attempting to retry the export of item \"{0}\".", watcherResult.Title);
                        continue;

                    case DialogResult.Ignore:
                        break;
                    }
                }

                // Continue with the next finding
                ++ndx;
            }

            // TODO: Make the SaveResult return type more generic.  Returning null here is
            // a kludge since output plugins were originally intended to return a Stream.
            return(null);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// This method maps Watcher fields to SDL fields.
        /// </summary>
        /// <remarks>
        /// TODO: Mappings should be pulled from the user-configurable XML file.
        /// TODO: Description should be converted to HTML and include the URI.
        /// TODO: Mappings should work even if the configuration file does not exist.
        /// </remarks>
        /// <param name="workItem">The TFS work item.</param>
        /// <param name="watcherResult">The Watcher finding.</param>
        private void PopulateWorkItem(WorkItem workItem, WatcherResult watcherResult)
        {
            // Set defaults
            //
            // Set the origin to "Watcher"
            if (workItem.Fields.Contains("Microsoft.SDL.Security.Origin"))      // TODO: optimize. use single string
            {
                workItem["Microsoft.SDL.Security.Origin"] = "Watcher Web Security Tool (Casaba Security, LLC.)";
            }

            // Set the title of the work item.
            //
            // If the configuration contains a destination entry of System.Title and is sourced by
            // the CasabaSecurity.Watcher.Title, use a Watcher-default title.  If the source does
            // not exist, use the default value specified in the configuration.
            //
            foreach (TeamFoundationConfiguration.FindingMapEntry entry in _adapter.Configuration.ExportMap.Mappings)
            {
                // TODO: This is the case where source and destination are specified
                // TODO: Case 2: Where destination and default value are specified
                Debug.Assert(entry.Destination != null, "Destination must always be specified in the mapping.");
                if (entry.Destination == null)
                {
                    Trace.TraceError("TeamFoundationMapEntry contains a destination that is null.  This should never happen.");
                    throw new WatcherException("TeamFoundationMapEntry contains a destination that is null."); // TODO: review
                }

                // The destination field name must exist in the work item
                // TODO: this should have already been checked
                if (workItem.Fields.Contains(entry.Destination) == false)
                {
                    Trace.TraceError("Destination name does not exist in the work item template.");           // TODO: single string
                    throw new WatcherException("Destination name does not exist in the work item template."); // TODO: be more descript
                }

                // XXX Enumerate each source, if it matches one we know about, add our version of the value to the field.
                // XXX Otherwise, if there is no match, it's an error.
                // XXX TODO: what if this is null?
                switch (entry.Source)
                {
                case "CasabaSecurity.Web.Watcher.Title":
                    workItem[entry.Destination] = String.Format("{0}", watcherResult.Title);
                    break;

                // TODO: The Watcher description should be translated to HTML prior to setting this field.
                case "CasabaSecurity.Web.Watcher.Description":
                    workItem[entry.Destination] = watcherResult.Description;
                    break;

                case "CasabaSecurity.Web.Watcher.Origin":
                    workItem[entry.Destination] = "Watcher Web Security Tool (Casaba Security, LLC.)";
                    break;

                case "CasabaSecurity.Web.Watcher.Severity":
                    workItem[entry.Destination] = _adapter.Configuration.GetTranslatedValue("CasabaSecurity.Web.Watcher.Severity", watcherResult.Severity.ToString());     //XXX TODO
                    break;

                // If no source field exists for this destination, use the default value defined in the mapping
                default:
                    // TODO: ensure when reading mapping that the above fields are the only valid fields
                    // TODO: ensure that only source/destination and destination/default value pairs are specified.
                    // TODO: ensure DefaultValue is not null?
                    workItem[entry.Destination] = entry.DefaultValue;
                    break;
                }
            }
        }