-
Notifications
You must be signed in to change notification settings - Fork 0
/
lambda_caller.go
193 lines (173 loc) · 5.07 KB
/
lambda_caller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package mantil
import (
"bufio"
"bytes"
"context"
"encoding/base64"
"fmt"
"log"
"net/http"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/arn"
awsConfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
"github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
"github.com/aws/aws-sdk-go-v2/service/lambda"
"github.com/aws/aws-sdk-go-v2/service/lambda/types"
"github.com/aws/aws-sdk-go-v2/service/sts"
)
// LambdaInvoker represents a helper for invoking lambda
// functions with cross-account support.
type LambdaInvoker struct {
function string
role string
client *lambda.Client
functionConfig *lambda.GetFunctionConfigurationOutput
}
// NewLambdaInvoker builds helper for invoking lambda functions.
//
// function can be name of the function or full arn
// name - my-function (name-only), my-function:v1 (with alias).
// arn:aws:lambda:us-west-2:123456789012:function:my-function.
//
// role is iam role to assume
// empty string if not needed; if the function is in the same aws account
// and caller has iam rights to invoke
// otherwise provide arn of the role
//
// Example of full format:
// NewLambdaInvoker(
// "arn:aws:lambda:eu-central-1:123456789012:function:dummy",
// "arn:aws:iam::123456789012:role/cross-account-execute-lambda",
// )
func NewLambdaInvoker(function, role string) (*LambdaInvoker, error) {
l := &LambdaInvoker{
function: function,
role: role,
}
return l, l.setup()
}
func (l *LambdaInvoker) setup() error {
cfg, err := awsConfig.LoadDefaultConfig(context.Background())
if err != nil {
return err
}
cred := cfg.Credentials
if l.role != "" {
cred = stscreds.NewAssumeRoleProvider(sts.NewFromConfig(cfg), l.role)
}
l.client = lambda.New(lambda.Options{
Region: l.region(cfg),
Credentials: cred,
})
return l.getConfig()
}
func (l *LambdaInvoker) region(cfg aws.Config) string {
// from lambda function arn
arn, err := arn.Parse(l.function)
if err == nil && arn.Region != "" {
return arn.Region
}
// from config
if cfg.Region != "" {
return cfg.Region
}
// from instance metadata
imdsc := imds.New(imds.Options{}) // Amazon EC2 Instance Metadata Service Client
ctx := context.Background()
iid, err := imdsc.GetInstanceIdentityDocument(ctx, nil)
if err == nil {
return iid.Region
}
// give up
return ""
}
// Call executes sync Lambda invoke.
// Expects payload to send in the Lambda function call.
func (l *LambdaInvoker) Call(payload []byte) ([]byte, error) {
input := &lambda.InvokeInput{
FunctionName: &l.function,
LogType: types.LogTypeTail,
Payload: payload,
}
output, err := l.client.Invoke(context.Background(), input)
if err != nil {
return nil, err
}
if !(output.StatusCode >= http.StatusOK && output.StatusCode < http.StatusMultipleChoices) {
if output.FunctionError != nil {
return nil, fmt.Errorf("failed with error: %s, status code: %d", *output.FunctionError, output.StatusCode)
}
return nil, fmt.Errorf("failed with status code: %d", output.StatusCode)
}
if err := l.showLog(output.LogResult); err != nil {
return nil, fmt.Errorf("showLog failed %w", err)
}
return output.Payload, nil
}
// CallAsync invokes the Lambda function asynchronously
func (l *LambdaInvoker) CallAsync(payload []byte) error {
return l.Cast(payload)
}
// Cast makes async Lambda invoke
func (l *LambdaInvoker) Cast(payload []byte) error {
input := &lambda.InvokeInput{
FunctionName: &l.function,
Payload: payload,
InvocationType: types.InvocationTypeEvent,
}
output, err := l.client.Invoke(context.Background(), input)
if err != nil {
return err
}
if !(output.StatusCode >= http.StatusOK && output.StatusCode < http.StatusMultipleChoices) {
return fmt.Errorf("failed with status code: %d", output.StatusCode)
}
return nil
}
func (l *LambdaInvoker) showLog(logResult *string) error {
if logResult == nil {
return nil
}
dec, err := base64.StdEncoding.DecodeString(*logResult)
if err != nil {
return err
}
scanner := bufio.NewScanner(bytes.NewBuffer(dec))
for scanner.Scan() {
log.Printf("%s >> %s", l.function, scanner.Text())
}
return nil
}
func instanceMetadata() (*imds.GetInstanceIdentityDocumentOutput, *aws.Config, error) {
imdsc := imds.New(imds.Options{}) // Amazon EC2 Instance Metadata Service Client
ctx := context.Background()
iid, err := imdsc.GetInstanceIdentityDocument(ctx, nil)
if err != nil {
return nil, nil, err
}
cfg, err := awsConfig.LoadDefaultConfig(ctx, awsConfig.WithRegion(iid.Region))
if err != nil {
return nil, nil, err
}
return iid, &cfg, nil
}
func (l *LambdaInvoker) getConfig() error {
input := &lambda.GetFunctionConfigurationInput{
FunctionName: &l.function,
}
output, err := l.client.GetFunctionConfiguration(context.Background(), input)
if err != nil {
return err
}
l.functionConfig = output
return nil
}
// Timeout returns the lambda's timeout duration setting
func (l *LambdaInvoker) Timeout() time.Duration {
if l.functionConfig == nil || l.functionConfig.Timeout == nil {
return 0
}
return time.Duration(*l.functionConfig.Timeout) * time.Second
}