-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
command.go
641 lines (545 loc) · 19.4 KB
/
command.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
/*
Copyright 2019 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 nodeup
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"os/exec"
"strconv"
"strings"
"time"
"k8s.io/kops/nodeup/pkg/distros"
"k8s.io/kops/nodeup/pkg/model"
api "k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/apis/kops/registry"
"k8s.io/kops/pkg/apis/nodeup"
"k8s.io/kops/pkg/assets"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/nodeup/cloudinit"
"k8s.io/kops/upup/pkg/fi/nodeup/local"
"k8s.io/kops/upup/pkg/fi/nodeup/nodetasks"
"k8s.io/kops/upup/pkg/fi/secrets"
"k8s.io/kops/upup/pkg/fi/utils"
"k8s.io/kops/util/pkg/vfs"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/klog"
)
// MaxTaskDuration is the amount of time to keep trying for; we retry for a long time - there is not really any great fallback
const MaxTaskDuration = 365 * 24 * time.Hour
// NodeUpCommand is the configuration for nodeup
type NodeUpCommand struct {
CacheDir string
ConfigLocation string
FSRoot string
ModelDir vfs.Path
Target string
cluster *api.Cluster
config *nodeup.Config
instanceGroup *api.InstanceGroup
}
// Run is responsible for perform the nodeup process
func (c *NodeUpCommand) Run(out io.Writer) error {
if c.FSRoot == "" {
return fmt.Errorf("FSRoot is required")
}
if c.ConfigLocation != "" {
config, err := vfs.Context.ReadFile(c.ConfigLocation)
if err != nil {
return fmt.Errorf("error loading configuration %q: %v", c.ConfigLocation, err)
}
err = utils.YamlUnmarshal(config, &c.config)
if err != nil {
return fmt.Errorf("error parsing configuration %q: %v", c.ConfigLocation, err)
}
} else {
return fmt.Errorf("ConfigLocation is required")
}
if c.CacheDir == "" {
return fmt.Errorf("CacheDir is required")
}
assetStore := fi.NewAssetStore(c.CacheDir)
for _, asset := range c.config.Assets {
err := assetStore.Add(asset)
if err != nil {
return fmt.Errorf("error adding asset %q: %v", asset, err)
}
}
var configBase vfs.Path
if fi.StringValue(c.config.ConfigBase) != "" {
var err error
configBase, err = vfs.Context.BuildVfsPath(*c.config.ConfigBase)
if err != nil {
return fmt.Errorf("cannot parse ConfigBase %q: %v", *c.config.ConfigBase, err)
}
} else if fi.StringValue(c.config.ClusterLocation) != "" {
basePath := *c.config.ClusterLocation
lastSlash := strings.LastIndex(basePath, "/")
if lastSlash != -1 {
basePath = basePath[0:lastSlash]
}
var err error
configBase, err = vfs.Context.BuildVfsPath(basePath)
if err != nil {
return fmt.Errorf("cannot parse inferred ConfigBase %q: %v", basePath, err)
}
} else {
return fmt.Errorf("ConfigBase is required")
}
c.cluster = &api.Cluster{}
{
clusterLocation := fi.StringValue(c.config.ClusterLocation)
var p vfs.Path
if clusterLocation != "" {
var err error
p, err = vfs.Context.BuildVfsPath(clusterLocation)
if err != nil {
return fmt.Errorf("error parsing ClusterLocation %q: %v", clusterLocation, err)
}
} else {
p = configBase.Join(registry.PathClusterCompleted)
}
b, err := p.ReadFile()
if err != nil {
return fmt.Errorf("error loading Cluster %q: %v", p, err)
}
err = utils.YamlUnmarshal(b, c.cluster)
if err != nil {
return fmt.Errorf("error parsing Cluster %q: %v", p, err)
}
}
if c.config.InstanceGroupName != "" {
instanceGroupLocation := configBase.Join("instancegroup", c.config.InstanceGroupName)
c.instanceGroup = &api.InstanceGroup{}
b, err := instanceGroupLocation.ReadFile()
if err != nil {
return fmt.Errorf("error loading InstanceGroup %q: %v", instanceGroupLocation, err)
}
if err = utils.YamlUnmarshal(b, c.instanceGroup); err != nil {
return fmt.Errorf("error parsing InstanceGroup %q: %v", instanceGroupLocation, err)
}
} else {
klog.Warningf("No instance group defined in nodeup config")
}
err := evaluateSpec(c.cluster)
if err != nil {
return err
}
distribution, err := distros.FindDistribution(c.FSRoot)
if err != nil {
return fmt.Errorf("error determining OS distribution: %v", err)
}
osTags := distribution.BuildTags()
nodeTags := sets.NewString()
nodeTags.Insert(osTags...)
nodeTags.Insert(c.config.Tags...)
klog.Infof("Config tags: %v", c.config.Tags)
klog.Infof("OS tags: %v", osTags)
modelContext := &model.NodeupModelContext{
Architecture: model.ArchitectureAmd64,
Assets: assetStore,
Cluster: c.cluster,
Distribution: distribution,
InstanceGroup: c.instanceGroup,
NodeupConfig: c.config,
}
if c.cluster.Spec.SecretStore != "" {
klog.Infof("Building SecretStore at %q", c.cluster.Spec.SecretStore)
p, err := vfs.Context.BuildVfsPath(c.cluster.Spec.SecretStore)
if err != nil {
return fmt.Errorf("error building secret store path: %v", err)
}
modelContext.SecretStore = secrets.NewVFSSecretStore(c.cluster, p)
} else {
return fmt.Errorf("SecretStore not set")
}
if c.cluster.Spec.KeyStore != "" {
klog.Infof("Building KeyStore at %q", c.cluster.Spec.KeyStore)
p, err := vfs.Context.BuildVfsPath(c.cluster.Spec.KeyStore)
if err != nil {
return fmt.Errorf("error building key store path: %v", err)
}
modelContext.KeyStore = fi.NewVFSCAStore(c.cluster, p, false)
} else {
return fmt.Errorf("KeyStore not set")
}
if err := modelContext.Init(); err != nil {
return err
}
if err := loadKernelModules(modelContext); err != nil {
return err
}
loader := NewLoader(c.config, c.cluster, assetStore, nodeTags)
loader.Builders = append(loader.Builders, &model.NTPBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.MiscUtilsBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.DirectoryBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.UpdateServiceBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.VolumesBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.ContainerdBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.DockerBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.ProtokubeBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.CloudConfigBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.FileAssetsBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.HookBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.NodeAuthorizationBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.KubeletBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.KubectlBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.EtcdBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.LogrotateBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.ManifestsBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.PackagesBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.SecretBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.FirewallBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.NetworkBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.SysctlBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.KubeAPIServerBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.KubeControllerManagerBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.KubeSchedulerBuilder{NodeupModelContext: modelContext})
loader.Builders = append(loader.Builders, &model.EtcdManagerTLSBuilder{NodeupModelContext: modelContext})
if c.cluster.Spec.Networking.Kuberouter == nil {
loader.Builders = append(loader.Builders, &model.KubeProxyBuilder{NodeupModelContext: modelContext})
} else {
loader.Builders = append(loader.Builders, &model.KubeRouterBuilder{NodeupModelContext: modelContext})
}
if c.cluster.Spec.Networking.Calico != nil {
loader.Builders = append(loader.Builders, &model.EtcdTLSBuilder{NodeupModelContext: modelContext})
}
if c.cluster.Spec.Networking.LyftVPC != nil {
loader.TemplateFunctions["SubnetTags"] = func() (string, error) {
tags := map[string]string{
"Type": "pod",
}
if len(c.cluster.Spec.Networking.LyftVPC.SubnetTags) > 0 {
tags = c.cluster.Spec.Networking.LyftVPC.SubnetTags
}
bytes, err := json.Marshal(tags)
if err != nil {
return "", err
}
return string(bytes), nil
}
loader.TemplateFunctions["NodeSecurityGroups"] = func() (string, error) {
// use the same security groups as the node
ids, err := evaluateSecurityGroups(c.cluster.Spec.NetworkID)
if err != nil {
return "", err
}
bytes, err := json.Marshal(ids)
if err != nil {
return "", err
}
return string(bytes), nil
}
}
taskMap, err := loader.Build(c.ModelDir)
if err != nil {
return fmt.Errorf("error building loader: %v", err)
}
for i, image := range c.config.Images {
taskMap["LoadImage."+strconv.Itoa(i)] = &nodetasks.LoadImageTask{
Sources: image.Sources,
Hash: image.Hash,
Runtime: c.cluster.Spec.ContainerRuntime,
}
}
// Protokube load image task is in ProtokubeBuilder
var cloud fi.Cloud
var keyStore fi.Keystore
var secretStore fi.SecretStore
var target fi.Target
checkExisting := true
switch c.Target {
case "direct":
target = &local.LocalTarget{
CacheDir: c.CacheDir,
Tags: nodeTags,
}
case "dryrun":
assetBuilder := assets.NewAssetBuilder(c.cluster, "")
target = fi.NewDryRunTarget(assetBuilder, out)
case "cloudinit":
checkExisting = false
target = cloudinit.NewCloudInitTarget(out, nodeTags)
default:
return fmt.Errorf("unsupported target type %q", c.Target)
}
context, err := fi.NewContext(target, nil, cloud, keyStore, secretStore, configBase, checkExisting, taskMap)
if err != nil {
klog.Exitf("error building context: %v", err)
}
defer context.Close()
var options fi.RunTasksOptions
options.InitDefaults()
err = context.RunTasks(options)
if err != nil {
klog.Exitf("error running tasks: %v", err)
}
err = target.Finish(taskMap)
if err != nil {
klog.Exitf("error closing target: %v", err)
}
return nil
}
func evaluateSpec(c *api.Cluster) error {
var err error
c.Spec.Kubelet.HostnameOverride, err = evaluateHostnameOverride(c.Spec.Kubelet.HostnameOverride)
if err != nil {
return err
}
c.Spec.MasterKubelet.HostnameOverride, err = evaluateHostnameOverride(c.Spec.MasterKubelet.HostnameOverride)
if err != nil {
return err
}
if c.Spec.KubeProxy != nil {
c.Spec.KubeProxy.HostnameOverride, err = evaluateHostnameOverride(c.Spec.KubeProxy.HostnameOverride)
if err != nil {
return err
}
c.Spec.KubeProxy.BindAddress, err = evaluateBindAddress(c.Spec.KubeProxy.BindAddress)
if err != nil {
return err
}
}
if c.Spec.Docker != nil {
err = evaluateDockerSpecStorage(c.Spec.Docker)
if err != nil {
return err
}
}
return nil
}
func evaluateSecurityGroups(vpcId string) ([]string, error) {
config := aws.NewConfig()
config = config.WithCredentialsChainVerboseErrors(true)
s, err := session.NewSession(config)
if err != nil {
return nil, fmt.Errorf("error starting new AWS session: %v", err)
}
s.Handlers.Send.PushFront(func(r *request.Request) {
// Log requests
klog.V(4).Infof("AWS API Request: %s/%s", r.ClientInfo.ServiceName, r.Operation.Name)
})
metadata := ec2metadata.New(s, config)
region, err := metadata.Region()
if err != nil {
return nil, fmt.Errorf("error querying ec2 metadata service (for az/region): %v", err)
}
sgNames, err := metadata.GetMetadata("security-groups")
if err != nil {
return nil, fmt.Errorf("error querying ec2 metadata service (for security-groups): %v", err)
}
svc := ec2.New(s, config.WithRegion(region))
result, err := svc.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("group-name"),
Values: aws.StringSlice(strings.Fields(sgNames)),
},
{
Name: aws.String("vpc-id"),
Values: []*string{aws.String(vpcId)},
},
},
})
if err != nil {
return nil, fmt.Errorf("error looking up instance security group ids: %v", err)
}
var sgIds []string
for _, group := range result.SecurityGroups {
sgIds = append(sgIds, *group.GroupId)
}
return sgIds, nil
}
func evaluateHostnameOverride(hostnameOverride string) (string, error) {
if hostnameOverride == "" || hostnameOverride == "@hostname" {
return "", nil
}
k := strings.TrimSpace(hostnameOverride)
k = strings.ToLower(k)
if k == "@aws" {
// We recognize @aws as meaning "the private DNS name from AWS", to generate this we need to get a few pieces of information
azBytes, err := vfs.Context.ReadFile("metadata://aws/meta-data/placement/availability-zone")
if err != nil {
return "", fmt.Errorf("error reading availability zone from AWS metadata: %v", err)
}
instanceIDBytes, err := vfs.Context.ReadFile("metadata://aws/meta-data/instance-id")
if err != nil {
return "", fmt.Errorf("error reading instance-id from AWS metadata: %v", err)
}
instanceID := string(instanceIDBytes)
config := aws.NewConfig()
config = config.WithCredentialsChainVerboseErrors(true)
s, err := session.NewSession(config)
if err != nil {
return "", fmt.Errorf("error starting new AWS session: %v", err)
}
svc := ec2.New(s, config.WithRegion(string(azBytes[:len(azBytes)-1])))
result, err := svc.DescribeInstances(&ec2.DescribeInstancesInput{
InstanceIds: []*string{&instanceID},
})
if err != nil {
return "", fmt.Errorf("error describing instances: %v", err)
}
if len(result.Reservations) != 1 {
return "", fmt.Errorf("Too many reservations returned for the single instance-id")
}
if len(result.Reservations[0].Instances) != 1 {
return "", fmt.Errorf("Too many instances returned for the single instance-id")
}
return *(result.Reservations[0].Instances[0].PrivateDnsName), nil
}
if k == "@digitalocean" {
// @digitalocean means to use the private ipv4 address of a droplet as the hostname override
vBytes, err := vfs.Context.ReadFile("metadata://digitalocean/interfaces/private/0/ipv4/address")
if err != nil {
return "", fmt.Errorf("error reading droplet private IP from DigitalOcean metadata: %v", err)
}
hostname := string(vBytes)
if hostname == "" {
return "", errors.New("private IP for digitalocean droplet was empty")
}
return hostname, nil
}
if k == "@alicloud" {
// @alicloud means to use the "{az}.{instance-id}" of a instance as the hostname override
azBytes, err := vfs.Context.ReadFile("metadata://alicloud/zone-id")
if err != nil {
return "", fmt.Errorf("error reading zone-id from Alicloud metadata: %v", err)
}
az := string(azBytes)
instanceIDBytes, err := vfs.Context.ReadFile("metadata://alicloud/instance-id")
if err != nil {
return "", fmt.Errorf("error reading instance-id from Alicloud metadata: %v", err)
}
instanceID := string(instanceIDBytes)
return fmt.Sprintf("%s.%s", az, instanceID), nil
}
return hostnameOverride, nil
}
func evaluateBindAddress(bindAddress string) (string, error) {
if bindAddress == "" {
return "", nil
}
if bindAddress == "@aws" {
vBytes, err := vfs.Context.ReadFile("metadata://aws/meta-data/local-ipv4")
if err != nil {
return "", fmt.Errorf("error reading local IP from AWS metadata: %v", err)
}
// The local-ipv4 gets it's IP from the AWS.
// For now just choose the first one.
ips := strings.Fields(string(vBytes))
if len(ips) == 0 {
klog.Warningf("Local IP from AWS metadata service was empty")
return "", nil
}
ip := ips[0]
klog.Infof("Using IP from AWS metadata service: %s", ip)
return ip, nil
}
if net.ParseIP(bindAddress) == nil {
return "", fmt.Errorf("bindAddress is not valid IP address")
}
return bindAddress, nil
}
// evaluateDockerSpec selects the first supported storage mode, if it is a list
func evaluateDockerSpecStorage(spec *api.DockerConfig) error {
storage := fi.StringValue(spec.Storage)
if strings.Contains(fi.StringValue(spec.Storage), ",") {
precedence := strings.Split(storage, ",")
for _, opt := range precedence {
fs := opt
if fs == "overlay2" {
fs = "overlay"
}
supported, err := kernelHasFilesystem(fs)
if err != nil {
klog.Warningf("error checking if %q filesystem is supported: %v", fs, err)
continue
}
if !supported {
// overlay -> overlay
// aufs -> aufs
module := fs
if err = modprobe(fs); err != nil {
klog.Warningf("error running `modprobe %q`: %v", module, err)
}
}
supported, err = kernelHasFilesystem(fs)
if err != nil {
klog.Warningf("error checking if %q filesystem is supported: %v", fs, err)
continue
}
if supported {
klog.Infof("Using supported docker storage %q", opt)
spec.Storage = fi.String(opt)
return nil
}
klog.Warningf("%q docker storage was specified, but filesystem is not supported", opt)
}
// Just in case we don't recognize the driver?
// TODO: Is this the best behaviour
klog.Warningf("No storage module was supported from %q, will default to %q", storage, precedence[0])
spec.Storage = fi.String(precedence[0])
return nil
}
return nil
}
// kernelHasFilesystem checks if /proc/filesystems contains the specified filesystem
func kernelHasFilesystem(fs string) (bool, error) {
contents, err := ioutil.ReadFile("/proc/filesystems")
if err != nil {
return false, fmt.Errorf("error reading /proc/filesystems: %v", err)
}
for _, line := range strings.Split(string(contents), "\n") {
tokens := strings.Fields(line)
for _, token := range tokens {
// Technically we should skip "nodev", but it doesn't matter
if token == fs {
return true, nil
}
}
}
return false, nil
}
// modprobe will exec `modprobe <module>`
func modprobe(module string) error {
klog.Infof("Doing modprobe for module %v", module)
out, err := exec.Command("/sbin/modprobe", module).CombinedOutput()
outString := string(out)
if err != nil {
return fmt.Errorf("modprobe for module %q failed (%v): %s", module, err, outString)
}
if outString != "" {
klog.Infof("Output from modprobe %s:\n%s", module, outString)
}
return nil
}
// loadKernelModules is a hack to force br_netfilter to be loaded
// TODO: Move to tasks architecture
func loadKernelModules(context *model.NodeupModelContext) error {
err := modprobe("br_netfilter")
if err != nil {
// TODO: Return error in 1.11 (too risky for 1.10)
klog.Warningf("error loading br_netfilter module: %v", err)
}
// TODO: Add to /etc/modules-load.d/ ?
return nil
}