/// <summary>
        /// Initiates an asynchronous operation for running the Smart Detector analysis on the specified resources.
        /// </summary>
        /// <param name="analysisRequest">The analysis request data.</param>
        /// <param name="tracer">
        /// A tracer used for emitting telemetry from the Smart Detector's execution. This telemetry will be used for troubleshooting and
        /// monitoring the Smart Detector's executions.
        /// </param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe while waiting for a task to complete.</param>
        /// <returns>
        /// A <see cref="Task"/> that represents the asynchronous operation, returning the Alerts detected for the target resources.
        /// </returns>
        public async Task <List <Alert> > AnalyzeResourcesAsync(AnalysisRequest analysisRequest, ITracer tracer, CancellationToken cancellationToken)
        {
            tracer.TraceInformation("Analyzing the specified resources...");

            // Get the metrics client
            IMetricClient metricsClient = await analysisRequest.AnalysisServicesFactory.CreateMetricClientAsync(analysisRequest.TargetResources.First(), cancellationToken);

            // Get the resource metrics. In the example below, the requested metric values are the total number of messages
            // in the storage queue over the last day, in hourly interval
            var parameters = new QueryParameters()
            {
                StartTime    = DateTime.UtcNow.Date.AddDays(-1),
                EndTime      = DateTime.UtcNow.Date,
                Aggregations = new List <Aggregation> {
                    Aggregation.Total
                },
                MetricName = "QueueMessageCount",
                Interval   = TimeSpan.FromMinutes(60)
            };

            IEnumerable <MetricQueryResult> metrics = (await metricsClient.GetResourceMetricsAsync(ServiceType.AzureStorageQueue, parameters, default(CancellationToken)));

            // Process the resource metric values and create alerts
            List <Alert> alerts = new List <Alert>();

            if (metrics.Count() > 0)
            {
                alerts.Add(new $alertName$("Title", analysisRequest.RequestParameters.First()));
            }

            tracer.TraceInformation($"Created {alerts.Count()} alerts");
            return(alerts);
        }
        public async Task WhenCreatingMetricClientThenItIsCreatedSuccessfully()
        {
            IAnalysisServicesFactory factory = new AnalysisServicesFactory(this.tracerMock.Object, this.httpClientWrapperMock.Object, this.credentialsFactoryMock.Object, this.azureResourceManagerClientMock.Object);
            IMetricClient            client  = await factory.CreateMetricClientAsync(SubscriptionId, default(CancellationToken));

            Assert.IsNotNull(client);
            Assert.IsTrue(client is MetricClient);
        }
Пример #3
0
 public StackDriverClient(IErrorReportingClient errorReportingClient, IMetricClient metricClient)
 {
     ErrorReporting = errorReportingClient;
     Metric         = metricClient;
 }
 public void SetUp()
 {
     _metricClient = MockRepository.GenerateMock<IMetricClient>();
     _clientFactory = MockRepository.GenerateMock<ICoreClientFactory>();
     _metricRepository = MockRepository.GenerateStub<IMetricRepository>();
     _service = new MetricService(_clientFactory, _metricRepository);
 }
        /// <summary>
        /// Read the metric values
        /// </summary>
        /// <returns>A <see cref="Task"/>, running the current operation, returning the metric values as a <see cref="LineSeries"/></returns>
        private async Task <ChartValues <DateTimePoint> > ReadChartValuesAsync()
        {
            CancellationToken cancellationToken = CancellationToken.None;

            // Verify start/end times
            DateTime startTime = this.metricChartAlertProperty.StartTimeUtc ?? throw new ApplicationException("Start time cannot be null");
            DateTime endTime   = this.metricChartAlertProperty.EndTimeUtc ?? throw new ApplicationException("End time cannot be null");

            if (endTime > DateTime.UtcNow)
            {
                endTime = DateTime.UtcNow;
            }

            // Convert from aggregation type to aggregation
            Aggregation aggregation;

            switch (this.metricChartAlertProperty.AggregationType)
            {
            case AggregationType.Average:
                aggregation = Aggregation.Average;
                break;

            case AggregationType.Count:
                aggregation = Aggregation.Count;
                break;

            case AggregationType.Sum:
                aggregation = Aggregation.Total;
                break;

            case AggregationType.Maximum:
                aggregation = Aggregation.Maximum;
                break;

            case AggregationType.Minimum:
                aggregation = Aggregation.Minimum;
                break;

            default:
                throw new ApplicationException($"Invalid aggregation type {this.metricChartAlertProperty.AggregationType}");
            }

            // Create the metrics client
            ResourceIdentifier resource     = ResourceIdentifier.CreateFromResourceId(this.metricChartAlertProperty.ResourceId);
            IMetricClient      metricClient = await this.analysisServicesFactory.CreateMetricClientAsync(resource.SubscriptionId, cancellationToken)
                                              .ConfigureAwait(false);

            // Send a metric query using the metric client
            IEnumerable <MetricQueryResult> metricQueryResults = await metricClient.GetResourceMetricsAsync(
                this.metricChartAlertProperty.ResourceId,
                new QueryParameters()
            {
                MetricNamespace = this.metricChartAlertProperty.MetricNamespace,
                MetricNames     = new List <string>()
                {
                    this.metricChartAlertProperty.MetricName
                },
                StartTime    = startTime,
                EndTime      = endTime,
                Interval     = this.metricChartAlertProperty.TimeGrain,
                Aggregations = new List <Aggregation>()
                {
                    aggregation
                },
            },
                cancellationToken)
                                                                 .ConfigureAwait(false);

            // Get chart points
            ChartValues <DateTimePoint> values = new ChartValues <DateTimePoint>(
                metricQueryResults
                .Single()
                .Timeseries
                .Single()
                .Data
                .Select(p => new DateTimePoint(p.TimeStamp, p.GetValue(aggregation))));

            return(values);
        }