func ExampleCloudWatch_DescribeAlarmHistory() { sess, err := session.NewSession() if err != nil { fmt.Println("failed to create session,", err) return } svc := cloudwatch.New(sess) params := &cloudwatch.DescribeAlarmHistoryInput{ AlarmName: aws.String("AlarmName"), EndDate: aws.Time(time.Now()), HistoryItemType: aws.String("HistoryItemType"), MaxRecords: aws.Int64(1), NextToken: aws.String("NextToken"), StartDate: aws.Time(time.Now()), } resp, err := svc.DescribeAlarmHistory(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) }
func ExampleCloudWatch_SetAlarmState() { sess, err := session.NewSession() if err != nil { fmt.Println("failed to create session,", err) return } svc := cloudwatch.New(sess) params := &cloudwatch.SetAlarmStateInput{ AlarmName: aws.String("AlarmName"), // Required StateReason: aws.String("StateReason"), // Required StateValue: aws.String("StateValue"), // Required StateReasonData: aws.String("StateReasonData"), } resp, err := svc.SetAlarmState(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) }
func handleListMetrics(req *cwRequest, c *middleware.Context) { svc := cloudwatch.New(&aws.Config{Region: aws.String(req.Region)}) reqParam := &struct { Parameters struct { Namespace string `json:"namespace"` MetricName string `json:"metricName"` Dimensions []*cloudwatch.DimensionFilter `json:"dimensions"` } `json:"parameters"` }{} json.Unmarshal(req.Body, reqParam) params := &cloudwatch.ListMetricsInput{ Namespace: aws.String(reqParam.Parameters.Namespace), MetricName: aws.String(reqParam.Parameters.MetricName), Dimensions: reqParam.Parameters.Dimensions, } resp, err := svc.ListMetrics(params) if err != nil { c.JsonApiErr(500, "Unable to call AWS API", err) return } c.JSON(200, resp) }
func getAllMetrics(region string, namespace string, database string) (cloudwatch.ListMetricsOutput, error) { cfg := &aws.Config{ Region: aws.String(region), Credentials: getCredentials(database), } svc := cloudwatch.New(session.New(cfg), cfg) params := &cloudwatch.ListMetricsInput{ Namespace: aws.String(namespace), } var resp cloudwatch.ListMetricsOutput err := svc.ListMetricsPages(params, func(page *cloudwatch.ListMetricsOutput, lastPage bool) bool { metrics, _ := awsutil.ValuesAtPath(page, "Metrics") for _, metric := range metrics { resp.Metrics = append(resp.Metrics, metric.(*cloudwatch.Metric)) } return !lastPage }) if err != nil { return resp, err } return resp, nil }
func ExampleCloudWatch_EnableAlarmActions() { sess, err := session.NewSession() if err != nil { fmt.Println("failed to create session,", err) return } svc := cloudwatch.New(sess) params := &cloudwatch.EnableAlarmActionsInput{ AlarmNames: []*string{ // Required aws.String("AlarmName"), // Required // More values... }, } resp, err := svc.EnableAlarmActions(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) }
func (c *CloudWatch) Connect() error { credentialConfig := &internalaws.CredentialConfig{ Region: c.Region, AccessKey: c.AccessKey, SecretKey: c.SecretKey, RoleARN: c.RoleARN, Profile: c.Profile, Filename: c.Filename, Token: c.Token, } configProvider := credentialConfig.Credentials() svc := cloudwatch.New(configProvider) params := &cloudwatch.ListMetricsInput{ Namespace: aws.String(c.Namespace), } _, err := svc.ListMetrics(params) // Try a read-only call to test connection. if err != nil { log.Printf("E! cloudwatch: Error in ListMetrics API call : %+v \n", err.Error()) } c.svc = svc return err }
// Run command. func run(c *cobra.Command, args []string) error { if err := root.Project.LoadFunctions(args...); err != nil { return err } config := metrics.Config{ Service: cloudwatch.New(root.Session), StartDate: time.Now().UTC().Add(-duration), EndDate: time.Now().UTC(), } m := metrics.Metrics{ Config: config, } for _, fn := range root.Project.Functions { m.FunctionNames = append(m.FunctionNames, fn.FunctionName) } aggregated := m.Collect() fmt.Println() for _, fn := range root.Project.Functions { fnMetrics := aggregated[fn.FunctionName] fmt.Printf(" \033[%dm%s\033[0m\n", colors.Blue, fn.Name) fmt.Printf(" invocations: %v\n", fnMetrics.Invocations) fmt.Printf(" duration: %vms\n", fnMetrics.Duration) fmt.Printf(" throttles: %v\n", fnMetrics.Throttles) fmt.Printf(" error: %v\n", fnMetrics.Errors) fmt.Println() } return nil }
func handleGetMetricStatistics(req *cwRequest, c *middleware.Context) { svc := cloudwatch.New(&aws.Config{Region: aws.String(req.Region)}) reqParam := &struct { Parameters struct { Namespace string `json:"namespace"` MetricName string `json:"metricName"` Dimensions []*cloudwatch.Dimension `json:"dimensions"` Statistics []*string `json:"statistics"` StartTime int64 `json:"startTime"` EndTime int64 `json:"endTime"` Period int64 `json:"period"` } `json:"parameters"` }{} json.Unmarshal(req.Body, reqParam) params := &cloudwatch.GetMetricStatisticsInput{ Namespace: aws.String(reqParam.Parameters.Namespace), MetricName: aws.String(reqParam.Parameters.MetricName), Dimensions: reqParam.Parameters.Dimensions, Statistics: reqParam.Parameters.Statistics, StartTime: aws.Time(time.Unix(reqParam.Parameters.StartTime, 0)), EndTime: aws.Time(time.Unix(reqParam.Parameters.EndTime, 0)), Period: aws.Int64(reqParam.Parameters.Period), } resp, err := svc.GetMetricStatistics(params) if err != nil { c.JsonApiErr(500, "Unable to call AWS API", err) return } c.JSON(200, resp) }
func main() { kingpin.Parse() me := ec2metadata.New(session.New(), &aws.Config{}) region, err := me.Region() if err != nil { fmt.Println(err) os.Exit(1) } cw := cloudwatch.New(session.New(&aws.Config{Region: aws.String(region)})) as := autoscaling.New(session.New(&aws.Config{Region: aws.String(region)})) // Get the name of this instance. instance, err := me.GetMetadata("instance-id") if err != nil { fmt.Println(err) os.Exit(1) } log.Printf("Instance: %s", instance) // Check if this instance is in an auto scaling group. gps, err := as.DescribeAutoScalingInstances(&autoscaling.DescribeAutoScalingInstancesInput{ InstanceIds: []*string{ aws.String(instance), }, }) if err == nil && len(gps.AutoScalingInstances) > 0 { group = *gps.AutoScalingInstances[0].AutoScalingGroupName log.Printf("AutoScaling group: %s", group) } // Loop and send to the backend. limiter := time.Tick(time.Second * 60) for { <-limiter // Submit all the values. for _, mn := range strings.Split(*cliMetrics, ",") { m, err := metric.New(mn) if err != nil { log.Printf("Cannot find metric: %s" + mn) continue } v, err := m.Value() if err != nil { log.Println("Cannot get metric.") } // Send the instance metrics. Send(cw, "InstanceId", instance, m.Name(), v) // Send the autoscaling. if group != "" { Send(cw, "AutoScalingGroupName", group, m.Name(), v) } } } }
func get_metric_stats(sess *session.Session, identity_name, target_id, metric_name, metric_namespace string) []*cloudwatch.Datapoint { svc := cloudwatch.New(sess) t := time.Now() input := &cloudwatch.GetMetricStatisticsInput{ Namespace: aws.String(metric_namespace), Statistics: []*string{aws.String("Average")}, EndTime: aws.Time(t), Period: aws.Int64(300), StartTime: aws.Time(t.Add(time.Duration(-10) * time.Minute)), MetricName: aws.String(metric_name), Dimensions: []*cloudwatch.Dimension{ { Name: aws.String(identity_name), Value: aws.String(target_id), }, }, } value, err := svc.GetMetricStatistics(input) if err != nil { fmt.Printf("[ERROR] Fail GetMetricStatistics API call: %s \n", err.Error()) return nil } return value.Datapoints }
func ExampleCloudWatch_DescribeAlarmsForMetric() { svc := cloudwatch.New(session.New()) params := &cloudwatch.DescribeAlarmsForMetricInput{ MetricName: aws.String("MetricName"), // Required Namespace: aws.String("Namespace"), // Required Dimensions: []*cloudwatch.Dimension{ { // Required Name: aws.String("DimensionName"), // Required Value: aws.String("DimensionValue"), // Required }, // More values... }, Period: aws.Int64(1), Statistic: aws.String("Statistic"), Unit: aws.String("StandardUnit"), } resp, err := svc.DescribeAlarmsForMetric(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) }
func handleDescribeAlarmsForMetric(req *cwRequest, c *middleware.Context) { cfg := getAwsConfig(req) svc := cloudwatch.New(session.New(cfg), cfg) reqParam := &struct { Parameters struct { Namespace string `json:"namespace"` MetricName string `json:"metricName"` Dimensions []*cloudwatch.Dimension `json:"dimensions"` Statistic string `json:"statistic"` Period int64 `json:"period"` } `json:"parameters"` }{} json.Unmarshal(req.Body, reqParam) params := &cloudwatch.DescribeAlarmsForMetricInput{ Namespace: aws.String(reqParam.Parameters.Namespace), MetricName: aws.String(reqParam.Parameters.MetricName), Period: aws.Int64(reqParam.Parameters.Period), } if len(reqParam.Parameters.Dimensions) != 0 { params.Dimensions = reqParam.Parameters.Dimensions } if reqParam.Parameters.Statistic != "" { params.Statistic = aws.String(reqParam.Parameters.Statistic) } resp, err := svc.DescribeAlarmsForMetric(params) if err != nil { c.JsonApiErr(500, "Unable to call AWS API", err) return } c.JSON(200, resp) }
func ExampleCloudWatch_DescribeAlarms() { svc := cloudwatch.New(session.New()) params := &cloudwatch.DescribeAlarmsInput{ ActionPrefix: aws.String("ActionPrefix"), AlarmNamePrefix: aws.String("AlarmNamePrefix"), AlarmNames: []*string{ aws.String("AlarmName"), // Required // More values... }, MaxRecords: aws.Int64(1), NextToken: aws.String("NextToken"), StateValue: aws.String("StateValue"), } resp, err := svc.DescribeAlarms(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) }
func ExampleCloudWatch_ListMetrics() { svc := cloudwatch.New(session.New()) params := &cloudwatch.ListMetricsInput{ Dimensions: []*cloudwatch.DimensionFilter{ { // Required Name: aws.String("DimensionName"), // Required Value: aws.String("DimensionValue"), }, // More values... }, MetricName: aws.String("MetricName"), Namespace: aws.String("Namespace"), NextToken: aws.String("NextToken"), } resp, err := svc.ListMetrics(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) }
func ExampleCloudWatch_GetMetricStatistics() { svc := cloudwatch.New(session.New()) params := &cloudwatch.GetMetricStatisticsInput{ EndTime: aws.Time(time.Now()), // Required MetricName: aws.String("MetricName"), // Required Namespace: aws.String("Namespace"), // Required Period: aws.Int64(1), // Required StartTime: aws.Time(time.Now()), // Required Statistics: []*string{ // Required aws.String("Statistic"), // Required // More values... }, Dimensions: []*cloudwatch.Dimension{ { // Required Name: aws.String("DimensionName"), // Required Value: aws.String("DimensionValue"), // Required }, // More values... }, Unit: aws.String("StandardUnit"), } resp, err := svc.GetMetricStatistics(params) if err != nil { // Print the error, cast err to awserr.Error to get the Code and // Message from an error. fmt.Println(err.Error()) return } // Pretty-print the response data. fmt.Println(resp) }
func getAllMetrics(cwData *datasourceInfo) (cloudwatch.ListMetricsOutput, error) { creds, err := getCredentials(cwData) if err != nil { return cloudwatch.ListMetricsOutput{}, err } cfg := &aws.Config{ Region: aws.String(cwData.Region), Credentials: creds, } svc := cloudwatch.New(session.New(cfg), cfg) params := &cloudwatch.ListMetricsInput{ Namespace: aws.String(cwData.Namespace), } var resp cloudwatch.ListMetricsOutput err = svc.ListMetricsPages(params, func(page *cloudwatch.ListMetricsOutput, lastPage bool) bool { metrics.M_Aws_CloudWatch_ListMetrics.Inc(1) metrics, _ := awsutil.ValuesAtPath(page, "Metrics") for _, metric := range metrics { resp.Metrics = append(resp.Metrics, metric.(*cloudwatch.Metric)) } return !lastPage }) if err != nil { return resp, err } return resp, nil }
func ExampleCloudWatch_ListMetrics() { svc := cloudwatch.New(nil) params := &cloudwatch.ListMetricsInput{ Dimensions: []*cloudwatch.DimensionFilter{ { // Required Name: aws.String("DimensionName"), // Required Value: aws.String("DimensionValue"), }, // More values... }, MetricName: aws.String("MetricName"), Namespace: aws.String("Namespace"), NextToken: aws.String("NextToken"), } resp, err := svc.ListMetrics(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { // Generic AWS error with Code, Message, and original error (if any) fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { // A service error occurred fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } } // Pretty-print the response data. fmt.Println(awsutil.StringValue(resp)) }
func ExampleCloudWatch_EnableAlarmActions() { svc := cloudwatch.New(nil) params := &cloudwatch.EnableAlarmActionsInput{ AlarmNames: []*string{ // Required aws.String("AlarmName"), // Required // More values... }, } resp, err := svc.EnableAlarmActions(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { // Generic AWS error with Code, Message, and original error (if any) fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { // A service error occurred fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } } // Pretty-print the response data. fmt.Println(awsutil.Prettify(resp)) }
// FetchMetrics fetch the metrics func (p EBSPlugin) FetchMetrics() (map[string]interface{}, error) { stat := make(map[string]interface{}) p.CloudWatch = cloudwatch.New(session.New(&aws.Config{Credentials: p.Credentials, Region: &p.Region})) for _, vol := range p.Volumes { volumeID := normalizeVolumeID(*vol.VolumeId) graphs := defaultGraphs if *vol.VolumeType == "io1" { graphs = allGraphs } for _, graphName := range graphs { for _, metric := range graphdef[graphName].Metrics { metricKey := graphName + "." + metric.Name cloudwatchdef := cloudwatchdefs[metricKey] val, period, err := p.getLastPoint(vol, cloudwatchdef.MetricName, cloudwatchdef.Statistics) if err != nil { retErr := errors.New(volumeID + " " + err.Error() + ":" + cloudwatchdef.MetricName) if err.Error() == "fetched no datapoints" { getStderrLogger().Println(retErr) } else { return nil, retErr } } else { stat[strings.Replace(metricKey, "#", volumeID, -1)] = cloudwatchdef.CalcFunc(val, float64(period)) } } } } return stat, nil }
func handleListMetrics(req *cwRequest, c *middleware.Context) { creds := credentials.NewChainCredentials( []credentials.Provider{ &credentials.EnvProvider{}, &credentials.SharedCredentialsProvider{Filename: "", Profile: req.DataSource.Database}, &ec2rolecreds.EC2RoleProvider{ExpiryWindow: 5 * time.Minute}, }) svc := cloudwatch.New(&aws.Config{ Region: aws.String(req.Region), Credentials: creds, }) reqParam := &struct { Parameters struct { Namespace string `json:"namespace"` MetricName string `json:"metricName"` Dimensions []*cloudwatch.DimensionFilter `json:"dimensions"` } `json:"parameters"` }{} json.Unmarshal(req.Body, reqParam) params := &cloudwatch.ListMetricsInput{ Namespace: aws.String(reqParam.Parameters.Namespace), MetricName: aws.String(reqParam.Parameters.MetricName), Dimensions: reqParam.Parameters.Dimensions, } resp, err := svc.ListMetrics(params) if err != nil { c.JsonApiErr(500, "Unable to call AWS API", err) return } c.JSON(200, resp) }
// FetchMetrics fetch the metrics func (p EBSPlugin) FetchMetrics() (map[string]float64, error) { stat := make(map[string]float64) p.CloudWatch = cloudwatch.New(&aws.Config{Credentials: p.Credentials, Region: &p.Region}) for _, vol := range *p.Volumes { graphs := graphsToProcess(vol.VolumeType) for _, graph := range *graphs { for _, met := range graphdef[graph].Metrics { cwdef := cloudwatchdef[met.Name] val, period, err := p.getLastPoint(vol, cwdef.MetricName, cwdef.Statistics) skey := fmt.Sprintf(met.Name, *vol.VolumeId) if err != nil { retErr := errors.New(*vol.VolumeId + " " + err.Error() + ":" + cwdef.MetricName) if err.Error() == "fetched no datapoints" { getStderrLogger().Println(retErr) } else { return nil, retErr } } else { stat[skey] = cwdef.CalcFunc(val, float64(period)) } } } } return stat, nil }
func (c *CloudWatch) Connect() error { Config := &aws.Config{ Region: aws.String(c.Region), Credentials: credentials.NewChainCredentials( []credentials.Provider{ &ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(session.New())}, &credentials.EnvProvider{}, &credentials.SharedCredentialsProvider{}, }), } svc := cloudwatch.New(session.New(Config)) params := &cloudwatch.ListMetricsInput{ Namespace: aws.String(c.Namespace), } _, err := svc.ListMetrics(params) // Try a read-only call to test connection. if err != nil { log.Printf("cloudwatch: Error in ListMetrics API call : %+v \n", err.Error()) } c.svc = svc return err }
func handleListMetrics(req *cwRequest, c *middleware.Context) { cfg := getAwsConfig(req) svc := cloudwatch.New(session.New(cfg), cfg) reqParam := &struct { Parameters struct { Namespace string `json:"namespace"` MetricName string `json:"metricName"` Dimensions []*cloudwatch.DimensionFilter `json:"dimensions"` } `json:"parameters"` }{} json.Unmarshal(req.Body, reqParam) params := &cloudwatch.ListMetricsInput{ Namespace: aws.String(reqParam.Parameters.Namespace), MetricName: aws.String(reqParam.Parameters.MetricName), Dimensions: reqParam.Parameters.Dimensions, } var resp cloudwatch.ListMetricsOutput err := svc.ListMetricsPages(params, func(page *cloudwatch.ListMetricsOutput, lastPage bool) bool { metrics, _ := awsutil.ValuesAtPath(page, "Metrics") for _, metric := range metrics { resp.Metrics = append(resp.Metrics, metric.(*cloudwatch.Metric)) } return !lastPage }) if err != nil { c.JsonApiErr(500, "Unable to call AWS API", err) return } c.JSON(200, resp) }
func handleDescribeAlarmHistory(req *cwRequest, c *middleware.Context) { cfg := &aws.Config{ Region: aws.String(req.Region), Credentials: getCredentials(req.DataSource.Database), } svc := cloudwatch.New(session.New(cfg), cfg) reqParam := &struct { Parameters struct { AlarmName string `json:"alarmName"` HistoryItemType string `json:"historyItemType"` StartDate int64 `json:"startDate"` EndDate int64 `json:"endDate"` } `json:"parameters"` }{} json.Unmarshal(req.Body, reqParam) params := &cloudwatch.DescribeAlarmHistoryInput{ AlarmName: aws.String(reqParam.Parameters.AlarmName), StartDate: aws.Time(time.Unix(reqParam.Parameters.StartDate, 0)), EndDate: aws.Time(time.Unix(reqParam.Parameters.EndDate, 0)), } if reqParam.Parameters.HistoryItemType != "" { params.HistoryItemType = aws.String(reqParam.Parameters.HistoryItemType) } resp, err := svc.DescribeAlarmHistory(params) if err != nil { c.JsonApiErr(500, "Unable to call AWS API", err) return } c.JSON(200, resp) }
func ExampleCloudWatch_DescribeAlarms() { svc := cloudwatch.New(nil) params := &cloudwatch.DescribeAlarmsInput{ ActionPrefix: aws.String("ActionPrefix"), AlarmNamePrefix: aws.String("AlarmNamePrefix"), AlarmNames: []*string{ aws.String("AlarmName"), // Required // More values... }, MaxRecords: aws.Long(1), NextToken: aws.String("NextToken"), StateValue: aws.String("StateValue"), } resp, err := svc.DescribeAlarms(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { // Generic AWS error with Code, Message, and original error (if any) fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { // A service error occurred fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } } // Pretty-print the response data. fmt.Println(awsutil.StringValue(resp)) }
func ExampleCloudWatch_DescribeAlarmHistory() { svc := cloudwatch.New(nil) params := &cloudwatch.DescribeAlarmHistoryInput{ AlarmName: aws.String("AlarmName"), EndDate: aws.Time(time.Now()), HistoryItemType: aws.String("HistoryItemType"), MaxRecords: aws.Long(1), NextToken: aws.String("NextToken"), StartDate: aws.Time(time.Now()), } resp, err := svc.DescribeAlarmHistory(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { // Generic AWS error with Code, Message, and original error (if any) fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { // A service error occurred fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } } // Pretty-print the response data. fmt.Println(awsutil.StringValue(resp)) }
func ExampleCloudWatch_SetAlarmState() { svc := cloudwatch.New(nil) params := &cloudwatch.SetAlarmStateInput{ AlarmName: aws.String("AlarmName"), // Required StateReason: aws.String("StateReason"), // Required StateValue: aws.String("StateValue"), // Required StateReasonData: aws.String("StateReasonData"), } resp, err := svc.SetAlarmState(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { // Generic AWS error with Code, Message, and original error (if any) fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { // A service error occurred fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } } // Pretty-print the response data. fmt.Println(awsutil.StringValue(resp)) }
func (s *AWSSession) getMetricStatistics(rds *AWSElement, graphdefs map[string](Graphs), namespace string, dimensions []*cloudwatch.Dimension) []*mkr.MetricValue { svc := cloudwatch.New(s.Sess) var metricValues []*mkr.MetricValue for key, graphdef := range graphdefs { for _, metrics := range graphdef.Metrics { statistics := metrics.Statistics if metrics.Statistics == "" { statistics = "Average" } params := &cloudwatch.GetMetricStatisticsInput{ EndTime: aws.Time(time.Now()), MetricName: aws.String(metrics.Name), Namespace: aws.String(namespace), Period: aws.Int64(60), StartTime: aws.Time(time.Now().Add(-2 * time.Minute)), Statistics: []*string{ aws.String(statistics), }, Dimensions: dimensions, } resp, err := svc.GetMetricStatistics(params) if err != nil { fmt.Println(err.Error()) return metricValues } //fmt.Println(rds.Name, metrics.Name) //fmt.Println(resp) latestTime := int64(0) var latestValue float64 for _, dp := range resp.Datapoints { timestamp := dp.Timestamp.Unix() var value float64 switch statistics { case "Sum": value = *(dp.Sum) default: value = *(dp.Average) } if latestTime < timestamp { latestValue = value latestTime = timestamp } //fmt.Println(rds.Name, metrics.Name, value) } if latestTime > 0 { metricValues = append(metricValues, &mkr.MetricValue{ Name: "custom." + key + "." + metrics.Name, Value: latestValue, Time: latestTime, }) } } } return metricValues }
/* * Initialize CloudWatch client */ func (c *CloudWatch) initializeCloudWatch() error { config := &aws.Config{ Region: aws.String(c.Region), } c.client = cloudwatch.New(session.New(config)) return nil }
func ExampleCloudWatch_PutMetricAlarm() { svc := cloudwatch.New(nil) params := &cloudwatch.PutMetricAlarmInput{ AlarmName: aws.String("AlarmName"), // Required ComparisonOperator: aws.String("ComparisonOperator"), // Required EvaluationPeriods: aws.Long(1), // Required MetricName: aws.String("MetricName"), // Required Namespace: aws.String("Namespace"), // Required Period: aws.Long(1), // Required Statistic: aws.String("Statistic"), // Required Threshold: aws.Double(1.0), // Required ActionsEnabled: aws.Boolean(true), AlarmActions: []*string{ aws.String("ResourceName"), // Required // More values... }, AlarmDescription: aws.String("AlarmDescription"), Dimensions: []*cloudwatch.Dimension{ { // Required Name: aws.String("DimensionName"), // Required Value: aws.String("DimensionValue"), // Required }, // More values... }, InsufficientDataActions: []*string{ aws.String("ResourceName"), // Required // More values... }, OKActions: []*string{ aws.String("ResourceName"), // Required // More values... }, Unit: aws.String("StandardUnit"), } resp, err := svc.PutMetricAlarm(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { // Generic AWS error with Code, Message, and original error (if any) fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { // A service error occurred fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } } // Pretty-print the response data. fmt.Println(awsutil.StringValue(resp)) }