/
up.go
660 lines (523 loc) · 17.9 KB
/
up.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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
package cmd
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/covexo/devspace/pkg/util/yamlutil"
"github.com/covexo/devspace/pkg/devspace/builder"
"github.com/docker/docker/api/types"
"github.com/covexo/devspace/pkg/devspace/builder/docker"
"github.com/covexo/devspace/pkg/devspace/config/v1"
"github.com/covexo/devspace/pkg/util/randutil"
"github.com/covexo/devspace/pkg/util/log"
"github.com/covexo/devspace/pkg/devspace/builder/kaniko"
"github.com/covexo/devspace/pkg/devspace/registry"
synctool "github.com/covexo/devspace/pkg/devspace/sync"
helmClient "github.com/covexo/devspace/pkg/devspace/clients/helm"
"github.com/covexo/devspace/pkg/devspace/clients/kubectl"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/covexo/devspace/pkg/devspace/config/configutil"
"github.com/spf13/cobra"
k8sv1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/util/exec"
)
// UpCmd is a struct that defines a command call for "up"
type UpCmd struct {
flags *UpCmdFlags
helm *helmClient.HelmClientWrapper
kubectl *kubernetes.Clientset
workdir string
pod *k8sv1.Pod
container *k8sv1.Container
}
// UpCmdFlags are the flags available for the up-command
type UpCmdFlags struct {
tiller bool
open string
initRegistries bool
build bool
shell string
sync bool
deploy bool
portforwarding bool
noSleep bool
}
//UpFlagsDefault are the default flags for UpCmdFlags
var UpFlagsDefault = &UpCmdFlags{
tiller: true,
open: "cmd",
initRegistries: true,
build: true,
sync: true,
deploy: false,
portforwarding: true,
noSleep: false,
}
func init() {
cmd := &UpCmd{
flags: UpFlagsDefault,
}
cobraCmd := &cobra.Command{
Use: "up",
Short: "Starts your DevSpace",
Long: `
#######################################################
#################### devspace up ######################
#######################################################
Starts and connects your DevSpace:
1. Connects to the Tiller server
2. Builds your Docker image (if your Dockerfile has changed)
3. Deploys the Helm chart in /chart
4. Starts the sync client
5. Enters the container shell
#######################################################`,
Args: cobra.NoArgs,
Run: cmd.Run,
}
rootCmd.AddCommand(cobraCmd)
cobraCmd.Flags().BoolVar(&cmd.flags.tiller, "tiller", cmd.flags.tiller, "Install/upgrade tiller")
cobraCmd.Flags().BoolVar(&cmd.flags.initRegistries, "init-registries", cmd.flags.initRegistries, "Initialize registries (and install internal one)")
cobraCmd.Flags().BoolVarP(&cmd.flags.build, "build", "b", cmd.flags.build, "Build image if Dockerfile has been modified")
cobraCmd.Flags().StringVarP(&cmd.flags.shell, "shell", "s", "", "Shell command (default: bash, fallback: sh)")
cobraCmd.Flags().BoolVar(&cmd.flags.sync, "sync", cmd.flags.sync, "Enable code synchronization")
cobraCmd.Flags().BoolVar(&cmd.flags.portforwarding, "portforwarding", cmd.flags.portforwarding, "Enable port forwarding")
cobraCmd.Flags().BoolVarP(&cmd.flags.deploy, "deploy", "d", cmd.flags.deploy, "Deploy chart")
cobraCmd.Flags().BoolVar(&cmd.flags.noSleep, "no-sleep", cmd.flags.noSleep, "Enable no-sleep")
}
// Run executes the command logic
func (cmd *UpCmd) Run(cobraCmd *cobra.Command, args []string) {
log.StartFileLogging()
workdir, err := os.Getwd()
if err != nil {
log.Fatalf("Unable to determine current workdir: %s", err.Error())
}
cmd.workdir = workdir
configExists, _ := configutil.ConfigExists()
if !configExists {
initCmd := &InitCmd{
flags: InitCmdFlagsDefault,
}
initCmd.Run(nil, []string{})
}
cmd.kubectl, err = kubectl.NewClient()
if err != nil {
log.Fatalf("Unable to create new kubectl client: %v", err)
}
err = cmd.ensureNamespace()
if err != nil {
log.Fatalf("Unable to create release namespace: %v", err)
}
cmd.initHelm()
if cmd.flags.initRegistries {
cmd.initRegistries()
}
mustRedeploy := cmd.flags.deploy
if cmd.flags.build {
mustRedeploy = cmd.buildImages(cobraCmd.Flags().Changed("build"))
}
// Check if we find a running release pod
pod, err := getRunningDevSpacePod(cmd.helm, cmd.kubectl)
if err != nil || mustRedeploy {
cmd.deployChart()
} else {
cmd.pod = pod
}
if cmd.flags.portforwarding {
cmd.startPortForwarding()
}
if cmd.flags.sync {
syncConfigs := cmd.startSync()
defer func() {
for _, v := range syncConfigs {
v.Stop()
}
}()
}
cmd.enterTerminal()
}
func (cmd *UpCmd) ensureNamespace() error {
config := configutil.GetConfig(false)
releaseNamespace := *config.DevSpace.Release.Namespace
// Check if registry namespace exists
_, err := cmd.kubectl.CoreV1().Namespaces().Get(releaseNamespace, metav1.GetOptions{})
if err != nil {
// Create registry namespace
_, err = cmd.kubectl.CoreV1().Namespaces().Create(&k8sv1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: releaseNamespace,
},
})
if err != nil {
return err
}
}
return nil
}
func (cmd *UpCmd) initRegistries() {
config := configutil.GetConfig(false)
registryMap := *config.Registries
if config.Services.InternalRegistry != nil {
registryConf, regConfExists := registryMap["internal"]
if !regConfExists {
log.Fatal("Registry config not found for internal registry")
}
log.StartWait("Initializing internal registry")
err := registry.InitInternalRegistry(cmd.kubectl, cmd.helm, config.Services.InternalRegistry, registryConf)
err = configutil.SaveConfig()
log.StopWait()
if err != nil {
log.Fatalf("Internal registry error: %v", err)
}
log.Done("Internal registry started")
}
for registryName, registryConf := range registryMap {
if registryConf.Auth != nil && registryConf.Auth.Password != nil {
username := ""
password := *registryConf.Auth.Password
email := "noreply@devspace-cloud.com"
if registryConf.Auth.Username != nil {
username = *registryConf.Auth.Username
}
log.StartWait("Creating image pull secret for registry: " + registryName)
err := registry.CreatePullSecret(cmd.kubectl, *config.DevSpace.Release.Namespace, *registryConf.URL, username, password, email)
log.StopWait()
if err != nil {
log.Fatalf("Failed to create pull secret for registry: %v", err)
}
}
}
}
func (cmd *UpCmd) shouldRebuild(imageConf *v1.ImageConfig, dockerfilePath string, buildFlagChanged bool) bool {
mustRebuild := true
dockerfileInfo, statErr := os.Stat(dockerfilePath)
var dockerfileModTime time.Time
if statErr != nil {
if imageConf.Build.LatestTimestamp == nil {
log.Fatalf("Dockerfile missing: %s", statErr.Error())
} else {
mustRebuild = false
}
} else {
dockerfileModTime = dockerfileInfo.ModTime()
// When user has not used -b or --build flags
if buildFlagChanged == false {
if imageConf.Build.LatestTimestamp != nil {
latestBuildTime, _ := time.Parse(time.RFC3339Nano, *imageConf.Build.LatestTimestamp)
// only rebuild Docker image when Dockerfile has changed since latest build
mustRebuild = (latestBuildTime.Equal(dockerfileModTime) == false)
}
}
}
imageConf.Build.LatestTimestamp = configutil.String(dockerfileModTime.Format(time.RFC3339Nano))
return mustRebuild
}
// returns true when one of the images had to be rebuild
func (cmd *UpCmd) buildImages(buildFlagChanged bool) bool {
re := false
config := configutil.GetConfig(false)
for imageName, imageConf := range *config.Images {
dockerfilePath := "./Dockerfile"
contextPath := "./"
if imageConf.Build.DockerfilePath != nil {
dockerfilePath = *imageConf.Build.DockerfilePath
}
if imageConf.Build.ContextPath != nil {
contextPath = *imageConf.Build.ContextPath
}
dockerfilePath = filepath.Join(cmd.workdir, strings.TrimPrefix(dockerfilePath, "."))
contextPath = filepath.Join(cmd.workdir, strings.TrimPrefix(contextPath, "."))
if cmd.shouldRebuild(imageConf, dockerfilePath, buildFlagChanged) {
re = true
imageTag, randErr := randutil.GenerateRandomString(7)
if randErr != nil {
log.Fatalf("Image building failed: %s", randErr.Error())
}
registryConf, registryErr := registry.GetRegistryConfig(imageConf)
if registryErr != nil {
log.Fatal(registryErr)
}
var buildErr error
var imageBuilder builder.BuilderInterface
buildInfo := "Building image '%s' with engine '%s'"
registryURL := *registryConf.URL
if registryURL == "hub.docker.com" {
registryURL = ""
}
engineName := ""
if imageConf.Build.Engine.Kaniko != nil {
engineName = "kaniko"
buildNamespace := *config.DevSpace.Release.Namespace
allowInsecurePush := false
if imageConf.Build.Engine.Kaniko.Namespace != nil {
buildNamespace = *imageConf.Build.Engine.Kaniko.Namespace
}
if registryConf.Insecure != nil {
allowInsecurePush = *registryConf.Insecure
}
imageBuilder, buildErr = kaniko.NewBuilder(registryURL, *imageConf.Name, imageTag, buildNamespace, cmd.kubectl, allowInsecurePush)
} else {
engineName = "docker"
preferMinikube := true
if imageConf.Build.Engine.Docker.PreferMinikube != nil {
preferMinikube = *imageConf.Build.Engine.Docker.PreferMinikube
}
imageBuilder, buildErr = docker.NewBuilder(registryURL, *imageConf.Name, imageTag, preferMinikube)
}
log.Infof(buildInfo, imageName, engineName)
if buildErr == nil {
username := ""
password := ""
if registryConf.Auth != nil {
if registryConf.Auth.Username != nil {
username = *registryConf.Auth.Username
}
if registryConf.Auth.Password != nil {
password = *registryConf.Auth.Password
}
}
log.StartWait("Authenticating (" + *registryConf.URL + ")")
_, buildErr = imageBuilder.Authenticate(username, password, len(username) == 0)
log.StopWait()
if buildErr == nil {
log.Done("Authentication successful (" + *registryConf.URL + ")")
buildOptions := &types.ImageBuildOptions{}
if imageConf.Build.Options != nil {
if imageConf.Build.Options.BuildArgs != nil {
buildOptions.BuildArgs = *imageConf.Build.Options.BuildArgs
}
}
buildErr = imageBuilder.BuildImage(contextPath, dockerfilePath, buildOptions)
if buildErr == nil {
buildErr = imageBuilder.PushImage()
if buildErr == nil {
log.Info("Image pushed to registry (" + *registryConf.URL + ")")
}
}
}
}
if buildErr != nil {
log.Fatalf("Image building failed: %s", buildErr.Error())
}
imageConf.Tag = &imageTag
err := configutil.SaveConfig()
if err != nil {
log.Fatalf("Config saving error: %s", err.Error())
}
log.Done("Done building and pushing image '" + imageName + "'")
} else {
log.Infof("Skip building image '%s'", imageName)
}
}
return re
}
func (cmd *UpCmd) initHelm() {
if cmd.helm == nil {
log.StartWait("Initializing helm client")
defer log.StopWait()
client, err := helmClient.NewClient(cmd.kubectl, false)
if err != nil {
log.Fatalf("Error initializing helm client: %s", err.Error())
}
cmd.helm = client
log.Done("Initialized helm client")
}
}
func (cmd *UpCmd) deployChart() {
config := configutil.GetConfig(false)
log.StartWait("Deploying helm chart")
releaseName := *config.DevSpace.Release.Name
releaseNamespace := *config.DevSpace.Release.Namespace
chartPath := "chart/"
values := map[interface{}]interface{}{}
overwriteValues := map[interface{}]interface{}{}
yamlutil.ReadYamlFromFile(chartPath, values)
containerValues := map[string]interface{}{}
for imageName, imageConf := range *config.Images {
container := map[string]interface{}{}
container["image"] = registry.GetImageURL(imageConf, true)
if !cmd.flags.noSleep {
container["command"] = []string{"sleep"}
container["args"] = []string{"99999999"}
}
containerValues[imageName] = container
}
pullSecrets := []string{}
existingPullSecrets, pullSecretsExisting := values["pullSecrets"]
if pullSecretsExisting {
pullSecrets = existingPullSecrets.([]string)
}
for _, registryConf := range *config.Registries {
if registryConf.URL != nil {
registrySecretName := registry.GetRegistryAuthSecretName(*registryConf.URL)
pullSecrets = append(pullSecrets, registrySecretName)
}
}
overwriteValues["containers"] = containerValues
overwriteValues["pullSecrets"] = pullSecrets
appRelease, err := cmd.helm.InstallChartByPath(releaseName, releaseNamespace, chartPath, &overwriteValues)
log.StopWait()
if err != nil {
log.Fatalf("Unable to deploy helm chart: %s", err.Error())
}
releaseRevision := int(appRelease.Version)
log.Donef("Deployed helm chart (Release revision: %d)", releaseRevision)
log.StartWait("Waiting for release pod to become ready")
defer log.StopWait()
for true {
podList, err := cmd.kubectl.Core().Pods(releaseNamespace).List(metav1.ListOptions{
LabelSelector: "release=" + releaseName,
})
if err != nil {
log.Panicf("Unable to list devspace pods: %s", err.Error())
}
if len(podList.Items) > 0 {
highestRevision := 0
var selectedPod k8sv1.Pod
for i, pod := range podList.Items {
podRevision, podHasRevision := pod.Annotations["revision"]
hasHigherRevision := (i == 0)
if !hasHigherRevision && podHasRevision {
podRevisionInt, _ := strconv.Atoi(podRevision)
if podRevisionInt > highestRevision {
hasHigherRevision = true
}
}
if hasHigherRevision {
selectedPod = pod
highestRevision, _ = strconv.Atoi(podRevision)
}
}
_, hasRevision := selectedPod.Annotations["revision"]
if !hasRevision || highestRevision == releaseRevision {
if !hasRevision {
log.Warn("Found pod without revision. Use annotation 'revision' for your pods to avoid this warning.")
}
cmd.pod = &selectedPod
err = waitForPodReady(cmd.kubectl, cmd.pod, 2*60*time.Second, 5*time.Second)
if err != nil {
log.Fatalf("Error during waiting for pod: %s", err.Error())
}
break
} else {
log.Info("Waiting for release upgrade to complete.")
}
} else {
log.Info("Waiting for release to be deployed.")
}
time.Sleep(2 * time.Second)
}
log.StopWait()
}
func (cmd *UpCmd) startSync() []*synctool.SyncConfig {
config := configutil.GetConfig(false)
syncConfigs := make([]*synctool.SyncConfig, 0, len(*config.DevSpace.Sync))
for _, syncPath := range *config.DevSpace.Sync {
absLocalPath, err := filepath.Abs(cmd.workdir + *syncPath.LocalSubPath)
if err != nil {
log.Panicf("Unable to resolve localSubPath %s: %s", *syncPath.LocalSubPath, err.Error())
} else {
// Retrieve pod from label selector
labels := make([]string, 0, len(*syncPath.LabelSelector))
for key, value := range *syncPath.LabelSelector {
labels = append(labels, key+"="+*value)
}
pod, err := kubectl.GetFirstRunningPod(cmd.kubectl, strings.Join(labels, ", "), *config.DevSpace.Release.Namespace)
if err != nil {
log.Panicf("Unable to list devspace pods: %s", err.Error())
} else if pod != nil {
syncConfig := &synctool.SyncConfig{
Kubectl: cmd.kubectl,
Pod: pod,
Container: &pod.Spec.Containers[0],
WatchPath: absLocalPath,
DestPath: *syncPath.ContainerPath,
}
if syncPath.ExcludePaths != nil {
syncConfig.ExcludePaths = *syncPath.ExcludePaths
}
if syncPath.DownloadExcludePaths != nil {
syncConfig.DownloadExcludePaths = *syncPath.DownloadExcludePaths
}
if syncPath.UploadExcludePaths != nil {
syncConfig.UploadExcludePaths = *syncPath.UploadExcludePaths
}
err = syncConfig.Start()
if err != nil {
log.Fatalf("Sync error: %s", err.Error())
}
log.Donef("Sync started on %s <-> %s", absLocalPath, *syncPath.ContainerPath)
syncConfigs = append(syncConfigs, syncConfig)
}
}
}
return syncConfigs
}
func (cmd *UpCmd) startPortForwarding() {
config := configutil.GetConfig(false)
for _, portForwarding := range *config.DevSpace.PortForwarding {
if *portForwarding.ResourceType == "pod" {
if len(*portForwarding.LabelSelector) > 0 {
labels := make([]string, 0, len(*portForwarding.LabelSelector))
for key, value := range *portForwarding.LabelSelector {
labels = append(labels, key+"="+*value)
}
pod, err := kubectl.GetFirstRunningPod(cmd.kubectl, strings.Join(labels, ", "), *config.DevSpace.Release.Namespace)
if err != nil {
log.Errorf("Unable to list devspace pods: %s", err.Error())
} else if pod != nil {
ports := make([]string, len(*portForwarding.PortMappings))
for index, value := range *portForwarding.PortMappings {
ports[index] = strconv.Itoa(*value.LocalPort) + ":" + strconv.Itoa(*value.RemotePort)
}
readyChan := make(chan struct{})
go kubectl.ForwardPorts(cmd.kubectl, pod, ports, make(chan struct{}), readyChan)
// Wait till forwarding is ready
select {
case <-readyChan:
log.Donef("Port forwarding started on %s", strings.Join(ports, ", "))
case <-time.After(5 * time.Second):
log.Error("Timeout waiting for port forwarding to start")
}
}
}
} else {
log.Warn("Currently only pod resource type is supported for portforwarding")
}
}
}
func (cmd *UpCmd) enterTerminal() {
var shell []string
if len(cmd.flags.shell) == 0 {
shell = []string{
"sh",
"-c",
"command -v bash >/dev/null 2>&1 && exec bash || exec sh",
}
} else {
shell = []string{cmd.flags.shell}
}
_, _, _, terminalErr := kubectl.Exec(cmd.kubectl, cmd.pod, cmd.pod.Spec.Containers[0].Name, shell, true, nil)
if terminalErr != nil {
if _, ok := terminalErr.(exec.CodeExitError); ok == false {
log.Fatalf("Unable to start terminal session: %s", terminalErr.Error())
}
}
}
func waitForPodReady(kubectl *kubernetes.Clientset, pod *k8sv1.Pod, maxWaitTime time.Duration, checkInterval time.Duration) error {
for maxWaitTime > 0 {
pod, err := kubectl.Core().Pods(pod.Namespace).Get(pod.Name, metav1.GetOptions{})
if err != nil {
return err
}
if len(pod.Status.ContainerStatuses) > 0 && pod.Status.ContainerStatuses[0].Ready {
return nil
}
time.Sleep(checkInterval)
maxWaitTime = maxWaitTime - checkInterval
}
return fmt.Errorf("Max wait time expired")
}