コード例 #1
0
        protected override void InitializeTarget()
        {
            base.InitializeTarget();

            InternalLogger.Debug("Initialising AWSCloudWatch '{0}' target", Endpoint);

            try
            {
                if (string.IsNullOrEmpty(AwsAccessKey) || string.IsNullOrEmpty(AwsSecretAccessKey))
                {
                    InternalLogger.Info("AWS Access Keys are not specified. Use Application Setting or EC2 Instance profile for keys.");
                    client = AWSClientFactory.CreateAmazonCloudWatchClient(RegionEndpoint.GetBySystemName(Endpoint));
                }
                else
                {
                    client = AWSClientFactory.CreateAmazonCloudWatchClient(AwsAccessKey, AwsSecretAccessKey, RegionEndpoint.GetBySystemName(Endpoint));
                }
            }
            catch (Exception e)
            {
                InternalLogger.Fatal("Amazon CloudWatch client failed to be configured and won't send any messages. Error is\n{0}\n{1}", e.Message, e.StackTrace);
            }

            InternalLogger.Debug("Initialised AWSCloudWatch '{0}' target", Endpoint);
        }
コード例 #2
0
        public static IAmazonCloudWatch GetCloudWatchConnection()
        {
            if (cloudWatch == null)
            {
                cloudWatch = AWSClientFactory.CreateAmazonCloudWatchClient(AwsKeyProviders.Key, AwsKeyProviders.Secret, RegionEndpoint.EUWest1);
            }

            return cloudWatch;
            ;
        }
コード例 #3
0
        /// <summary>
        /// Disable the actions for the list of CloudWatch alarm names passed
        /// in the alarmNames parameter.
        /// </summary>
        /// <param name="client">An initialized CloudWatch client object.</param>
        /// <param name="alarmNames">The list of CloudWatch alarms to disable.</param>
        /// <returns>A Boolean value indicating the success of the call.</returns>
        public static async Task <bool> DisableAlarmsActionsAsync(
            IAmazonCloudWatch client,
            List <string> alarmNames)
        {
            var request = new DisableAlarmActionsRequest
            {
                AlarmNames = alarmNames,
            };

            var response = await client.DisableAlarmActionsAsync(request);

            return(response.HttpStatusCode == System.Net.HttpStatusCode.OK);
        }
コード例 #4
0
        public Worker(
            IAmazonCloudWatch awsCloudWatchClient,
            IManagementClient rabbitMqClient,
            ILogger <Worker> logger,
            IOptionsMonitor <WorkerOptions> options
            )
        {
            _awsCloudWatchClient = awsCloudWatchClient;
            _rabbitMqClient      = rabbitMqClient;
            _logger = logger;

            _interval = options.CurrentValue.Interval;
        }
コード例 #5
0
        public async Task Test1()
        {
            ILambdaContext    context    = new TestLambdaContext();
            IAmazonCloudWatch cloudwatch = Substitute.For <IAmazonCloudWatch>();

            var function = new Function(cloudwatch);

            SimpleFunctionArgs args = new SimpleFunctionArgs {
                Name = "ProjectBaseName"
            };
            SimpleFunctionResult result = await function.Handler(args, context);

            Assert.Equal("Hello, ProjectBaseName", result.Message);
        }
コード例 #6
0
        private const int FLUSH_QUEUE_DELAY = 100; //Throttle at about 10 TPS

        public CloudWatchSink(int defaultInterval, IPlugInContext context, IAmazonCloudWatch cloudWatchClient) : base(defaultInterval, context)
        {
            _cloudWatchClient   = cloudWatchClient;
            _defaultRetryPolicy = new DefaultRetryPolicy(_cloudWatchClient.Config);

            //StorageResolution is used to specify standard or high-resolution metrics. Valid values are 1 and 60
            //It is different to interval.
            //See https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html for full details
            _storageResolution = base._interval < 60 ? 1 : 60;

            string dimensionsConfig = null;

            if (_config != null)
            {
                dimensionsConfig = _config["dimensions"];
                _namespace       = _config["namespace"];
            }
            if (!string.IsNullOrEmpty(dimensionsConfig))
            {
                List <Dimension> dimensions     = new List <Dimension>();
                string[]         dimensionPairs = dimensionsConfig.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var dimensionPair in dimensionPairs)
                {
                    string[] keyValue = dimensionPair.Split('=');
                    string   value    = ResolveVariables(keyValue[1]);
                    dimensions.Add(new Dimension()
                    {
                        Name = keyValue[0], Value = value
                    });
                }
                _dimensions = dimensions.ToArray();
            }
            else
            {
                _dimensions = DefaultDimensions;
            }

            if (string.IsNullOrEmpty(_namespace))
            {
                _namespace = "KinesisTap";
            }
            else
            {
                _namespace = ResolveVariables(_namespace);
            }
        }
コード例 #7
0
            public async Task ShouldReportMetricDataToCloudWatchWithValue(
                IMetric <double> metric,
                [Frozen, Substitute] IAmazonCloudWatch cloudwatch,
                [Target] CloudWatchMetricReporter reporter
                )
            {
                var cancellationToken = new CancellationToken(false);

                await reporter.Report(metric, cancellationToken);

                await cloudwatch.Received().PutMetricDataAsync(Any <PutMetricDataRequest>(), Any <CancellationToken>());

                var request = (PutMetricDataRequest)cloudwatch.ReceivedCalls().ElementAt(0).GetArguments()[0];

                request.MetricData.Should().Contain(data =>
                                                    data.Value == metric.Value
                                                    );
            }
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (this.cloudWatchClient != null)
                    {
                        this.cloudWatchClient.Dispose();
                        this.cloudWatchClient = null;
                    }

                    this.sender = null;
                }

                _disposed = true;
            }
        }
コード例 #9
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));
        }
コード例 #10
0
            public async Task ShouldReportMetricDataToCloudWatchWithNamespace(
                string metricNamespace,
                IMetric <double> metric,
                [Frozen, Options] IOptions <MetricOptions> options,
                [Frozen, Substitute] IAmazonCloudWatch cloudwatch,
                [Target] CloudWatchMetricReporter reporter
                )
            {
                var cancellationToken = new CancellationToken(false);

                options.Value.Namespace = metricNamespace;

                await reporter.Report(metric, cancellationToken);

                await cloudwatch.Received().PutMetricDataAsync(Any <PutMetricDataRequest>(), Any <CancellationToken>());

                var request = (PutMetricDataRequest)cloudwatch.ReceivedCalls().ElementAt(0).GetArguments()[0];

                request.Namespace.Should().Be(metricNamespace);
            }
コード例 #11
0
        static void Main(string[] args)
        {
            PerformanceCounter percentPageFile = new PerformanceCounter("Paging File", "% Usage", "_Total");
            PerformanceCounter peakPageFile    = new PerformanceCounter("Paging File", "% Usage Peak", "_Total");


            IAmazonCloudWatch client = Amazon.AWSClientFactory.CreateAmazonCloudWatchClient(RegionEndpoint.USWest2);

            // Once a minute, send paging file usage statistics to CloudWatch
            for (; ;)
            {
                List <MetricDatum> data = new List <MetricDatum>();

                data.Add(new MetricDatum()
                {
                    MetricName = "PagingFilePctUsage",
                    Timestamp  = DateTime.Now,
                    Unit       = StandardUnit.Percent,
                    Value      = percentPageFile.NextValue()
                });

                data.Add(new MetricDatum()
                {
                    MetricName = "PagingFilePctUsagePeak",
                    Timestamp  = DateTime.Now,
                    Unit       = StandardUnit.Percent,
                    Value      = peakPageFile.NextValue()
                });


                client.PutMetricData(new PutMetricDataRequest()
                {
                    MetricData = data,
                    Namespace  = "System/Windows"
                });

                Thread.Sleep(1000 * 60);
            }
        }
コード例 #12
0
 private Amazon.CloudWatch.Model.PutDashboardResponse CallAWSServiceOperation(IAmazonCloudWatch client, Amazon.CloudWatch.Model.PutDashboardRequest request)
 {
     Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon CloudWatch", "PutDashboard");
     try
     {
         #if DESKTOP
         return(client.PutDashboard(request));
         #elif CORECLR
         return(client.PutDashboardAsync(request).GetAwaiter().GetResult());
         #else
                 #error "Unknown build edition"
         #endif
     }
     catch (AmazonServiceException exc)
     {
         var webException = exc.InnerException as System.Net.WebException;
         if (webException != null)
         {
             throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
         }
         throw;
     }
 }
コード例 #13
0
        /// <summary>
        /// Delete the alarms whose names are listed in the alarmNames parameter.
        /// </summary>
        /// <param name="client">The initialized Amazon CloudWatch client.</param>
        /// <param name="alarmNames">A list of names for the alarms to be
        /// deleted.</param>
        public static async Task DeleteAlarmsAsyncExample(IAmazonCloudWatch client, List <string> alarmNames)
        {
            var request = new DeleteAlarmsRequest
            {
                AlarmNames = alarmNames,
            };

            try
            {
                var response = await client.DeleteAlarmsAsync(request);

                if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
                {
                    Console.WriteLine("Alarms successfully deleted:");
                    alarmNames
                    .ForEach(name => Console.WriteLine($"{name}"));
                }
            }
            catch (ResourceNotFoundException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
コード例 #14
0
 public QueueDataV2Source(IAmazonCloudWatch amazonCloudWatch)
 {
     _amazonCloudWatch = amazonCloudWatch;
 }
コード例 #15
0
 internal CloudWatchPaginatorFactory(IAmazonCloudWatch client)
 {
     this.client = client;
 }
コード例 #16
0
        public CloudWatchClient()
        {
            var aws = CManager.Settings.AWS;

            _service = AWSClientFactory.CreateAmazonCloudWatchClient(aws.AccessKey, aws.SecretAccessKey, RegionEndpoint.GetBySystemName(aws.RegionEndpoint));
        }
コード例 #17
0
 static Metrics()
 {
     _data             = new List <MetricDatum>();
     _amazonCloudWatch = new AmazonCloudWatchClient(RegionEndpoint.EUWest1);
 }
コード例 #18
0
 internal GetMetricDataPaginator(IAmazonCloudWatch client, GetMetricDataRequest request)
 {
     this._client  = client;
     this._request = request;
 }
コード例 #19
0
        /// <summary>
        /// Get the list of available dashboards.
        /// </summary>
        /// <param name="client">The initialized CloudWatch client used to
        /// retrieve a list of defined dashboards.</param>
        /// <returns>A list of DashboardEntry objects.</returns>
        public static async Task <List <DashboardEntry> > ListDashboardsAsync(IAmazonCloudWatch client)
        {
            var response = await client.ListDashboardsAsync(new ListDashboardsRequest());

            return(response.DashboardEntries);
        }
コード例 #20
0
 internal DescribeAlarmsPaginator(IAmazonCloudWatch client, DescribeAlarmsRequest request)
 {
     this._client  = client;
     this._request = request;
 }
コード例 #21
0
 public CloudWatchDynamoDbTableMetricsClient(IAmazonCloudWatch client)
 {
     this.client = client;
 }
        public void Start(CounterSampleSenderBase sender)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("Resource was disposed.");
            }

            if (this.sender != null)
            {
                throw new InvalidOperationException("Already started(), can't call for second time");
            }

            this.sender = sender;

            if (this.sender.SendInterval < MinSendInterval)
            {
                throw new ArgumentOutOfRangeException("sender", "sender.SendInterval is out of range. Min value is " + MinSendInterval);
            }

            // Dimension of InstanceId
            if (!String.IsNullOrEmpty(this.settings.AWSInstanceIdLookupUrl))
            {
                try
                {
                    this.instanceId = new WebClient().DownloadString(this.settings.AWSInstanceIdLookupUrl);
                }
                catch (Exception e)
                {
                    // This will fail if running machine is not in AWS EC2
                    Log.Error(e);
                    Log.WarnFormat(
                        "Failed to retrieve AWS instance id. Use hostname {0} instead. Lookup URL was: {1}",
                        this.instanceId,
                        this.settings.AWSInstanceIdLookupUrl);
                }
            }

            // Dimension of AutoScalingGroup
            if (!String.IsNullOrEmpty(this.settings.AutoScalingConfigFilePath))
            {
                try
                {
                    var autoScalingConfigFile = new FileInfo(this.settings.AutoScalingConfigFilePath);
                    if (!autoScalingConfigFile.Exists)
                    {
                        Log.WarnFormat("AutoScalingConfigFile not found: {0}",
                                       this.settings.AutoScalingConfigFilePath);
                    }
                    else
                    {
                        using (var sr = new StreamReader(autoScalingConfigFile.FullName))
                        {
                            this.autoScalingGroupName = sr.ReadToEnd().Trim();
                        }

                        Log.InfoFormat(
                            "AutoScalingGroupName {0} read from config file {1}",
                            this.autoScalingGroupName,
                            autoScalingConfigFile.FullName);
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    Log.WarnFormat(
                        "Failed to read AutoScalingGroupName from config file {0}",
                        this.settings.AutoScalingConfigFilePath);
                }
            }

            // Amazon AWS CloudWatch Client init
            this.cloudWatchClient =
                new AmazonCloudWatchClient(
                    this.settings.AWSCloudWatchAccessKey,
                    this.settings.AWSCloudWatchSecretKey, new AmazonCloudWatchConfig
            {
                ServiceURL = this.settings.AWSCloudWatchServiceUrl.OriginalString
            });
        }
コード例 #23
0
 public KinesisStreamSource(IAmazonCloudWatch amazonCloudWatch)
 {
     _amazonCloudWatch = amazonCloudWatch;
 }
コード例 #24
0
 public AutoScalingGroupAlarmDataProvider(IAmazonCloudWatch cloudWatch, ICurrentTimeProvider timeProvider = null)
 {
     _cloudWatch   = cloudWatch;
     _timeProvider = timeProvider ?? new CurrentTimeProvider();
 }
コード例 #25
0
 public CloudWatchExecutionTimeService(RequestDelegate next, ILogger <CloudWatchExecutionTimeService> logger, IAmazonCloudWatch amazonCloudWatch)
 {
     _next             = next;
     _logger           = logger;
     _amazonCloudWatch = amazonCloudWatch;
 }
コード例 #26
0
 internal DescribeInsightRulesPaginator(IAmazonCloudWatch client, DescribeInsightRulesRequest request)
 {
     this._client  = client;
     this._request = request;
 }
コード例 #27
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            Client = CreateClient(_CurrentCredentials, _RegionEndpoint);
        }
コード例 #28
0
 internal ListDashboardsPaginator(IAmazonCloudWatch client, ListDashboardsRequest request)
 {
     this._client  = client;
     this._request = request;
 }
コード例 #29
0
 public PlatformLogsController(PlatformResourcesContext context, UserManager <IdentityUser> userManager, IAmazonCloudWatch cloudwatchClient, IAmazonCloudWatchEvents cloudwatcheventsClient, IAmazonCloudWatchLogs cloudwatchLogsClient)
 {
     this._context               = context;
     this.CloudwatchClient       = cloudwatchClient;
     this.CloudwatchEventsClient = cloudwatcheventsClient;
     this.CloudwatchLogsClient   = cloudwatchLogsClient;
     this._userManager           = userManager;
 }
コード例 #30
0
 internal ListMetricsPaginator(IAmazonCloudWatch client, ListMetricsRequest request)
 {
     this._client  = client;
     this._request = request;
 }
コード例 #31
0
        public HomeController(IAmazonCloudWatch cloudwatchClient)
        {
            this.CloudwatchClient = cloudwatchClient;

            var dimension = new Dimension
            {
                Name  = "Desktop Machine Metrics",
                Value = "Virtual Desktop Machine Usage"
            };

            var metric1 = new MetricDatum
            {
                Dimensions      = new List <Dimension>(),
                MetricName      = "Desktop Machines Online",
                StatisticValues = new StatisticSet(),
                Timestamp       = DateTime.Today,
                Unit            = StandardUnit.Count,
                Value           = 14
            };

            var metric2 = new MetricDatum
            {
                Dimensions      = new List <Dimension>(),
                MetricName      = "Desktop Machines Offline",
                StatisticValues = new StatisticSet(),
                Timestamp       = DateTime.Today,
                Unit            = StandardUnit.Count,
                Value           = 7
            };

            var metric3 = new MetricDatum
            {
                Dimensions      = new List <Dimension>(),
                MetricName      = "Desktop Machines Online",
                StatisticValues = new StatisticSet(),
                Timestamp       = DateTime.Today,
                Unit            = StandardUnit.Count,
                Value           = 12
            };

            var metric4 = new MetricDatum
            {
                Dimensions      = new List <Dimension>(),
                MetricName      = "Desktop Machines Offline",
                StatisticValues = new StatisticSet(),
                Timestamp       = DateTime.Today,
                Unit            = StandardUnit.Count,
                Value           = 9
            };

            var request = new PutMetricDataRequest
            {
                MetricData = new List <MetricDatum>()
                {
                    metric1,
                    metric2,
                    metric3,
                    metric4
                },
                Namespace = "Example.com Custom Metrics"
            };

            cloudwatchClient.PutMetricDataAsync(request).GetAwaiter().GetResult();
        }
コード例 #32
0
 public ScopedUpdatingService(ILogger <ScopedUpdatingService> logger, PlatformResourcesContext context, IAmazonEC2 EC2Client, IAmazonCloudWatch cloudwatchClient, IAmazonCloudWatchEvents cloudwatcheventsClient, IAmazonCloudWatchLogs cloudwatchlogsClient)
 {
     _logger      = logger;
     this.context = context;
     ec2Client    = EC2Client;
     cwClient     = cloudwatchClient;
     cweClient    = cloudwatcheventsClient;
     cwlClient    = cloudwatchlogsClient;
 }
コード例 #33
0
 public CloudWatchMetricPersister(IAmazonCloudWatch cloudWatch, IOptions <CloudWatchMetricPersisterConfiguration> configuration, ILogger <CloudWatchMetricPersister> logger)
 {
     this.cloudWatch    = cloudWatch ?? throw new ArgumentNullException(nameof(cloudWatch));
     this.logger        = logger ?? throw new ArgumentNullException(nameof(logger));
     this.configuration = configuration?.Value ?? throw new ArgumentNullException(nameof(configuration));
 }