Exemple #1
0
        public void TestInitialize()
        {
            // Create property
            this.resource = new ResourceIdentifier(ResourceType.AzureStorage, "subscriptionId", "resourceGroupName", "storage1");
            this.property = new MetricChartAlertProperty(
                propertyName: "metric",
                displayName: "metric display",
                order: 1,
                metricName: "metric1",
                timeGrain: TimeSpan.FromMinutes(5),
                aggregationType: AggregationType.Sum)
            {
                StartTimeUtc    = new DateTime(2019, 4, 1, 10, 0, 0),
                EndTimeUtc      = new DateTime(2019, 4, 1, 12, 0, 0),
                MetricNamespace = "nameSpace",
                ResourceId      = this.resource.ToResourceId()
            };

            // Create metric data
            this.values     = Enumerable.Range(0, (int)((this.property.EndTimeUtc - this.property.StartTimeUtc).Value.Ticks / this.property.TimeGrain.Ticks)).Select(n => (double)n).ToList();
            this.timestamps = this.values.Select(n => new DateTime((long)(this.property.StartTimeUtc.Value.Ticks + (this.property.TimeGrain.Ticks * n)))).ToList();
            MetricQueryResult metricQueryResult = new MetricQueryResult("name", "unit", new List <MetricTimeSeries>()
            {
                new MetricTimeSeries(
                    this.timestamps.Zip(this.values, (t, v) => new MetricValues(t, v, v, v, v, 1)).ToList(),
                    new List <KeyValuePair <string, string> >()
                {
                })
            });

            // Mock metric client result
            this.metricClientMock = new Mock <IMetricClient>();
            this.metricClientMock
            .Setup(x => x.GetResourceMetricsAsync(this.resource.ToResourceId(), It.IsAny <QueryParameters>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((string resourceId, QueryParameters queryParameters, CancellationToken ct) =>
            {
                // Verify the query parameters
                Assert.AreEqual(Aggregation.Total, queryParameters.Aggregations.Single());
                Assert.AreEqual(TimeSpan.FromMinutes(5), queryParameters.Interval);
                Assert.AreEqual(new DateTime(2019, 4, 1, 10, 0, 0), queryParameters.StartTime);
                Assert.AreEqual(new DateTime(2019, 4, 1, 12, 0, 0), queryParameters.EndTime);
                Assert.AreEqual("metric1", queryParameters.MetricNames.Single());
                Assert.AreEqual("nameSpace", queryParameters.MetricNamespace);

                return(new[] { metricQueryResult });
            });

            this.analysisServicesFactoryMock = new Mock <IAnalysisServicesFactory>();
            this.analysisServicesFactoryMock
            .Setup(x => x.CreateMetricClientAsync(this.resource.SubscriptionId, It.IsAny <CancellationToken>()))
            .ReturnsAsync(this.metricClientMock.Object);

            this.tracerMock = new Mock <ITracer>();
        }
        /// <summary>
        /// Converts a metric query response to an internal DTO and returns it
        /// </summary>
        /// <param name="queryResponse">The metric query response as returned by Azure Monitoring</param>
        /// <returns>A list of metric query results</returns>
        private IList <MetricQueryResult> ConvertResponseToQueryResult(ResponseInner queryResponse)
        {
            var queryResults = new List <MetricQueryResult>();

            // Convert each metric (a single metric is created per metric name)
            foreach (Metric metric in queryResponse.Value)
            {
                List <MetricTimeSeries> timeSeriesList = new List <MetricTimeSeries>();

                if (metric.Timeseries != null)
                {
                    // Convert the time series. A time series is created per filtered dimension.
                    // The info regarding the relevant dimension is set int he MetaData field
                    foreach (TimeSeriesElement timeSeries in metric.Timeseries)
                    {
                        var data     = new List <MetricValues>();
                        var metaData = new List <KeyValuePair <string, string> >();

                        if (timeSeries.Data != null)
                        {
                            // Convert all metric values
                            data = timeSeries.Data.Select(metricValue =>
                                                          new MetricValues(metricValue.TimeStamp, metricValue.Average, metricValue.Minimum, metricValue.Maximum, metricValue.Total, metricValue.Count)).ToList();
                        }

                        if (timeSeries.Metadatavalues != null)
                        {
                            // Convert metadata
                            metaData = timeSeries.Metadatavalues.Select(metaDataValue =>
                                                                        new KeyValuePair <string, string>(metaDataValue.Name.Value, metaDataValue.Value)).ToList();
                        }

                        timeSeriesList.Add(new MetricTimeSeries(data, metaData));
                    }
                }

                var queryResult = new MetricQueryResult(metric.Name.Value, metric.Unit.ToString(), timeSeriesList);

                queryResults.Add(queryResult);
                this.tracer.TraceInformation($"Metric converted successfully. Name: {queryResult.Name}, Timeseries count: {queryResult.Timeseries.Count}, Total series length: {queryResult.Timeseries.Sum(timeSeries => timeSeries.Data.Count)}");
            }

            return(queryResults);
        }
Exemple #3
0
        /// <summary>
        /// Converts a <see cref="ResponseInner"/> to a list of <see cref="MetricQueryResult"/> and returns it
        /// </summary>
        /// <param name="queryResponse">The metric query response as returned by Azure Monitoring</param>
        /// <returns>A list of metric query results</returns>
        public static IList <MetricQueryResult> ToMetricQueryResult(this ResponseInner queryResponse)
        {
            var queryResults = new List <MetricQueryResult>();

            // Convert each metric (a single metric is created per metric name)
            foreach (Metric metric in queryResponse.Value)
            {
                List <MetricTimeSeries> timeSeriesList = new List <MetricTimeSeries>();

                if (metric.Timeseries != null)
                {
                    // Convert the time series. A time series is created per filtered dimension.
                    // The info regarding the relevant dimension is set int he MetaData field
                    foreach (TimeSeriesElement timeSeries in metric.Timeseries)
                    {
                        var data     = new List <MetricValues>();
                        var metaData = new List <KeyValuePair <string, string> >();

                        if (timeSeries.Data != null)
                        {
                            // Convert all metric values
                            data = timeSeries.Data.Select(metricValue =>
                                                          new MetricValues(metricValue.TimeStamp, metricValue.Average, metricValue.Minimum, metricValue.Maximum, metricValue.Total, metricValue.Count)).ToList();
                        }

                        if (timeSeries.Metadatavalues != null)
                        {
                            // Convert metadata
                            metaData = timeSeries.Metadatavalues.Select(metaDataValue =>
                                                                        new KeyValuePair <string, string>(metaDataValue.Name.Value, metaDataValue.Value)).ToList();
                        }

                        timeSeriesList.Add(new MetricTimeSeries(data, metaData));
                    }
                }

                var queryResult = new MetricQueryResult(metric.Name.Value, metric.Unit.ToString(), timeSeriesList);

                queryResults.Add(queryResult);
            }

            return(queryResults);
        }
Exemple #4
0
        public async Task <Response <MetricQueryResult> > ListAsync(string resourceUri, string timespan = null, TimeSpan?interval = null, string metricnames = null, string aggregation = null, int?top = null, string orderby = null, string filter = null, ResultType?resultType = null, string metricnamespace = null, CancellationToken cancellationToken = default)
        {
            if (resourceUri == null)
            {
                throw new ArgumentNullException(nameof(resourceUri));
            }

            using var message = CreateListRequest(resourceUri, timespan, interval, metricnames, aggregation, top, orderby, filter, resultType, metricnamespace);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);

            switch (message.Response.Status)
            {
            case 200:
            {
                MetricQueryResult value = default;
                using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);

                value = MetricQueryResult.DeserializeMetricQueryResult(document.RootElement);
                return(Response.FromValue(value, message.Response));
            }