示例#1
0
func ExampleBudgets_UpdateNotification() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := budgets.New(sess)

	params := &budgets.UpdateNotificationInput{
		AccountId:  aws.String("AccountId"),  // Required
		BudgetName: aws.String("BudgetName"), // Required
		NewNotification: &budgets.Notification{ // Required
			ComparisonOperator: aws.String("ComparisonOperator"), // Required
			NotificationType:   aws.String("NotificationType"),   // Required
			Threshold:          aws.Float64(1.0),                 // Required
		},
		OldNotification: &budgets.Notification{ // Required
			ComparisonOperator: aws.String("ComparisonOperator"), // Required
			NotificationType:   aws.String("NotificationType"),   // Required
			Threshold:          aws.Float64(1.0),                 // Required
		},
	}
	resp, err := svc.UpdateNotification(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)
}
示例#2
0
func ExampleAutoScaling_ExecutePolicy() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := autoscaling.New(sess)

	params := &autoscaling.ExecutePolicyInput{
		PolicyName:           aws.String("ResourceName"), // Required
		AutoScalingGroupName: aws.String("ResourceName"),
		BreachThreshold:      aws.Float64(1.0),
		HonorCooldown:        aws.Bool(true),
		MetricValue:          aws.Float64(1.0),
	}
	resp, err := svc.ExecutePolicy(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)
}
示例#3
0
func ExampleAutoScaling_PutScalingPolicy() {
	svc := autoscaling.New(session.New())

	params := &autoscaling.PutScalingPolicyInput{
		AdjustmentType:          aws.String("XmlStringMaxLen255"), // Required
		AutoScalingGroupName:    aws.String("ResourceName"),       // Required
		PolicyName:              aws.String("XmlStringMaxLen255"), // Required
		Cooldown:                aws.Int64(1),
		EstimatedInstanceWarmup: aws.Int64(1),
		MetricAggregationType:   aws.String("XmlStringMaxLen32"),
		MinAdjustmentMagnitude:  aws.Int64(1),
		MinAdjustmentStep:       aws.Int64(1),
		PolicyType:              aws.String("XmlStringMaxLen64"),
		ScalingAdjustment:       aws.Int64(1),
		StepAdjustments: []*autoscaling.StepAdjustment{
			{ // Required
				ScalingAdjustment:        aws.Int64(1), // Required
				MetricIntervalLowerBound: aws.Float64(1.0),
				MetricIntervalUpperBound: aws.Float64(1.0),
			},
			// More values...
		},
	}
	resp, err := svc.PutScalingPolicy(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 TestExpandStepAdjustments(t *testing.T) {
	expanded := []interface{}{
		map[string]interface{}{
			"metric_interval_lower_bound": "1.0",
			"metric_interval_upper_bound": "2.0",
			"scaling_adjustment":          1,
		},
	}
	parameters, err := expandStepAdjustments(expanded)
	if err != nil {
		t.Fatalf("bad: %#v", err)
	}

	expected := &autoscaling.StepAdjustment{
		MetricIntervalLowerBound: aws.Float64(1.0),
		MetricIntervalUpperBound: aws.Float64(2.0),
		ScalingAdjustment:        aws.Int64(int64(1)),
	}

	if !reflect.DeepEqual(parameters[0], expected) {
		t.Fatalf(
			"Got:\n\n%#v\n\nExpected:\n\n%#v\n",
			parameters[0],
			expected)
	}
}
func createScheduleRunInput(p *model.RunParameters) *devicefarm.ScheduleRunInput {
	var wg sync.WaitGroup
	result := &devicefarm.ScheduleRunInput{
		ProjectArn: aws.String(p.ProjectArn),
		Test:       &devicefarm.ScheduleRunTest{},
		Configuration: &devicefarm.ScheduleRunConfiguration{
			Radios: &devicefarm.Radios{
				Bluetooth: aws.Bool(true),
				Gps:       aws.Bool(true),
				Nfc:       aws.Bool(true),
				Wifi:      aws.Bool(true),
			},
			Location: &devicefarm.Location{
				Latitude:  aws.Float64(47.6204),
				Longitude: aws.Float64(-122.3491),
			},
		},
	}

	result.Name = aws.String(p.Config.RunName)
	result.Configuration.AuxiliaryApps = aws.StringSlice(p.Config.AdditionalData.AuxiliaryApps)
	if p.Config.AdditionalData.BillingMethod != "" {
		result.Configuration.BillingMethod = aws.String(p.Config.AdditionalData.BillingMethod)
	}
	result.Configuration.Locale = aws.String(p.Config.AdditionalData.Locale)
	if p.Config.AdditionalData.Location.Latitude != 0 {
		result.Configuration.Location.Latitude = aws.Float64(p.Config.AdditionalData.Location.Latitude)
	}
	if p.Config.AdditionalData.Location.Longitude != 0 {
		result.Configuration.Location.Longitude = aws.Float64(p.Config.AdditionalData.Location.Longitude)
	}
	if p.Config.AdditionalData.NetworkProfileArn != "" {
		result.Configuration.NetworkProfileArn = aws.String(p.Config.AdditionalData.NetworkProfileArn)
	}
	result.Configuration.Radios.Bluetooth = aws.Bool(stringToBool(p.Config.AdditionalData.Radios.Bluetooth))
	result.Configuration.Radios.Gps = aws.Bool(stringToBool(p.Config.AdditionalData.Radios.Gps))
	result.Configuration.Radios.Nfc = aws.Bool(stringToBool(p.Config.AdditionalData.Radios.Nfc))
	result.Configuration.Radios.Wifi = aws.Bool(stringToBool(p.Config.AdditionalData.Radios.Wifi))
	result.Test.Filter = aws.String(p.Config.Test.Filter)
	result.Test.Parameters = aws.StringMap(p.Config.Test.Parameters)
	if p.Config.Test.Type != "" {
		result.Test.Type = aws.String(p.Config.Test.Type)
	} else {
		result.Test.Type = aws.String("BUILTIN_FUZZ")
	}
	if p.Config.Test.TestPackageArn != "" {
		result.Test.TestPackageArn = aws.String(p.Config.Test.TestPackageArn)
	} else {
		uploadTestPackage(p, result, &wg)
	}
	if p.Config.AdditionalData.ExtraDataPackageArn != "" {
		result.Configuration.ExtraDataPackageArn = aws.String(p.Config.AdditionalData.ExtraDataPackageArn)
	} else {
		uploadExtraData(p, result, &wg)
	}
	wg.Wait()
	return result
}
示例#6
0
func ExampleDeviceFarm_ScheduleRun() {
	svc := devicefarm.New(nil)

	params := &devicefarm.ScheduleRunInput{
		AppARN:        aws.String("AmazonResourceName"), // Required
		DevicePoolARN: aws.String("AmazonResourceName"), // Required
		ProjectARN:    aws.String("AmazonResourceName"), // Required
		Test: &devicefarm.ScheduleRunTest{ // Required
			Type:   aws.String("TestType"), // Required
			Filter: aws.String("Filter"),
			Parameters: map[string]*string{
				"Key": aws.String("String"), // Required
				// More values...
			},
			TestPackageARN: aws.String("AmazonResourceName"),
		},
		Configuration: &devicefarm.ScheduleRunConfiguration{
			AuxiliaryApps: []*string{
				aws.String("AmazonResourceName"), // Required
				// More values...
			},
			BillingMethod:       aws.String("BillingMethod"),
			ExtraDataPackageARN: aws.String("AmazonResourceName"),
			Locale:              aws.String("String"),
			Location: &devicefarm.Location{
				Latitude:  aws.Float64(1.0), // Required
				Longitude: aws.Float64(1.0), // Required
			},
			NetworkProfileARN: aws.String("AmazonResourceName"),
			Radios: &devicefarm.Radios{
				Bluetooth: aws.Bool(true),
				Gps:       aws.Bool(true),
				Nfc:       aws.Bool(true),
				Wifi:      aws.Bool(true),
			},
		},
		Name: aws.String("Name"),
	}
	resp, err := svc.ScheduleRun(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))
}
示例#7
0
func ExampleDeviceFarm_ScheduleRun() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := devicefarm.New(sess)

	params := &devicefarm.ScheduleRunInput{
		DevicePoolArn: aws.String("AmazonResourceName"), // Required
		ProjectArn:    aws.String("AmazonResourceName"), // Required
		Test: &devicefarm.ScheduleRunTest{ // Required
			Type:   aws.String("TestType"), // Required
			Filter: aws.String("Filter"),
			Parameters: map[string]*string{
				"Key": aws.String("String"), // Required
				// More values...
			},
			TestPackageArn: aws.String("AmazonResourceName"),
		},
		AppArn: aws.String("AmazonResourceName"),
		Configuration: &devicefarm.ScheduleRunConfiguration{
			AuxiliaryApps: []*string{
				aws.String("AmazonResourceName"), // Required
				// More values...
			},
			BillingMethod:       aws.String("BillingMethod"),
			ExtraDataPackageArn: aws.String("AmazonResourceName"),
			Locale:              aws.String("String"),
			Location: &devicefarm.Location{
				Latitude:  aws.Float64(1.0), // Required
				Longitude: aws.Float64(1.0), // Required
			},
			NetworkProfileArn: aws.String("AmazonResourceName"),
			Radios: &devicefarm.Radios{
				Bluetooth: aws.Bool(true),
				Gps:       aws.Bool(true),
				Nfc:       aws.Bool(true),
				Wifi:      aws.Bool(true),
			},
		},
		Name: aws.String("Name"),
	}
	resp, err := svc.ScheduleRun(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)
}
// Takes the result of flatmap.Expand for an array of step adjustments and
// returns a []*applicationautoscaling.StepAdjustment.
func expandAppautoscalingStepAdjustments(configured []interface{}) ([]*applicationautoscaling.StepAdjustment, error) {
	var adjustments []*applicationautoscaling.StepAdjustment

	// Loop over our configured step adjustments and create an array
	// of aws-sdk-go compatible objects. We're forced to convert strings
	// to floats here because there's no way to detect whether or not
	// an uninitialized, optional schema element is "0.0" deliberately.
	// With strings, we can test for "", which is definitely an empty
	// struct value.
	for _, raw := range configured {
		data := raw.(map[string]interface{})
		a := &applicationautoscaling.StepAdjustment{
			ScalingAdjustment: aws.Int64(int64(data["scaling_adjustment"].(int))),
		}
		if data["metric_interval_lower_bound"] != "" {
			bound := data["metric_interval_lower_bound"]
			switch bound := bound.(type) {
			case string:
				f, err := strconv.ParseFloat(bound, 64)
				if err != nil {
					return nil, fmt.Errorf(
						"metric_interval_lower_bound must be a float value represented as a string")
				}
				a.MetricIntervalLowerBound = aws.Float64(f)
			default:
				return nil, fmt.Errorf(
					"metric_interval_lower_bound isn't a string. This is a bug. Please file an issue.")
			}
		}
		if data["metric_interval_upper_bound"] != "" {
			bound := data["metric_interval_upper_bound"]
			switch bound := bound.(type) {
			case string:
				f, err := strconv.ParseFloat(bound, 64)
				if err != nil {
					return nil, fmt.Errorf(
						"metric_interval_upper_bound must be a float value represented as a string")
				}
				a.MetricIntervalUpperBound = aws.Float64(f)
			default:
				return nil, fmt.Errorf(
					"metric_interval_upper_bound isn't a string. This is a bug. Please file an issue.")
			}
		}
		adjustments = append(adjustments, a)
	}

	return adjustments, nil
}
func ExampleCloudWatch_PutMetricData() {
	svc := cloudwatch.New(nil)

	params := &cloudwatch.PutMetricDataInput{
		MetricData: []*cloudwatch.MetricDatum{ // Required
			{ // Required
				MetricName: aws.String("MetricName"), // Required
				Dimensions: []*cloudwatch.Dimension{
					{ // Required
						Name:  aws.String("DimensionName"),  // Required
						Value: aws.String("DimensionValue"), // Required
					},
					// More values...
				},
				StatisticValues: &cloudwatch.StatisticSet{
					Maximum:     aws.Float64(1.0), // Required
					Minimum:     aws.Float64(1.0), // Required
					SampleCount: aws.Float64(1.0), // Required
					Sum:         aws.Float64(1.0), // Required
				},
				Timestamp: aws.Time(time.Now()),
				Unit:      aws.String("StandardUnit"),
				Value:     aws.Float64(1.0),
			},
			// More values...
		},
		Namespace: aws.String("Namespace"), // Required
	}
	resp, err := svc.PutMetricData(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))
}
示例#10
0
func ExampleGameLift_PutScalingPolicy() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := gamelift.New(sess)

	params := &gamelift.PutScalingPolicyInput{
		ComparisonOperator:    aws.String("ComparisonOperatorType"), // Required
		EvaluationPeriods:     aws.Int64(1),                         // Required
		FleetId:               aws.String("FleetId"),                // Required
		MetricName:            aws.String("MetricName"),             // Required
		Name:                  aws.String("NonZeroAndMaxString"),    // Required
		ScalingAdjustment:     aws.Int64(1),                         // Required
		ScalingAdjustmentType: aws.String("ScalingAdjustmentType"),  // Required
		Threshold:             aws.Float64(1.0),                     // Required
	}
	resp, err := svc.PutScalingPolicy(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)
}
示例#11
0
// Helper function to send data.
func Send(cw *cloudwatch.CloudWatch, dn, dv, n string, v float64) {
	_, err := cw.PutMetricData(&cloudwatch.PutMetricDataInput{
		MetricData: []*cloudwatch.MetricDatum{
			{
				MetricName: aws.String(n),
				Dimensions: []*cloudwatch.Dimension{
					{
						Name:  aws.String(dn),
						Value: aws.String(dv),
					},
				},
				Timestamp: aws.Time(time.Now()),
				Value:     aws.Float64(v),
			},
		},
		Namespace: aws.String("Custom"),
	})
	if err != nil {
		log.Println(err)
		return
	}

	log.WithFields(log.Fields{
		"DimensionName":  dn,
		"DimensionValue": dv,
		"MetricName":     n,
		"MetricValue":    v,
	}).Info("Successfully posted to CloudWatch")
}
示例#12
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")
	}
}
示例#13
0
func ExampleMachineLearning_UpdateMLModel() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := machinelearning.New(sess)

	params := &machinelearning.UpdateMLModelInput{
		MLModelId:      aws.String("EntityId"), // Required
		MLModelName:    aws.String("EntityName"),
		ScoreThreshold: aws.Float64(1.0),
	}
	resp, err := svc.UpdateMLModel(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)
}
示例#14
0
// Test loading a series of items succeeds and Run exits cleanly
func TestLoadOK(t *testing.T) {
	items := newLoadItems(makeIntItem("v", 1), makeIntItem("v", 2), makeIntItem("v", 3))
	var values stringVals
	dyn := &fakeDynPuter{
		put: func(input *dynamodb.PutItemInput) (*dynamodb.PutItemOutput, error) {
			values.Add(aws.StringValue(input.Item["v"].N))
			return &dynamodb.PutItemOutput{
				ConsumedCapacity: &dynamodb.ConsumedCapacity{CapacityUnits: aws.Float64(1)},
			}, nil
		},
	}
	ld := &Loader{
		Dyn:         dyn,
		TableName:   "test-table",
		MaxParallel: 2,
		Source:      items,
	}

	done := make(chan error)
	go func() { done <- ld.Run() }()

	select {
	case <-time.After(time.Second):
		t.Fatal("Timed out waiting for Run to complete")
	case err := <-done:
		if err != nil {
			t.Error("Unexpected error from Run", err)
		}
	}

	expected := []string{"1", "2", "3"}
	if vals := values.Sorted(); !reflect.DeepEqual(vals, expected) {
		t.Error("Incorrect values sent to Dynamo", vals)
	}
}
示例#15
0
func ExampleMachineLearning_UpdateMLModel() {
	svc := machinelearning.New(nil)

	params := &machinelearning.UpdateMLModelInput{
		MLModelId:      aws.String("EntityId"), // Required
		MLModelName:    aws.String("EntityName"),
		ScoreThreshold: aws.Float64(1.0),
	}
	resp, err := svc.UpdateMLModel(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
// Test that a failure from readitem causes Run to exit with error
func TestLoadReadErr(t *testing.T) {
	testErr := errors.New("test error")
	items := newLoadItems(makeIntItem("v", 1), makeIntItem("v", 2), makeIntItem("v", 3))
	items.appendError(testErr)

	dyn := &fakeDynPuter{
		put: func(input *dynamodb.PutItemInput) (*dynamodb.PutItemOutput, error) {
			return &dynamodb.PutItemOutput{
				ConsumedCapacity: &dynamodb.ConsumedCapacity{CapacityUnits: aws.Float64(1)},
			}, nil
		},
	}

	ld := &Loader{
		Dyn:         dyn,
		TableName:   "test-table",
		MaxParallel: 2,
		Source:      items,
	}

	done := make(chan error)
	go func() { done <- ld.Run() }()

	select {
	case <-time.After(time.Second):
		t.Fatal("Timed out waiting for Run to complete")
	case err := <-done:
		if err != testErr {
			t.Error("Incorrect error from Run", err)
		}
	}
}
示例#17
0
func (m *mockCloudWatchClient) GetMetricStatistics(params *cloudwatch.GetMetricStatisticsInput) (*cloudwatch.GetMetricStatisticsOutput, error) {
	dataPoint := &cloudwatch.Datapoint{
		Timestamp:   params.EndTime,
		Minimum:     aws.Float64(0.1),
		Maximum:     aws.Float64(0.3),
		Average:     aws.Float64(0.2),
		Sum:         aws.Float64(123),
		SampleCount: aws.Float64(100),
		Unit:        aws.String("Seconds"),
	}
	result := &cloudwatch.GetMetricStatisticsOutput{
		Label:      aws.String("Latency"),
		Datapoints: []*cloudwatch.Datapoint{dataPoint},
	}
	return result, nil
}
示例#18
0
func ExampleCloudWatchLogs_PutMetricFilter() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := cloudwatchlogs.New(sess)

	params := &cloudwatchlogs.PutMetricFilterInput{
		FilterName:    aws.String("FilterName"),    // Required
		FilterPattern: aws.String("FilterPattern"), // Required
		LogGroupName:  aws.String("LogGroupName"),  // Required
		MetricTransformations: []*cloudwatchlogs.MetricTransformation{ // Required
			{ // Required
				MetricName:      aws.String("MetricName"),      // Required
				MetricNamespace: aws.String("MetricNamespace"), // Required
				MetricValue:     aws.String("MetricValue"),     // Required
				DefaultValue:    aws.Float64(1.0),
			},
			// More values...
		},
	}
	resp, err := svc.PutMetricFilter(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)
}
示例#19
0
func ExampleCloudWatch_PutMetricData() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := cloudwatch.New(sess)

	params := &cloudwatch.PutMetricDataInput{
		MetricData: []*cloudwatch.MetricDatum{ // Required
			{ // Required
				MetricName: aws.String("MetricName"), // Required
				Dimensions: []*cloudwatch.Dimension{
					{ // Required
						Name:  aws.String("DimensionName"),  // Required
						Value: aws.String("DimensionValue"), // Required
					},
					// More values...
				},
				StatisticValues: &cloudwatch.StatisticSet{
					Maximum:     aws.Float64(1.0), // Required
					Minimum:     aws.Float64(1.0), // Required
					SampleCount: aws.Float64(1.0), // Required
					Sum:         aws.Float64(1.0), // Required
				},
				Timestamp: aws.Time(time.Now()),
				Unit:      aws.String("StandardUnit"),
				Value:     aws.Float64(1.0),
			},
			// More values...
		},
		Namespace: aws.String("Namespace"), // Required
	}
	resp, err := svc.PutMetricData(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
文件: cw.go 项目: vanga/go-aws-mon
func addMetric(name, unit string, value float64, dimensions []*cloudwatch.Dimension, metricData []*cloudwatch.MetricDatum) (ret []*cloudwatch.MetricDatum, err error) {
	_metric := cloudwatch.MetricDatum{
		MetricName: aws.String(name),
		Unit:       aws.String(unit),
		Value:      aws.Float64(value),
		Dimensions: dimensions,
	}
	metricData = append(metricData, &_metric)
	return metricData, nil
}
func ExampleCloudWatch_PutMetricAlarm() {
	svc := cloudwatch.New(nil)

	params := &cloudwatch.PutMetricAlarmInput{
		AlarmName:          aws.String("AlarmName"),          // Required
		ComparisonOperator: aws.String("ComparisonOperator"), // Required
		EvaluationPeriods:  aws.Int64(1),                     // Required
		MetricName:         aws.String("MetricName"),         // Required
		Namespace:          aws.String("Namespace"),          // Required
		Period:             aws.Int64(1),                     // Required
		Statistic:          aws.String("Statistic"),          // Required
		Threshold:          aws.Float64(1.0),                 // Required
		ActionsEnabled:     aws.Bool(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.Prettify(resp))
}
示例#22
0
func ExampleApplicationAutoScaling_PutScalingPolicy() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := applicationautoscaling.New(sess)

	params := &applicationautoscaling.PutScalingPolicyInput{
		PolicyName:        aws.String("PolicyName"),           // Required
		ResourceId:        aws.String("ResourceIdMaxLen1600"), // Required
		ScalableDimension: aws.String("ScalableDimension"),    // Required
		ServiceNamespace:  aws.String("ServiceNamespace"),     // Required
		PolicyType:        aws.String("PolicyType"),
		StepScalingPolicyConfiguration: &applicationautoscaling.StepScalingPolicyConfiguration{
			AdjustmentType:         aws.String("AdjustmentType"),
			Cooldown:               aws.Int64(1),
			MetricAggregationType:  aws.String("MetricAggregationType"),
			MinAdjustmentMagnitude: aws.Int64(1),
			StepAdjustments: []*applicationautoscaling.StepAdjustment{
				{ // Required
					ScalingAdjustment:        aws.Int64(1), // Required
					MetricIntervalLowerBound: aws.Float64(1.0),
					MetricIntervalUpperBound: aws.Float64(1.0),
				},
				// More values...
			},
		},
	}
	resp, err := svc.PutScalingPolicy(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 buildMetricDatum(metricType string, unit string, value float64, dimensionData []*cloudwatch.Dimension) (metricDatum *cloudwatch.MetricDatum) {
	metricDatum = &cloudwatch.MetricDatum{
		MetricName: aws.String(metricType),
		Dimensions: dimensionData,
		Timestamp:  aws.Time(time.Now()),
		Unit:       aws.String(unit),
		Value:      aws.Float64(value),
	}

	return metricDatum
}
示例#24
0
func ExampleCloudWatch_PutMetricAlarm() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := cloudwatch.New(sess)

	params := &cloudwatch.PutMetricAlarmInput{
		AlarmName:          aws.String("AlarmName"),          // Required
		ComparisonOperator: aws.String("ComparisonOperator"), // Required
		EvaluationPeriods:  aws.Int64(1),                     // Required
		MetricName:         aws.String("MetricName"),         // Required
		Namespace:          aws.String("Namespace"),          // Required
		Period:             aws.Int64(1),                     // Required
		Statistic:          aws.String("Statistic"),          // Required
		Threshold:          aws.Float64(1.0),                 // Required
		ActionsEnabled:     aws.Bool(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 {
		// 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)
}
示例#25
0
func ExampleECS_RegisterContainerInstance() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := ecs.New(sess)

	params := &ecs.RegisterContainerInstanceInput{
		Attributes: []*ecs.Attribute{
			{ // Required
				Name:  aws.String("String"), // Required
				Value: aws.String("String"),
			},
			// More values...
		},
		Cluster:                           aws.String("String"),
		ContainerInstanceArn:              aws.String("String"),
		InstanceIdentityDocument:          aws.String("String"),
		InstanceIdentityDocumentSignature: aws.String("String"),
		TotalResources: []*ecs.Resource{
			{ // Required
				DoubleValue:  aws.Float64(1.0),
				IntegerValue: aws.Int64(1),
				LongValue:    aws.Int64(1),
				Name:         aws.String("String"),
				StringSetValue: []*string{
					aws.String("String"), // Required
					// More values...
				},
				Type: aws.String("String"),
			},
			// More values...
		},
		VersionInfo: &ecs.VersionInfo{
			AgentHash:     aws.String("String"),
			AgentVersion:  aws.String("String"),
			DockerVersion: aws.String("String"),
		},
	}
	resp, err := svc.RegisterContainerInstance(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 TestFlattenStepAdjustments(t *testing.T) {
	expanded := []*autoscaling.StepAdjustment{
		&autoscaling.StepAdjustment{
			MetricIntervalLowerBound: aws.Float64(1.0),
			MetricIntervalUpperBound: aws.Float64(2.0),
			ScalingAdjustment:        aws.Int64(int64(1)),
		},
	}

	result := flattenStepAdjustments(expanded)[0]
	if result == nil {
		t.Fatal("expected result to have value, but got nil")
	}
	if result["metric_interval_lower_bound"] != float64(1.0) {
		t.Fatalf("expected metric_interval_lower_bound to be 1.0, but got %d", result["metric_interval_lower_bound"])
	}
	if result["metric_interval_upper_bound"] != float64(2.0) {
		t.Fatalf("expected metric_interval_upper_bound to be 1.0, but got %d", result["metric_interval_upper_bound"])
	}
	if result["scaling_adjustment"] != int64(1) {
		t.Fatalf("expected scaling_adjustment to be 1, but got %d", result["scaling_adjustment"])
	}
}
示例#27
0
func ExampleMobileAnalytics_PutEvents() {
	svc := mobileanalytics.New(nil)

	params := &mobileanalytics.PutEventsInput{
		ClientContext: aws.String("String"), // Required
		Events: []*mobileanalytics.Event{ // Required
			{ // Required
				EventType: aws.String("String50Chars"),    // Required
				Timestamp: aws.String("ISO8601Timestamp"), // Required
				Attributes: map[string]*string{
					"Key": aws.String("String0to1000Chars"), // Required
					// More values...
				},
				Metrics: map[string]*float64{
					"Key": aws.Float64(1.0), // Required
					// More values...
				},
				Session: &mobileanalytics.Session{
					Duration:       aws.Int64(1),
					Id:             aws.String("String50Chars"),
					StartTimestamp: aws.String("ISO8601Timestamp"),
					StopTimestamp:  aws.String("ISO8601Timestamp"),
				},
				Version: aws.String("String10Chars"),
			},
			// More values...
		},
		ClientContextEncoding: aws.String("String"),
	}
	resp, err := svc.PutEvents(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))
}
示例#28
0
func ExampleECS_RegisterContainerInstance() {
	svc := ecs.New(nil)

	params := &ecs.RegisterContainerInstanceInput{
		Cluster:                           aws.String("String"),
		ContainerInstanceArn:              aws.String("String"),
		InstanceIdentityDocument:          aws.String("String"),
		InstanceIdentityDocumentSignature: aws.String("String"),
		TotalResources: []*ecs.Resource{
			{ // Required
				DoubleValue:  aws.Float64(1.0),
				IntegerValue: aws.Int64(1),
				LongValue:    aws.Int64(1),
				Name:         aws.String("String"),
				StringSetValue: []*string{
					aws.String("String"), // Required
					// More values...
				},
				Type: aws.String("String"),
			},
			// More values...
		},
		VersionInfo: &ecs.VersionInfo{
			AgentHash:     aws.String("String"),
			AgentVersion:  aws.String("String"),
			DockerVersion: aws.String("String"),
		},
	}
	resp, err := svc.RegisterContainerInstance(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))
}
示例#29
0
func ExampleMobileAnalytics_PutEvents() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := mobileanalytics.New(sess)

	params := &mobileanalytics.PutEventsInput{
		ClientContext: aws.String("String"), // Required
		Events: []*mobileanalytics.Event{ // Required
			{ // Required
				EventType: aws.String("String50Chars"),    // Required
				Timestamp: aws.String("ISO8601Timestamp"), // Required
				Attributes: map[string]*string{
					"Key": aws.String("String0to1000Chars"), // Required
					// More values...
				},
				Metrics: map[string]*float64{
					"Key": aws.Float64(1.0), // Required
					// More values...
				},
				Session: &mobileanalytics.Session{
					Duration:       aws.Int64(1),
					Id:             aws.String("String50Chars"),
					StartTimestamp: aws.String("ISO8601Timestamp"),
					StopTimestamp:  aws.String("ISO8601Timestamp"),
				},
				Version: aws.String("String10Chars"),
			},
			// More values...
		},
		ClientContextEncoding: aws.String("String"),
	}
	resp, err := svc.PutEvents(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 TestRunOK(t *testing.T) {
	// Start four parallel readers and make sure all data was read correctly
	dyn := &fakeDynamo{
		scan: func(input *dynamodb.ScanInput) (*dynamodb.ScanOutput, error) {
			segnum := int(aws.Int64Value(input.Segment))
			items := makeItems(segnum*10, 3)
			return &dynamodb.ScanOutput{
				Items:            items,
				ConsumedCapacity: &dynamodb.ConsumedCapacity{CapacityUnits: aws.Float64(1)},
			}, nil
		},
	}

	iw := new(testItemWriter)
	f := &Fetcher{
		Dyn:          dyn,
		limitCalc:    newLimitCalc(limitCalcSize),
		TableName:    "table-name",
		MaxParallel:  4,
		ReadCapacity: 10,
		Writer:       iw,
	}

	done := make(chan error)
	go func() { done <- f.Run() }()

	select {
	case <-time.After(time.Second):
		t.Fatal("Timed out waiting for Run to complete")
	case err := <-done:
		if err != nil {
			t.Error("Unexpected error from Run", err)
		}
	}

	expected := []int{0, 1, 2, 10, 11, 12, 20, 21, 22, 30, 31, 32}
	var actual []int
	for _, item := range iw.items {
		actual = append(actual, intItemValue("key", item))
	}
	sort.Ints(actual)

	if !reflect.DeepEqual(expected, actual) {
		t.Errorf("expected=%#v actual=%#v", expected, actual)
	}
}