Exemplo n.º 1
0
func ExampleLambda_CreateFunction() {
	svc := lambda.New(session.New())

	params := &lambda.CreateFunctionInput{
		Code: &lambda.FunctionCode{ // Required
			S3Bucket:        aws.String("S3Bucket"),
			S3Key:           aws.String("S3Key"),
			S3ObjectVersion: aws.String("S3ObjectVersion"),
			ZipFile:         []byte("PAYLOAD"),
		},
		FunctionName: aws.String("FunctionName"), // Required
		Handler:      aws.String("Handler"),      // Required
		Role:         aws.String("RoleArn"),      // Required
		Runtime:      aws.String("Runtime"),      // Required
		Description:  aws.String("Description"),
		MemorySize:   aws.Int64(1),
		Publish:      aws.Bool(true),
		Timeout:      aws.Int64(1),
	}
	resp, err := svc.CreateFunction(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)
}
Exemplo n.º 2
0
func ExampleSQS_ReceiveMessage() {
	svc := sqs.New(session.New())

	params := &sqs.ReceiveMessageInput{
		QueueUrl: aws.String("String"), // Required
		AttributeNames: []*string{
			aws.String("QueueAttributeName"), // Required
			// More values...
		},
		MaxNumberOfMessages: aws.Int64(1),
		MessageAttributeNames: []*string{
			aws.String("MessageAttributeName"), // Required
			// More values...
		},
		VisibilityTimeout: aws.Int64(1),
		WaitTimeSeconds:   aws.Int64(1),
	}
	resp, err := svc.ReceiveMessage(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)
}
Exemplo n.º 3
0
// Retrieve generates a new set of temporary credentials using STS.
func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error) {

	// Apply defaults where parameters are not set.
	if p.RoleSessionName == "" {
		// Try to work out a role name that will hopefully end up unique.
		p.RoleSessionName = fmt.Sprintf("%d", time.Now().UTC().UnixNano())
	}
	if p.Duration == 0 {
		// Expire as often as AWS permits.
		p.Duration = DefaultDuration
	}

	roleOutput, err := p.Client.AssumeRole(&sts.AssumeRoleInput{
		DurationSeconds: aws.Int64(int64(p.Duration / time.Second)),
		RoleArn:         aws.String(p.RoleARN),
		RoleSessionName: aws.String(p.RoleSessionName),
		ExternalId:      p.ExternalID,
	})

	if err != nil {
		return credentials.Value{}, err
	}

	// We will proactively generate new credentials before they expire.
	p.SetExpiration(*roleOutput.Credentials.Expiration, p.ExpiryWindow)

	return credentials.Value{
		AccessKeyID:     *roleOutput.Credentials.AccessKeyId,
		SecretAccessKey: *roleOutput.Credentials.SecretAccessKey,
		SessionToken:    *roleOutput.Credentials.SessionToken,
	}, nil
}
Exemplo n.º 4
0
func ExampleSQS_ChangeMessageVisibilityBatch() {
	svc := sqs.New(session.New())

	params := &sqs.ChangeMessageVisibilityBatchInput{
		Entries: []*sqs.ChangeMessageVisibilityBatchRequestEntry{ // Required
			{ // Required
				Id:                aws.String("String"), // Required
				ReceiptHandle:     aws.String("String"), // Required
				VisibilityTimeout: aws.Int64(1),
			},
			// More values...
		},
		QueueUrl: aws.String("String"), // Required
	}
	resp, err := svc.ChangeMessageVisibilityBatch(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 BenchmarkCodegenIterator(b *testing.B) {
	reqNum := 0
	db := benchDb()
	db.Handlers.Unmarshal.PushBack(func(r *request.Request) {
		r.Data = benchResps[reqNum]
		reqNum++
	})

	input := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
	iter := func(fn func(*dynamodb.ListTablesOutput, bool) bool) error {
		page, _ := db.ListTablesRequest(input)
		for ; page != nil; page = page.NextPage() {
			page.Send()
			out := page.Data.(*dynamodb.ListTablesOutput)
			if result := fn(out, !page.HasNextPage()); page.Error != nil || !result {
				return page.Error
			}
		}
		return nil
	}

	for i := 0; i < b.N; i++ {
		reqNum = 0
		iter(func(p *dynamodb.ListTablesOutput, last bool) bool {
			return true
		})
	}
}
Exemplo n.º 6
0
func (infra *Infrastructure) createLambdaFunction(region, roleArn string, payload []byte) error {
	config := aws.NewConfig().WithRegion(region)
	svc := lambda.New(session.New(), config)

	_, err := svc.GetFunction(&lambda.GetFunctionInput{
		FunctionName: aws.String("goad"),
	})

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			if awsErr.Code() == "ResourceNotFoundException" {
				_, err := svc.CreateFunction(&lambda.CreateFunctionInput{
					Code: &lambda.FunctionCode{
						ZipFile: payload,
					},
					FunctionName: aws.String("goad"),
					Handler:      aws.String("index.handler"),
					Role:         aws.String(roleArn),
					Runtime:      aws.String("nodejs"),
					MemorySize:   aws.Int64(1536),
					Publish:      aws.Bool(true),
					Timeout:      aws.Int64(300),
				})
				if err != nil {
					if awsErr, ok := err.(awserr.Error); ok {
						// Calling this function too soon after creating the role might
						// fail, so we should retry after a little while.
						// TODO: limit the number of retries.
						if awsErr.Code() == "InvalidParameterValueException" {
							time.Sleep(time.Second)
							return infra.createLambdaFunction(region, roleArn, payload)
						}
					}
					return err
				}
			}
		}
	}

	return nil
}
Exemplo n.º 7
0
// Receive a result, or timeout in 1 second
func (adaptor SQSAdaptor) Receive() *AggData {
	params := &sqs.ReceiveMessageInput{
		QueueUrl:            aws.String(adaptor.QueueURL),
		MaxNumberOfMessages: aws.Int64(1),
		VisibilityTimeout:   aws.Int64(1),
		WaitTimeSeconds:     aws.Int64(1),
	}
	resp, err := adaptor.Client.ReceiveMessage(params)

	if err != nil {
		fmt.Println(err.Error())
		return nil
	}

	if len(resp.Messages) == 0 {
		return nil
	}

	item := resp.Messages[0]

	deleteParams := &sqs.DeleteMessageInput{
		QueueUrl:      aws.String(adaptor.QueueURL),
		ReceiptHandle: aws.String(*item.ReceiptHandle),
	}
	_, delerr := adaptor.Client.DeleteMessage(deleteParams)

	if delerr != nil {
		fmt.Println(err.Error())
		return nil
	}

	result, jsonerr := resultFromJSON(*item.Body)
	if jsonerr != nil {
		fmt.Println(err.Error())
		return nil
	}

	return &result
}
// Use DynamoDB methods for simplicity
func TestPaginationEachPage(t *testing.T) {
	db := dynamodb.New(unit.Session)
	tokens, pages, numPages, gotToEnd := []string{}, []string{}, 0, false

	reqNum := 0
	resps := []*dynamodb.ListTablesOutput{
		{TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")},
		{TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")},
		{TableNames: []*string{aws.String("Table5")}},
	}

	db.Handlers.Send.Clear() // mock sending
	db.Handlers.Unmarshal.Clear()
	db.Handlers.UnmarshalMeta.Clear()
	db.Handlers.ValidateResponse.Clear()
	db.Handlers.Build.PushBack(func(r *request.Request) {
		in := r.Params.(*dynamodb.ListTablesInput)
		if in == nil {
			tokens = append(tokens, "")
		} else if in.ExclusiveStartTableName != nil {
			tokens = append(tokens, *in.ExclusiveStartTableName)
		}
	})
	db.Handlers.Unmarshal.PushBack(func(r *request.Request) {
		r.Data = resps[reqNum]
		reqNum++
	})

	params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
	req, _ := db.ListTablesRequest(params)
	err := req.EachPage(func(p interface{}, last bool) bool {
		numPages++
		for _, t := range p.(*dynamodb.ListTablesOutput).TableNames {
			pages = append(pages, *t)
		}
		if last {
			if gotToEnd {
				assert.Fail(t, "last=true happened twice")
			}
			gotToEnd = true
		}

		return true
	})

	assert.Equal(t, []string{"Table2", "Table4"}, tokens)
	assert.Equal(t, []string{"Table1", "Table2", "Table3", "Table4", "Table5"}, pages)
	assert.Equal(t, 3, numPages)
	assert.True(t, gotToEnd)
	assert.Nil(t, err)
}
Exemplo n.º 9
0
func ExampleLambda_UpdateFunctionConfiguration() {
	svc := lambda.New(session.New())

	params := &lambda.UpdateFunctionConfigurationInput{
		FunctionName: aws.String("FunctionName"), // Required
		Description:  aws.String("Description"),
		Handler:      aws.String("Handler"),
		MemorySize:   aws.Int64(1),
		Role:         aws.String("RoleArn"),
		Timeout:      aws.Int64(1),
	}
	resp, err := svc.UpdateFunctionConfiguration(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)
}
Exemplo n.º 10
0
func BenchmarkEachPageIterator(b *testing.B) {
	reqNum := 0
	db := benchDb()
	db.Handlers.Unmarshal.PushBack(func(r *request.Request) {
		r.Data = benchResps[reqNum]
		reqNum++
	})

	input := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
	for i := 0; i < b.N; i++ {
		reqNum = 0
		req, _ := db.ListTablesRequest(input)
		req.EachPage(func(p interface{}, last bool) bool {
			return true
		})
	}
}
Exemplo n.º 11
0
func ExampleLambda_ListFunctions() {
	svc := lambda.New(session.New())

	params := &lambda.ListFunctionsInput{
		Marker:   aws.String("String"),
		MaxItems: aws.Int64(1),
	}
	resp, err := svc.ListFunctions(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)
}
Exemplo n.º 12
0
func ExampleSQS_SendMessageBatch() {
	svc := sqs.New(session.New())

	params := &sqs.SendMessageBatchInput{
		Entries: []*sqs.SendMessageBatchRequestEntry{ // Required
			{ // Required
				Id:           aws.String("String"), // Required
				MessageBody:  aws.String("String"), // Required
				DelaySeconds: aws.Int64(1),
				MessageAttributes: map[string]*sqs.MessageAttributeValue{
					"Key": { // Required
						DataType: aws.String("String"), // Required
						BinaryListValues: [][]byte{
							[]byte("PAYLOAD"), // Required
							// More values...
						},
						BinaryValue: []byte("PAYLOAD"),
						StringListValues: []*string{
							aws.String("String"), // Required
							// More values...
						},
						StringValue: aws.String("String"),
					},
					// More values...
				},
			},
			// More values...
		},
		QueueUrl: aws.String("String"), // Required
	}
	resp, err := svc.SendMessageBatch(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)
}
Exemplo n.º 13
0
func ExampleLambda_UpdateEventSourceMapping() {
	svc := lambda.New(session.New())

	params := &lambda.UpdateEventSourceMappingInput{
		UUID:         aws.String("String"), // Required
		BatchSize:    aws.Int64(1),
		Enabled:      aws.Bool(true),
		FunctionName: aws.String("FunctionName"),
	}
	resp, err := svc.UpdateEventSourceMapping(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)
}
Exemplo n.º 14
0
// Use DynamoDB methods for simplicity
func TestPaginationEarlyExit(t *testing.T) {
	db := dynamodb.New(unit.Session)
	numPages, gotToEnd := 0, false

	reqNum := 0
	resps := []*dynamodb.ListTablesOutput{
		{TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")},
		{TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")},
		{TableNames: []*string{aws.String("Table5")}},
	}

	db.Handlers.Send.Clear() // mock sending
	db.Handlers.Unmarshal.Clear()
	db.Handlers.UnmarshalMeta.Clear()
	db.Handlers.ValidateResponse.Clear()
	db.Handlers.Unmarshal.PushBack(func(r *request.Request) {
		r.Data = resps[reqNum]
		reqNum++
	})

	params := &dynamodb.ListTablesInput{Limit: aws.Int64(2)}
	err := db.ListTablesPages(params, func(p *dynamodb.ListTablesOutput, last bool) bool {
		numPages++
		if numPages == 2 {
			return false
		}
		if last {
			if gotToEnd {
				assert.Fail(t, "last=true happened twice")
			}
			gotToEnd = true
		}
		return true
	})

	assert.Equal(t, 2, numPages)
	assert.False(t, gotToEnd)
	assert.Nil(t, err)
}
Exemplo n.º 15
0
	for i := 0; i < b.N; i++ {
		buf := &bytes.Buffer{}
		encoder := json.NewEncoder(buf)
		if err := encoder.Encode(params); err != nil {
			b.Fatal("Unexpected error", err)
		}
	}
}

var restjsonBuildParms = &elastictranscoder.CreateJobInput{
	Input: &elastictranscoder.JobInput{ // Required
		AspectRatio: aws.String("AspectRatio"),
		Container:   aws.String("JobContainer"),
		DetectedProperties: &elastictranscoder.DetectedProperties{
			DurationMillis: aws.Int64(1),
			FileSize:       aws.Int64(1),
			FrameRate:      aws.String("FloatString"),
			Height:         aws.Int64(1),
			Width:          aws.Int64(1),
		},
		Encryption: &elastictranscoder.Encryption{
			InitializationVector: aws.String("ZeroTo255String"),
			Key:                  aws.String("Base64EncodedString"),
			KeyMd5:               aws.String("Base64EncodedString"),
			Mode:                 aws.String("EncryptionMode"),
		},
		FrameRate:  aws.String("FrameRate"),
		Interlaced: aws.String("Interlaced"),
		Key:        aws.String("Key"),
		Resolution: aws.String("Resolution"),
Exemplo n.º 16
0
// Use DynamoDB methods for simplicity
func TestPaginationQueryPage(t *testing.T) {
	db := dynamodb.New(unit.Session)
	tokens, pages, numPages, gotToEnd := []map[string]*dynamodb.AttributeValue{}, []map[string]*dynamodb.AttributeValue{}, 0, false

	reqNum := 0
	resps := []*dynamodb.QueryOutput{
		{
			LastEvaluatedKey: map[string]*dynamodb.AttributeValue{"key": {S: aws.String("key1")}},
			Count:            aws.Int64(1),
			Items: []map[string]*dynamodb.AttributeValue{
				{
					"key": {S: aws.String("key1")},
				},
			},
		},
		{
			LastEvaluatedKey: map[string]*dynamodb.AttributeValue{"key": {S: aws.String("key2")}},
			Count:            aws.Int64(1),
			Items: []map[string]*dynamodb.AttributeValue{
				{
					"key": {S: aws.String("key2")},
				},
			},
		},
		{
			LastEvaluatedKey: map[string]*dynamodb.AttributeValue{},
			Count:            aws.Int64(1),
			Items: []map[string]*dynamodb.AttributeValue{
				{
					"key": {S: aws.String("key3")},
				},
			},
		},
	}

	db.Handlers.Send.Clear() // mock sending
	db.Handlers.Unmarshal.Clear()
	db.Handlers.UnmarshalMeta.Clear()
	db.Handlers.ValidateResponse.Clear()
	db.Handlers.Build.PushBack(func(r *request.Request) {
		in := r.Params.(*dynamodb.QueryInput)
		if in == nil {
			tokens = append(tokens, nil)
		} else if len(in.ExclusiveStartKey) != 0 {
			tokens = append(tokens, in.ExclusiveStartKey)
		}
	})
	db.Handlers.Unmarshal.PushBack(func(r *request.Request) {
		r.Data = resps[reqNum]
		reqNum++
	})

	params := &dynamodb.QueryInput{
		Limit:     aws.Int64(2),
		TableName: aws.String("tablename"),
	}
	err := db.QueryPages(params, func(p *dynamodb.QueryOutput, last bool) bool {
		numPages++
		for _, item := range p.Items {
			pages = append(pages, item)
		}
		if last {
			if gotToEnd {
				assert.Fail(t, "last=true happened twice")
			}
			gotToEnd = true
		}
		return true
	})
	assert.Nil(t, err)

	assert.Equal(t,
		[]map[string]*dynamodb.AttributeValue{
			{"key": {S: aws.String("key1")}},
			{"key": {S: aws.String("key2")}},
		}, tokens)
	assert.Equal(t,
		[]map[string]*dynamodb.AttributeValue{
			{"key": {S: aws.String("key1")}},
			{"key": {S: aws.String("key2")}},
			{"key": {S: aws.String("key3")}},
		}, pages)
	assert.Equal(t, 3, numPages)
	assert.True(t, gotToEnd)
	assert.Nil(t, params.ExclusiveStartKey)
}