Skip to content

Commit

Permalink
add invoke
Browse files Browse the repository at this point in the history
  • Loading branch information
fujiwara committed Oct 28, 2019
1 parent 42bc087 commit f970370
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
9 changes: 9 additions & 0 deletions cmd/lambroll/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,13 @@ func _main() int {
DryRun: delete.Flag("dry-run", "dry run").Bool(),
}

invoke := kingpin.Command("invoke", "invoke function")
invokeOption := lambroll.InvokeOption{
FunctionFilePath: invoke.Flag("function", "Function file path").Default(lambroll.FunctionFilename).String(),
Async: invoke.Flag("async", "invocation type async").Bool(),
LogTail: invoke.Flag("log-tail", "output tail of log to STDERR").Bool(),
}

command := kingpin.Parse()

filter := &logutils.LevelFilter{
Expand Down Expand Up @@ -80,6 +87,8 @@ func _main() int {
err = app.Rollback(rollbackOption)
case "delete":
err = app.Delete(deleteOption)
case "invoke":
err = app.Invoke(invokeOption)
}

if err != nil {
Expand Down
78 changes: 78 additions & 0 deletions invoke.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package lambroll

import (
"bufio"
"encoding/base64"
"encoding/json"
"io"
"log"
"os"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/pkg/errors"
)

// InvokeOption represents option for Invoke()
type InvokeOption struct {
FunctionFilePath *string
Async *bool
LogTail *bool
}

// Invoke invokes function
func (app *App) Invoke(opt InvokeOption) error {
def, err := app.loadFunction(*opt.FunctionFilePath)
if err != nil {
return errors.Wrap(err, "failed to load function")
}
var invocationType, logType *string
if *opt.Async {
invocationType = aws.String("Event")
} else {
invocationType = aws.String("RequestResponse")
}
if *opt.LogTail {
logType = aws.String("Tail")
}

dec := json.NewDecoder(os.Stdin)
stdout := bufio.NewWriter(os.Stdout)
stderr := bufio.NewWriter(os.Stderr)
PAYLOAD:
for {
var payload interface{}
err := dec.Decode(&payload)
if err != nil {
if err == io.EOF {
break
}
return errors.Wrap(err, "failed to decode payload as JSON")
}
b, _ := json.Marshal(payload)
in := &lambda.InvokeInput{
FunctionName: def.FunctionName,
InvocationType: invocationType,
LogType: logType,
Payload: b,
}
log.Println("[debug] invoking function", in.String())
res, err := app.lambda.Invoke(in)
if err != nil {
log.Println("[error] failed to invoke function", err.Error())
continue PAYLOAD
}
stdout.Write(res.Payload)
stdout.Write([]byte("\n"))
stdout.Flush()

log.Printf("[info] StatusCode:%d ExecutionVersion:%s", *res.StatusCode, *res.ExecutedVersion)
if res.LogResult != nil {
b, _ := base64.StdEncoding.DecodeString(*res.LogResult)
stderr.Write(b)
stderr.Flush()
}
}

return nil
}

0 comments on commit f970370

Please sign in to comment.