forked from pingcap/kops
/
instancetemplate.go
585 lines (484 loc) · 16.1 KB
/
instancetemplate.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
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package gcetasks
import (
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"time"
compute "google.golang.org/api/compute/v0.beta"
"k8s.io/klog"
"k8s.io/kops/pkg/diff"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/gce"
"k8s.io/kops/upup/pkg/fi/cloudup/terraform"
)
// InstanceTemplateNamePrefixMaxLength is the max length for the NamePrefix of an InstanceTemplate
// 52 = 63 - 10 - 1; 63 is the GCE limit; 10 is the length of seconds since epoch; and one for the dash
const InstanceTemplateNamePrefixMaxLength = 63 - 10 - 1
// InstanceTemplate represents a GCE InstanceTemplate
//go:generate fitask -type=InstanceTemplate
type InstanceTemplate struct {
Name *string
// NamePrefix is used as the prefix for the names; we add a timestamp. Max = InstanceTemplateNamePrefixMaxLength
NamePrefix *string
Lifecycle *fi.Lifecycle
Network *Network
Tags []string
//Labels map[string]string
Preemptible *bool
BootDiskImage *string
BootDiskSizeGB *int64
BootDiskType *string
CanIPForward *bool
Subnet *Subnet
AliasIPRanges map[string]string
Scopes []string
Metadata map[string]*fi.ResourceHolder
MachineType *string
// ID is the actual name
ID *string
}
var _ fi.CompareWithID = &InstanceTemplate{}
func (e *InstanceTemplate) CompareWithID() *string {
return e.ID
}
func (e *InstanceTemplate) Find(c *fi.Context) (*InstanceTemplate, error) {
cloud := c.Cloud.(gce.GCECloud)
response, err := cloud.Compute().InstanceTemplates.List(cloud.Project()).Do()
if err != nil {
if gce.IsNotFound(err) {
return nil, nil
}
return nil, fmt.Errorf("error listing InstanceTemplates: %v", err)
}
expected, err := e.mapToGCE(cloud.Project(), cloud.Region())
if err != nil {
return nil, err
}
for _, r := range response.Items {
if !strings.HasPrefix(r.Name, fi.StringValue(e.NamePrefix)+"-") {
continue
}
if !matches(expected, r) {
continue
}
actual := &InstanceTemplate{}
p := r.Properties
for _, tag := range p.Tags.Items {
actual.Tags = append(actual.Tags, tag)
}
actual.MachineType = fi.String(lastComponent(p.MachineType))
actual.CanIPForward = &p.CanIpForward
bootDiskImage, err := ShortenImageURL(cloud.Project(), p.Disks[0].InitializeParams.SourceImage)
if err != nil {
return nil, fmt.Errorf("error parsing source image URL: %v", err)
}
actual.BootDiskImage = fi.String(bootDiskImage)
actual.BootDiskType = &p.Disks[0].InitializeParams.DiskType
actual.BootDiskSizeGB = &p.Disks[0].InitializeParams.DiskSizeGb
if p.Scheduling != nil {
actual.Preemptible = &p.Scheduling.Preemptible
}
if len(p.NetworkInterfaces) != 0 {
ni := p.NetworkInterfaces[0]
actual.Network = &Network{Name: fi.String(lastComponent(ni.Network))}
if len(ni.AliasIpRanges) != 0 {
actual.AliasIPRanges = make(map[string]string)
for _, aliasIPRange := range ni.AliasIpRanges {
actual.AliasIPRanges[aliasIPRange.SubnetworkRangeName] = aliasIPRange.IpCidrRange
}
}
if ni.Subnetwork != "" {
actual.Subnet = &Subnet{Name: fi.String(lastComponent(ni.Subnetwork))}
}
}
for _, serviceAccount := range p.ServiceAccounts {
for _, scope := range serviceAccount.Scopes {
actual.Scopes = append(actual.Scopes, scopeToShortForm(scope))
}
}
// When we deal with additional disks (local disks), we'll need to map them like this...
//for i, disk := range p.Disks {
// if i == 0 {
// source := disk.Source
//
// // TODO: Parse source URL instead of assuming same project/zone?
// name := lastComponent(source)
// d, err := cloud.Compute.Disks.Get(cloud.Project, *e.Zone, name).Do()
// if err != nil {
// if gce.IsNotFound(err) {
// return nil, fmt.Errorf("disk not found %q: %v", source, err)
// }
// return nil, fmt.Errorf("error querying for disk %q: %v", source, err)
// } else {
// imageURL, err := gce.ParseGoogleCloudURL(d.SourceImage)
// if err != nil {
// return nil, fmt.Errorf("unable to parse image URL: %q", d.SourceImage)
// }
// actual.Image = fi.String(imageURL.Project + "/" + imageURL.Name)
// }
// }
//}
if p.Metadata != nil {
actual.Metadata = make(map[string]*fi.ResourceHolder)
for _, meta := range p.Metadata.Items {
actual.Metadata[meta.Key] = fi.WrapResource(fi.NewStringResource(fi.StringValue(meta.Value)))
}
}
// Prevent spurious changes
actual.Name = e.Name
actual.NamePrefix = e.NamePrefix
actual.ID = &r.Name
if e.ID == nil {
e.ID = actual.ID
}
// System fields
actual.Lifecycle = e.Lifecycle
return actual, nil
}
return nil, nil
}
func (e *InstanceTemplate) Run(c *fi.Context) error {
return fi.DefaultDeltaRunMethod(e, c)
}
func (_ *InstanceTemplate) CheckChanges(a, e, changes *InstanceTemplate) error {
if fi.StringValue(e.BootDiskImage) == "" {
return fi.RequiredField("BootDiskImage")
}
if fi.StringValue(e.MachineType) == "" {
return fi.RequiredField("MachineType")
}
return nil
}
func (e *InstanceTemplate) mapToGCE(project string, region string) (*compute.InstanceTemplate, error) {
// TODO: This is similar to Instance...
var scheduling *compute.Scheduling
if fi.BoolValue(e.Preemptible) {
scheduling = &compute.Scheduling{
AutomaticRestart: fi.Bool(false),
OnHostMaintenance: "TERMINATE",
Preemptible: true,
}
} else {
scheduling = &compute.Scheduling{
AutomaticRestart: fi.Bool(true),
// TODO: Migrate or terminate?
OnHostMaintenance: "MIGRATE",
Preemptible: false,
}
}
klog.Infof("We should be using NVME for GCE")
var disks []*compute.AttachedDisk
disks = append(disks, &compute.AttachedDisk{
Kind: "compute#attachedDisk",
InitializeParams: &compute.AttachedDiskInitializeParams{
SourceImage: BuildImageURL(project, *e.BootDiskImage),
DiskSizeGb: *e.BootDiskSizeGB,
DiskType: *e.BootDiskType,
},
Boot: true,
DeviceName: "persistent-disks-0",
Index: 0,
AutoDelete: true,
Mode: "READ_WRITE",
Type: "PERSISTENT",
})
var tags *compute.Tags
if e.Tags != nil {
tags = &compute.Tags{
Items: e.Tags,
}
}
var networkInterfaces []*compute.NetworkInterface
ni := &compute.NetworkInterface{
Kind: "compute#networkInterface",
AccessConfigs: []*compute.AccessConfig{{
Kind: "compute#accessConfig",
//NatIP: *e.IPAddress.Address,
Type: "ONE_TO_ONE_NAT",
NetworkTier: "PREMIUM",
}},
Network: e.Network.URL(project),
}
if e.Subnet != nil {
ni.Subnetwork = e.Subnet.URL(project, region)
}
if e.AliasIPRanges != nil {
for k, v := range e.AliasIPRanges {
ni.AliasIpRanges = append(ni.AliasIpRanges, &compute.AliasIpRange{
SubnetworkRangeName: k,
IpCidrRange: v,
})
}
}
networkInterfaces = append(networkInterfaces, ni)
var serviceAccounts []*compute.ServiceAccount
if e.Scopes != nil {
var scopes []string
for _, s := range e.Scopes {
s = scopeToLongForm(s)
scopes = append(scopes, s)
}
serviceAccounts = append(serviceAccounts, &compute.ServiceAccount{
Email: "default",
Scopes: scopes,
})
}
var metadataItems []*compute.MetadataItems
for key, r := range e.Metadata {
v, err := r.AsString()
if err != nil {
return nil, fmt.Errorf("error rendering InstanceTemplate metadata %q: %v", key, err)
}
metadataItems = append(metadataItems, &compute.MetadataItems{
Key: key,
Value: fi.String(v),
})
}
i := &compute.InstanceTemplate{
Kind: "compute#instanceTemplate",
Properties: &compute.InstanceProperties{
CanIpForward: *e.CanIPForward,
Disks: disks,
MachineType: *e.MachineType,
Metadata: &compute.Metadata{
Kind: "compute#metadata",
Items: metadataItems,
},
NetworkInterfaces: networkInterfaces,
Scheduling: scheduling,
ServiceAccounts: serviceAccounts,
Tags: tags,
},
}
return i, nil
}
type ByKey []*compute.MetadataItems
func (a ByKey) Len() int { return len(a) }
func (a ByKey) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByKey) Less(i, j int) bool { return a[i].Key < a[j].Key }
func matches(l, r *compute.InstanceTemplate) bool {
normalizeInstanceProperties := func(v *compute.InstanceProperties) *compute.InstanceProperties {
c := *v
if c.Metadata != nil {
cm := *c.Metadata
c.Metadata = &cm
c.Metadata.Fingerprint = ""
sort.Sort(ByKey(c.Metadata.Items))
}
return &c
}
normalize := func(v *compute.InstanceTemplate) *compute.InstanceTemplate {
c := *v
c.SelfLink = ""
c.CreationTimestamp = ""
c.Id = 0
c.Name = ""
c.Properties = normalizeInstanceProperties(c.Properties)
return &c
}
normalizedL := normalize(l)
normalizedR := normalize(r)
if !reflect.DeepEqual(normalizedL, normalizedR) {
if klog.V(10) {
ls := fi.DebugAsJsonStringIndent(normalizedL)
rs := fi.DebugAsJsonStringIndent(normalizedR)
klog.V(10).Infof("Not equal")
klog.V(10).Infof(diff.FormatDiff(ls, rs))
}
return false
}
return true
}
func (e *InstanceTemplate) URL(project string) (string, error) {
if e.ID == nil {
return "", fmt.Errorf("InstanceTemplate not yet built; ID is not yet known")
}
return fmt.Sprintf("https://www.googleapis.com/compute/v1/projects/%s/global/instanceTemplates/%s", project, *e.ID), nil
}
func (_ *InstanceTemplate) RenderGCE(t *gce.GCEAPITarget, a, e, changes *InstanceTemplate) error {
project := t.Cloud.Project()
region := t.Cloud.Region()
i, err := e.mapToGCE(project, region)
if err != nil {
return err
}
if a == nil {
klog.V(4).Infof("Creating InstanceTemplate %v", i)
name := fi.StringValue(e.NamePrefix) + "-" + strconv.FormatInt(time.Now().Unix(), 10)
e.ID = &name
i.Name = name
op, err := t.Cloud.Compute().InstanceTemplates.Insert(t.Cloud.Project(), i).Do()
if err != nil {
return fmt.Errorf("error creating InstanceTemplate: %v", err)
}
if err := t.Cloud.WaitForOp(op); err != nil {
return fmt.Errorf("error creating InstanceTemplate: %v", err)
}
} else {
return fmt.Errorf("Cannot apply changes to InstanceTemplate: %v", changes)
}
return nil
}
type terraformInstanceTemplate struct {
terraformInstanceCommon
NamePrefix string `json:"name_prefix"`
}
type terraformInstanceCommon struct {
CanIPForward bool `json:"can_ip_forward"`
MachineType string `json:"machine_type,omitempty"`
ServiceAccount *terraformServiceAccount `json:"service_account,omitempty"`
Scheduling *terraformScheduling `json:"scheduling,omitempty"`
Disks []*terraformAttachedDisk `json:"disk,omitempty"`
NetworkInterfaces []*terraformNetworkInterface `json:"network_interface,omitempty"`
Metadata map[string]*terraform.Literal `json:"metadata,omitempty"`
MetadataStartupScript *terraform.Literal `json:"metadata_startup_script,omitempty"`
Tags []string `json:"tags,omitempty"`
// Only for instances:
Zone string `json:"zone,omitempty"`
}
type terraformServiceAccount struct {
Scopes []string `json:"scopes"`
}
type terraformScheduling struct {
AutomaticRestart bool `json:"automatic_restart"`
OnHostMaintenance string `json:"on_host_maintenance,omitempty"`
Preemptible bool `json:"preemptible"`
}
type terraformAttachedDisk struct {
// These values are common
AutoDelete bool `json:"auto_delete,omitempty"`
DeviceName string `json:"device_name,omitempty"`
// DANGER - common but different meaning:
// for an instance template this is scratch vs persistent
// for an instance this is 'pd-standard', 'pd-ssd', 'local-ssd' etc
Type string `json:"type,omitempty"`
// These values are only for instance templates:
Boot bool `json:"boot,omitempty"`
DiskName string `json:"disk_name,omitempty"`
SourceImage string `json:"source_image,omitempty"`
Source string `json:"source,omitempty"`
Interface string `json:"interface,omitempty"`
Mode string `json:"mode,omitempty"`
DiskType string `json:"disk_type,omitempty"`
DiskSizeGB int64 `json:"disk_size_gb,omitempty"`
// These values are only for instances:
Disk string `json:"disk,omitempty"`
Image string `json:"image,omitempty"`
Scratch bool `json:"scratch,omitempty"`
Size int64 `json:"size,omitempty"`
}
type terraformNetworkInterface struct {
Network *terraform.Literal `json:"network,omitempty"`
Subnetwork *terraform.Literal `json:"subnetwork,omitempty"`
AccessConfig []*terraformAccessConfig `json:"access_config"`
}
type terraformAccessConfig struct {
NatIP *terraform.Literal `json:"nat_ip,omitempty"`
}
func (t *terraformInstanceCommon) AddNetworks(network *Network, subnet *Subnet, networkInterfacs []*compute.NetworkInterface) {
for _, g := range networkInterfacs {
tf := &terraformNetworkInterface{}
if network != nil {
tf.Network = network.TerraformName()
}
if subnet != nil {
tf.Subnetwork = subnet.TerraformName()
}
for _, gac := range g.AccessConfigs {
tac := &terraformAccessConfig{}
natIP := gac.NatIP
if strings.HasPrefix(natIP, "${") {
tac.NatIP = terraform.LiteralExpression(natIP)
} else if natIP != "" {
tac.NatIP = terraform.LiteralFromStringValue(natIP)
}
tf.AccessConfig = append(tf.AccessConfig, tac)
}
t.NetworkInterfaces = append(t.NetworkInterfaces, tf)
}
}
func (t *terraformInstanceCommon) AddMetadata(target *terraform.TerraformTarget, name string, metadata *compute.Metadata) error {
if metadata != nil {
if t.Metadata == nil {
t.Metadata = make(map[string]*terraform.Literal)
}
for _, g := range metadata.Items {
v := fi.NewStringResource(fi.StringValue(g.Value))
tfResource, err := target.AddFile("google_compute_instance_template", name, "metadata_"+g.Key, v)
if err != nil {
return err
}
t.Metadata[g.Key] = tfResource
}
}
return nil
}
func (t *terraformInstanceCommon) AddServiceAccounts(serviceAccounts []*compute.ServiceAccount) {
for _, g := range serviceAccounts {
for _, scope := range g.Scopes {
if t.ServiceAccount == nil {
t.ServiceAccount = &terraformServiceAccount{}
}
t.ServiceAccount.Scopes = append(t.ServiceAccount.Scopes, scope)
}
}
}
func (_ *InstanceTemplate) RenderTerraform(t *terraform.TerraformTarget, a, e, changes *InstanceTemplate) error {
project := t.Project
i, err := e.mapToGCE(project, t.Region)
if err != nil {
return err
}
name := fi.StringValue(e.Name)
tf := &terraformInstanceTemplate{
NamePrefix: fi.StringValue(e.NamePrefix) + "-",
}
tf.CanIPForward = i.Properties.CanIpForward
tf.MachineType = lastComponent(i.Properties.MachineType)
//tf.Zone = i.Properties.Zone
tf.Tags = i.Properties.Tags.Items
tf.AddServiceAccounts(i.Properties.ServiceAccounts)
for _, d := range i.Properties.Disks {
tfd := &terraformAttachedDisk{
AutoDelete: d.AutoDelete,
Boot: d.Boot,
DeviceName: d.DeviceName,
DiskName: d.InitializeParams.DiskName,
SourceImage: d.InitializeParams.SourceImage,
Source: d.Source,
Interface: d.Interface,
Mode: d.Mode,
DiskType: d.InitializeParams.DiskType,
DiskSizeGB: d.InitializeParams.DiskSizeGb,
Type: d.Type,
}
tf.Disks = append(tf.Disks, tfd)
}
tf.AddNetworks(e.Network, e.Subnet, i.Properties.NetworkInterfaces)
tf.AddMetadata(t, name, i.Properties.Metadata)
if i.Properties.Scheduling != nil {
tf.Scheduling = &terraformScheduling{
AutomaticRestart: fi.BoolValue(i.Properties.Scheduling.AutomaticRestart),
OnHostMaintenance: i.Properties.Scheduling.OnHostMaintenance,
Preemptible: i.Properties.Scheduling.Preemptible,
}
}
return t.RenderResource("google_compute_instance_template", name, tf)
}
func (i *InstanceTemplate) TerraformLink() *terraform.Literal {
return terraform.LiteralSelfLink("google_compute_instance_template", *i.Name)
}