/
lambda.go
421 lines (323 loc) · 9.88 KB
/
lambda.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package lambda
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
"github.com/edobtc/cloudkit/labels"
"github.com/edobtc/cloudkit/resources/providers"
"github.com/edobtc/cloudkit/resources/providers/aws/auth"
"github.com/edobtc/cloudkit/target"
"github.com/google/uuid"
pb "github.com/edobtc/cloudkit/rpc/controlplane/resources/v1"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/lambda"
log "github.com/sirupsen/logrus"
)
const (
// DefaultOperation is the default mode with which to perform a clone
DefaultOperation = "clone"
// DefaultCanaryWeight shall be an equal, uniform split
DefaultCanaryWeight = 0.5
DefaultSize = 512
)
var (
// ErrOperationNotDefined is returned if we attempt to clone a function and the
// given operation in the config is neither clone or alias
ErrOperationNotDefined = errors.New("operation not defined, expecting clone or alias")
)
// Config holds allowed values
// for an implemented resource provider.
// Any value outside of this config
// is unable to be modified during an experiment
type Config struct {
// Operation allows you to chose between
// clone or alias, default is to alias
Operation string
// Canary defaults to false
Canary bool
Name string
// CanaryWeight, which should be set from the
CanaryWeight float64
// MemorySize is the lambda compute resources size
MemorySize int64
Timeout int64
// Handler allows a different handler to be used
Handler string
// Version of the deployed function
Version string
// Function runtime
Runtime string
}
// Provider implements a lambda Provider
type Provider struct {
Target target.Target
// Config holds our internal configuration options
// for the instance of the Provider
Config Config
// RemoteConfig identifies the
RemoteConfig *lambda.GetFunctionOutput
// CurrentAliasArn is the ARN of an alias if we are operating a clone
CurrentAliasArn string
}
// NewProvider initializes a Provider
// with defaults
func NewProvider(req *pb.CreateRequest) providers.Provider {
cfg := Config{
Name: req.Config.Name,
MemorySize: sizeMap(req.Config.Size),
Version: req.Config.Version,
}
return &Provider{Config: cfg}
}
func sizeMap(size string) int64 {
value, err := strconv.Atoi(size)
if err != nil {
return DefaultSize
}
return int64(value)
}
// Read fetches and stores the configuration for an existing
// lambda cluster. What is read of the existing resource acts
// as the template/configuration to implement a clone via creating a
// new resource with the existing output as input for a variant
func (p *Provider) Read() error {
sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String("us-west-2"),
}))
svc := lambda.New(sess)
input := &lambda.GetFunctionInput{
FunctionName: aws.String(p.Target.ID),
// Qualifier can specify a different version (ie: deployed but not released)
// Qualifier: aws.String("$LATEST"),
}
result, err := svc.GetFunction(input)
if err != nil {
return err
}
p.RemoteConfig = result
return nil
}
// Clone creates a modified variant
func (p *Provider) Clone() error {
switch p.Config.Operation {
case "clone":
return p.clone()
case "alias":
return p.aliasClone()
default:
return ErrOperationNotDefined
}
}
// clone duplicates the target function into a COMPLETELY new function
// resource with it's own ARN
func (p *Provider) clone() error {
sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String("us-west-2"),
}))
svc := lambda.New(sess)
uuid := uuid.New()
variantName := fmt.Sprintf("%s-%s", uuid, *p.RemoteConfig.Configuration.FunctionName)
code, err := download(*p.RemoteConfig.Code.Location)
if err != nil {
return err
}
input := &lambda.CreateFunctionInput{
Code: &lambda.FunctionCode{
ZipFile: code,
},
FunctionName: aws.String(variantName),
Handler: p.RemoteConfig.Configuration.Handler,
MemorySize: aws.Int64(p.Config.MemorySize),
Publish: aws.Bool(true),
Role: p.RemoteConfig.Configuration.Role,
Runtime: p.RemoteConfig.Configuration.Runtime,
Timeout: aws.Int64(p.Config.Timeout),
VpcConfig: &lambda.VpcConfig{},
}
log.Info("Creating lambda clone")
result, err := svc.CreateFunction(input)
if err != nil {
return err
}
log.Info(result)
return nil
}
// aliasClone uses built in versioning + alias with optional traffic shifting
// to create a new version of the current function as a variant and optionally
// split traffic if Canary is set to true
//
// This requires a few steps to execute:
// First we need to make an explicit version of the targetted function as $LATEST can't be used in an alias,
// this is the controlFunction and snapshots the current function config
// Then we must modify the source function to apply the new config
// we then create another named version for the function with THAT variant config
// Then if Canary is true, we configure an alias of the two, determine proper weights based on if variants have configured
// weights and assign that to the traffic split. Invocations of the function that target the alias arn THEN
// will be split between the control and variant
func (p *Provider) aliasClone() error {
experiment := fmt.Sprintf("%v-hiero", time.Now().Unix())
sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String("us-west-2"),
}))
svc := lambda.New(sess)
input := &lambda.PublishVersionInput{
Description: aws.String(fmt.Sprintf("%s.control", experiment)),
FunctionName: aws.String(p.Target.ID),
}
controlFunction, err := svc.PublishVersion(input)
if err != nil {
return err
}
updateInput := &lambda.UpdateFunctionConfigurationInput{
FunctionName: aws.String(p.Target.ID),
MemorySize: aws.Int64(p.Config.MemorySize),
}
_, err = svc.UpdateFunctionConfiguration(updateInput)
if err != nil {
return err
}
versionInput := &lambda.PublishVersionInput{
Description: aws.String(fmt.Sprintf("%s.variant", experiment)),
FunctionName: aws.String(p.Target.ID),
}
variantFunction, err := svc.PublishVersion(versionInput)
if err != nil {
return err
}
if p.Config.Canary {
if p.Config.CanaryWeight == 0.0 {
p.Config.CanaryWeight = DefaultCanaryWeight
}
aliasInput := &lambda.CreateAliasInput{
Name: aws.String(experiment),
Description: aws.String(fmt.Sprintf("request group for hieroglyph %s", experiment)),
FunctionName: aws.String(p.Target.ID),
FunctionVersion: controlFunction.Version,
RoutingConfig: &lambda.AliasRoutingConfiguration{
AdditionalVersionWeights: RoutingConfigurationWeights{
fmt.Sprintf("%v", *variantFunction.Version): aws.Float64(p.Config.CanaryWeight), // get proper weighting and routes here
},
},
}
aliasConfig, err := svc.CreateAlias(aliasInput)
if err != nil {
return err
}
p.CurrentAliasArn = *aliasConfig.AliasArn
}
return nil
}
// ProbeReadiness checks that the provisioned resource is available and
// ready to be included in a live experiment
func (p *Provider) ProbeReadiness() (bool, error) {
return false, nil
}
// Teardown eradicates any resource that has been
// provisioned as part of a variant
func (p *Provider) Teardown() error {
// Needs to look up variants based on
// labels / tags which identify a variant name, experiment,
// and ideally a namespace
return nil
}
func download(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
log.Println(err)
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
// Apply runs the Provider end to end, so calls
// read and clone
func (p *Provider) Apply() error {
err := p.Read()
if err != nil {
return err
}
err = p.Clone()
if err != nil {
return err
}
return nil
}
// Cancel will abort and running or submitted Provider
func (p *Provider) Cancel() error { return nil }
// Stop will stop any running Provider
func (p *Provider) Stop() error { return nil }
// AwaitReadiness should be implemented to detect
// when a Provider has finished setting up a variant
// and can begin using it in an experiment
func (p *Provider) AwaitReadiness() chan error { return make(chan error) }
// Select is similar to Read yet copies a selection of resources based on the Target configuration
func (p *Provider) Select() (target.Selection, error) {
selection := target.Selection{}
sess, err := auth.Session()
if err != nil {
return selection, err
}
svc := lambda.New(sess)
input := lambda.ListFunctionsInput{
FunctionVersion: aws.String("ALL"),
}
results, err := svc.ListFunctions(&input)
for _, function := range results.Functions {
if *function.FunctionArn == p.Target.ID {
selection.Add(target.Resource{
ID: *function.FunctionArn,
Config: function,
})
} else {
tagInput := lambda.ListTagsInput{
Resource: function.FunctionArn,
}
if tags, err := svc.ListTags(&tagInput); err == nil {
var matches bool
if len(tags.Tags) > 0 && p.Target.Selectors.Any() {
for key, value := range tags.Tags {
matches = p.Target.Selectors.Contains(labels.Label{
Name: key,
Value: *value,
})
}
if matches {
selection.Add(target.Resource{
ID: *function.FunctionArn,
Config: function,
})
}
}
}
}
}
return target.Selection{}, nil
}
// Annotate should implement applying labels or tags for a given resource type
func (p *Provider) Annotate(id string, l labels.Labels) error {
sess, err := auth.Session()
if err != nil {
return err
}
svc := lambda.New(sess)
tags := map[string]*string{}
for _, selector := range l {
tags[selector.Name] = aws.String(selector.Value)
}
input := &lambda.TagResourceInput{
Resource: aws.String(id),
Tags: tags,
}
result, err := svc.TagResource(input)
if err != nil {
return err
}
log.Info(result)
return nil
}
// RoutingConfigurationWeights is for configuration of routing weights if
// Canary is true
type RoutingConfigurationWeights map[string]*float64