Пример #1
1
func awsGetELBHostCounts(cw cloudwatch.CloudWatch, md *opentsdb.MultiDataPoint, loadBalancer *elb.LoadBalancerDescription) error {
	search := cloudwatch.GetMetricStatisticsInput{
		StartTime:  aws.Time(time.Now().UTC().Add(time.Second * -60)),
		EndTime:    aws.Time(time.Now().UTC()),
		MetricName: aws.String("HealthyHostCount"),
		Period:     &aws_period,
		Statistics: []*string{aws.String("Average")},
		Namespace:  aws.String("AWS/ELB"),
		Unit:       aws.String("Count"),
		Dimensions: []*cloudwatch.Dimension{{Name: aws.String("LoadBalancerName"), Value: loadBalancer.LoadBalancerName}},
	}
	resp, err := cw.GetMetricStatistics(&search)
	if err != nil {
		return err
	}
	for _, datapoint := range resp.Datapoints {
		AddTS(md, awsELBHostsHealthy, datapoint.Timestamp.Unix(), *datapoint.Average, opentsdb.TagSet{"loadbalancer": *loadBalancer.LoadBalancerName}, metadata.Gauge, metadata.Count, descAWSELBHostCount)
	}
	search.MetricName = aws.String("UnhealthyHostCount")
	resp, err = cw.GetMetricStatistics(&search)
	if err != nil {
		return err
	}
	if resp.Datapoints == nil {
		AddTS(md, awsELBHostsUnHealthy, time.Now().UTC().Unix(), 0, opentsdb.TagSet{"loadbalancer": *loadBalancer.LoadBalancerName}, metadata.Gauge, metadata.Count, descAWSELBHostCount)
	} else {
		for _, datapoint := range resp.Datapoints {
			AddTS(md, awsELBHostsUnHealthy, datapoint.Timestamp.Unix(), *datapoint.Average, opentsdb.TagSet{"loadbalancer": *loadBalancer.LoadBalancerName}, metadata.Gauge, metadata.Count, descAWSELBHostCount)
		}
	}
	return nil
}
Пример #2
0
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
}
Пример #3
0
func ExampleConfigService_GetResourceConfigHistory() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := configservice.New(sess)

	params := &configservice.GetResourceConfigHistoryInput{
		ResourceId:         aws.String("ResourceId"),   // Required
		ResourceType:       aws.String("ResourceType"), // Required
		ChronologicalOrder: aws.String("ChronologicalOrder"),
		EarlierTime:        aws.Time(time.Now()),
		LaterTime:          aws.Time(time.Now()),
		Limit:              aws.Int64(1),
		NextToken:          aws.String("NextToken"),
	}
	resp, err := svc.GetResourceConfigHistory(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)
}
Пример #4
0
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))
}
Пример #5
0
func ExampleAutoScaling_DescribeScheduledActions() {
	svc := autoscaling.New(session.New())

	params := &autoscaling.DescribeScheduledActionsInput{
		AutoScalingGroupName: aws.String("ResourceName"),
		EndTime:              aws.Time(time.Now()),
		MaxRecords:           aws.Int64(1),
		NextToken:            aws.String("XmlString"),
		ScheduledActionNames: []*string{
			aws.String("ResourceName"), // Required
			// More values...
		},
		StartTime: aws.Time(time.Now()),
	}
	resp, err := svc.DescribeScheduledActions(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)
}
Пример #6
0
func ExampleRedshift_DescribeClusterSnapshots() {
	svc := redshift.New(session.New())

	params := &redshift.DescribeClusterSnapshotsInput{
		ClusterIdentifier:  aws.String("String"),
		EndTime:            aws.Time(time.Now()),
		Marker:             aws.String("String"),
		MaxRecords:         aws.Int64(1),
		OwnerAccount:       aws.String("String"),
		SnapshotIdentifier: aws.String("String"),
		SnapshotType:       aws.String("String"),
		StartTime:          aws.Time(time.Now()),
		TagKeys: []*string{
			aws.String("String"), // Required
			// More values...
		},
		TagValues: []*string{
			aws.String("String"), // Required
			// More values...
		},
	}
	resp, err := svc.DescribeClusterSnapshots(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)
}
Пример #7
0
func ExampleElastiCache_DescribeEvents() {
	svc := elasticache.New(nil)

	params := &elasticache.DescribeEventsInput{
		Duration:         aws.Int64(1),
		EndTime:          aws.Time(time.Now()),
		Marker:           aws.String("String"),
		MaxRecords:       aws.Int64(1),
		SourceIdentifier: aws.String("String"),
		SourceType:       aws.String("SourceType"),
		StartTime:        aws.Time(time.Now()),
	}
	resp, err := svc.DescribeEvents(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))
}
Пример #8
0
func ExampleAutoScaling_PutScheduledUpdateGroupAction() {
	svc := autoscaling.New(nil)

	params := &autoscaling.PutScheduledUpdateGroupActionInput{
		AutoScalingGroupName: aws.String("ResourceName"),       // Required
		ScheduledActionName:  aws.String("XmlStringMaxLen255"), // Required
		DesiredCapacity:      aws.Long(1),
		EndTime:              aws.Time(time.Now()),
		MaxSize:              aws.Long(1),
		MinSize:              aws.Long(1),
		Recurrence:           aws.String("XmlStringMaxLen255"),
		StartTime:            aws.Time(time.Now()),
		Time:                 aws.Time(time.Now()),
	}
	resp, err := svc.PutScheduledUpdateGroupAction(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))
}
Пример #9
0
func ExampleAutoScaling_DescribeScheduledActions() {
	svc := autoscaling.New(nil)

	params := &autoscaling.DescribeScheduledActionsInput{
		AutoScalingGroupName: aws.String("ResourceName"),
		EndTime:              aws.Time(time.Now()),
		MaxRecords:           aws.Long(1),
		NextToken:            aws.String("XmlString"),
		ScheduledActionNames: []*string{
			aws.String("ResourceName"), // Required
			// More values...
		},
		StartTime: aws.Time(time.Now()),
	}
	resp, err := svc.DescribeScheduledActions(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 (suite *GetAuthorizationTokenTestSuite) TestGetAuthorizationTokenCacheHitExpiredToken() {
	expiredAuthData := &ecrapi.AuthorizationData{
		ProxyEndpoint:      aws.String(testProxyEndpoint),
		AuthorizationToken: aws.String(testToken),
		ExpiresAt:          aws.Time(time.Now().Add(-5 * time.Minute)),
	}

	testAuthData := &ecrapi.AuthorizationData{
		ProxyEndpoint:      aws.String(testProxyEndpoint),
		AuthorizationToken: aws.String(testToken),
		ExpiresAt:          aws.Time(time.Now().Add(12 * time.Hour)),
	}

	suite.mockClient.EXPECT().GetAuthorizationToken(
		&ecrapi.GetAuthorizationTokenInput{
			RegistryIds: []*string{aws.String(testRegistryId)},
		}).Return(&ecrapi.GetAuthorizationTokenOutput{
		AuthorizationData: []*ecrapi.AuthorizationData{testAuthData},
	}, nil)

	suite.mockCache.EXPECT().Get(testRegistryId).Return(expiredAuthData, true)
	suite.mockCache.EXPECT().Set(testRegistryId, testAuthData)

	authorizationData, err := suite.ecrClient.GetAuthorizationToken(testRegistryId)
	assert.NoError(suite.T(), err)
	assert.Equal(suite.T(), testAuthData, authorizationData)
}
Пример #11
0
func ExampleEMR_DescribeJobFlows() {
	svc := emr.New(session.New())

	params := &emr.DescribeJobFlowsInput{
		CreatedAfter:  aws.Time(time.Now()),
		CreatedBefore: aws.Time(time.Now()),
		JobFlowIds: []*string{
			aws.String("XmlString"), // Required
			// More values...
		},
		JobFlowStates: []*string{
			aws.String("JobFlowExecutionState"), // Required
			// More values...
		},
	}
	resp, err := svc.DescribeJobFlows(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)
}
Пример #12
0
func ExampleCloudTrail_ListPublicKeys() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := cloudtrail.New(sess)

	params := &cloudtrail.ListPublicKeysInput{
		EndTime:   aws.Time(time.Now()),
		NextToken: aws.String("String"),
		StartTime: aws.Time(time.Now()),
	}
	resp, err := svc.ListPublicKeys(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)
}
Пример #13
0
func ExampleEMR_ListClusters() {
	svc := emr.New(nil)

	params := &emr.ListClustersInput{
		ClusterStates: []*string{
			aws.String("ClusterState"), // Required
			// More values...
		},
		CreatedAfter:  aws.Time(time.Now()),
		CreatedBefore: aws.Time(time.Now()),
		Marker:        aws.String("Marker"),
	}
	resp, err := svc.ListClusters(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))
}
Пример #14
0
func ExampleWAF_GetSampledRequests() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := waf.New(sess)

	params := &waf.GetSampledRequestsInput{
		MaxItems: aws.Int64(1),             // Required
		RuleId:   aws.String("ResourceId"), // Required
		TimeWindow: &waf.TimeWindow{ // Required
			EndTime:   aws.Time(time.Now()), // Required
			StartTime: aws.Time(time.Now()), // Required
		},
		WebAclId: aws.String("ResourceId"), // Required
	}
	resp, err := svc.GetSampledRequests(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)
}
Пример #15
0
func ExampleConfigService_GetResourceConfigHistory() {
	svc := configservice.New(nil)

	params := &configservice.GetResourceConfigHistoryInput{
		ResourceID:         aws.String("ResourceId"),   // Required
		ResourceType:       aws.String("ResourceType"), // Required
		ChronologicalOrder: aws.String("ChronologicalOrder"),
		EarlierTime:        aws.Time(time.Now()),
		LaterTime:          aws.Time(time.Now()),
		Limit:              aws.Int64(1),
		NextToken:          aws.String("NextToken"),
	}
	resp, err := svc.GetResourceConfigHistory(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))
}
Пример #16
0
func ExampleRedshift_DescribeEvents() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := redshift.New(sess)

	params := &redshift.DescribeEventsInput{
		Duration:         aws.Int64(1),
		EndTime:          aws.Time(time.Now()),
		Marker:           aws.String("String"),
		MaxRecords:       aws.Int64(1),
		SourceIdentifier: aws.String("String"),
		SourceType:       aws.String("SourceType"),
		StartTime:        aws.Time(time.Now()),
	}
	resp, err := svc.DescribeEvents(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)
}
Пример #17
0
func TestGetStatistics(t *testing.T) {
	mockCtrl := gomock.NewController(t)
	defer mockCtrl.Finish()
	serviceMock := mock_cloudwatchiface.NewMockCloudWatchAPI(mockCtrl)

	metrics := [][]string{
		[]string{"Invocations", "Count"},
		[]string{"Errors", "Count"},
		[]string{"Duration", "Milliseconds"},
		[]string{"Throttles", "Count"},
	}

	startTime := time.Date(2016, time.January, 17, 10, 0, 0, 0, time.UTC)
	endTime := time.Date(2016, time.January, 18, 18, 0, 0, 0, time.UTC)

	for _, metric := range metrics {
		rand.Seed(time.Now().UTC().UnixNano())
		serviceMock.EXPECT().GetMetricStatistics(&cloudwatch.GetMetricStatisticsInput{
			MetricName: aws.String(metric[0]),
			Namespace:  aws.String("AWS/Lambda"),
			StartTime:  aws.Time(startTime),
			EndTime:    aws.Time(endTime),
			Period:     aws.Int64(int64((time.Duration(24) * time.Hour).Seconds())),
			Statistics: []*string{
				aws.String("Sum"),
			},
			Dimensions: []*cloudwatch.Dimension{
				{
					Name:  aws.String("FunctionName"),
					Value: aws.String("go_testf"),
				},
			},
			Unit: aws.String(metric[1]),
		}).Return(&cloudwatch.GetMetricStatisticsOutput{
			Datapoints: []*cloudwatch.Datapoint{
				&cloudwatch.Datapoint{Sum: aws.Float64(float64(rand.Intn(9999)))},
			},
			Label: aws.String("label"),
		}, nil)
	}

	name := "go_testf"

	mc := &MetricCollector{
		Metrics:      []string{"Invocations", "Errors", "Duration", "Throttles"},
		Collected:    0,
		FunctionName: name,
		Service:      serviceMock,
		StartDate:    startTime,
		EndDate:      endTime,
	}

	count := 0
	for _ = range mc.Collect() {
		count++
	}
	if count != 4 {
		t.Errorf("Wrong metrics count")
	}
}
func ExampleSWF_CountOpenWorkflowExecutions() {
	svc := swf.New(session.New())

	params := &swf.CountOpenWorkflowExecutionsInput{
		Domain: aws.String("DomainName"), // Required
		StartTimeFilter: &swf.ExecutionTimeFilter{ // Required
			OldestDate: aws.Time(time.Now()), // Required
			LatestDate: aws.Time(time.Now()),
		},
		ExecutionFilter: &swf.WorkflowExecutionFilter{
			WorkflowId: aws.String("WorkflowId"), // Required
		},
		TagFilter: &swf.TagFilter{
			Tag: aws.String("Tag"), // Required
		},
		TypeFilter: &swf.WorkflowTypeFilter{
			Name:    aws.String("Name"), // Required
			Version: aws.String("VersionOptional"),
		},
	}
	resp, err := svc.CountOpenWorkflowExecutions(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 ExampleElasticBeanstalk_DescribeEvents() {
	svc := elasticbeanstalk.New(session.New())

	params := &elasticbeanstalk.DescribeEventsInput{
		ApplicationName: aws.String("ApplicationName"),
		EndTime:         aws.Time(time.Now()),
		EnvironmentId:   aws.String("EnvironmentId"),
		EnvironmentName: aws.String("EnvironmentName"),
		MaxRecords:      aws.Int64(1),
		NextToken:       aws.String("Token"),
		RequestId:       aws.String("RequestId"),
		Severity:        aws.String("EventSeverity"),
		StartTime:       aws.Time(time.Now()),
		TemplateName:    aws.String("ConfigurationTemplateName"),
		VersionLabel:    aws.String("VersionLabel"),
	}
	resp, err := svc.DescribeEvents(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)
}
Пример #20
0
func ExampleCloudTrail_LookupEvents() {
	svc := cloudtrail.New(nil)

	params := &cloudtrail.LookupEventsInput{
		EndTime: aws.Time(time.Now()),
		LookupAttributes: []*cloudtrail.LookupAttribute{
			{ // Required
				AttributeKey:   aws.String("LookupAttributeKey"), // Required
				AttributeValue: aws.String("String"),             // Required
			},
			// More values...
		},
		MaxResults: aws.Int64(1),
		NextToken:  aws.String("NextToken"),
		StartTime:  aws.Time(time.Now()),
	}
	resp, err := svc.LookupEvents(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)
}
Пример #21
0
func ExampleGameLift_DescribeFleetEvents() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := gamelift.New(sess)

	params := &gamelift.DescribeFleetEventsInput{
		FleetId:   aws.String("FleetId"), // Required
		EndTime:   aws.Time(time.Now()),
		Limit:     aws.Int64(1),
		NextToken: aws.String("NonZeroAndMaxString"),
		StartTime: aws.Time(time.Now()),
	}
	resp, err := svc.DescribeFleetEvents(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)
}
Пример #22
0
func getLastPoint(cloudWatch *cloudwatch.CloudWatch, dimension *cloudwatch.Dimension, metricName string) (float64, error) {
	now := time.Now()
	response, err := cloudWatch.GetMetricStatistics(&cloudwatch.GetMetricStatisticsInput{
		StartTime:  aws.Time(now.Add(time.Duration(600) * time.Second * -1)),
		EndTime:    aws.Time(now),
		Period:     aws.Int64(60),
		Namespace:  aws.String("AWS/EC2"),
		Dimensions: []*cloudwatch.Dimension{dimension},
		MetricName: aws.String(metricName),
		Statistics: []*string{aws.String("Average")},
	})
	if err != nil {
		return 0, err
	}

	datapoints := response.Datapoints
	if len(datapoints) == 0 {
		return 0, errors.New("fetched no datapoints")
	}

	latest := time.Unix(0, 0)
	var latestVal float64
	for _, dp := range datapoints {
		if dp.Timestamp.Before(latest) {
			continue
		}

		latest = *dp.Timestamp
		latestVal = *dp.Average
	}

	return latestVal, nil
}
Пример #23
0
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)
}
Пример #24
0
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)
}
Пример #25
0
func ExampleAutoScaling_PutScheduledUpdateGroupAction() {
	svc := autoscaling.New(session.New())

	params := &autoscaling.PutScheduledUpdateGroupActionInput{
		AutoScalingGroupName: aws.String("ResourceName"),       // Required
		ScheduledActionName:  aws.String("XmlStringMaxLen255"), // Required
		DesiredCapacity:      aws.Int64(1),
		EndTime:              aws.Time(time.Now()),
		MaxSize:              aws.Int64(1),
		MinSize:              aws.Int64(1),
		Recurrence:           aws.String("XmlStringMaxLen255"),
		StartTime:            aws.Time(time.Now()),
		Time:                 aws.Time(time.Now()),
	}
	resp, err := svc.PutScheduledUpdateGroupAction(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)
}
Пример #26
0
func ExampleS3_UploadPartCopy() {
	svc := s3.New(nil)

	params := &s3.UploadPartCopyInput{
		Bucket:                         aws.String("BucketName"),        // Required
		CopySource:                     aws.String("CopySource"),        // Required
		Key:                            aws.String("ObjectKey"),         // Required
		PartNumber:                     aws.Int64(1),                    // Required
		UploadId:                       aws.String("MultipartUploadId"), // Required
		CopySourceIfMatch:              aws.String("CopySourceIfMatch"),
		CopySourceIfModifiedSince:      aws.Time(time.Now()),
		CopySourceIfNoneMatch:          aws.String("CopySourceIfNoneMatch"),
		CopySourceIfUnmodifiedSince:    aws.Time(time.Now()),
		CopySourceRange:                aws.String("CopySourceRange"),
		CopySourceSSECustomerAlgorithm: aws.String("CopySourceSSECustomerAlgorithm"),
		CopySourceSSECustomerKey:       aws.String("CopySourceSSECustomerKey"),
		CopySourceSSECustomerKeyMD5:    aws.String("CopySourceSSECustomerKeyMD5"),
		RequestPayer:                   aws.String("RequestPayer"),
		SSECustomerAlgorithm:           aws.String("SSECustomerAlgorithm"),
		SSECustomerKey:                 aws.String("SSECustomerKey"),
		SSECustomerKeyMD5:              aws.String("SSECustomerKeyMD5"),
	}
	resp, err := svc.UploadPartCopy(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)
}
Пример #27
0
func awsGetDiskOps(cw cloudwatch.CloudWatch, md *opentsdb.MultiDataPoint, instance *ec2.Instance) error {
	search := cloudwatch.GetMetricStatisticsInput{
		StartTime:  aws.Time(time.Now().UTC().Add(time.Second * -600)),
		EndTime:    aws.Time(time.Now().UTC()),
		MetricName: aws.String("DiskReadOps"),
		Period:     &aws_period,
		Statistics: []*string{aws.String("Average")},
		Namespace:  aws.String("AWS/EC2"),
		Unit:       aws.String("Count"),
		Dimensions: []*cloudwatch.Dimension{{Name: aws.String("InstanceId"), Value: instance.InstanceId}},
	}
	resp, err := cw.GetMetricStatistics(&search)
	if err != nil {
		return err
	}
	for _, datapoint := range resp.Datapoints {
		AddTS(md, awsEC2DiskOps, datapoint.Timestamp.Unix(), *datapoint.Average, opentsdb.TagSet{"instance": *instance.InstanceId, "operation": "read"}, metadata.Gauge, metadata.Count, descAWSEC2DiskOps)
	}
	search.MetricName = aws.String("DiskWriteOps")
	resp, err = cw.GetMetricStatistics(&search)
	if err != nil {
		return err
	}
	for _, datapoint := range resp.Datapoints {
		AddTS(md, awsEC2DiskOps, datapoint.Timestamp.Unix(), *datapoint.Average, opentsdb.TagSet{"instance": *instance.InstanceId, "operation": "write"}, metadata.Gauge, metadata.Count, descAWSEC2DiskOps)
	}
	return nil
}
Пример #28
0
func ExampleS3_HeadObject() {
	svc := s3.New(nil)

	params := &s3.HeadObjectInput{
		Bucket:               aws.String("BucketName"), // Required
		Key:                  aws.String("ObjectKey"),  // Required
		IfMatch:              aws.String("IfMatch"),
		IfModifiedSince:      aws.Time(time.Now()),
		IfNoneMatch:          aws.String("IfNoneMatch"),
		IfUnmodifiedSince:    aws.Time(time.Now()),
		Range:                aws.String("Range"),
		RequestPayer:         aws.String("RequestPayer"),
		SSECustomerAlgorithm: aws.String("SSECustomerAlgorithm"),
		SSECustomerKey:       aws.String("SSECustomerKey"),
		SSECustomerKeyMD5:    aws.String("SSECustomerKeyMD5"),
		VersionId:            aws.String("ObjectVersionId"),
	}
	resp, err := svc.HeadObject(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)
}
Пример #29
0
func ExampleCodeDeploy_ListDeployments() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := codedeploy.New(sess)

	params := &codedeploy.ListDeploymentsInput{
		ApplicationName: aws.String("ApplicationName"),
		CreateTimeRange: &codedeploy.TimeRange{
			End:   aws.Time(time.Now()),
			Start: aws.Time(time.Now()),
		},
		DeploymentGroupName: aws.String("DeploymentGroupName"),
		IncludeOnlyStatuses: []*string{
			aws.String("DeploymentStatus"), // Required
			// More values...
		},
		NextToken: aws.String("NextToken"),
	}
	resp, err := svc.ListDeployments(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)
}
Пример #30
0
func ExampleRoute53Domains_ViewBilling() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := route53domains.New(sess)

	params := &route53domains.ViewBillingInput{
		End:      aws.Time(time.Now()),
		Marker:   aws.String("PageMarker"),
		MaxItems: aws.Int64(1),
		Start:    aws.Time(time.Now()),
	}
	resp, err := svc.ViewBilling(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)
}