Exemplo n.º 1
0
func addToLambda(dir string) error {
	desc, err := util.ReadTestDescription(dir)
	if err != nil {
		return err
	}

	var zipContents []byte
	if desc.Runtime == "java8" {
		zipContents, err = ioutil.ReadFile(filepath.Join(dir, "test-build.jar"))
		if err != nil {
			return err
		}
	} else {
		zipContents, err = makeZip(dir)
		if err != nil {
			return err
		}
	}

	s := session.New(&aws.Config{Region: aws.String("us-east-1"), Credentials: credentials.NewEnvCredentials()})

	l := lambda.New(s)

	err = createLambdaFunction(l, zipContents, desc.Runtime, lambdaRole, desc.Name, desc.Handler, desc.Timeout)
	return err
}
Exemplo n.º 2
0
func ExampleLambda_UpdateFunctionCode() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := lambda.New(sess)

	params := &lambda.UpdateFunctionCodeInput{
		FunctionName:    aws.String("FunctionName"), // Required
		Publish:         aws.Bool(true),
		S3Bucket:        aws.String("S3Bucket"),
		S3Key:           aws.String("S3Key"),
		S3ObjectVersion: aws.String("S3ObjectVersion"),
		ZipFile:         []byte("PAYLOAD"),
	}
	resp, err := svc.UpdateFunctionCode(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
func ExampleLambda_InvokeAsync() {
	svc := lambda.New(nil)

	params := &lambda.InvokeAsyncInput{
		FunctionName: aws.String("FunctionName"),         // Required
		InvokeArgs:   bytes.NewReader([]byte("PAYLOAD")), // Required
	}
	resp, err := svc.InvokeAsync(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))
}
Exemplo n.º 4
0
func (s *Service) InvokeLambda(payload *bridge.Request) (br bridge.Response) {
	if s.lamdbaSvc == nil {
		// Setup the AWS Creds.
		c := aws.NewConfig().WithCredentials(credentials.NewStaticCredentials(s.AWS.AccessKey, s.AWS.SecretKey, "")).WithRegion(s.AWS.Region)
		s.lamdbaSvc = lambda.New(session.New(c))
	}

	params := &lambda.InvokeInput{
		FunctionName: aws.String(s.FunctionName),
		Payload:      payload.JSON(),
	}

	resp, err := s.lamdbaSvc.Invoke(params)
	if err != nil {
		return bridge.ErrorResponse(fmt.Sprintf("lambda invoke error %v", err))
	}

	// Pretty-print the response data.
	log.Println("lambda response", string(resp.Payload))

	err = json.Unmarshal(resp.Payload, &br)
	if err != nil {
		log.Println("failed to unmarshal response", err)
		return bridge.ErrorResponse("failed to unmarshal response")
	}

	return
}
Exemplo n.º 5
0
func ExampleLambda_UpdateAlias() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := lambda.New(sess)

	params := &lambda.UpdateAliasInput{
		FunctionName:    aws.String("FunctionName"), // Required
		Name:            aws.String("Alias"),        // Required
		Description:     aws.String("Description"),
		FunctionVersion: aws.String("Version"),
	}
	resp, err := svc.UpdateAlias(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.º 6
0
func ExampleLambda_ListFunctions() {
	svc := lambda.New(nil)

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

	params := &lambda.AddPermissionInput{
		Action:           aws.String("Action"),       // Required
		FunctionName:     aws.String("FunctionName"), // Required
		Principal:        aws.String("Principal"),    // Required
		StatementId:      aws.String("StatementId"),  // Required
		EventSourceToken: aws.String("EventSourceToken"),
		Qualifier:        aws.String("Qualifier"),
		SourceAccount:    aws.String("SourceOwner"),
		SourceArn:        aws.String("Arn"),
	}
	resp, err := svc.AddPermission(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.º 8
0
func (b *Build) CreateLambda() error {

	zipBytes, err := ioutil.ReadFile(b.Directory + ".zip")
	if err != nil {
		return err
	}

	svc := lambda.New(&aws.Config{Region: aws.String("us-east-1")})

	params := &lambda.CreateFunctionInput{
		Code: &lambda.FunctionCode{
			ZipFile: zipBytes,
		},
		FunctionName: aws.String(b.Directory),                                             // Required
		Handler:      aws.String("handler_example.handler"),                               // Required
		Role:         aws.String("arn:aws:iam::651778473396:role/lambda_basic_execution"), // Required
		Runtime:      aws.String("nodejs"),                                                // Required
		// Description:  aws.String("nodejs"),
		MemorySize: aws.Int64(150),
		Timeout:    aws.Int64(3),
	}
	resp, err := svc.CreateFunction(params)
	_ = resp
	if err != nil {
		return err
	}
	return nil
}
Exemplo n.º 9
0
func ExampleLambda_UpdateFunctionConfiguration() {
	svc := lambda.New(nil)

	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 {
		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))
}
Exemplo n.º 10
0
func ExampleLambda_RemovePermission() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := lambda.New(sess)

	params := &lambda.RemovePermissionInput{
		FunctionName: aws.String("FunctionName"), // Required
		StatementId:  aws.String("StatementId"),  // Required
		Qualifier:    aws.String("Qualifier"),
	}
	resp, err := svc.RemovePermission(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.º 11
0
func ExampleLambda_RemovePermission() {
	svc := lambda.New(nil)

	params := &lambda.RemovePermissionInput{
		FunctionName: aws.String("FunctionName"), // Required
		StatementID:  aws.String("StatementId"),  // Required
	}
	resp, err := svc.RemovePermission(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))
}
Exemplo n.º 12
0
func ExampleLambda_InvokeAsync() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := lambda.New(sess)

	params := &lambda.InvokeAsyncInput{
		FunctionName: aws.String("FunctionName"),         // Required
		InvokeArgs:   bytes.NewReader([]byte("PAYLOAD")), // Required
	}
	resp, err := svc.InvokeAsync(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_ListVersionsByFunction() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := lambda.New(sess)

	params := &lambda.ListVersionsByFunctionInput{
		FunctionName: aws.String("FunctionName"), // Required
		Marker:       aws.String("String"),
		MaxItems:     aws.Int64(1),
	}
	resp, err := svc.ListVersionsByFunction(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
func ExampleLambda_Invoke() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := lambda.New(sess)

	params := &lambda.InvokeInput{
		FunctionName:   aws.String("FunctionName"), // Required
		ClientContext:  aws.String("String"),
		InvocationType: aws.String("InvocationType"),
		LogType:        aws.String("LogType"),
		Payload:        []byte("PAYLOAD"),
		Qualifier:      aws.String("Qualifier"),
	}
	resp, err := svc.Invoke(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.º 15
0
func ExampleLambda_CreateEventSourceMapping() {
	svc := lambda.New(nil)

	params := &lambda.CreateEventSourceMappingInput{
		EventSourceARN:   aws.String("Arn"),                 // Required
		FunctionName:     aws.String("FunctionName"),        // Required
		StartingPosition: aws.String("EventSourcePosition"), // Required
		BatchSize:        aws.Int64(1),
		Enabled:          aws.Bool(true),
	}
	resp, err := svc.CreateEventSourceMapping(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))
}
Exemplo n.º 16
0
func (pv *PersistentValues) preRun(c *cobra.Command, args []string) {
	if l, err := log.ParseLevel(pv.LogLevel); err == nil {
		log.SetLevel(l)
	}

	pv.session = session.New(aws.NewConfig())

	pv.project = &project.Project{
		Log:  log.Log,
		Path: ".",
	}

	if pv.DryRun {
		log.SetLevel(log.WarnLevel)
		pv.project.Service = dryrun.New(pv.session)
		pv.project.Concurrency = 1
	} else {
		pv.project.Service = lambda.New(pv.session)
	}

	if pv.Chdir != "" {
		if err := os.Chdir(pv.Chdir); err != nil {
			log.Fatalf("error: %s", err)
		}
	}

	if err := pv.project.Open(); err != nil {
		log.Fatalf("error opening project: %s", err)
	}
}
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"),
		Runtime:      aws.String("Runtime"),
		Timeout:      aws.Int64(1),
		VpcConfig: &lambda.VpcConfig{
			SecurityGroupIds: []*string{
				aws.String("SecurityGroupId"), // Required
				// More values...
			},
			SubnetIds: []*string{
				aws.String("SubnetId"), // Required
				// More values...
			},
		},
	}
	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.º 18
0
func ExampleLambda_DeleteEventSourceMapping() {
	svc := lambda.New(nil)

	params := &lambda.DeleteEventSourceMappingInput{
		UUID: aws.String("String"), // Required
	}
	resp, err := svc.DeleteEventSourceMapping(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))
}
Exemplo n.º 19
0
func ExampleLambda_CreateEventSourceMapping() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := lambda.New(sess)

	params := &lambda.CreateEventSourceMappingInput{
		EventSourceArn:   aws.String("Arn"),                 // Required
		FunctionName:     aws.String("FunctionName"),        // Required
		StartingPosition: aws.String("EventSourcePosition"), // Required
		BatchSize:        aws.Int64(1),
		Enabled:          aws.Bool(true),
	}
	resp, err := svc.CreateEventSourceMapping(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.º 20
0
func ExampleLambda_Invoke() {
	svc := lambda.New(nil)

	params := &lambda.InvokeInput{
		FunctionName:   aws.String("FunctionName"), // Required
		ClientContext:  aws.String("String"),
		InvocationType: aws.String("InvocationType"),
		LogType:        aws.String("LogType"),
		Payload:        []byte("PAYLOAD"),
	}
	resp, err := svc.Invoke(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))
}
Exemplo n.º 21
0
func ExampleLambda_UpdateFunctionCode() {
	svc := lambda.New(nil)

	params := &lambda.UpdateFunctionCodeInput{
		FunctionName:    aws.String("FunctionName"), // Required
		S3Bucket:        aws.String("S3Bucket"),
		S3Key:           aws.String("S3Key"),
		S3ObjectVersion: aws.String("S3ObjectVersion"),
		ZipFile:         []byte("PAYLOAD"),
	}
	resp, err := svc.UpdateFunctionCode(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))
}
Exemplo n.º 22
0
func ExampleLambda_CreateFunction() {
	svc := lambda.New(nil)

	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),
		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.º 23
0
Arquivo: root.go Projeto: aom/apex
// PreRun sets up global tasks used for most commands, some use PreRunNoop
// to remove this default behaviour.
func preRun(c *cobra.Command, args []string) error {
	if l, err := log.ParseLevel(logLevel); err == nil {
		log.SetLevel(l)
	}

	config := aws.NewConfig()

	if profile != "" {
		config = config.WithCredentials(credentials.NewSharedCredentials("", profile))
	}

	Session = session.New(config)

	Project = &project.Project{
		Log:  log.Log,
		Path: ".",
	}

	if dryRun {
		log.SetLevel(log.WarnLevel)
		Project.Service = dryrun.New(Session)
		Project.Concurrency = 1
	} else {
		Project.Service = lambda.New(Session)
	}

	if chdir != "" {
		if err := os.Chdir(chdir); err != nil {
			return err
		}
	}

	return Project.Open()
}
Exemplo n.º 24
0
Arquivo: apex.go Projeto: yuishug/apex
func main() {
	args, err := docopt.Parse(usage, nil, true, version, false)
	if err != nil {
		log.Fatalf("error: %s", err)
	}

	log.SetHandler(cli.Default)

	if l, err := log.ParseLevel(args["--log-level"].(string)); err == nil {
		log.SetLevel(l)
	}

	if args["help"].(bool) {
		showHelp(args["<topic>"])
		return
	}

	session := session.New(aws.NewConfig())

	project := &project.Project{
		Log:  log.Log,
		Path: ".",
	}

	if args["--dry-run"].(bool) {
		log.SetLevel(log.WarnLevel)
		project.Service = dryrun.New(session)
		project.Concurrency = 1
	} else {
		project.Service = lambda.New(session)
	}

	if dir, ok := args["--chdir"].(string); ok {
		if err := os.Chdir(dir); err != nil {
			log.Fatalf("error: %s", err)
		}
	}

	if err := project.Open(); err != nil {
		log.Fatalf("error opening project: %s", err)
	}

	switch {
	case args["list"].(bool):
		list(project)
	case args["deploy"].(bool):
		deploy(project, args["<name>"].([]string), args["--env"].([]string))
	case args["delete"].(bool):
		delete(project, args["<name>"].([]string), args["--yes"].(bool))
	case args["invoke"].(bool):
		invoke(project, args["<name>"].([]string), args["--verbose"].(bool), args["--async"].(bool))
	case args["rollback"].(bool):
		rollback(project, args["<name>"].([]string), args["<version>"])
	case args["build"].(bool):
		build(project, args["<name>"].([]string))
	case args["logs"].(bool):
		tail(project, args["<name>"].([]string), args["--filter"].(string))
	}
}
Exemplo n.º 25
0
// Prepare handles the global CLI flags and shared functionality without
// the assumption that a Project has already been initialized.
//
// Precedence is currently:
//
//  - flags such as --profile
//  - env vars such as AWS_PROFILE
//  - files such as ~/.aws/config
//
func Prepare(c *cobra.Command, args []string) error {
	if l, err := log.ParseLevel(logLevel); err == nil {
		log.SetLevel(l)
	}

	// config defaults
	Config = aws.NewConfig()

	// profile from flag, config, env, "default"
	if profile == "" {
		profile, _ = utils.ProfileFromConfig(environment)
		if profile == "" {
			profile = os.Getenv("AWS_PROFILE")
			if profile == "" {
				profile = "default"
			}
		}
	}

	// the default SharedCredentialsProvider checks the env
	os.Setenv("AWS_PROFILE", profile)

	// region from flag, env, file
	if region == "" {
		region = os.Getenv("AWS_REGION")
		if region == "" {
			region, _ = utils.GetRegion(profile)
		}
	}

	if region != "" {
		Config = Config.WithRegion(region)
	}

	Session = session.New(Config)

	Project = &project.Project{
		Environment:      environment,
		InfraEnvironment: environment,
		Log:              log.Log,
		Path:             ".",
	}

	if dryRun {
		log.SetLevel(log.WarnLevel)
		Project.Service = dryrun.New(Session)
		Project.Concurrency = 1
	} else {
		Project.Service = lambda.New(Session)
	}

	if chdir != "" {
		if err := os.Chdir(chdir); err != nil {
			return err
		}
	}

	return nil
}
Exemplo n.º 26
0
func LambdaLoop(event <-chan *d2k.Event, callback func(*d2k.Event) interface{}) {
	// main driver for pushing Lambda events to trigger Lambda Function

	svc := lambda.New(&aws.Config{Region: "us-west-2"})

	// check if the target Lambda function exist
	params := new(lambda.ListFunctionsInput)
	if resp, err := svc.ListFunctions(params); err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			log.Fatalln("LambdaLoop:", awsErr.Code(), awsErr.Message())
		} else {
			log.Fatalln("LambdaLoop:", err)
		}
	} else if resp.Functions == nil {
		log.Fatalln("LambdaLoop: enpoint not found:", LambdaEndpoint)
	} else {
		found := false
		for _, desc := range resp.Functions {
			found = found || (*desc.FunctionName == LambdaEndpoint)
		}
		if !found {
			log.Fatalln("LambdaLoop: enpoint not found:", LambdaEndpoint)
		}
	}

	// timer for triggering a Lambda invoke
	var ticker = time.Tick(10 * time.Second)

	var backlog []interface{}

	// Enpoint exist, beging polling for events
	for {
		select {
		case one_event, ok := <-event:
			if !ok {
				log.Fatalln("LambdaLoop: docker event channel closed")
				return
			}
			backlog = append(backlog, callback(one_event))
		case <-ticker:
			if len(backlog) != 0 {
				if data, err := json.Marshal(backlog); err != nil {
					log.Fatalln(err)
				} else {
					params := &lambda.InvokeInput{
						FunctionName: &LambdaEndpoint,
						Payload:      data,
					}
					if _, err := svc.Invoke(params); err != nil {
						log.Fatalln(err)
					}
					log.Println("LambdaLoop: Invoke function:", LambdaEndpoint, "Payload:", string(data))
				}
				backlog = backlog[:0]
			}
		}
	}
}
Exemplo n.º 27
0
Arquivo: goad.go Projeto: goadapp/goad
func (t *Test) invokeLambda(awsConfig *aws.Config, args invokeArgs) {
	svc := lambda.New(session.New(), awsConfig)

	j, _ := json.Marshal(args)

	svc.InvokeAsync(&lambda.InvokeAsyncInput{
		FunctionName: aws.String("goad:" + version.LambdaVersion()),
		InvokeArgs:   bytes.NewReader(j),
	})
}
Exemplo n.º 28
0
func ExampleLambda_CreateFunction() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := lambda.New(sess)

	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"),
		Environment: &lambda.Environment{
			Variables: map[string]*string{
				"Key": aws.String("EnvironmentVariableValue"), // Required
				// More values...
			},
		},
		KMSKeyArn:  aws.String("KMSKeyArn"),
		MemorySize: aws.Int64(1),
		Publish:    aws.Bool(true),
		Timeout:    aws.Int64(1),
		VpcConfig: &lambda.VpcConfig{
			SecurityGroupIds: []*string{
				aws.String("SecurityGroupId"), // Required
				// More values...
			},
			SubnetIds: []*string{
				aws.String("SubnetId"), // Required
				// More values...
			},
		},
	}
	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.º 29
0
// Run command.
func run(c *cobra.Command, args []string) error {
	stats.Track("Metrics", map[string]interface{}{
		"since": duration,
	})

	if err := root.Project.LoadFunctions(args...); err != nil {
		return err
	}

	service := lambda.New(root.Session)

	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 {
		m := aggregated[fn.FunctionName]

		conf, err := service.GetFunctionConfiguration(&lambda.GetFunctionConfigurationInput{FunctionName: &fn.FunctionName})
		if err != nil {
			return err
		}

		memory := int(*conf.MemorySize)
		costTotal := humanize.FormatFloat("", cost.Cost(m.Invocations, m.Duration, memory))
		costDuration := humanize.FormatFloat("", cost.DurationCost(m.Duration, memory))
		costInvocations := humanize.FormatFloat("", cost.RequestCost(m.Invocations))

		fmt.Printf("  \033[%dm%s\033[0m\n", colors.Blue, fn.Name)
		fmt.Printf("    total cost: $%s\n", costTotal)
		fmt.Printf("    invocations: %s ($%s)\n", humanize.Comma(int64(m.Invocations)), costInvocations)
		fmt.Printf("    duration: %s ($%s)\n", time.Millisecond*time.Duration(m.Duration), costDuration)
		fmt.Printf("    throttles: %v\n", m.Throttles)
		fmt.Printf("    errors: %s\n", humanize.Comma(int64(m.Errors)))
		fmt.Printf("    memory: %d\n", memory)
		fmt.Println()
	}

	return nil
}
Exemplo n.º 30
0
func InvokeLambda(name string, payload []byte) (response *lambda.InvokeOutput, err error) {
	svc := lambda.New(&aws.Config{Region: aws.String("us-east-1")})

	params := &lambda.InvokeInput{
		FunctionName: aws.String(name), // Required
		// ClientContext:  aws.String("String"),
		InvocationType: aws.String("RequestResponse"),
		LogType:        aws.String("Tail"),
		Payload:        payload,
	}
	return svc.Invoke(params)
}