-
Notifications
You must be signed in to change notification settings - Fork 371
/
Copy pathup.go
392 lines (329 loc) · 12.2 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
package cmd
import (
"fmt"
"sync"
"time"
"github.com/covexo/devspace/pkg/devspace/watch"
"github.com/covexo/devspace/pkg/devspace/cloud"
"github.com/covexo/devspace/pkg/devspace/config/configutil"
"github.com/covexo/devspace/pkg/devspace/config/generated"
"github.com/covexo/devspace/pkg/devspace/deploy"
"github.com/covexo/devspace/pkg/devspace/docker"
"github.com/covexo/devspace/pkg/devspace/image"
"github.com/covexo/devspace/pkg/devspace/kubectl"
"github.com/covexo/devspace/pkg/devspace/registry"
"github.com/covexo/devspace/pkg/devspace/services"
"github.com/covexo/devspace/pkg/util/log"
"github.com/spf13/cobra"
"k8s.io/client-go/kubernetes"
)
// UpCmd is a struct that defines a command call for "up"
type UpCmd struct {
flags *UpCmdFlags
}
// UpCmdFlags are the flags available for the up-command
type UpCmdFlags struct {
tiller bool
open string
initRegistries bool
build bool
sync bool
terminal bool
deploy bool
exitAfterDeploy bool
skipPipeline bool
allyes bool
switchContext bool
portforwarding bool
verboseSync bool
service string
container string
labelSelector string
namespace string
config string
configOverwrite string
}
//UpFlagsDefault are the default flags for UpCmdFlags
var UpFlagsDefault = &UpCmdFlags{
tiller: true,
open: "cmd",
initRegistries: true,
build: false,
sync: true,
terminal: true,
switchContext: true,
exitAfterDeploy: false,
skipPipeline: false,
allyes: false,
deploy: false,
portforwarding: true,
verboseSync: false,
container: "",
namespace: "",
labelSelector: "",
}
func init() {
cmd := &UpCmd{
flags: UpFlagsDefault,
}
cobraCmd := &cobra.Command{
Use: "up",
Short: "Starts your DevSpace",
Long: `
#######################################################
#################### devspace up ######################
#######################################################
Starts and connects your DevSpace:
1. Builds your Docker images (if any Dockerfile has changed)
2. Deploys your application via helm or kubectl
3. Forwards container ports to the local computer
4. Starts the sync client
5. Enters the container shell
#######################################################`,
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, "Force image build")
cobraCmd.Flags().BoolVarP(&cmd.flags.deploy, "deploy", "d", cmd.flags.deploy, "Force chart deployment")
cobraCmd.Flags().BoolVarP(&cmd.flags.skipPipeline, "skip-pipeline", "x", cmd.flags.skipPipeline, "Skips build & deployment and only starts sync, portforwarding & terminal")
cobraCmd.Flags().BoolVar(&cmd.flags.sync, "sync", cmd.flags.sync, "Enable code synchronization")
cobraCmd.Flags().BoolVar(&cmd.flags.verboseSync, "verbose-sync", cmd.flags.verboseSync, "When enabled the sync will log every file change")
cobraCmd.Flags().BoolVar(&cmd.flags.portforwarding, "portforwarding", cmd.flags.portforwarding, "Enable port forwarding")
cobraCmd.Flags().BoolVar(&cmd.flags.terminal, "terminal", cmd.flags.terminal, "Enable terminal")
cobraCmd.Flags().StringVarP(&cmd.flags.service, "service", "s", "", "Service name (in config) to select pods/container for terminal")
cobraCmd.Flags().StringVarP(&cmd.flags.container, "container", "c", cmd.flags.container, "Container name where to open the shell")
cobraCmd.Flags().StringVarP(&cmd.flags.labelSelector, "label-selector", "l", "", "Comma separated key=value selector list to use for terminal (e.g. release=test)")
cobraCmd.Flags().StringVarP(&cmd.flags.namespace, "namespace", "n", "", "Namespace where to select pods for terminal")
cobraCmd.Flags().BoolVar(&cmd.flags.switchContext, "switch-context", cmd.flags.switchContext, "Switch kubectl context to the devspace context")
cobraCmd.Flags().BoolVar(&cmd.flags.exitAfterDeploy, "exit-after-deploy", cmd.flags.exitAfterDeploy, "Exits the command after building the images and deploying the devspace")
cobraCmd.Flags().BoolVarP(&cmd.flags.allyes, "yes", "y", cmd.flags.allyes, "Answer every questions with the default")
cobraCmd.Flags().StringVar(&cmd.flags.config, "config", configutil.ConfigPath, "The devspace config file to load (default: '.devspace/config.yaml'")
cobraCmd.Flags().StringVar(&cmd.flags.configOverwrite, "config-overwrite", configutil.OverwriteConfigPath, "The devspace config overwrite file to load (default: '.devspace/overwrite.yaml'")
}
// Run executes the command logic
func (cmd *UpCmd) Run(cobraCmd *cobra.Command, args []string) {
if configutil.ConfigPath != cmd.flags.config {
configutil.ConfigPath = cmd.flags.config
// Don't use overwrite config if we use a different config
configutil.OverwriteConfigPath = ""
}
if configutil.OverwriteConfigPath != cmd.flags.configOverwrite {
configutil.OverwriteConfigPath = cmd.flags.configOverwrite
}
log.StartFileLogging()
log.Infof("Loading config %s with overwrite config %s", configutil.ConfigPath, configutil.OverwriteConfigPath)
configExists, _ := configutil.ConfigExists()
if !configExists {
log.Write([]byte("\n"))
initFlags := &InitCmdFlags{
reconfigure: false,
overwrite: false,
skipQuestions: cmd.flags.allyes,
templateRepoURL: "https://github.com/covexo/devspace-templates.git",
templateRepoPath: "",
language: "",
}
initCmd := &InitCmd{
flags: initFlags,
}
initCmd.Run(nil, []string{})
// Ensure that config is initialized correctly
configutil.SetDefaultsOnce()
}
// Create kubectl client and switch context if specified
client, err := kubectl.NewClientWithContextSwitch(cmd.flags.switchContext)
if err != nil {
log.Fatalf("Unable to create new kubectl client: %v", err)
}
// Create namespace if necessary
err = kubectl.EnsureDefaultNamespace(client, log.GetInstance())
if err != nil {
log.Fatalf("Unable to create namespace: %v", err)
}
// Create cluster role binding if necessary
err = kubectl.EnsureGoogleCloudClusterRoleBinding(client, log.GetInstance())
if err != nil {
log.Fatalf("Unable to create ClusterRoleBinding: %v", err)
}
// Init image registries
if cmd.flags.initRegistries {
dockerClient, err := docker.NewClient(false)
if err != nil {
dockerClient = nil
}
err = registry.InitRegistries(dockerClient, client, log.GetInstance())
if err != nil {
log.Fatal(err)
}
}
// Build and deploy images
err = buildAndDeploy(client, cmd.flags, args)
if err != nil {
log.Fatal(err)
}
}
func buildAndDeploy(client *kubernetes.Clientset, flags *UpCmdFlags, args []string) error {
config := configutil.GetConfig()
if flags.skipPipeline == false {
// Load config
generatedConfig, err := generated.LoadConfig()
if err != nil {
return fmt.Errorf("Error loading generated.yaml: %v", err)
}
// Build image if necessary
mustRedeploy, err := image.BuildAll(client, generatedConfig, flags.build, log.GetInstance())
if err != nil {
return fmt.Errorf("Error building image: %v", err)
}
// Save config if an image was built
if mustRedeploy == true {
err := generated.SaveConfig(generatedConfig)
if err != nil {
return fmt.Errorf("Error saving generated config: %v", err)
}
}
// Deploy all defined deployments
if config.DevSpace.Deployments != nil {
// Deploy all
err = deploy.All(client, generatedConfig, mustRedeploy || flags.deploy, true, log.GetInstance())
if err != nil {
return fmt.Errorf("Error deploying devspace: %v", err)
}
// Save Config
err = generated.SaveConfig(generatedConfig)
if err != nil {
return fmt.Errorf("Error saving generated config: %v", err)
}
}
}
// Start services
if flags.exitAfterDeploy == false {
// Start services
err := startServices(client, flags, args, log.GetInstance())
if err != nil {
// Check if we should reload
if _, ok := err.(*reloadError); ok {
// Trigger rebuild & redeploy
return buildAndDeploy(client, flags, args)
}
return err
}
}
return nil
}
func startServices(client *kubernetes.Clientset, flags *UpCmdFlags, args []string, log log.Logger) error {
if flags.portforwarding {
portForwarder, err := services.StartPortForwarding(client, log)
if err != nil {
return fmt.Errorf("Unable to start portforwarding: %v", err)
}
defer func() {
for _, v := range portForwarder {
v.Close()
}
}()
}
if flags.sync {
syncConfigs, err := services.StartSync(client, flags.verboseSync, log)
if err != nil {
return fmt.Errorf("Unable to start sync: %v", err)
}
defer func() {
for _, v := range syncConfigs {
v.Stop(nil)
}
}()
}
// Print domain name if we use a cloud provider
// TODO: Change this
if cloud.DevSpaceURL != "" {
log.Infof("Your DevSpace is now reachable via ingress on this URL: http://%s", cloud.DevSpaceURL)
log.Info("See https://devspace-cloud.com/domain-guide for more information")
}
config := configutil.GetConfig()
exitChan := make(chan error)
autoReloadPaths := GetPaths()
// Start watcher if we have at least one auto reload path and if we should not skip the pipeline
if flags.skipPipeline == false && len(autoReloadPaths) > 0 {
var once sync.Once
watcher, err := watch.New(autoReloadPaths, func(changed []string, deleted []string) error {
once.Do(func() {
log.Info("Change detected, will reload in 2 seconds")
time.Sleep(time.Second * 2)
exitChan <- &reloadError{}
})
return nil
}, log)
if err != nil {
return err
}
watcher.Start()
defer watcher.Stop()
}
if flags.terminal && (config.DevSpace == nil || config.DevSpace.Terminal == nil || config.DevSpace.Terminal.Disabled == nil || *config.DevSpace.Terminal.Disabled == false) {
return services.StartTerminal(client, flags.service, flags.container, flags.labelSelector, flags.namespace, args, exitChan, log)
}
log.Info("Will now try to print the logs of a running devspace pod...")
// Start attaching to a running devspace pod
err := services.StartAttach(client, flags.service, flags.container, flags.labelSelector, flags.namespace, exitChan, log)
if err != nil {
// If it's a reload error we return that so we can rebuild & redeploy
if _, ok := err.(*reloadError); ok {
return err
}
log.Infof("Couldn't print logs of running devspace pod: %v", err)
}
log.Done("Services started (Press Ctrl+C to abort port-forwarding and sync)")
return <-exitChan
}
// GetPaths retrieves the watch paths from the config object
func GetPaths() []string {
paths := make([]string, 0, 1)
config := configutil.GetConfig()
// Add the deploy manifest paths
if config.DevSpace != nil && config.DevSpace.Deployments != nil {
for _, deployConf := range *config.DevSpace.Deployments {
if deployConf.AutoReload != nil && deployConf.AutoReload.Disabled != nil && *deployConf.AutoReload.Disabled == true {
continue
}
if deployConf.Helm != nil && deployConf.Helm.ChartPath != nil {
chartPath := *deployConf.Helm.ChartPath
if chartPath[len(chartPath)-1] != '/' {
chartPath += "/"
}
paths = append(paths, chartPath+"**")
} else if deployConf.Kubectl != nil && deployConf.Kubectl.Manifests != nil {
for _, manifestPath := range *deployConf.Kubectl.Manifests {
paths = append(paths, *manifestPath)
}
}
}
}
// Add the dockerfile paths
if config.Images != nil {
for _, imageConf := range *config.Images {
if imageConf.AutoReload != nil && imageConf.AutoReload.Disabled != nil && *imageConf.AutoReload.Disabled == true {
continue
}
dockerfilePath := "./Dockerfile"
if imageConf.Build != nil && imageConf.Build.DockerfilePath != nil {
dockerfilePath = *imageConf.Build.DockerfilePath
}
paths = append(paths, dockerfilePath)
}
}
// Add the additional paths
if config.DevSpace != nil && config.DevSpace.AutoReload != nil && config.DevSpace.AutoReload.Paths != nil {
for _, path := range *config.DevSpace.AutoReload.Paths {
paths = append(paths, *path)
}
}
return paths
}
type reloadError struct {
}
func (r *reloadError) Error() string {
return ""
}