Exemplo n.º 1
0
        private void PutPerformanceMetricDataForProcess(AmazonCloudWatchClient client, Process process)
        {
            var memoryUsage = 0.0;
            var cpuUsage    = 0.0f;

            using (process)
            {
                var instance = new PerformanceCounter("Process", "% Processor Time", process.ProcessName, true);
                memoryUsage = Math.Round(process.PrivateMemorySize64 / 1024.0 / 1024.0, 2);
                cpuUsage    = instance.NextValue();
            }

            client.PutMetricData(new PutMetricDataRequest
            {
                Namespace  = $"MemoryCPUServicesUsage/{process.ProcessName}",
                MetricData = new List <MetricDatum>
                {
                    new MetricDatum
                    {
                        MetricName = "Memory Usage",
                        Unit       = StandardUnit.Megabits,
                        Value      = memoryUsage,
                        Dimensions = MetricDatumDimensions
                    },
                    new MetricDatum
                    {
                        MetricName = "CPU Usage",
                        Unit       = StandardUnit.Percent,
                        Value      = cpuUsage,
                        Dimensions = MetricDatumDimensions
                    }
                }
            });
        }
Exemplo n.º 2
0
        public static async Task Main()
        {
            IAmazonCloudWatch cwClient = new AmazonCloudWatchClient();
            var dashboards             = await ListDashboardsAsync(cwClient);

            DisplayDashboardList(dashboards);
        }
        /// <summary>
        /// Opens the component.
        /// </summary>
        /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
        public async Task OpenAsync(string correlationId)
        {
            if (_opened)
            {
                return;
            }

            var awsConnection = await _connectionResolver.ResolveAsync(correlationId);

            // Validate connection params
            var err = awsConnection.Validate(correlationId);

            if (err != null)
            {
                throw err;
            }

            // Create client
            var region = RegionEndpoint.GetBySystemName(awsConnection.Region);
            var config = new AmazonCloudWatchConfig()
            {
                RegionEndpoint = region
            };

            _client = new AmazonCloudWatchClient(awsConnection.AccessId, awsConnection.AccessKey, config);
            _opened = true;

            await Task.Delay(0);
        }
Exemplo n.º 4
0
        public CloudWatchMetrics(AmazonCloudWatchClient cloudWatchClient, ILogger <CloudWatchMetrics> logger)
        {
            this.cloudWatchClient = cloudWatchClient;
            this.logger           = logger;

            MetricData = new List <MetricDatum>();
        }
Exemplo n.º 5
0
        public static string PushMetrics(string ns, List <MetricDatum> metrics)
        {
            var request = new PutMetricDataRequest
            {
                Namespace  = ns,
                MetricData = metrics
            };

            //
            Amazon.Runtime.AWSCredentials credentials = null;
            if (Configuration.IsLinux())
            {
                string AccessKey = "xxx";
                string SecretKey = "xxx";
                credentials = new Amazon.Runtime.BasicAWSCredentials(AccessKey, SecretKey);
            }
            else
            {
                credentials = new Amazon.Runtime.StoredProfileAWSCredentials("cloudwatch");
            }
            //
            var client = new AmazonCloudWatchClient(credentials, Amazon.RegionEndpoint.APSoutheast1);

            System.Threading.Tasks.Task <PutMetricDataResponse> task = client.PutMetricDataAsync(request);
            PutMetricDataResponse response = task.Result;

            //
            System.Net.HttpStatusCode statusCode = response.HttpStatusCode;
            Console.WriteLine(DateTime.Now.ToString("HH:mm ") + statusCode.ToString());
            return(statusCode.ToString());
        }
Exemplo n.º 6
0
        public CloudWatchMetricsReporter(MetricsReportingCloudWatchOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (options.FlushInterval < TimeSpan.Zero)
            {
                throw new InvalidOperationException($"{nameof(MetricsReportingCloudWatchOptions.FlushInterval)} must not be less than zero");
            }

            FlushInterval = options.FlushInterval > TimeSpan.Zero
                ? options.FlushInterval
                : AppMetricsConstants.Reporting.DefaultFlushInterval;

            Filter = options.Filter;

            _namespace = options.AwsNamespace;

            if (!string.IsNullOrEmpty(options.AccessKeyId) && !string.IsNullOrEmpty(options.SecretAccessKey))
            {
                _client = new AmazonCloudWatchClient(options.AccessKeyId, options.SecretAccessKey, options.Endpoint);
            }
            else
            {
                _client = new AmazonCloudWatchClient(options.Endpoint);
            }

            _dimensions = options.Dimensions;

            Logger.Info($"Using Metrics Reporter {this}. FlushInterval: {FlushInterval}");
        }
        /// <summary>
        /// Closes component and frees used resources.
        /// </summary>
        /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
        public async Task CloseAsync(string correlationId)
        {
            _opened = false;
            _client = null;

            await Task.Delay(0);
        }
        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));
        }
Exemplo n.º 9
0
        public static void PutMetricAlarm()
        {
            var client = new AmazonCloudWatchClient(RegionEndpoint.USWest2);

            client.PutMetricAlarm(new PutMetricAlarmRequest
            {
                AlarmName          = "Web_Server_CPU_Utilization",
                ComparisonOperator = ComparisonOperator.GreaterThanThreshold,
                EvaluationPeriods  = 1,
                MetricName         = "CPUUtilization",
                Namespace          = "AWS/EC2",
                Period             = 60,
                Statistic          = Statistic.Average,
                Threshold          = 70.0,
                ActionsEnabled     = true,
                AlarmActions       = new List <string> {
                    "arn:aws:swf:us-west-2:" + "customerAccount" + ":action/actions/AWS_EC2.InstanceId.Reboot/1.0"
                },
                AlarmDescription = "Alarm when server CPU exceeds 70%",
                Dimensions       = new List <Dimension>
                {
                    new Dimension {
                        Name = "InstanceId", Value = "INSTANCE_ID"
                    }
                },
                Unit = StandardUnit.Seconds
            });
        }
Exemplo n.º 10
0
        private async Task <PutMetricDataResponse> LogAPICall(PagerDutyAPICallType apiCallType)
        {
            IAmazonCloudWatch client = new AmazonCloudWatchClient();

            Dimension dimension = new Dimension()
            {
                Name  = "PagerDuty",
                Value = "API Calls"
            };

            MetricDatum point = new MetricDatum()
            {
                Dimensions = new List <Dimension>()
                {
                    dimension
                },
                MetricName        = apiCallType.ToString(),
                Unit              = StandardUnit.Count,
                StorageResolution = 1,
                Value             = 1.0
            };

            PutMetricDataRequest request = new PutMetricDataRequest
            {
                MetricData = new List <MetricDatum>()
                {
                    point
                },
                Namespace = "External API Calls"
            };

            return(await client.PutMetricDataAsync(request));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Check service health.
        /// </summary>
        /// <param name="client">Instance of <see cref="AmazonCloudWatchClient"/> class.</param>
        /// <returns>Success, RountTripTime.</returns>
        public static async Task <(bool, double)> CheckServiceReachable(AmazonCloudWatchClient client)
        {
            var stopwatch = new Stopwatch();

            try
            {
                stopwatch.Start();
                await client.DescribeAlarmsAsync(new DescribeAlarmsRequest
                {
                    AlarmNamePrefix = "KinesisTap"
                });

                stopwatch.Stop();
            }
            catch (AmazonCloudWatchException)
            {
                stopwatch.Stop();
                // Any exception is fine, we are currently only looking to
                // check if the service is reachable and what is the RTT.
                return(true, stopwatch.ElapsedMilliseconds);
            }
            catch (Exception)
            {
                stopwatch.Stop();
                return(false, stopwatch.ElapsedMilliseconds);
            }

            return(true, stopwatch.ElapsedMilliseconds);
        }
Exemplo n.º 12
0
        private static QueueSource InitializeQueueSource()
        {
            var creds            = CredentialsReader.GetCredentials();
            var cloudWatchClient = new AmazonCloudWatchClient(creds, RegionEndpoint.EUWest1);

            return(new QueueSource(cloudWatchClient));
        }
Exemplo n.º 13
0
 public ShowSentimentMessageProcessor(DiscordClient discordClient,
                                      CloudWatchMetrics metrics,
                                      ILogger <AbstractDiscordMessageProcessor> logger,
                                      AmazonCloudWatchClient cloudWatchClient) : base(discordClient, metrics, logger)
 {
     CloudWatchClient = cloudWatchClient;
 }
Exemplo n.º 14
0
        public static void CWDescribeAlarmHistory()
        {
            #region CWDescribeAlarmHistory
            var client = new AmazonCloudWatchClient();

            var request = new DescribeAlarmHistoryRequest
            {
                AlarmName =
                    "awseb-e-kkbEXAMPLE-stack-CloudwatchAlarmLow-1WVXD9EXAMPLE",
                EndDate         = DateTime.Today,
                HistoryItemType = HistoryItemType.Action,
                MaxRecords      = 1,
                StartDate       = DateTime.Today.Subtract(TimeSpan.FromDays(30))
            };

            var response = new DescribeAlarmHistoryResponse();

            do
            {
                response = client.DescribeAlarmHistory(request);

                foreach (var item in response.AlarmHistoryItems)
                {
                    Console.WriteLine(item.AlarmName);
                    Console.WriteLine(item.HistorySummary);
                    Console.WriteLine();
                }

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

            Console.ReadLine();
        }
Exemplo n.º 15
0
        public static async Task Main()
        {
            IAmazonCloudWatch cwClient = new AmazonCloudWatchClient();

            var alarmNames = CreateAlarmNameList();

            await DeleteAlarmsAsyncExample(cwClient, alarmNames);
        }
Exemplo n.º 16
0
        public static AmazonCloudWatchClient GetAmazonCloudWatchClient()
        {
            AmazonCloudWatchClient amazon_cloud_watch_client = (!string.IsNullOrEmpty(access_key_id) && !string.IsNullOrEmpty(secret_access_key)
                                ? new AmazonCloudWatchClient(access_key_id, secret_access_key, GetRegion())
                                : new AmazonCloudWatchClient(GetRegion()));

            return(amazon_cloud_watch_client);
        }
        public async Task <GetMetricStatisticsResponse> GetMetricStatistics(GetMetricStatisticsRequest metricStatisticsRequest)
        {
            using (var amazonCloudWatchClient = new AmazonCloudWatchClient(awsCredentials, RegionEndpoint.GetBySystemName(Region)))
            {
                var response = await amazonCloudWatchClient.GetMetricStatisticsAsync(metricStatisticsRequest);

                return(response);
            }
        }
Exemplo n.º 18
0
        public static async Task Main()
        {
            IAmazonCloudWatch cwClient      = new AmazonCloudWatchClient();
            string            dashboardName = "CloudWatch-Default";

            var body = await GetDashboardAsync(cwClient, dashboardName);

            Console.WriteLine(body);
        }
        public async Task <ListMetricsResponse> ListMetrics()
        {
            using (var amazonCloudWatchClient = new AmazonCloudWatchClient(awsCredentials, RegionEndpoint.GetBySystemName(Region)))
            {
                var response = await amazonCloudWatchClient.ListMetricsAsync();

                return(response);
            }
        }
Exemplo n.º 20
0
        private static IAlarmFinder MakeAlarmFinder()
        {
            var cloudwatch = new AmazonCloudWatchClient(CredentialsReader.GetCredentials(),
                                                        new AmazonCloudWatchConfig {
                RegionEndpoint = RegionEndpoint.EUWest1
            });

            return(new AlarmFinder(new ConsoleAlarmLogger(false), cloudwatch));
        }
Exemplo n.º 21
0
        public static void CloudWatchMetricsTest()
        {
            var             logGroupName    = "LogGroupName";
            DimensionFilter dimensionFilter = new DimensionFilter()
            {
                Name = logGroupName
            };
            var dimensionFilterList = new List <DimensionFilter>();

            dimensionFilterList.Add(dimensionFilter);

            var dimension = new Dimension
            {
                Name  = "UniquePages",
                Value = "URLs"
            };

            using (var cw = new AmazonCloudWatchClient(RegionEndpoint.USWest2))
            {
                var listMetricsResponse = cw.ListMetrics(new ListMetricsRequest
                {
                    Dimensions = dimensionFilterList,
                    MetricName = "IncomingLogEvents",
                    Namespace  = "AWS/Logs"
                });

                Console.WriteLine(listMetricsResponse.Metrics);

                cw.PutMetricData(new PutMetricDataRequest
                {
                    MetricData = new List <MetricDatum> {
                        new MetricDatum
                        {
                            MetricName = "PagesVisited",
                            Dimensions = new List <Dimension> {
                                dimension
                            },
                            Unit  = "None",
                            Value = 1.0
                        }
                    },
                    Namespace = "SITE/TRAFFIC"
                });

                var describeMetricsResponse = cw.DescribeAlarmsForMetric(new DescribeAlarmsForMetricRequest
                {
                    MetricName = "PagesVisited",
                    Dimensions = new List <Dimension>()
                    {
                        dimension
                    },
                    Namespace = "SITE/TRAFFIC"
                });

                Console.WriteLine(describeMetricsResponse.MetricAlarms);
            }
        }
        // Initialize all clients for send to cloudWatch with the clients AmazonCloudWatchEventsClient and AmazonCloudWatchClient
        public override void Initialize()
        {
            //Get all configuration on appsettings.
            CloudWatchConfiguration cloudWatchConfiuration = LightConfigurator.Config <CloudWatchConfiguration>("CloudWatch");

            //Generate a client to send events with te configuration access key and secret key.
            _amazonCloudEvents = new AmazonCloudWatchEventsClient(cloudWatchConfiuration.AccessKeyID, cloudWatchConfiuration.SecretAccessKey);
            //Generate a client to send metrics and alarms with te configuration access key and secret key.
            _amazonCloud = new AmazonCloudWatchClient(cloudWatchConfiuration.AccessKeyID, cloudWatchConfiuration.SecretAccessKey);
        }
        /// <summary>
        /// Retrieves a list of alarms and then passes each name to the
        /// DescribeAlarmHistoriesAsync method to retrieve its history.
        /// </summary>
        public static async Task Main()
        {
            IAmazonCloudWatch cwClient = new AmazonCloudWatchClient();
            var response = await cwClient.DescribeAlarmsAsync();

            foreach (var alarm in response.MetricAlarms)
            {
                await DescribeAlarmHistoriesAsync(cwClient, alarm.AlarmName);
            }
        }
Exemplo n.º 24
0
 public static void DeleteAlarm(List <string> alarmNames)
 {
     using (var cloudWatch = new AmazonCloudWatchClient(RegionEndpoint.USWest2))
     {
         var response = cloudWatch.DeleteAlarms(
             new DeleteAlarmsRequest
         {
             AlarmNames = alarmNames
         });
     }
 }
Exemplo n.º 25
0
 public static void DisableAlarmActions()
 {
     using (var client = new AmazonCloudWatchClient(RegionEndpoint.USWest2))
     {
         client.DisableAlarmActions(new DisableAlarmActionsRequest
         {
             AlarmNames = new List <string> {
                 "Web_Server_CPU_Utilization"
             }
         });
     }
 }
Exemplo n.º 26
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();
        }
Exemplo n.º 27
0
        public static async Task Main()
        {
            IAmazonCloudWatch cwClient = new AmazonCloudWatchClient();

            var filter = new DimensionFilter
            {
                Name  = "InstanceType",
                Value = "t1.micro",
            };
            string metricName    = "CPUUtilization";
            string namespaceName = "AWS/EC2";

            await ListMetricsAsync(cwClient, filter, metricName, namespaceName);
        }
Exemplo n.º 28
0
        protected IAmazonCloudWatch CreateClient(AWSCredentials credentials, RegionEndpoint region)
        {
            var config = new AmazonCloudWatchConfig {
                RegionEndpoint = region
            };

            Amazon.PowerShell.Utils.Common.PopulateConfig(this, config);
            this.CustomizeClientConfig(config);
            var client = new AmazonCloudWatchClient(credentials, config);

            client.BeforeRequestEvent += RequestEventHandler;
            client.AfterResponseEvent += ResponseEventHandler;
            return(client);
        }
Exemplo n.º 29
0
        public TelemetryLogService(ILogger <TelemetryLogService> logger, ICacheStore store,
                                   AwsConfiguration awsConfiguration = null, MetricsConfiguration metricsConfiguration = null)
        {
            _logger = logger;
            _metricsConfiguration = metricsConfiguration;
            _redisStore           = store as RedisCacheStore;

            if (awsConfiguration != null && metricsConfiguration != null)
            {
                _amazonCloudWatchClient = new AmazonCloudWatchClient(awsConfiguration.AccessKeyId,
                                                                     awsConfiguration.SecretAccessKey,
                                                                     RegionEndpoint.GetBySystemName(awsConfiguration.Region));
            }
        }
Exemplo n.º 30
0
        public static void EnableAlarmAction(string instanceId, string customerAccount)
        {
            using (var client = new AmazonCloudWatchClient(Amazon.RegionEndpoint.USWest2))
            {
                client.PutMetricAlarm(new PutMetricAlarmRequest
                {
                    AlarmName          = "Web_Server_CPU_Utilization",
                    ComparisonOperator = ComparisonOperator.GreaterThanThreshold,
                    EvaluationPeriods  = 1,
                    MetricName         = "CPUUtilization",
                    Namespace          = "AWS/EC2",
                    Period             = 60,
                    Statistic          = Statistic.Average,
                    Threshold          = 70.0,
                    ActionsEnabled     = true,
                    AlarmActions       = new List <string> {
                        "arn:aws:swf:us-west-2:" + customerAccount + ":action/actions/AWS_EC2.InstanceId.Reboot/1.0"
                    },
                    AlarmDescription = "Alarm when server CPU exceeds 70%",
                    Dimensions       = new List <Dimension>
                    {
                        new Dimension {
                            Name = "InstanceId", Value = instanceId
                        }
                    },
                    Unit = StandardUnit.Seconds
                });

                client.EnableAlarmActions(new EnableAlarmActionsRequest
                {
                    AlarmNames = new List <string> {
                        "Web_Server_CPU_Utilization"
                    }
                });

                MetricDatum metricDatum = new MetricDatum
                {
                    MetricName = "CPUUtilization"
                };

                PutMetricDataRequest putMetricDatarequest = new PutMetricDataRequest
                {
                    MetricData = new List <MetricDatum> {
                        metricDatum
                    }
                };
                client.PutMetricData(putMetricDatarequest);
            }
        }