示例#1
0
        public async Task <IEnumerable <Metric> > ListHealthChecksAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            var list = new List <Metric>();
            ListMetricsResponse response = null;

            while ((response = await _client.ListMetricsAsync(new ListMetricsRequest()
            {
                NextToken = response?.NextToken
            }, cancellationToken))?.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                if (!response.Metrics.IsNullOrEmpty())
                {
                    list.AddRange(response.Metrics);
                }

                if (response.NextToken.IsNullOrEmpty())
                {
                    break;
                }

                await Task.Delay(100);
            }

            response.EnsureSuccess();
            return(list);
        }
示例#2
0
        public static ListMetricsResponse Unmarshall(UnmarshallerContext _ctx)
        {
            ListMetricsResponse listMetricsResponse = new ListMetricsResponse();

            listMetricsResponse.HttpResponse = _ctx.HttpResponse;
            listMetricsResponse.Code         = _ctx.StringValue("ListMetrics.Code");
            listMetricsResponse.Message      = _ctx.StringValue("ListMetrics.Message");
            listMetricsResponse.RequestId    = _ctx.StringValue("ListMetrics.RequestId");
            listMetricsResponse.PageNumber   = _ctx.StringValue("ListMetrics.PageNumber");
            listMetricsResponse.PageSize     = _ctx.StringValue("ListMetrics.PageSize");
            listMetricsResponse.TotalCount   = _ctx.StringValue("ListMetrics.TotalCount");

            List <ListMetricsResponse.ListMetrics_DataItem> listMetricsResponse_data = new List <ListMetricsResponse.ListMetrics_DataItem>();

            for (int i = 0; i < _ctx.Length("ListMetrics.Data.Length"); i++)
            {
                ListMetricsResponse.ListMetrics_DataItem dataItem = new ListMetricsResponse.ListMetrics_DataItem();
                dataItem.DateTime  = _ctx.StringValue("ListMetrics.Data[" + i + "].DateTime");
                dataItem.TagCode   = _ctx.StringValue("ListMetrics.Data[" + i + "].TagCode");
                dataItem.TagValue  = _ctx.StringValue("ListMetrics.Data[" + i + "].TagValue");
                dataItem.TagMetric = _ctx.StringValue("ListMetrics.Data[" + i + "].TagMetric");
                dataItem.CorpId    = _ctx.StringValue("ListMetrics.Data[" + i + "].CorpId");

                listMetricsResponse_data.Add(dataItem);
            }
            listMetricsResponse.Data = listMetricsResponse_data;

            return(listMetricsResponse);
        }
        public async Task <List <Metric> > GetMetrics(string region, string nameSpace, string metric, List <string> dimensions)
        {
            cloudWatchRepository.Region = region;
            var dimensionFilter = new List <DimensionFilter>();

            dimensions.ForEach(x => {
                dimensionFilter.Add(new DimensionFilter()
                {
                    Name  = MonitoringConstants.nameSpaceIdentifiers[nameSpace],
                    Value = x
                });
            });
            var request = new ListMetricsRequest()
            {
                Namespace = nameSpace, MetricName = metric, Dimensions = dimensionFilter
            };
            var response = new ListMetricsResponse();

            do
            {
                response = await cloudWatchRepository.ListMetrics(request);

                request.NextToken = response.NextToken;
            } while (!string.IsNullOrEmpty(request.NextToken));

            return(response.Metrics);
        }
示例#4
0
        public static void InvokeListMetrics()
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            // Print the number of Amazon CloudWatch metrics.
            IAmazonCloudWatch cw = AWSClientFactory.CreateAmazonCloudWatchClient(RegionEndpoint.USWest2);

            try
            {
                ListMetricsResponse cwResponse = cw.ListMetrics(new ListMetricsRequest());

                int numMetrics = 0;
                numMetrics = cwResponse.Metrics.Count;
                Console.WriteLine("You have " + numMetrics + " Amazon CloudWatch metric(s).");
            }
            catch (AmazonCloudWatchException ex)
            {
                if (ex.ErrorCode.Equals("OptInRequired"))
                {
                    Console.WriteLine("You are not signed for Amazon EC2.");
                    Console.WriteLine("You can sign up at http://aws.amazon.com/ec2.");
                }
                else
                {
                    Console.WriteLine("Caught Exception: " + ex.Message);
                    Console.WriteLine("Response Status Code: " + ex.StatusCode);
                    Console.WriteLine("Error Code: " + ex.ErrorCode);
                    Console.WriteLine("Error Type: " + ex.ErrorType);
                    Console.WriteLine("Request ID: " + ex.RequestId);
                }
            }
            Console.WriteLine();
        }
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonCloudWatchConfig config = new AmazonCloudWatchConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonCloudWatchClient client = new AmazonCloudWatchClient(creds, config);

            ListMetricsResponse resp = new ListMetricsResponse();

            do
            {
                ListMetricsRequest req = new ListMetricsRequest
                {
                    NextToken = resp.NextToken
                };

                resp = client.ListMetrics(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.Metrics)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
        private static void UnmarshallResult(XmlUnmarshallerContext context, ListMetricsResponse response)
        {
            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

            if (context.IsStartOfDocument)
            {
                targetDepth += 2;
            }

            while (context.ReadAtDepth(originalDepth))
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("Metrics/member", targetDepth))
                    {
                        var unmarshaller = MetricUnmarshaller.Instance;
                        var item         = unmarshaller.Unmarshall(context);
                        response.Metrics.Add(item);
                        continue;
                    }
                    if (context.TestExpression("NextToken", targetDepth))
                    {
                        var unmarshaller = StringUnmarshaller.Instance;
                        response.NextToken = unmarshaller.Unmarshall(context);
                        continue;
                    }
                }
            }

            return;
        }
示例#7
0
        public static ListMetricsResponse Unmarshall(UnmarshallerContext context)
        {
            ListMetricsResponse listMetricsResponse = new ListMetricsResponse();

            listMetricsResponse.HttpResponse = context.HttpResponse;
            listMetricsResponse.Code         = context.StringValue("ListMetrics.Code");
            listMetricsResponse.Message      = context.StringValue("ListMetrics.Message");
            listMetricsResponse.RequestId    = context.StringValue("ListMetrics.RequestId");

            ListMetricsResponse.ListMetrics_Data data = new ListMetricsResponse.ListMetrics_Data();
            data.PageNumber = context.IntegerValue("ListMetrics.Data.PageNumber");
            data.PageSize   = context.IntegerValue("ListMetrics.Data.PageSize");
            data.TotalCount = context.IntegerValue("ListMetrics.Data.TotalCount");
            data.TotalPage  = context.IntegerValue("ListMetrics.Data.TotalPage");

            List <ListMetricsResponse.ListMetrics_Data.ListMetrics_RecordsItem> data_records = new List <ListMetricsResponse.ListMetrics_Data.ListMetrics_RecordsItem>();

            for (int i = 0; i < context.Length("ListMetrics.Data.Records.Length"); i++)
            {
                ListMetricsResponse.ListMetrics_Data.ListMetrics_RecordsItem recordsItem = new ListMetricsResponse.ListMetrics_Data.ListMetrics_RecordsItem();
                recordsItem.DateTime  = context.StringValue("ListMetrics.Data.Records[" + i + "].DateTime");
                recordsItem.TagCode   = context.StringValue("ListMetrics.Data.Records[" + i + "].TagCode");
                recordsItem.TagValue  = context.StringValue("ListMetrics.Data.Records[" + i + "].TagValue");
                recordsItem.TagMetric = context.StringValue("ListMetrics.Data.Records[" + i + "].TagMetric");

                data_records.Add(recordsItem);
            }
            data.Records             = data_records;
            listMetricsResponse.Data = data;

            return(listMetricsResponse);
        }
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            ListMetricsResponse response = new ListMetricsResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.IsStartElement)
                {
                    if (context.TestExpression("ListMetricsResult", 2))
                    {
                        UnmarshallResult(context, response);
                        continue;
                    }

                    if (context.TestExpression("ResponseMetadata", 2))
                    {
                        response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context);
                    }
                }
            }

            return(response);
        }
示例#9
0
        public static void CWListMetrics()
        {
            #region CWListMetrics
            var client = new AmazonCloudWatchClient();

            var filter = new DimensionFilter
            {
                Name  = "InstanceType",
                Value = "t1.micro"
            };

            var request = new ListMetricsRequest
            {
                Dimensions = new List <DimensionFilter>()
                {
                    filter
                },
                MetricName = "CPUUtilization",
                Namespace  = "AWS/EC2"
            };

            var response = new ListMetricsResponse();

            do
            {
                response = client.ListMetrics(request);

                if (response.Metrics.Count > 0)
                {
                    foreach (var metric in response.Metrics)
                    {
                        Console.WriteLine(metric.MetricName +
                                          " (" + metric.Namespace + ")");

                        foreach (var dimension in metric.Dimensions)
                        {
                            Console.WriteLine("  " + dimension.Name + ": "
                                              + dimension.Value);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No metrics found.");
                }

                request.NextToken = response.NextToken;
            } while (!string.IsNullOrEmpty(response.NextToken));
            #endregion

            Console.ReadLine();
        }
示例#10
0
        public override AsyncUnaryCall <ListMetricsResponse> ListMetricsAsync(ListMetricsRequest request, Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default)
        {
            DateTimeOffset endDateTime;

            if (string.IsNullOrEmpty(request.PageToken))
            {
                endDateTime = request.EndTime?.ToDateTimeOffset() ?? DateTimeOffset.UtcNow;
            }
            else
            {
                endDateTime = DateTimeOffset.Parse(request.PageToken, CultureInfo.InvariantCulture);
            }

            endDateTime = endDateTime.ToUniversalTime();
            var startDateTime = request.StartTime?.ToDateTime();

            var metrics = new List <Metric>(request.PageSize);

            for (int i = 0; i < request.PageSize; i++)
            {
                endDateTime = endDateTime.Subtract(TimeSpan.FromSeconds(5));
                if (startDateTime.HasValue && startDateTime > endDateTime)
                {
                    break;
                }

                metrics.Add(new Metric
                {
                    CreateTime = Timestamp.FromDateTimeOffset(endDateTime),
                    InputWaterCelsiusDegree            = RandomUtils.NextFloat(10, 20),
                    OutputWaterCelsiusDegree           = RandomUtils.NextFloat(10, 20),
                    HeaterOutputWaterCelsiusDegree     = RandomUtils.NextFloat(10, 20),
                    EnvironmentCelsiusDegree           = RandomUtils.NextFloat(10, 20),
                    HeaterPowerKilowatt                = RandomUtils.NextFloat(0, 12),
                    WaterPumpFlowRateCubicMeterPerHour = RandomUtils.NextFloat(1, 3),
                });
            }

            var response = new ListMetricsResponse
            {
                NextPageToken = endDateTime.ToUniversalTime().ToString(CultureInfo.InvariantCulture),
            };

            response.Metrics.AddRange(metrics);

            return(TestCalls.AsyncUnaryCall(
                       Task.FromResult(response),
                       Task.FromResult(new Metadata()),
                       () => Status.DefaultSuccess,
                       () => new Metadata(),
                       () => { }));
        }
示例#11
0
        public override Task <ListMetricsResponse> ListMetrics(ListMetricsRequest request, ServerCallContext context)
        {
            string id = BitConverter.ToString(request.DeviceId.ToByteArray());

            DateTimeOffset endDateTime;

            if (string.IsNullOrEmpty(request.PageToken))
            {
                endDateTime = request.EndTime?.ToDateTimeOffset() ?? DateTimeOffset.UtcNow;
            }
            else
            {
                endDateTime = DateTimeOffset.Parse(request.PageToken, CultureInfo.InvariantCulture);
            }

            endDateTime = endDateTime.ToUniversalTime();
            DateTimeOffset?startDateTime = request.StartTime?.ToDateTimeOffset().ToUniversalTime();

            var response = new ListMetricsResponse();

            using (BjdireContext db = this.serviceProvider.GetRequiredService <BjdireContext>())
            {
                var metrics = (from m in db.Metrics
                               where m.DeviceId == id &&
                               (startDateTime == null || startDateTime <= m.Timestamp) &&
                               m.Timestamp <= endDateTime
                               orderby m.Timestamp descending
                               select m)
                              .Take(request.PageSize)
                              .ToList();
                response.Metrics.AddRange(metrics.Select(metric =>
                {
                    var m = new GrpcMetric();
                    m.AssignFrom(metric);
                    return(m);
                }));

                if (metrics.Count == request.PageSize && metrics.Last().Timestamp > startDateTime)
                {
                    response.NextPageToken = metrics.Last().Timestamp
                                             .ToUniversalTime()
                                             .ToString(CultureInfo.InvariantCulture);
                }
            }

            return(Task.FromResult(response));
        }
        public async Task <List <Metric> > GetMetrics(string region, string nameSpace, string metric)
        {
            cloudWatchRepository.Region = region;
            var request = new ListMetricsRequest()
            {
                Namespace = nameSpace, MetricName = metric
            };
            var response = new ListMetricsResponse();

            do
            {
                response = await cloudWatchRepository.ListMetrics(request);

                request.NextToken = response.NextToken;
            } while (!string.IsNullOrEmpty(request.NextToken));

            return(response.Metrics);
        }
示例#13
0
        /// <summary>
        /// Retrieve CloudWatch metrics using the supplied filter, metrics name,
        /// and namespace.
        /// </summary>
        /// <param name="client">An initialized CloudWatch client.</param>
        /// <param name="filter">The filter to apply in retrieving metrics.</param>
        /// <param name="metricName">The metric name for which to retrieve
        /// information.</param>
        /// <param name="nameSpaceName">The name of the namespace from which
        /// to retrieve metric information.</param>
        public static async Task ListMetricsAsync(
            IAmazonCloudWatch client,
            DimensionFilter filter,
            string metricName,
            string nameSpaceName)
        {
            var request = new ListMetricsRequest
            {
                Dimensions = new List <DimensionFilter>()
                {
                    filter
                },
                MetricName = metricName,
                Namespace  = nameSpaceName,
            };

            var response = new ListMetricsResponse();

            do
            {
                response = await client.ListMetricsAsync(request);

                if (response.Metrics.Count > 0)
                {
                    foreach (var metric in response.Metrics)
                    {
                        Console.WriteLine(metric.MetricName +
                                          " (" + metric.Namespace + ")");

                        foreach (var dimension in metric.Dimensions)
                        {
                            Console.WriteLine("  " + dimension.Name + ": "
                                              + dimension.Value);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No metrics found.");
                }

                request.NextToken = response.NextToken;
            } while (!string.IsNullOrEmpty(response.NextToken));
        }
        public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            ListMetricsResponse response = new ListMetricsResponse();

            while (context.Read())
            {
                if (context.IsStartElement)
                {
                    if (context.TestExpression("ListMetricsResult", 2))
                    {
                        response.ListMetricsResult = ListMetricsResultUnmarshaller.GetInstance().Unmarshall(context);
                        continue;
                    }
                    if (context.TestExpression("ResponseMetadata", 2))
                    {
                        response.ResponseMetadata = ResponseMetadataUnmarshaller.GetInstance().Unmarshall(context);
                    }
                }
            }


            return(response);
        }
示例#15
0
        /// <summary>
        /// 查询系统当前可监控指标列表,可以指定指标命名空间、指标名称、维度、排序方式,起始记录和最大记录条数过滤查询结果。
        /// </summary>
        /// <param name="cesV1Client"></param>
        private static void ListMetrics(CesClient cesClient)
        {
            ListMetricsRequest listMetricsRequest = new ListMetricsRequest()
            {
                MetricName = "cpu_util",
                Namespace  = "SYS.ECS",
                // Dim0 = "",
                // Dim1 = "",
                // Dim2 = "",
                // Start = "",
                Limit = 100,
                Order = ListMetricsRequest.OrderEnum.ASC
            };

            try
            {
                ListMetricsResponse metricList = cesClient.ListMetrics(listMetricsRequest);
                foreach (var metric in metricList.Metrics)
                {
                    Console.WriteLine(metric.ToString());
                }
            }
            catch (RequestTimeoutException requestTimeoutException)
            {
                Console.WriteLine(requestTimeoutException.ErrorMessage);
            }
            catch (ServiceResponseException clientRequestException)
            {
                Console.WriteLine(clientRequestException.HttpStatusCode);
                Console.WriteLine(clientRequestException.ErrorCode);
                Console.WriteLine(clientRequestException.ErrorMsg);
            }
            catch (ConnectionException connectionException)
            {
                Console.WriteLine(connectionException.ErrorMessage);
            }
        }
示例#16
0
        private static void UnmarshallResult(XmlUnmarshallerContext context, ListMetricsResponse response)
        {
            int originalDepth = context.CurrentDepth;
            int targetDepth   = originalDepth + 1;

            if (context.IsStartOfDocument)
            {
                targetDepth += 2;
            }

            while (context.Read())
            {
                if (context.IsStartElement || context.IsAttribute)
                {
                    if (context.TestExpression("Metrics/member", targetDepth))
                    {
                        response.Metrics.Add(MetricUnmarshaller.GetInstance().Unmarshall(context));

                        continue;
                    }
                    if (context.TestExpression("NextToken", targetDepth))
                    {
                        response.NextToken = StringUnmarshaller.GetInstance().Unmarshall(context);

                        continue;
                    }
                }
                else if (context.IsEndElement && context.CurrentDepth < originalDepth)
                {
                    return;
                }
            }



            return;
        }
示例#17
0
        public void ListMetricResponse()
        {
            var text = @"
<ListMetricsResponse xmlns=""http://monitoring.amazonaws.com/doc/2010-08-01/"">
  <ListMetricsResult>
    <Metrics>
      <member>
        <Namespace>AWS/ELB</Namespace>
        <MetricName>BackendConnectionErrors</MetricName>
        <Dimensions>
          <member>
            <Name>Namespace</Name>
            <Value>AWS</Value>
          </member>
        </Dimensions>
      </member>
      <member>
        <Namespace>AWS/ELB</Namespace>
        <MetricName>HTTPCode_ELB_5XX</MetricName>
        <Dimensions>
          <member>
            <Name>Namespace</Name>
            <Value>AWS</Value>
          </member>
        </Dimensions>
      </member>
      <member>
        <Namespace>AWS/ELB</Namespace>
        <MetricName>HealthyHostCount</MetricName>
        <Dimensions>
          <member>
            <Name>Namespace</Name>
            <Value>AWS</Value>
          </member>
        </Dimensions>
      </member>
      <member>
        <Namespace>AWS/ELB</Namespace>
        <MetricName>HTTPCode_Backend_2XX</MetricName>
        <Dimensions>
          <member>
            <Name>Namespace</Name>
            <Value>AWS</Value>
          </member>
        </Dimensions>
      </member>
      <member>
        <Namespace>AWS/ELB</Namespace>
        <MetricName>UnHealthyHostCount</MetricName>
        <Dimensions>
          <member>
            <Name>Namespace</Name>
            <Value>AWS</Value>
          </member>
        </Dimensions>
      </member>
      <member>
        <Namespace>AWS/ELB</Namespace>
        <MetricName>SurgeQueueLength</MetricName>
        <Dimensions>
          <member>
            <Name>Namespace</Name>
            <Value>AWS</Value>
          </member>
        </Dimensions>
      </member>
      <member>
        <Namespace>AWS/ELB</Namespace>
        <MetricName>HTTPCode_Backend_5XX</MetricName>
        <Dimensions>
          <member>
            <Name>Namespace</Name>
            <Value>AWS</Value>
          </member>
        </Dimensions>
      </member>
      <member>
        <Namespace>AWS/ELB</Namespace>
        <MetricName>HTTPCode_Backend_4XX</MetricName>
        <Dimensions>
          <member>
            <Name>Namespace</Name>
            <Value>AWS</Value>
          </member>
        </Dimensions>
      </member>
      <member>
        <Namespace>AWS/ELB</Namespace>
        <MetricName>HTTPCode_Backend_3XX</MetricName>
        <Dimensions>
          <member>
            <Name>Namespace</Name>
            <Value>AWS</Value>
          </member>
        </Dimensions>
      </member>
      <member>
        <Namespace>AWS/ELB</Namespace>
        <MetricName>Latency</MetricName>
        <Dimensions>
          <member>
            <Name>Namespace</Name>
            <Value>AWS</Value>
          </member>
        </Dimensions>
      </member>
      <member>
        <Namespace>AWS/ELB</Namespace>
        <MetricName>RequestCount</MetricName>
        <Dimensions>
          <member>
            <Name>Namespace</Name>
            <Value>AWS</Value>
          </member>
        </Dimensions>
      </member>
    </Metrics>
  </ListMetricsResult>
  <ResponseMetadata>
    <RequestId>c919ffb2-a13d-11e6-994f-1d1bb7ed25dd</RequestId>
  </ResponseMetadata>
</ListMetricsResponse>";


            var result = ListMetricsResponse.Parse(text);


            Assert.Equal(11, result.Count);

            /*
             * <member>
             * <Namespace>AWS/ELB</Namespace>
             * <MetricName>BackendConnectionErrors</MetricName>
             * <Dimensions>
             * <member>
             * <Name>Namespace</Name>
             * <Value>AWS</Value>
             * </member>
             * </Dimensions>
             * </member>
             */

            Assert.Equal("AWS/ELB", result[0].Namespace);
            Assert.Equal("BackendConnectionErrors", result[0].MetricName);
            Assert.Equal(1, result[0].Dimensions.Count);
            Assert.Equal("Namespace", result[0].Dimensions[0].Name);
            Assert.Equal("AWS", result[0].Dimensions[0].Value);
        }
        public void Setup()
        {
            _firstPage = new ListMetricsResponse
            {
                NextToken = "token-1",
                Metrics   = new List <Metric>
                {
                    new Metric
                    {
                        MetricName = "GetRecords.IteratorAgeMilliseconds",
                        Dimensions = new List <Dimension>
                        {
                            new Dimension
                            {
                                Name  = "StreamName",
                                Value = "Stream-1"
                            }
                        }
                    }
                }
            };
            _secondPage = new ListMetricsResponse
            {
                NextToken = "token-2",
                Metrics   = new List <Metric>
                {
                    new Metric
                    {
                        MetricName = "GetRecords.IteratorAgeMilliseconds",
                        Dimensions = new List <Dimension>
                        {
                            new Dimension
                            {
                                Name  = "StreamName",
                                Value = "Stream-2"
                            }
                        }
                    }
                }
            };
            _thirdPage = new ListMetricsResponse
            {
                Metrics = new List <Metric>
                {
                    new Metric
                    {
                        MetricName = "GetRecords.IteratorAgeMilliseconds",
                        Dimensions = new List <Dimension>
                        {
                            new Dimension
                            {
                                Name  = "StreamName",
                                Value = "Stream-3"
                            }
                        }
                    }
                }
            };

            var cloudWatchMock = new Mock <IAmazonCloudWatch>();

            cloudWatchMock.Setup(s => s.ListMetricsAsync(
                                     It.Is <ListMetricsRequest>(r => r.MetricName == "GetRecords.IteratorAgeMilliseconds" && r.NextToken == null),
                                     It.IsAny <CancellationToken>()))
            .ReturnsAsync(_firstPage);

            cloudWatchMock.Setup(s => s.ListMetricsAsync(
                                     It.Is <ListMetricsRequest>(r => r.MetricName == "GetRecords.IteratorAgeMilliseconds" && r.NextToken == "token-1"),
                                     It.IsAny <CancellationToken>()))
            .ReturnsAsync(_secondPage);

            cloudWatchMock.Setup(s => s.ListMetricsAsync(
                                     It.Is <ListMetricsRequest>(r => r.MetricName == "GetRecords.IteratorAgeMilliseconds" && r.NextToken == "token-2"),
                                     It.IsAny <CancellationToken>()))
            .ReturnsAsync(_thirdPage);

            _streamSource = new KinesisStreamSource(cloudWatchMock.Object);
        }
示例#19
0
        public void Setup()
        {
            _firstPage = new ListMetricsResponse
            {
                NextToken = "token-1",
                Metrics   = new List <Metric>
                {
                    new Metric
                    {
                        MetricName = "ApproximateAgeOfOldestMessage",
                        Dimensions = new List <Dimension>
                        {
                            new Dimension
                            {
                                Name  = "QueueName",
                                Value = "Queue-1"
                            }
                        }
                    }
                }
            };
            _secondPage = new ListMetricsResponse
            {
                NextToken = "token-2",
                Metrics   = new List <Metric>
                {
                    new Metric
                    {
                        MetricName = "ApproximateAgeOfOldestMessage",
                        Dimensions = new List <Dimension>
                        {
                            new Dimension
                            {
                                Name  = "QueueName",
                                Value = "Queue-2"
                            }
                        }
                    }
                }
            };
            _thirdPage = new ListMetricsResponse
            {
                NextToken = "token-3",
                Metrics   = new List <Metric>
                {
                    new Metric
                    {
                        MetricName = "ApproximateAgeOfOldestMessage",
                        Dimensions = new List <Dimension>
                        {
                            new Dimension
                            {
                                Name  = "QueueName",
                                Value = "Queue-3"
                            }
                        }
                    }
                }
            };

            _attributes = new Dictionary <string, string>
            {
                { "AttrName", "AttrValue" }
            };

            var cloudWatchMock = new Mock <IAmazonCloudWatch>();

            cloudWatchMock.Setup(s => s.ListMetricsAsync(
                                     It.Is <ListMetricsRequest>(r => r.MetricName == "ApproximateAgeOfOldestMessage" && r.NextToken == null),
                                     It.IsAny <CancellationToken>()))
            .ReturnsAsync(_firstPage);

            cloudWatchMock.Setup(s => s.ListMetricsAsync(
                                     It.Is <ListMetricsRequest>(r => r.MetricName == "ApproximateAgeOfOldestMessage" && r.NextToken == "token-1"),
                                     It.IsAny <CancellationToken>()))
            .ReturnsAsync(_secondPage);

            cloudWatchMock.Setup(s => s.ListMetricsAsync(
                                     It.Is <ListMetricsRequest>(r => r.MetricName == "ApproximateAgeOfOldestMessage" && r.NextToken == "token-2"),
                                     It.IsAny <CancellationToken>()))
            .ReturnsAsync(_thirdPage);


            _queueSource = new QueueSource(cloudWatchMock.Object);
        }
示例#20
0
        private static string GetResourceName(ListMetricsResponse metrics)
        {
            var queueName = metrics.Metrics.SelectMany(i => i.Dimensions).First(i => i.Name == "QueueName").Value;

            return(TrimEnd(queueName, "_error", StringComparison.OrdinalIgnoreCase));
        }