forked from gruntwork-io/terratest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compute.go
622 lines (499 loc) · 19.2 KB
/
compute.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
package gcp
import (
"context"
"fmt"
"path"
"strings"
"testing"
"github.com/gruntwork-io/terratest/modules/logger"
"github.com/gruntwork-io/terratest/modules/random"
"golang.org/x/oauth2/google"
"google.golang.org/api/compute/v1"
)
// Corresponds to a GCP Compute Instance (https://cloud.google.com/compute/docs/instances/)
type Instance struct {
projectID string
*compute.Instance
}
// Corresponds to a GCP Image (https://cloud.google.com/compute/docs/images)
type Image struct {
projectID string
*compute.Image
}
// Corresponds to a GCP Zonal Instance Group (https://cloud.google.com/compute/docs/instance-groups/)
type ZonalInstanceGroup struct {
projectID string
*compute.InstanceGroup
}
// Corresponds to a GCP Regional Instance Group (https://cloud.google.com/compute/docs/instance-groups/)
type RegionalInstanceGroup struct {
projectID string
*compute.InstanceGroup
}
type InstanceGroup interface {
GetInstanceIds(t *testing.T) []string
GetInstanceIdsE(t *testing.T) ([]string, error)
}
// FetchInstance queries GCP to return an instance of the (GCP Compute) Instance type
func FetchInstance(t *testing.T, projectID string, name string) *Instance {
instance, err := FetchInstanceE(t, projectID, name)
if err != nil {
t.Fatal(err)
}
return instance
}
// FetchInstance queries GCP to return an instance of the (GCP Compute) Instance type
func FetchInstanceE(t *testing.T, projectID string, name string) (*Instance, error) {
logger.Logf(t, "Getting Compute Instance %s", name)
ctx := context.Background()
service, err := NewComputeServiceE(t)
if err != nil {
t.Fatal(err)
}
// If we want to fetch an Instance without knowing its Zone, we have to query GCP for all Instances in the project
// and match on name.
instanceAggregatedList, err := service.Instances.AggregatedList(projectID).Context(ctx).Do()
if err != nil {
return nil, fmt.Errorf("Instances.AggregatedList(%s) got error: %v", projectID, err)
}
for _, instanceList := range instanceAggregatedList.Items {
for _, instance := range instanceList.Instances {
if name == instance.Name {
return &Instance{projectID, instance}, nil
}
}
}
return nil, fmt.Errorf("Compute Instance %s could not be found in project %s", name, projectID)
}
// FetchImage queries GCP to return a new instance of the (GCP Compute) Image type
func FetchImage(t *testing.T, projectID string, name string) *Image {
image, err := FetchImageE(t, projectID, name)
if err != nil {
t.Fatal(err)
}
return image
}
// FetchImage queries GCP to return a new instance of the (GCP Compute) Image type
func FetchImageE(t *testing.T, projectID string, name string) (*Image, error) {
logger.Logf(t, "Getting Image %s", name)
ctx := context.Background()
service, err := NewComputeServiceE(t)
if err != nil {
return nil, err
}
req := service.Images.Get(projectID, name)
image, err := req.Context(ctx).Do()
if err != nil {
return nil, err
}
return &Image{projectID, image}, nil
}
// FetchRegionalInstanceGroup queries GCP to return a new instance of the Regional Instance Group type
func FetchRegionalInstanceGroup(t *testing.T, projectID string, region string, name string) *RegionalInstanceGroup {
instanceGroup, err := FetchRegionalInstanceGroupE(t, projectID, region, name)
if err != nil {
t.Fatal(err)
}
return instanceGroup
}
// FetchRegionalInstanceGroup queries GCP to return a new instance of the Regional Instance Group type
func FetchRegionalInstanceGroupE(t *testing.T, projectID string, region string, name string) (*RegionalInstanceGroup, error) {
logger.Logf(t, "Getting Regional Instance Group %s", name)
ctx := context.Background()
service, err := NewComputeServiceE(t)
if err != nil {
return nil, err
}
req := service.RegionInstanceGroups.Get(projectID, region, name)
instanceGroup, err := req.Context(ctx).Do()
if err != nil {
return nil, err
}
return &RegionalInstanceGroup{projectID, instanceGroup}, nil
}
// FetchZonalInstanceGroup queries GCP to return a new instance of the Regional Instance Group type
func FetchZonalInstanceGroup(t *testing.T, projectID string, zone string, name string) *ZonalInstanceGroup {
instanceGroup, err := FetchZonalInstanceGroupE(t, projectID, zone, name)
if err != nil {
t.Fatal(err)
}
return instanceGroup
}
// FetchZonalInstanceGroup queries GCP to return a new instance of the Regional Instance Group type
func FetchZonalInstanceGroupE(t *testing.T, projectID string, zone string, name string) (*ZonalInstanceGroup, error) {
logger.Logf(t, "Getting Zonal Instance Group %s", name)
ctx := context.Background()
service, err := NewComputeServiceE(t)
if err != nil {
return nil, err
}
req := service.InstanceGroups.Get(projectID, zone, name)
instanceGroup, err := req.Context(ctx).Do()
if err != nil {
return nil, err
}
return &ZonalInstanceGroup{projectID, instanceGroup}, nil
}
// GetPublicIP gets the public IP address of the given Compute Instance.
func (i *Instance) GetPublicIp(t *testing.T) string {
ip, err := i.GetPublicIpE(t)
if err != nil {
t.Fatal(err)
}
return ip
}
// GetPublicIpE gets the public IP address of the given Compute Instance.
func (i *Instance) GetPublicIpE(t *testing.T) (string, error) {
// If there are no accessConfigs specified, then this instance will have no external internet access:
// https://cloud.google.com/compute/docs/reference/rest/v1/instances.
if len(i.NetworkInterfaces[0].AccessConfigs) == 0 {
return "", fmt.Errorf("Attempted to get public IP of Compute Instance %s, but that Compute Instance does not have a public IP address", i.Name)
}
ip := i.NetworkInterfaces[0].AccessConfigs[0].NatIP
return ip, nil
}
// GetLabels returns all the tags for the given Compute Instance.
func (i *Instance) GetLabels(t *testing.T) map[string]string {
return i.Labels
}
// GetZone returns the Zone in which the Compute Instance is located.
func (i *Instance) GetZone(t *testing.T) string {
return ZoneUrlToZone(i.Zone)
}
// SetLabels adds the tags to the given Compute Instance.
func (i *Instance) SetLabels(t *testing.T, labels map[string]string) {
err := i.SetLabelsE(t, labels)
if err != nil {
t.Fatal(err)
}
}
// SetLabelsE adds the tags to the given Compute Instance.
func (i *Instance) SetLabelsE(t *testing.T, labels map[string]string) error {
logger.Logf(t, "Adding labels to instance %s in zone %s", i.Name, i.Zone)
ctx := context.Background()
service, err := NewComputeServiceE(t)
if err != nil {
return err
}
req := compute.InstancesSetLabelsRequest{Labels: labels, LabelFingerprint: i.LabelFingerprint}
if _, err := service.Instances.SetLabels(i.projectID, i.GetZone(t), i.Name, &req).Context(ctx).Do(); err != nil {
return fmt.Errorf("Instances.SetLabels(%s) got error: %v", i.Name, err)
}
return nil
}
// GetMetadata gets the given Compute Instance's metadata
func (i *Instance) GetMetadata(t *testing.T) []*compute.MetadataItems {
return i.Metadata.Items
}
// SetMetadata sets the given Compute Instance's metadata
func (i *Instance) SetMetadata(t *testing.T, metadata map[string]string) {
err := i.SetMetadataE(t, metadata)
if err != nil {
t.Fatal(err)
}
}
// SetLabelsE adds the given metadata map to the existing metadata of the given Compute Instance.
func (i *Instance) SetMetadataE(t *testing.T, metadata map[string]string) error {
logger.Logf(t, "Adding metadata to instance %s in zone %s", i.Name, i.Zone)
ctx := context.Background()
service, err := NewInstancesServiceE(t)
if err != nil {
return err
}
metadataItems := newMetadata(t, i.Metadata, metadata)
req := service.SetMetadata(i.projectID, i.GetZone(t), i.Name, metadataItems)
if _, err := req.Context(ctx).Do(); err != nil {
return fmt.Errorf("Instances.SetMetadata(%s) got error: %v", i.Name, err)
}
return nil
}
// newMetadata takes in a Compute Instance's existing metadata plus a new set of key-value pairs and returns an updated
// metadata object.
func newMetadata(t *testing.T, oldMetadata *compute.Metadata, kvs map[string]string) *compute.Metadata {
items := []*compute.MetadataItems{}
for key, val := range kvs {
item := &compute.MetadataItems{
Key: key,
Value: &val,
}
items = append(oldMetadata.Items, item)
}
newMetadata := &compute.Metadata{
Fingerprint: oldMetadata.Fingerprint,
Items: items,
}
return newMetadata
}
// Add the given public SSH key to the Compute Instance. Users can SSH in with the given username.
func (i *Instance) AddSshKey(t *testing.T, username string, publicKey string) {
err := i.AddSshKeyE(t, username, publicKey)
if err != nil {
t.Fatal(err)
}
}
// Add the given public SSH key to the Compute Instance. Users can SSH in with the given username.
func (i *Instance) AddSshKeyE(t *testing.T, username string, publicKey string) error {
logger.Logf(t, "Adding SSH Key to Compute Instance %s for username %s\n", i.Name, username)
// We represent the key in the format required per GCP docs (https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys)
publicKeyFormatted := strings.TrimSpace(publicKey)
sshKeyFormatted := fmt.Sprintf("%s:%s %s", username, publicKeyFormatted, username)
metadata := map[string]string{
"ssh-keys": sshKeyFormatted,
}
err := i.SetMetadataE(t, metadata)
if err != nil {
return fmt.Errorf("Failed to add SSH key to Compute Instance: %s", err)
}
return nil
}
// DeleteImage deletes the given Compute Image.
func (i *Image) DeleteImage(t *testing.T) {
err := i.DeleteImageE(t)
if err != nil {
t.Fatal(err)
}
}
// DeleteImageE deletes the given Compute Image.
func (i *Image) DeleteImageE(t *testing.T) error {
logger.Logf(t, "Destroying Image %s", i.Name)
ctx := context.Background()
service, err := NewComputeServiceE(t)
if err != nil {
return err
}
if _, err := service.Images.Delete(i.projectID, i.Name).Context(ctx).Do(); err != nil {
return fmt.Errorf("Images.Delete(%s) got error: %v", i.Name, err)
}
return nil
}
// GetInstanceIds gets the IDs of Instances in the given Instance Group.
func (ig *ZonalInstanceGroup) GetInstanceIds(t *testing.T) []string {
ids, err := ig.GetInstanceIdsE(t)
if err != nil {
t.Fatal(err)
}
return ids
}
// GetInstanceIdsE gets the IDs of Instances in the given Zonal Instance Group.
func (ig *ZonalInstanceGroup) GetInstanceIdsE(t *testing.T) ([]string, error) {
logger.Logf(t, "Get instances for Zonal Instance Group %s", ig.Name)
ctx := context.Background()
service, err := NewComputeServiceE(t)
if err != nil {
return nil, err
}
requestBody := &compute.InstanceGroupsListInstancesRequest{
InstanceState: "ALL",
}
instanceIDs := []string{}
zone := ZoneUrlToZone(ig.Zone)
req := service.InstanceGroups.ListInstances(ig.projectID, zone, ig.Name, requestBody)
err = req.Pages(ctx, func(page *compute.InstanceGroupsListInstances) error {
for _, instance := range page.Items {
// For some reason service.InstanceGroups.ListInstances returns us a collection
// with Instance URLs and we need only the Instance ID for the next call. Use
// the path functions to chop the Instance ID off the end of the URL.
instanceID := path.Base(instance.Instance)
instanceIDs = append(instanceIDs, instanceID)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("InstanceGroups.ListInstances(%s) got error: %v", ig.Name, err)
}
return instanceIDs, nil
}
// GetInstanceIds gets the IDs of Instances in the given Regional Instance Group.
func (ig *RegionalInstanceGroup) GetInstanceIds(t *testing.T) []string {
ids, err := ig.GetInstanceIdsE(t)
if err != nil {
t.Fatal(err)
}
return ids
}
// GetInstanceIdsE gets the IDs of Instances in the given Regional Instance Group.
func (ig *RegionalInstanceGroup) GetInstanceIdsE(t *testing.T) ([]string, error) {
logger.Logf(t, "Get instances for Regional Instance Group %s", ig.Name)
ctx := context.Background()
service, err := NewComputeServiceE(t)
if err != nil {
return nil, err
}
requestBody := &compute.RegionInstanceGroupsListInstancesRequest{
InstanceState: "ALL",
}
instanceIDs := []string{}
region := RegionUrlToRegion(ig.Region)
req := service.RegionInstanceGroups.ListInstances(ig.projectID, region, ig.Name, requestBody)
err = req.Pages(ctx, func(page *compute.RegionInstanceGroupsListInstances) error {
for _, instance := range page.Items {
// For some reason service.InstanceGroups.ListInstances returns us a collection
// with Instance URLs and we need only the Instance ID for the next call. Use
// the path functions to chop the Instance ID off the end of the URL.
instanceID := path.Base(instance.Instance)
instanceIDs = append(instanceIDs, instanceID)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("InstanceGroups.ListInstances(%s) got error: %v", ig.Name, err)
}
return instanceIDs, nil
}
// Return a collection of Instance structs from the given Instance Group
func (ig *ZonalInstanceGroup) GetInstances(t *testing.T, projectId string) []*Instance {
return getInstances(t, ig, projectId)
}
// Return a collection of Instance structs from the given Instance Group
func (ig *ZonalInstanceGroup) GetInstancesE(t *testing.T, projectId string) ([]*Instance, error) {
return getInstancesE(t, ig, projectId)
}
// Return a collection of Instance structs from the given Instance Group
func (ig *RegionalInstanceGroup) GetInstances(t *testing.T, projectId string) []*Instance {
return getInstances(t, ig, projectId)
}
// Return a collection of Instance structs from the given Instance Group
func (ig *RegionalInstanceGroup) GetInstancesE(t *testing.T, projectId string) ([]*Instance, error) {
return getInstancesE(t, ig, projectId)
}
// getInstancesE returns a collection of Instance structs from the given Instance Group
func getInstances(t *testing.T, ig InstanceGroup, projectId string) []*Instance {
instances, err := getInstancesE(t, ig, projectId)
if err != nil {
t.Fatal(err)
}
return instances
}
// getInstancesE returns a collection of Instance structs from the given Instance Group
func getInstancesE(t *testing.T, ig InstanceGroup, projectId string) ([]*Instance, error) {
instanceIds, err := ig.GetInstanceIdsE(t)
if err != nil {
return nil, fmt.Errorf("Failed to get Instance Group IDs: %s", err)
}
var instances []*Instance
for _, instanceId := range instanceIds {
instance, err := FetchInstanceE(t, projectId, instanceId)
if err != nil {
return nil, fmt.Errorf("Failed to get Instance: %s", err)
}
instances = append(instances, instance)
}
return instances, nil
}
// GetPublicIps returns a slice of the public IPs from the given Instance Group
func (ig *ZonalInstanceGroup) GetPublicIps(t *testing.T, projectId string) []string {
return getPublicIps(t, ig, projectId)
}
// GetPublicIpsE returns a slice of the public IPs from the given Instance Group
func (ig *ZonalInstanceGroup) GetPublicIpsE(t *testing.T, projectId string) ([]string, error) {
return getPublicIpsE(t, ig, projectId)
}
// GetPublicIps returns a slice of the public IPs from the given Instance Group
func (ig *RegionalInstanceGroup) GetPublicIps(t *testing.T, projectId string) []string {
return getPublicIps(t, ig, projectId)
}
// GetPublicIpsE returns a slice of the public IPs from the given Instance Group
func (ig *RegionalInstanceGroup) GetPublicIpsE(t *testing.T, projectId string) ([]string, error) {
return getPublicIpsE(t, ig, projectId)
}
// getPublicIps a slice of the public IPs from the given Instance Group
func getPublicIps(t *testing.T, ig InstanceGroup, projectId string) []string {
ips, err := getPublicIpsE(t, ig, projectId)
if err != nil {
t.Fatal(err)
}
return ips
}
// getPublicIpsE a slice of the public IPs from the given Instance Group
func getPublicIpsE(t *testing.T, ig InstanceGroup, projectId string) ([]string, error) {
instances, err := getInstancesE(t, ig, projectId)
if err != nil {
return nil, fmt.Errorf("Failed to get Compute Instances from Instance Group: %s", err)
}
var ips []string
for _, instance := range instances {
ip := instance.GetPublicIp(t)
ips = append(ips, ip)
}
return ips, nil
}
// getRandomInstance returns a randomly selected Instance from the Regional Instance Group
func (ig *ZonalInstanceGroup) GetRandomInstance(t *testing.T) *Instance {
return getRandomInstance(t, ig, ig.Name, ig.Region, ig.Size, ig.projectID)
}
// getRandomInstanceE returns a randomly selected Instance from the Regional Instance Group
func (ig *ZonalInstanceGroup) GetRandomInstanceE(t *testing.T) (*Instance, error) {
return getRandomInstanceE(t, ig, ig.Name, ig.Region, ig.Size, ig.projectID)
}
// getRandomInstance returns a randomly selected Instance from the Regional Instance Group
func (ig *RegionalInstanceGroup) GetRandomInstance(t *testing.T) *Instance {
return getRandomInstance(t, ig, ig.Name, ig.Region, ig.Size, ig.projectID)
}
// getRandomInstanceE returns a randomly selected Instance from the Regional Instance Group
func (ig *RegionalInstanceGroup) GetRandomInstanceE(t *testing.T) (*Instance, error) {
return getRandomInstanceE(t, ig, ig.Name, ig.Region, ig.Size, ig.projectID)
}
func getRandomInstance(t *testing.T, ig InstanceGroup, name string, region string, size int64, projectID string) *Instance {
instance, err := getRandomInstanceE(t, ig, name, region, size, projectID)
if err != nil {
t.Fatal(err)
}
return instance
}
func getRandomInstanceE(t *testing.T, ig InstanceGroup, name string, region string, size int64, projectID string) (*Instance, error) {
instanceIDs := ig.GetInstanceIds(t)
if len(instanceIDs) == 0 {
return nil, fmt.Errorf("Could not find any instances in Regional Instance Group %s in Region %s", name, region)
}
clusterSize := int(size)
if len(instanceIDs) != clusterSize {
return nil, fmt.Errorf("Expected Regional Instance Group %s in Region %s to have %d instances, but found %d", name, region, clusterSize, len(instanceIDs))
}
randIndex := random.Random(0, clusterSize-1)
instanceID := instanceIDs[randIndex]
instance := FetchInstance(t, projectID, instanceID)
return instance, nil
}
// NewComputeService creates a new Compute service, which is used to make GCE API calls.
func NewComputeService(t *testing.T) *compute.Service {
client, err := NewComputeServiceE(t)
if err != nil {
t.Fatal(err)
}
return client
}
// NewComputeServiceE creates a new Compute service, which is used to make GCE API calls.
func NewComputeServiceE(t *testing.T) (*compute.Service, error) {
ctx := context.Background()
client, err := google.DefaultClient(ctx, compute.CloudPlatformScope)
if err != nil {
return nil, fmt.Errorf("Failed to get default client: %v", err)
}
service, err := compute.New(client)
if err != nil {
return nil, err
}
return service, nil
}
// NewInstancesService creates a new InstancesService service, which is used to make a subset of GCE API calls.
func NewInstancesService(t *testing.T) *compute.InstancesService {
client, err := NewInstancesServiceE(t)
if err != nil {
t.Fatal(err)
}
return client
}
// NewInstancesServiceE creates a new InstancesService service, which is used to make a subset of GCE API calls.
func NewInstancesServiceE(t *testing.T) (*compute.InstancesService, error) {
service, err := NewComputeServiceE(t)
if err != nil {
return nil, fmt.Errorf("Failed to get new Instances Service\n")
}
return service.Instances, nil
}
// Return a random, valid name for GCP resources. Many resources in GCP requires lowercase letters only.
func RandomValidGcpName() string {
id := strings.ToLower(random.UniqueId())
instanceName := fmt.Sprintf("terratest-%s", id)
return instanceName
}