/
ec2.go
410 lines (356 loc) · 11.3 KB
/
ec2.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
// Package ec2 implements testing utilities using EC2.
package ec2
import (
"errors"
"fmt"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/aws/aws-k8s-tester/ec2config"
pkgaws "github.com/aws/aws-k8s-tester/pkg/aws"
"github.com/aws/aws-k8s-tester/pkg/logutil"
"github.com/aws/aws-k8s-tester/version"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/autoscaling/autoscalingiface"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/cloudformation/cloudformationiface"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/aws/aws-sdk-go/service/elbv2"
"github.com/aws/aws-sdk-go/service/elbv2/elbv2iface"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/iam/iamiface"
"github.com/aws/aws-sdk-go/service/kms"
"github.com/aws/aws-sdk-go/service/kms/kmsiface"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/aws/aws-sdk-go/service/ssm/ssmiface"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/dustin/go-humanize"
"go.uber.org/zap"
)
// Tester implements "kubetest2" Deployer.
// ref. https://github.com/kubernetes/test-infra/blob/master/kubetest2/pkg/types/types.go
type Tester struct {
stopCreationCh chan struct{}
stopCreationChOnce *sync.Once
interruptSig chan os.Signal
downMu *sync.Mutex
logsMu *sync.RWMutex
lg *zap.Logger
cfg *ec2config.Config
awsSession *session.Session
iamAPI iamiface.IAMAPI
kmsAPI kmsiface.KMSAPI
ssmAPI ssmiface.SSMAPI
cfnAPI cloudformationiface.CloudFormationAPI
ec2API ec2iface.EC2API
s3API s3iface.S3API
asgAPI autoscalingiface.AutoScalingAPI
elbv2API elbv2iface.ELBV2API
}
// New creates a new EC2 tester.
func New(cfg *ec2config.Config) (*Tester, error) {
fmt.Println("😎 🙏 🚶 ✔️ 👍")
fmt.Println(version.Version())
fmt.Printf("\n*********************************\n")
fmt.Printf("New %q\n", cfg.ConfigPath)
if err := cfg.ValidateAndSetDefaults(); err != nil {
return nil, err
}
lcfg := logutil.AddOutputPaths(logutil.GetDefaultZapLoggerConfig(), cfg.LogOutputs, cfg.LogOutputs)
lcfg.Level = zap.NewAtomicLevelAt(logutil.ConvertToZapLevel(cfg.LogLevel))
lg, err := lcfg.Build()
if err != nil {
return nil, err
}
ts := &Tester{
stopCreationCh: make(chan struct{}),
stopCreationChOnce: new(sync.Once),
interruptSig: make(chan os.Signal),
downMu: new(sync.Mutex),
logsMu: new(sync.RWMutex),
lg: lg,
cfg: cfg,
}
signal.Notify(ts.interruptSig, syscall.SIGTERM, syscall.SIGINT)
defer ts.cfg.Sync()
awsCfg := &pkgaws.Config{
Logger: ts.lg,
DebugAPICalls: ts.cfg.LogLevel == "debug",
Region: ts.cfg.Region,
}
var stsOutput *sts.GetCallerIdentityOutput
ts.awsSession, stsOutput, ts.cfg.AWSCredentialPath, err = pkgaws.New(awsCfg)
if err != nil {
return nil, err
}
ts.cfg.AWSAccountID = aws.StringValue(stsOutput.Account)
ts.cfg.AWSUserID = aws.StringValue(stsOutput.UserId)
ts.cfg.AWSIAMRoleARN = aws.StringValue(stsOutput.Arn)
ts.cfg.Sync()
ts.iamAPI = iam.New(ts.awsSession)
ts.kmsAPI = kms.New(ts.awsSession)
ts.ssmAPI = ssm.New(ts.awsSession)
ts.cfnAPI = cloudformation.New(ts.awsSession)
ts.ec2API = ec2.New(ts.awsSession)
if _, err := ts.ec2API.DescribeInstances(&ec2.DescribeInstancesInput{MaxResults: aws.Int64(5)}); err != nil {
return nil, fmt.Errorf("failed to describe instances using EC2 API (%v)", err)
}
fmt.Println("EC2 API available!")
ts.s3API = s3.New(ts.awsSession)
ts.asgAPI = autoscaling.New(ts.awsSession)
ts.elbv2API = elbv2.New(ts.awsSession)
return ts, nil
}
// Up should provision a new cluster for testing
func (ts *Tester) Up() (err error) {
fmt.Printf("\n*********************************\n")
ts.lg.Sugar().Infof("Up (%s)", ts.cfg.ConfigPath)
now := time.Now()
defer func() {
fmt.Printf("\n*********************************\n")
ts.lg.Sugar().Infof("Up.defer start (%s)", ts.cfg.ConfigPath)
if serr := ts.uploadToS3(); serr != nil {
ts.lg.Warn("failed to upload artifacts to S3", zap.Error(serr))
}
if err == nil {
if ts.cfg.Up {
fmt.Printf("\n*********************************\n")
ts.lg.Sugar().Infof("SSH (%s)", ts.cfg.ConfigPath)
fmt.Println(ts.cfg.SSHCommands())
ts.lg.Info("Up succeeded",
zap.String("started", humanize.RelTime(now, time.Now(), "ago", "from now")),
)
fmt.Printf("\n*********************************\n")
ts.lg.Sugar().Infof("Up.defer end (%s)", ts.cfg.ConfigPath)
fmt.Printf("\n\n💯 😁 👍 :) Up success\n\n\n")
} else {
fmt.Printf("\n\n😲 😲 aborted Up ???\n\n\n")
}
return
}
if !ts.cfg.OnFailureDelete {
if ts.cfg.Up {
fmt.Printf("\n*********************************\n")
ts.lg.Sugar().Infof("SSH (%s)", ts.cfg.ConfigPath)
fmt.Println(ts.cfg.SSHCommands())
}
ts.lg.Warn("Up failed",
zap.String("started", humanize.RelTime(now, time.Now(), "ago", "from now")),
zap.Error(err),
)
fmt.Printf("\n*********************************\n")
ts.lg.Sugar().Infof("Up.defer end (%s)", ts.cfg.ConfigPath)
fmt.Printf("\n\n🔥 💀 👽 😱 😡 (-_-) Up fail\n\n\n")
return
}
if ts.cfg.Up {
fmt.Printf("\n*********************************\n")
ts.lg.Sugar().Infof("SSH (%s)", ts.cfg.ConfigPath)
fmt.Println(ts.cfg.SSHCommands())
}
fmt.Printf("\n*********************************\n")
fmt.Printf("🔥 💀 👽 😱 😡 (-_-) Up fail\n")
ts.lg.Warn("Up failed; reverting resource creation",
zap.String("started", humanize.RelTime(now, time.Now(), "ago", "from now")),
zap.Error(err),
)
waitDur := time.Duration(ts.cfg.OnFailureDeleteWaitSeconds) * time.Second
if waitDur > 0 {
ts.lg.Info("waiting before clean up", zap.Duration("wait", waitDur))
select {
case <-ts.stopCreationCh:
ts.lg.Info("wait aborted before clean up")
case <-ts.interruptSig:
ts.lg.Info("wait aborted before clean up")
case <-time.After(waitDur):
}
}
derr := ts.down()
if derr != nil {
ts.lg.Warn("failed to revert Up", zap.Error(derr))
} else {
ts.lg.Warn("reverted Up")
}
fmt.Printf("\n*********************************\n")
ts.lg.Sugar().Infof("Up.defer end (%s)", ts.cfg.ConfigPath)
fmt.Printf("\n\n🔥 💀 👽 😱 😡 (-_-) Up fail\n\n\n")
}()
ts.lg.Info("Up started",
zap.String("version", version.Version()),
zap.String("name", ts.cfg.Name),
)
defer ts.cfg.Sync()
fmt.Printf("\n*********************************\n")
fmt.Printf("createS3 (%q)\n", ts.cfg.ConfigPath)
if err := catchInterrupt(
ts.lg,
ts.stopCreationCh,
ts.stopCreationChOnce,
ts.interruptSig,
ts.createS3,
); err != nil {
return err
}
fmt.Printf("\n*********************************\n")
fmt.Printf("createRole (%q)\n", ts.cfg.ConfigPath)
if err := catchInterrupt(
ts.lg,
ts.stopCreationCh,
ts.stopCreationChOnce,
ts.interruptSig,
ts.createRole,
); err != nil {
return err
}
fmt.Printf("\n*********************************\n")
fmt.Printf("createVPC (%q)\n", ts.cfg.ConfigPath)
if err := catchInterrupt(
ts.lg,
ts.stopCreationCh,
ts.stopCreationChOnce,
ts.interruptSig,
ts.createVPC,
); err != nil {
return err
}
fmt.Printf("\n*********************************\n")
fmt.Printf("createKeyPair (%q)\n", ts.cfg.ConfigPath)
if err := catchInterrupt(
ts.lg,
ts.stopCreationCh,
ts.stopCreationChOnce,
ts.interruptSig,
ts.createKeyPair,
); err != nil {
return err
}
fmt.Printf("\n*********************************\n")
fmt.Printf("createASGs (%q)\n", ts.cfg.ConfigPath)
if err := catchInterrupt(
ts.lg,
ts.stopCreationCh,
ts.stopCreationChOnce,
ts.interruptSig,
ts.createASGs,
); err != nil {
return err
}
fmt.Printf("\n*********************************\n")
fmt.Printf("createSSM (%q)\n", ts.cfg.ConfigPath)
if err := catchInterrupt(
ts.lg,
ts.stopCreationCh,
ts.stopCreationChOnce,
ts.interruptSig,
ts.createSSM,
); err != nil {
return err
}
if ts.cfg.ASGsFetchLogs {
fmt.Printf("\n*********************************\n")
fmt.Printf("FetchLogs (%q)\n", ts.cfg.ConfigPath)
waitDur := 20 * time.Second
ts.lg.Info("sleeping before FetchLogs", zap.Duration("wait", waitDur))
time.Sleep(waitDur)
if err := catchInterrupt(
ts.lg,
ts.stopCreationCh,
ts.stopCreationChOnce,
ts.interruptSig,
ts.FetchLogs,
); err != nil {
return err
}
}
return ts.cfg.Sync()
}
// Down cancels the cluster creation and destroy the test cluster if any.
func (ts *Tester) Down() error {
ts.downMu.Lock()
defer ts.downMu.Unlock()
return ts.down()
}
func (ts *Tester) down() (err error) {
fmt.Printf("\n*********************************\n")
fmt.Printf("Down start (%q)\n\n", ts.cfg.ConfigPath)
now := time.Now()
ts.lg.Warn("starting Down",
zap.String("name", ts.cfg.Name),
)
if serr := ts.uploadToS3(); serr != nil {
ts.lg.Warn("failed to upload artifacts to S3", zap.Error(serr))
}
defer func() {
ts.cfg.Sync()
if err == nil {
fmt.Printf("\n*********************************\n")
fmt.Printf("Down.defer end (%q)\n\n", ts.cfg.ConfigPath)
fmt.Printf("\n\n💯 😁 👍 :) Down success\n\n\n")
ts.lg.Info("successfully finished Down",
zap.String("started", humanize.RelTime(now, time.Now(), "ago", "from now")),
)
} else {
fmt.Printf("\n*********************************\n")
fmt.Printf("Down.defer end (%q)\n\n", ts.cfg.ConfigPath)
fmt.Printf("\n\n🔥 💀 👽 😱 😡 (-_-) Down fail\n\n\n")
ts.lg.Info("failed Down",
zap.Error(err),
zap.String("started", humanize.RelTime(now, time.Now(), "ago", "from now")),
)
}
}()
var errs []string
fmt.Printf("\n*********************************\n")
fmt.Printf("deleteSSM (%q)\n", ts.cfg.ConfigPath)
if err := ts.deleteSSM(); err != nil {
ts.lg.Warn("deleteSSM failed", zap.Error(err))
errs = append(errs, err.Error())
}
fmt.Printf("\n*********************************\n")
fmt.Printf("deleteASGs (%q)\n", ts.cfg.ConfigPath)
if err := ts.deleteASGs(); err != nil {
ts.lg.Warn("deleteASGs failed", zap.Error(err))
errs = append(errs, err.Error())
}
fmt.Printf("\n*********************************\n")
fmt.Printf("deleteKeyPair (%q)\n", ts.cfg.ConfigPath)
if err := ts.deleteKeyPair(); err != nil {
ts.lg.Warn("deleteKeyPair failed", zap.Error(err))
errs = append(errs, err.Error())
}
fmt.Printf("\n*********************************\n")
fmt.Printf("deleteRole (%q)\n", ts.cfg.ConfigPath)
if err := ts.deleteRole(); err != nil {
ts.lg.Warn("deleteRole failed", zap.Error(err))
errs = append(errs, err.Error())
}
if ts.cfg.VPCCreate { // VPC was created
waitDur := 30 * time.Second
ts.lg.Info("sleeping before VPC deletion", zap.Duration("wait", waitDur))
time.Sleep(waitDur)
}
fmt.Printf("\n*********************************\n")
fmt.Printf("deleteVPC (%q)\n", ts.cfg.ConfigPath)
if err := ts.deleteVPC(); err != nil {
ts.lg.Warn("deleteVPC failed", zap.Error(err))
errs = append(errs, err.Error())
}
fmt.Printf("\n*********************************\n")
fmt.Printf("deleteS3 (%q)\n", ts.cfg.ConfigPath)
if err := ts.deleteS3(); err != nil {
ts.lg.Warn("deleteS3 failed", zap.Error(err))
errs = append(errs, err.Error())
}
if len(errs) > 0 {
return errors.New(strings.Join(errs, ", "))
}
return ts.cfg.Sync()
}