コード例 #1
0
ファイル: AlertTests.cs プロジェクト: tdicks/LogicMonitor.Api
        public async void GetAlertsFilteredByDevice()
        {
            var device = await GetWindowsDeviceAsync().ConfigureAwait(false);

            var startUtcIsBefore = new DateTime(2018, 1, 1);

            foreach (var alertType in new List <AlertType> {
                AlertType.DataSource, AlertType.EventSource
            })
            {
                var alertTypes = new List <AlertType> {
                    alertType
                };
                var alertFilter = new AlertFilter
                {
                    AlertTypes       = alertTypes,
                    MonitorObjectId  = device.Id,
                    StartUtcIsBefore = startUtcIsBefore
                };
                var alerts = await PortalClient.GetAlertsAsync(alertFilter).ConfigureAwait(false);

                // TODO CheckAlertsAreValid(alerts);

                // Make sure there are no alerts for hosts not mentioned by the hostFilter
                Assert.DoesNotContain(alerts, alert => alert.MonitorObjectName != device.DisplayName);
                Assert.All(alerts, alert => Assert.Contains(alert.AlertType, alertTypes));
                Assert.All(alerts, alert => Assert.True(alert.StartOnUtc < startUtcIsBefore));
            }
        }
コード例 #2
0
ファイル: AlertTests.cs プロジェクト: tdicks/LogicMonitor.Api
        public void LevelDefaultsToError()
        {
            var alertFilter = new AlertFilter();

            Assert.Equal(2, alertFilter.Levels.Count);
            Assert.Equal(AlertLevel.Error, alertFilter.Levels[0]);
            Assert.Equal(AlertLevel.Critical, alertFilter.Levels[1]);
        }
コード例 #3
0
 public static void Checkbox(ProfileLog log)
 {
     if (AlertFilter.TryGetValue(log.type, out var value))
     {
         AlertFilter[log.type] = !value;
     }
     else
     {
         AlertFilter.Add(log.type, true);
     }
 }
コード例 #4
0
        /// <summary>
        /// Retrieves a list of open alerts
        /// </summary>
        /// <param name="page">
        /// The requested page from the server. This is an optional
        /// argument and if omitted the server will default to returning the
        /// first page with a maximum of <tt>100</tt> items.
        /// </param>
        /// <param name="filter">
        /// A filter object to filter the open alerts on the
        /// server.If omitted, the server will return all objects as a
        /// paginated response.
        /// </param>
        /// <exception cref="Core.NebException">
        /// An error with the GraphQL endpoint
        /// </exception>
        /// <returns>A paginated list of open alerts</returns>
        public AlertList GetOpenAlerts(
            PageInput page     = null,
            AlertFilter filter = null)
        {
            // setup parameters
            GraphQLParameters parameters = new GraphQLParameters();

            parameters.Add("page", page, true);
            parameters.Add("filter", filter, true);

            return(RunQuery <AlertList>(@"getOpenAlerts", parameters));
        }
コード例 #5
0
ファイル: AlertTests.cs プロジェクト: tdicks/LogicMonitor.Api
        public async void GetAlertsFilteredByDeviceRest()
        {
            var device = await GetWindowsDeviceAsync().ConfigureAwait(false);

            var deviceGroupFullPathFilter = new List <string> {
                "Collectors*"
            };
            const string    dataSourceNameFilter         = "Volume Usage-";
            const string    dataSourceInstanceNameFilter = @"WinVolumeUsage-C:\\";
            const string    dataPointNameFilter          = "Capacity";
            const AckFilter ackFilter    = AckFilter.Acked;
            const SdtFilter sdtFilter    = SdtFilter.Sdt;
            var             levelsFilter = new List <AlertLevel> {
                AlertLevel.Error, AlertLevel.Critical
            };
            bool?includeClearedFilter = true;
            var  utcNow = DateTime.UtcNow;

            var alertFilter = new AlertFilter
            {
                MonitorObjectGroupFullPaths = deviceGroupFullPathFilter,
                MonitorObjectName           = device.DisplayName,
                ResourceTemplateName        = dataSourceNameFilter,
                DataPointName      = dataPointNameFilter,
                InstanceName       = dataSourceInstanceNameFilter,
                AckFilter          = ackFilter,
                SdtFilter          = sdtFilter,
                Levels             = levelsFilter,
                IncludeCleared     = includeClearedFilter,
                StartEpochIsAfter  = utcNow.AddDays(-1).SecondsSinceTheEpoch(),
                StartEpochIsBefore = utcNow.SecondsSinceTheEpoch()
            };
            var alerts = await PortalClient.GetAlertsAsync(alertFilter).ConfigureAwait(false);

            // TODO CheckAlertsAreValid(alerts);

            // Make sure there are no alerts for hosts not mentioned by the hostFilter
            Assert.True(alerts.All(alert => alert.MonitorObjectName == device.DisplayName));
            //Assert.True(alerts.All(alert => alert.MonitorObjectGroups.Any(mog => mog.FullPath.StartsWith(deviceGroupFullPathFilter.Replace("*", "")))));
            Assert.True(alerts.All(alert => alert.InstanceName.StartsWith(dataSourceNameFilter)));
            Assert.True(alerts.All(alert => alert.DataPointName.StartsWith(dataPointNameFilter)));
        }
コード例 #6
0
        /// <summary>
        ///     Gets a list of alerts.
        ///     If no alert filter is present, all alerts are returned, including inactive alerts
        /// </summary>
        /// <param name="alertFilter">An alert filter</param>
        /// <param name="cancellationToken">An optional cancellation token</param>
        /// <returns>a list of alerts that meet the filter</returns>
        public async Task <List <Alert> > GetAlertsAsync(AlertFilter alertFilter = null, CancellationToken cancellationToken = default)
        {
            // When scanning using both startAfter and startBefore (but not endAfter or endBefore), apply the workaround to avoid LogicMonitor's 10,000 alert limit
            var alerts =
                alertFilter?.StartUtcIsAfter != null &&
                alertFilter.StartUtcIsBefore != null &&
                alertFilter.EndUtcIsAfter == null &&
                alertFilter.EndUtcIsBefore == null
                                        ? await GetRestAlertsWithV84Bug(alertFilter, TimeSpan.FromHours(8)).ConfigureAwait(false)
                                        : await GetRestAlertsWithoutV84BugAsync(alertFilter, cancellationToken).ConfigureAwait(false);

            if (alertFilter?.IsCleared == true)
            {
                return(alerts.Where(a => a.IsCleared).ToList());
            }
            if (alertFilter?.IsCleared == false)
            {
                return(alerts.Where(a => !a.IsCleared).ToList());
            }
            return(alerts);
        }
コード例 #7
0
        /// <summary>
        ///     This version of the call requests hourly chunks
        /// </summary>
        /// <param name="alertFilter"></param>
        /// <param name="chunkSize"></param>
        public async Task <List <Alert> > GetRestAlertsWithV84Bug(AlertFilter alertFilter, TimeSpan chunkSize)
        {
            var originalStartEpochIsAfter  = alertFilter.StartEpochIsAfter;
            var originalStartEpochIsBefore = alertFilter.StartEpochIsBefore;
            var utcNow = DateTime.UtcNow;

            if (alertFilter.StartEpochIsAfter == null)
            {
                alertFilter.StartEpochIsAfter = utcNow.AddYears(-1).SecondsSinceTheEpoch();
            }
            if (alertFilter.StartEpochIsBefore == null)
            {
                alertFilter.StartEpochIsBefore = utcNow.SecondsSinceTheEpoch();
            }
            var allAlerts = new ConcurrentBag <Alert>();

            var alertFilterList = ((long)alertFilter.StartEpochIsAfter).ToDateTimeUtc()
                                  .GetChunkedTimeRangeList(((long)alertFilter.StartEpochIsBefore).ToDateTimeUtc(), chunkSize)
                                  .Select(t =>
            {
                var newAlertFilter = alertFilter.Clone();
                newAlertFilter.ResetSearch();
                newAlertFilter.StartEpochIsAfter  = t.Item1.SecondsSinceTheEpoch() - 1;                        // Take one off to include anything raised on that exact second
                newAlertFilter.StartEpochIsBefore = t.Item2.SecondsSinceTheEpoch();
                return(newAlertFilter);
            });
            await Task.WhenAll(alertFilterList.Select(async individualAlertFilter =>
            {
                foreach (var alert in await GetRestAlertsWithoutV84BugAsync(individualAlertFilter).ConfigureAwait(false))
                {
                    allAlerts.Add(alert);
                }
            })).ConfigureAwait(false);

            alertFilter.StartEpochIsAfter  = originalStartEpochIsAfter;
            alertFilter.StartEpochIsBefore = originalStartEpochIsBefore;

            return(allAlerts.DistinctBy(a => a.Id).Take(alertFilter.Take ?? int.MaxValue).ToList());
        }
コード例 #8
0
ファイル: AlertTests.cs プロジェクト: tdicks/LogicMonitor.Api
        public async void GetAlerts_SdtsMatchRequest()
        {
            // Arrange
            var allFilter = new AlertFilter
            {
                SdtFilter          = SdtFilter.All,
                StartEpochIsAfter  = StartDateTimeSeconds,
                StartEpochIsBefore = EndDateTimeSeconds
            };
            var sdtFilter = new AlertFilter
            {
                SdtFilter          = SdtFilter.Sdt,
                StartEpochIsAfter  = StartDateTimeSeconds,
                StartEpochIsBefore = EndDateTimeSeconds
            };
            var nonSdtFilter = new AlertFilter
            {
                SdtFilter          = SdtFilter.NonSdt,
                StartEpochIsAfter  = StartDateTimeSeconds,
                StartEpochIsBefore = EndDateTimeSeconds
            };

            // Act
            var allAlerts = await PortalClient.GetAlertsAsync(allFilter).ConfigureAwait(false);

            var sdtAlerts = await PortalClient.GetAlertsAsync(sdtFilter).ConfigureAwait(false);

            var nonSdtAlerts = await PortalClient.GetAlertsAsync(nonSdtFilter).ConfigureAwait(false);

            // Assert

            // Alert counts add up
            Assert.Equal(allAlerts.Count, sdtAlerts.Count + nonSdtAlerts.Count);

            // Alerts have the expected SDT status
            Assert.True(sdtAlerts.All(a => a.InScheduledDownTime));
            Assert.True(nonSdtAlerts.All(a => !a.InScheduledDownTime));
        }
コード例 #9
0
ファイル: AlertTests.cs プロジェクト: tdicks/LogicMonitor.Api
        public async void GetAlertsIncludeInactiveShouldWork()
        {
            // IncludeCleared set false should bring back only active alerts
            var alertFilterNotIncludingCleared = new AlertFilter
            {
                IncludeCleared     = false,
                AckFilter          = AckFilter.All,
                AlertRuleName      = null,
                StartEpochIsBefore = DateTime.UtcNow.AddMinutes(-1).SecondsSinceTheEpoch(),
                SdtFilter          = SdtFilter.All,
                StartEpochIsAfter  = DateTime.UtcNow.AddDays(-7).SecondsSinceTheEpoch(),
                OrderByProperty    = nameof(Alert.StartOnSeconds),
                OrderDirection     = OrderDirection.Desc
            };
            var alertsNotIncludingCleared = await PortalClient.GetAlertsAsync(alertFilterNotIncludingCleared).ConfigureAwait(false);

            Assert.True(alertsNotIncludingCleared.Count > 0);
            Assert.DoesNotContain(alertsNotIncludingCleared, a => !a.IsActive);
            Assert.Contains(alertsNotIncludingCleared, a => a.IsActive);

            // IncludeCleared set true should bring back active AND non-active alerts
            var alertFilterIncludingCleared = new AlertFilter
            {
                IncludeCleared     = true,
                AckFilter          = AckFilter.All,
                AlertRuleName      = null,
                StartEpochIsBefore = DateTime.UtcNow.AddMinutes(-1).SecondsSinceTheEpoch(),
                SdtFilter          = SdtFilter.All,
                StartEpochIsAfter  = DateTime.UtcNow.AddDays(-7).SecondsSinceTheEpoch(),
                OrderByProperty    = nameof(Alert.StartOnSeconds),
                OrderDirection     = OrderDirection.Desc
            };
            var alertsIncludngCleared = await PortalClient.GetAlertsAsync(alertFilterIncludingCleared).ConfigureAwait(false);

            Assert.True(alertsIncludngCleared.Count > 0);
            Assert.Contains(alertsIncludngCleared, a => !a.IsActive);
            Assert.Contains(alertsIncludngCleared, a => a.IsActive);
        }
コード例 #10
0
 private void InitializeApiObjects()
 {
     //New API needs to be instantiated here, in the same alphabetical order as above
     Acsrf             = new Acsrf(this);
     AjaxSpider        = new AjaxSpider(this);
     Alert             = new Generated.Alert(this);
     AlertFilter       = new AlertFilter(this);
     Ascan             = new Ascan(this);
     Authentication    = new Authentication(this);
     Authorization     = new Authorization(this);
     AutoUpdate        = new AutoUpdate(this);
     Brk               = new Break(this);
     Context           = new Context(this);
     Core              = new Core(this);
     ForcedUser        = new ForcedUser(this);
     HttpSessions      = new HttpSessions(this);
     ImportLogFiles    = new ImportLogFiles(this);
     ImportUrls        = new ImportUrls(this);
     LocalProxies      = new LocalProxies(this);
     OpenApi           = new OpenApi(this);
     Parameters        = new Params(this);
     Pnh               = new Pnh(this);
     PScan             = new PScan(this);
     Replacer          = new Replacer(this);
     Reveal            = new Reveal(this);
     RuleConfig        = new RuleConfig(this);
     Script            = new Script(this);
     Search            = new Search(this);
     Selenium          = new Selenium(this);
     SessionManagement = new SessionManagement(this);
     Soap              = new Soap(this);
     Spider            = new Spider(this);
     Stats             = new Stats(this);
     Users             = new Users(this);
     Websocket         = new Websocket(this);
 }
コード例 #11
0
 private void InitializeApiObjects()
 {
     //New API needs to be instantiated here, in the same alphabetical order as above
     acsrf             = new Acsrf(this);
     ajaxspider        = new AjaxSpider(this);
     alert             = new OWASPZAPDotNetAPI.Generated.Alert(this);
     alertFilter       = new AlertFilter(this);
     ascan             = new Ascan(this);
     authentication    = new Authentication(this);
     authorization     = new OWASPZAPDotNetAPI.Generated.Authorization(this);
     autoupdate        = new Autoupdate(this);
     brk               = new Break(this);
     context           = new Context(this);
     core              = new Core(this);
     forcedUser        = new ForcedUser(this);
     httpSessions      = new HttpSessions(this);
     importLogFiles    = new ImportLogFiles(this);
     importurls        = new Importurls(this);
     localProxies      = new LocalProxies(this);
     openapi           = new Openapi(this);
     parameters        = new Params(this);
     pnh               = new Pnh(this);
     pscan             = new Pscan(this);
     replacer          = new Replacer(this);
     reveal            = new Reveal(this);
     ruleConfig        = new RuleConfig(this);
     script            = new Script(this);
     search            = new Search(this);
     selenium          = new Selenium(this);
     sessionManagement = new SessionManagement(this);
     soap              = new Soap(this);
     spider            = new Spider(this);
     stats             = new Stats(this);
     users             = new Users(this);
     websocket         = new Websocket(this);
 }
コード例 #12
0
        internal async Task <List <Alert> > GetRestAlertsWithoutV84BugAsync(AlertFilter alertFilter, CancellationToken cancellationToken = default)
        {
            var correctedAlertFilter = alertFilter?.Clone() ?? new AlertFilter
            {
                StartEpochIsAfter = 0
            };

            // There is a bug in LogicMonitor (https://jira.logicmonitor.com/browse/DEVTS-4968)
            // whereby the MonitorObjectId does not work in a filter.  If used, substitute the MonitorObjectName instead
            // If the MonitorObjectId is set, set the
            correctedAlertFilter.MonitorObjectId = null;
            var alertFilterMonitorObjectId = alertFilter?.MonitorObjectId;

            if (alertFilterMonitorObjectId.HasValue)
            {
                var alertTypesOrNull         = alertFilter.GetAlertTypes();
                var alertTypesAreOnlyWebsite = alertTypesOrNull?.All(alertType => alertType == AlertType.Website) ?? false;
                correctedAlertFilter.MonitorObjectName = alertTypesAreOnlyWebsite
                                        ? (await GetAsync <Website>(alertFilterMonitorObjectId.Value).ConfigureAwait(false)).Name
                                        : (await GetAsync <Device>(alertFilterMonitorObjectId.Value).ConfigureAwait(false)).DisplayName;
            }

            // If take is specified, do only that chunk.

            if (correctedAlertFilter.Skip == null)
            {
                correctedAlertFilter.Skip = 0;
            }
            int maxAlertCount;

            if (correctedAlertFilter.Take != null)
            {
                if (correctedAlertFilter.Take > AlertsMaxTake)
                {
                    maxAlertCount             = (int)correctedAlertFilter.Take;
                    correctedAlertFilter.Take = AlertsMaxTake;
                }
                else
                {
                    maxAlertCount = (int)correctedAlertFilter.Take;
                }
            }
            else
            {
                maxAlertCount             = int.MaxValue;
                correctedAlertFilter.Take = AlertsMaxTake;
            }

            var allAlerts = new List <Alert>();

            do
            {
                var page = await FilteredGetAsync("alert/alerts", correctedAlertFilter.GetFilter(), cancellationToken).ConfigureAwait(false);

                allAlerts.AddRange(page.Items.Where(a => !allAlerts.Select(aa => aa.Id).Contains(a.Id)).ToList());

                // The page TotalCount is negative if there are more to come, but this is not particularly useful to us.
                // The only way to be sure (while bugs exist) is to keep fetching the next batch until no more results are returned.
                if (page.Items?.Count == 0)
                {
                    break;
                }

                // Adjust the alertFilter
                if (correctedAlertFilter.SearchId == null && !string.IsNullOrWhiteSpace(page.SearchId))
                {
                    // We can re-use the searchId
                    correctedAlertFilter.SearchId = page.SearchId;
                }

                correctedAlertFilter.Skip += AlertsMaxTake;
                correctedAlertFilter.Take  = Math.Min(AlertsMaxTake, maxAlertCount - allAlerts.Count);
            }while (correctedAlertFilter.Take != 0);
            return(allAlerts);
        }
コード例 #13
0
        /// <summary>
        /// Performs execution of the command
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
                AlertFilter filter = new AlertFilter();

                if (ParameterPresent("CreatedAfter"))
                {
                    filter.CreatedAfter = CreatedAfter;
                }

                if (ParameterPresent("CreatedBefore"))
                {
                    filter.CreatedBefore = CreatedBefore;
                }

                if (ParameterPresent("ResourceId"))
                {
                    filter.ResourceID = ResourceId;
                }

                if (ParameterPresent("ResourceType"))
                {
                    filter.ResourceType = ResourceType;
                }

                if (ParameterPresent("Severity"))
                {
                    filter.Severity = Severity;
                }

                if (ParameterPresent("Status"))
                {
                    filter.Status = Status;
                }

                PageInput page = PageInput.First;
                AlertList list = Connection.GetOpenAlerts(page, filter);

                foreach (Alert alert in list.Items)
                {
                    WriteObject(alert);
                }

                while (list.More)
                {
                    // advance the page
                    page.Page = page.Page + 1;

                    list = Connection.GetOpenAlerts(page);
                    foreach (Alert alert in list.Items)
                    {
                        WriteObject(alert);
                    }
                }
            }
            catch (AggregateException exceptions)
            {
                foreach (Exception ex in exceptions.InnerExceptions)
                {
                    ErrorRecord record = new ErrorRecord(
                        ex,
                        ex.GetType().ToString(),
                        ErrorCategory.NotSpecified,
                        null);

                    WriteError(record);
                }
            }
            catch (Exception ex)
            {
                ErrorRecord record = new ErrorRecord(
                    ex,
                    ex.GetType().ToString(),
                    ErrorCategory.NotSpecified,
                    null);

                WriteError(record);
            }
        }