-
Notifications
You must be signed in to change notification settings - Fork 361
/
init.go
476 lines (409 loc) · 13.6 KB
/
init.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
package cmd
import (
"context"
"io/ioutil"
"os"
"strings"
"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/config/v1"
"github.com/covexo/devspace/pkg/devspace/configure"
"github.com/covexo/devspace/pkg/devspace/docker"
"github.com/covexo/devspace/pkg/devspace/generator"
"github.com/covexo/devspace/pkg/devspace/kubectl"
"github.com/covexo/devspace/pkg/util/dockerfile"
"github.com/covexo/devspace/pkg/util/kubeconfig"
"github.com/covexo/devspace/pkg/util/log"
"github.com/covexo/devspace/pkg/util/stdinutil"
"github.com/spf13/cobra"
)
// InitCmd is a struct that defines a command call for "init"
type InitCmd struct {
flags *InitCmdFlags
chartGenerator *generator.ChartGenerator
defaultImage *v1.ImageConfig
}
// InitCmdFlags are the flags available for the init-command
type InitCmdFlags struct {
reconfigure bool
overwrite bool
skipQuestions bool
templateRepoURL string
templateRepoPath string
language string
cloudProvider string
useDevSpaceCloud bool
addDevSpaceCloudToLocalKubernetes bool
namespace string
createInternalRegistry bool
registryURL string
defaultImageName string
createPullSecret bool
}
// InitCmdFlagsDefault are the default flags for InitCmdFlags
var InitCmdFlagsDefault = &InitCmdFlags{
reconfigure: false,
overwrite: false,
skipQuestions: false,
templateRepoURL: "https://github.com/covexo/devspace-templates.git",
templateRepoPath: "",
language: "",
cloudProvider: "",
useDevSpaceCloud: false,
addDevSpaceCloudToLocalKubernetes: false,
namespace: "",
createInternalRegistry: false,
}
func init() {
cmd := &InitCmd{
flags: InitCmdFlagsDefault,
}
cobraCmd := &cobra.Command{
Use: "init",
Short: "Initializes your DevSpace",
Long: `
#######################################################
#################### devspace init ####################
#######################################################
Gets your project ready to start a DevSpaces.
Creates the following files and directories:
YOUR_PROJECT_PATH/
|
|-- Dockerfile
|
|-- chart/
| |-- Chart.yaml
| |-- values.yaml
| |-- templates/
| |-- deployment.yaml
| |-- service.yaml
| |-- ingress.yaml
|
|-- .devspace/
| |-- .gitignore
| |-- cluster.yaml
| |-- config.yaml
#######################################################
`,
Args: cobra.NoArgs,
Run: cmd.Run,
}
rootCmd.AddCommand(cobraCmd)
cobraCmd.Flags().BoolVarP(&cmd.flags.reconfigure, "reconfigure", "r", cmd.flags.reconfigure, "Change existing configuration")
cobraCmd.Flags().BoolVarP(&cmd.flags.overwrite, "overwrite", "o", cmd.flags.overwrite, "Overwrite existing chart files and Dockerfile")
cobraCmd.Flags().BoolVarP(&cmd.flags.skipQuestions, "yes", "y", cmd.flags.skipQuestions, "Answer all questions with their default value")
cobraCmd.Flags().StringVar(&cmd.flags.templateRepoURL, "templateRepoUrl", cmd.flags.templateRepoURL, "Git repository for chart templates")
cobraCmd.Flags().StringVar(&cmd.flags.templateRepoPath, "templateRepoPath", cmd.flags.templateRepoPath, "Local path for cloning chart template repository (uses temp folder if not specified)")
cobraCmd.Flags().StringVarP(&cmd.flags.language, "language", "l", cmd.flags.language, "Programming language of your project")
}
// Run executes the command logic
func (cmd *InitCmd) Run(cobraCmd *cobra.Command, args []string) {
log.StartFileLogging()
var config *v1.Config
configExists, _ := configutil.ConfigExists()
if configExists && cmd.flags.reconfigure == false {
config = configutil.GetConfig()
} else {
// Delete config & overwrite config
os.Remove(configutil.ConfigPath)
os.Remove(configutil.OverwriteConfigPath)
os.Remove(generated.ConfigPath)
// Create config
config = configutil.InitConfig()
// Set intial deployments
config.DevSpace.Deployments = &[]*v1.DeploymentConfig{
{
Name: configutil.String(configutil.DefaultDevspaceDeploymentName),
Namespace: configutil.String(""),
Helm: &v1.HelmConfig{
ChartPath: configutil.String("./chart"),
DevOverwrite: configutil.String("./chart/dev-overwrite.yaml"),
},
},
}
}
configutil.Merge(&config, &v1.Config{
Version: configutil.String(configutil.CurrentConfigVersion),
Images: &map[string]*v1.ImageConfig{
"default": &v1.ImageConfig{
Name: configutil.String("devspace"),
},
},
Registries: &map[string]*v1.RegistryConfig{
"default": &v1.RegistryConfig{
Auth: &v1.RegistryAuth{},
},
"internal": &v1.RegistryConfig{
Auth: &v1.RegistryAuth{},
},
},
}, true)
imageMap := *config.Images
cmd.defaultImage = imageMap["default"]
cmd.initChartGenerator()
createChart := cmd.flags.overwrite
if !cmd.flags.overwrite {
_, chartDirNotFound := os.Stat("chart")
if chartDirNotFound == nil {
if !cmd.flags.skipQuestions {
createChart = *stdinutil.GetFromStdin(&stdinutil.GetFromStdinParams{
Question: "Do you want to overwrite the existing files in /chart? (yes | no)",
DefaultValue: "no",
ValidationRegexPattern: "^(yes)|(no)$",
}) == "yes"
}
} else {
createChart = true
}
}
if createChart {
cmd.initChartGenerator()
cmd.determineLanguage()
cmd.createChart()
}
if cmd.flags.reconfigure || !configExists {
// Check if devspace cloud should be used
if cmd.useCloudProvider() == false {
cmd.configureDevSpace()
}
cmd.addDefaultService()
cmd.addDefaultPorts()
cmd.addDefaultSyncConfig()
cmd.configureRegistry()
err := configutil.SaveConfig()
if err != nil {
log.With(err).Fatalf("Config error: %s", err.Error())
}
}
}
func (cmd *InitCmd) initChartGenerator() {
workdir, _ := os.Getwd()
templateRepoPath := cmd.flags.templateRepoPath
if len(templateRepoPath) == 0 {
templateRepoPath, _ = ioutil.TempDir("", "")
defer os.RemoveAll(templateRepoPath)
}
templateRepo := &generator.TemplateRepository{
URL: cmd.flags.templateRepoURL,
LocalPath: templateRepoPath,
}
cmd.chartGenerator = &generator.ChartGenerator{
TemplateRepo: templateRepo,
Path: workdir,
}
}
func (cmd *InitCmd) useCloudProvider() bool {
providerConfig, err := cloud.ParseCloudConfig()
if err != nil {
log.Fatalf("Error loading cloud config: %v", err)
}
if len(providerConfig) > 1 {
cloudProviderOptions := "("
for name := range providerConfig {
if len(cloudProviderOptions) > 1 {
cloudProviderOptions += ", "
}
cloudProviderOptions += name
}
cloudProviderOptions += ")"
cloudProviderSelected := cmd.flags.cloudProvider
for _, ok := providerConfig[cloudProviderSelected]; ok == false && cloudProviderSelected != "no"; {
cloudProviderSelected = strings.TrimSpace(*stdinutil.GetFromStdin(&stdinutil.GetFromStdinParams{
Question: "Do you want to use a cloud provider? (no to skip) " + cloudProviderOptions,
DefaultValue: cloud.DevSpaceCloudProviderName,
}))
_, ok = providerConfig[cloudProviderSelected]
}
if cloudProviderSelected != "no" {
cmd.loginToCloudProvider(providerConfig, cloudProviderSelected)
return true
}
} else {
useDevSpaceCloud := cmd.flags.useDevSpaceCloud || cmd.flags.skipQuestions
if !useDevSpaceCloud {
useDevSpaceCloud = *stdinutil.GetFromStdin(&stdinutil.GetFromStdinParams{
Question: "Do you want to use the DevSpace Cloud? (free ready-to-use Kubernetes) (yes | no)",
DefaultValue: "yes",
ValidationRegexPattern: "^(yes)|(no)$",
}) == "yes"
}
if useDevSpaceCloud {
cmd.loginToCloudProvider(providerConfig, cloud.DevSpaceCloudProviderName)
return true
}
}
return false
}
func (cmd *InitCmd) loginToCloudProvider(providerConfig cloud.ProviderConfig, cloudProviderSelected string) {
config := configutil.GetConfig()
addToContext := cmd.flags.skipQuestions || cmd.flags.addDevSpaceCloudToLocalKubernetes
if !addToContext {
addToContext = *stdinutil.GetFromStdin(&stdinutil.GetFromStdinParams{
Question: "Do you want to add the DevSpace Cloud to the $HOME/.kube/config file? (yes | no)",
DefaultValue: "yes",
ValidationRegexPattern: "^(yes)|(no)$",
}) == "yes"
}
config.Cluster.CloudProvider = &cloudProviderSelected
config.Cluster.CloudProviderDeployTarget = configutil.String(cloud.DefaultDeployTarget)
err := cloud.Update(providerConfig, &cloud.UpdateOptions{
UseKubeContext: addToContext,
SwitchKubeContext: true,
SkipSaveConfig: true,
}, log.GetInstance())
if err != nil {
log.Fatalf("Couldn't authenticate to %s: %v", cloudProviderSelected, err)
}
}
func (cmd *InitCmd) configureDevSpace() {
currentContext, err := kubeconfig.GetCurrentContext()
if err != nil {
log.Fatalf("Couldn't determine current kubernetes context: %v", err)
}
namespace := &cmd.flags.namespace
if *namespace == "" {
namespace = stdinutil.GetFromStdin(&stdinutil.GetFromStdinParams{
Question: "Which Kubernetes namespace should your application run in?",
DefaultValue: "default",
ValidationRegexPattern: v1.Kubernetes.RegexPatterns.Name,
})
}
config := configutil.GetConfig()
config.Cluster.KubeContext = ¤tContext
config.Cluster.Namespace = namespace
}
func (cmd *InitCmd) addDefaultService() {
config := configutil.GetConfig()
config.DevSpace.Services = &[]*v1.ServiceConfig{
{
Name: configutil.String(configutil.DefaultDevspaceServiceName),
LabelSelector: &map[string]*string{
"devspace": configutil.String("default"),
},
},
}
}
func (cmd *InitCmd) addDefaultPorts() {
ports, err := dockerfile.GetPorts("Dockerfile")
if err != nil {
log.Warnf("Error parsing dockerfile: %v", err)
return
}
if len(ports) == 0 {
return
}
portMappings := []*v1.PortMapping{}
for _, port := range ports {
portMappings = append(portMappings, &v1.PortMapping{
LocalPort: &port,
RemotePort: &port,
})
}
config := configutil.GetConfig()
config.DevSpace.Ports = &[]*v1.PortForwardingConfig{
{
Service: configutil.String(configutil.DefaultDevspaceServiceName),
PortMappings: &portMappings,
},
}
}
func (cmd *InitCmd) addDefaultSyncConfig() {
config := configutil.GetConfig()
if config.DevSpace.Sync == nil {
config.DevSpace.Sync = &[]*v1.SyncConfig{}
}
for _, syncPath := range *config.DevSpace.Sync {
if *syncPath.LocalSubPath == "./" || *syncPath.ContainerPath == "/app" {
return
}
}
dockerignore, err := ioutil.ReadFile(".dockerignore")
uploadExcludePaths := []string{}
if err == nil {
dockerignoreRules := strings.Split(string(dockerignore), "\n")
for _, ignoreRule := range dockerignoreRules {
if len(ignoreRule) > 0 {
uploadExcludePaths = append(uploadExcludePaths, ignoreRule)
}
}
}
syncConfig := append(*config.DevSpace.Sync, &v1.SyncConfig{
Service: configutil.String(configutil.DefaultDevspaceServiceName),
ContainerPath: configutil.String("/app"),
LocalSubPath: configutil.String("./"),
UploadExcludePaths: &uploadExcludePaths,
})
config.DevSpace.Sync = &syncConfig
}
func (cmd *InitCmd) configureRegistry() {
dockerUsername := ""
client, err := docker.NewClient(true)
if err != nil {
log.Fatalf("Cannot create docker client: %v", err)
}
// Check if docker is installed
_, err = client.Ping(context.Background())
if err != nil {
// Set default build engine to kaniko, if no docker is installed
cmd.defaultImage.Build = &v1.BuildConfig{
Kaniko: &v1.KanikoConfig{
Cache: configutil.Bool(true),
Namespace: configutil.String(""),
},
}
} else {
log.StartWait("Checking Docker credentials")
dockerAuthConfig, err := docker.GetAuthConfig(client, "", true)
log.StopWait()
if err == nil {
dockerUsername = dockerAuthConfig.Username
}
// Don't push image in minikube
if kubectl.IsMinikube() {
cmd.defaultImage.SkipPush = configutil.Bool(true)
return
}
}
err = configure.Image(dockerUsername, cmd.flags.skipQuestions, cmd.flags.registryURL, cmd.flags.defaultImageName, cmd.flags.createPullSecret)
if err != nil {
log.Fatal(err)
}
}
func (cmd *InitCmd) determineLanguage() {
if len(cmd.flags.language) != 0 {
if cmd.chartGenerator.IsSupportedLanguage(cmd.flags.language) {
cmd.chartGenerator.Language = cmd.flags.language
} else {
log.Info("Language '" + cmd.flags.language + "' not supported yet. Please open an issue here: https://github.com/covexo/devspace/issues/new?title=Feature%20Request:%20Language%20%22" + cmd.flags.language + "%22")
}
}
if len(cmd.chartGenerator.Language) == 0 {
log.StartWait("Detecting programming language")
detectedLang := ""
supportedLanguages, err := cmd.chartGenerator.GetSupportedLanguages()
if err == nil {
detectedLang, _ = cmd.chartGenerator.GetLanguage()
}
if detectedLang == "" {
detectedLang = "none"
}
if len(supportedLanguages) == 0 {
supportedLanguages = []string{"none"}
}
log.StopWait()
if !cmd.flags.skipQuestions {
cmd.chartGenerator.Language = *stdinutil.GetFromStdin(&stdinutil.GetFromStdinParams{
Question: "What is the major programming language of your project?\nSupported languages: " + strings.Join(supportedLanguages, ", "),
DefaultValue: detectedLang,
ValidationRegexPattern: "^(" + strings.Join(supportedLanguages, ")|(") + ")$",
})
}
}
}
func (cmd *InitCmd) createChart() {
err := cmd.chartGenerator.CreateChart()
if err != nil {
log.Fatalf("Error while creating Helm chart and Dockerfile: %s", err.Error())
}
}