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); }
public static IAmazonCloudWatch GetCloudWatchConnection() { if (cloudWatch == null) { cloudWatch = AWSClientFactory.CreateAmazonCloudWatchClient(AwsKeyProviders.Key, AwsKeyProviders.Secret, RegionEndpoint.EUWest1); } return cloudWatch; ; }
/// <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); }
public Worker( IAmazonCloudWatch awsCloudWatchClient, IManagementClient rabbitMqClient, ILogger <Worker> logger, IOptionsMonitor <WorkerOptions> options ) { _awsCloudWatchClient = awsCloudWatchClient; _rabbitMqClient = rabbitMqClient; _logger = logger; _interval = options.CurrentValue.Interval; }
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); }
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); } }
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; } }
/// <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 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); }
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); } }
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; } }
/// <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}"); } }
public QueueDataV2Source(IAmazonCloudWatch amazonCloudWatch) { _amazonCloudWatch = amazonCloudWatch; }
internal CloudWatchPaginatorFactory(IAmazonCloudWatch client) { this.client = client; }
public CloudWatchClient() { var aws = CManager.Settings.AWS; _service = AWSClientFactory.CreateAmazonCloudWatchClient(aws.AccessKey, aws.SecretAccessKey, RegionEndpoint.GetBySystemName(aws.RegionEndpoint)); }
static Metrics() { _data = new List <MetricDatum>(); _amazonCloudWatch = new AmazonCloudWatchClient(RegionEndpoint.EUWest1); }
internal GetMetricDataPaginator(IAmazonCloudWatch client, GetMetricDataRequest request) { this._client = client; this._request = request; }
/// <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); }
internal DescribeAlarmsPaginator(IAmazonCloudWatch client, DescribeAlarmsRequest request) { this._client = client; this._request = request; }
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 }); }
public KinesisStreamSource(IAmazonCloudWatch amazonCloudWatch) { _amazonCloudWatch = amazonCloudWatch; }
public AutoScalingGroupAlarmDataProvider(IAmazonCloudWatch cloudWatch, ICurrentTimeProvider timeProvider = null) { _cloudWatch = cloudWatch; _timeProvider = timeProvider ?? new CurrentTimeProvider(); }
public CloudWatchExecutionTimeService(RequestDelegate next, ILogger <CloudWatchExecutionTimeService> logger, IAmazonCloudWatch amazonCloudWatch) { _next = next; _logger = logger; _amazonCloudWatch = amazonCloudWatch; }
internal DescribeInsightRulesPaginator(IAmazonCloudWatch client, DescribeInsightRulesRequest request) { this._client = client; this._request = request; }
protected override void ProcessRecord() { base.ProcessRecord(); Client = CreateClient(_CurrentCredentials, _RegionEndpoint); }
internal ListDashboardsPaginator(IAmazonCloudWatch client, ListDashboardsRequest request) { this._client = client; this._request = request; }
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; }
internal ListMetricsPaginator(IAmazonCloudWatch client, ListMetricsRequest request) { this._client = client; this._request = request; }
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(); }
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; }
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)); }