/
root.go
463 lines (419 loc) · 14.6 KB
/
root.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
package cmd
import (
"bufio"
"context"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"time"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
lagooncli "github.com/uselagoon/lagoon-cli/internal/lagoon"
"github.com/uselagoon/lagoon-cli/internal/lagoon/client"
"github.com/uselagoon/lagoon-cli/pkg/app"
"github.com/uselagoon/lagoon-cli/pkg/graphql"
"github.com/uselagoon/lagoon-cli/pkg/lagoon/environments"
"github.com/uselagoon/lagoon-cli/pkg/lagoon/projects"
"github.com/uselagoon/lagoon-cli/pkg/lagoon/users"
"github.com/uselagoon/lagoon-cli/pkg/output"
"github.com/uselagoon/lagoon-cli/pkg/updatecheck"
)
var cmdProject app.LagoonProject
var cmdLagoon = ""
var forceAction bool
var cmdSSHKey = ""
var inputScanner = bufio.NewScanner(os.Stdin)
var versionFlag bool
var docsFlag bool
var updateInterval = time.Hour * 24 * 7 // One week interval between updates
var configName = ".lagoon"
var configExtension = ".yml"
var createConfig bool
var userPath string
var configFilePath string
var updateDocURL = "https://uselagoon.github.io/lagoon-cli"
var skipUpdateCheck bool
// global for the lagoon config that the cli uses
// @TODO: when lagoon-cli rewrite happens, do this a bit better
var lagoonCLIConfig lagooncli.Config
// version/build information (populated at build time by make file)
var (
lagoonCLIVersion = "0.x.x"
lagoonCLIBuild = ""
lagoonCLIBuildGoVersion = ""
)
var rootCmd = &cobra.Command{
Use: "lagoon",
Short: "Command line integration for Lagoon",
Long: `Lagoon CLI. Manage your Lagoon hosted projects.`,
DisableAutoGenTag: true,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
if lagoonCLIConfig.UpdateCheckDisable {
skipUpdateCheck = true
}
if !skipUpdateCheck {
// Using code from https://github.com/drud/ddev/
updateFile := filepath.Join(userPath, ".lagoon.update")
// Do periodic detection of whether an update is available for lagoon-cli users.
timeToCheckForUpdates, err := updatecheck.IsUpdateNeeded(updateFile, updateInterval)
if err != nil {
output.RenderInfo(fmt.Sprintf("Could not perform update check %v", err), outputOptions)
}
if timeToCheckForUpdates && isInternetActive() {
// Recreate the updatefile with current time so we won't do this again soon.
err = updatecheck.ResetUpdateTime(updateFile)
if err != nil {
output.RenderInfo(fmt.Sprintf("Failed to update updatecheck file %s", updateFile), outputOptions)
}
updateNeeded, updateURL, err := updatecheck.AvailableUpdates("uselagoon", "lagoon-cli", lagoonCLIVersion)
if err != nil {
output.RenderInfo("Could not check for updates. This is most often caused by a networking issue.", outputOptions)
output.RenderError(err.Error(), outputOptions)
return
}
if updateNeeded {
output.RenderInfo(fmt.Sprintf("A new update is available! please visit %s to download the update.\nFor upgrade help see %s\n\nIf installed using brew, upgrade using `brew upgrade lagoon`\n", updateURL, updateDocURL), outputOptions)
}
}
}
},
Run: func(cmd *cobra.Command, args []string) {
if docsFlag {
err := doc.GenMarkdownTree(cmd, "docs/commands")
if err != nil {
output.RenderError(err.Error(), outputOptions)
os.Exit(1)
}
fmt.Println("Documentation updated")
return
}
if versionFlag {
displayVersionInfo()
return
}
cmd.Help()
os.Exit(1)
},
}
// Execute the root command.
func Execute() {
if err := rootCmd.Execute(); err != nil {
output.RenderError(err.Error(), outputOptions)
os.Exit(1)
}
}
// IsInternetActive() checks to see if we have a viable
// internet connection. It just tries a quick DNS query.
// This requires that the named record be query-able.
func isInternetActive() bool {
_, err := net.LookupHost("amazee.io")
return err == nil
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVarP(&cmdProjectName, "project", "p", "", "Specify a project to use")
rootCmd.PersistentFlags().StringVarP(&cmdProjectEnvironment, "environment", "e", "", "Specify an environment to use")
rootCmd.PersistentFlags().StringVarP(&cmdLagoon, "lagoon", "l", "", "The Lagoon instance to interact with")
rootCmd.PersistentFlags().BoolVarP(&forceAction, "force", "", false, "Force yes on prompts (if supported)")
rootCmd.PersistentFlags().StringVarP(&cmdSSHKey, "ssh-key", "i", "", "Specify path to a specific SSH key to use for lagoon authentication")
// rootCmd.PersistentFlags().BoolVarP(&listAllProjects, "all-projects", "", false, "All projects (if supported)")
rootCmd.PersistentFlags().BoolVarP(&outputOptions.Header, "no-header", "", false, "No header on table (if supported)")
rootCmd.PersistentFlags().BoolVarP(&outputOptions.CSV, "output-csv", "", false, "Output as CSV (if supported)")
rootCmd.PersistentFlags().BoolVarP(&outputOptions.JSON, "output-json", "", false, "Output as JSON (if supported)")
rootCmd.PersistentFlags().BoolVarP(&outputOptions.Pretty, "pretty", "", false, "Make JSON pretty (if supported)")
rootCmd.PersistentFlags().BoolVarP(&debugEnable, "debug", "", false, "Enable debugging output (if supported)")
rootCmd.PersistentFlags().BoolVarP(&skipUpdateCheck, "skip-update-check", "", false, "Skip checking for updates")
// get config-file from flag
rootCmd.PersistentFlags().StringP("config-file", "", "", "Path to the config file to use (must be *.yml or *.yaml)")
rootCmd.Flags().BoolVarP(&versionFlag, "version", "", false, "Version information")
rootCmd.Flags().BoolVarP(&docsFlag, "docs", "", false, "Generate docs")
rootCmd.Flags().MarkHidden("docs")
rootCmd.SetUsageTemplate(`Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
Aliases:
{{.NameAndAliases}}{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}
{{- if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{- $current_command:= . }}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}
{{if .HasAvailableLocalFlags -}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`)
rootCmd.AddCommand(addCmd)
rootCmd.AddCommand(configCmd)
rootCmd.AddCommand(deleteCmd)
rootCmd.AddCommand(deployCmd)
rootCmd.AddCommand(getCmd)
rootCmd.AddCommand(kibanaCmd)
rootCmd.AddCommand(listCmd)
rootCmd.AddCommand(loginCmd)
rootCmd.AddCommand(runCmd)
rootCmd.AddCommand(sshEnvCmd)
rootCmd.AddCommand(updateCmd)
rootCmd.AddCommand(retrieveCmd)
rootCmd.AddCommand(versionCmd)
rootCmd.AddCommand(webCmd)
rootCmd.AddCommand(importCmd)
rootCmd.AddCommand(exportCmd)
rootCmd.AddCommand(whoamiCmd)
rootCmd.AddCommand(uploadCmd)
rootCmd.AddCommand(rawCmd)
}
// version/build information command
var versionCmd = &cobra.Command{
Use: "version",
Short: "Version information",
Run: func(cmd *cobra.Command, args []string) {
displayVersionInfo()
},
}
func displayVersionInfo() {
fmt.Printf("lagoon %s (%s)\n", lagoonCLIVersion, lagoonCLIBuildGoVersion)
fmt.Printf("built %s\n", lagoonCLIBuild)
}
func initConfig() {
var err error
// Find home directory.
userPath, err = os.UserHomeDir()
if err != nil {
output.RenderError(fmt.Errorf("couldn't get $HOME: %v", err).Error(), outputOptions)
os.Exit(1)
}
configFilePath = userPath
// check if we are being given a path to a different config file
err = getLagoonConfigFile(&configFilePath, &configName, &configExtension, createConfig, rootCmd)
if err != nil {
output.RenderError(err.Error(), outputOptions)
os.Exit(1)
}
err = readLagoonConfig(&lagoonCLIConfig, filepath.Join(configFilePath, configName+configExtension))
if err != nil {
output.RenderError(err.Error(), outputOptions)
os.Exit(1)
}
err = getLagoonContext(&lagoonCLIConfig, &cmdLagoon, rootCmd)
if err != nil {
output.RenderError(err.Error(), outputOptions)
os.Exit(1)
}
// if the directory or repository you're in has a valid .lagoon.yml and docker-compose.yml with x-lagoon-project in it
// we can use that inplaces where projects already exist so you don't have to type it out
// and environments too
// this option is opt-in now, so to use it you will need to `lagoon config feature --enable-local-dir-check=true`
if lagoonCLIConfig.EnvironmentFromDirectory {
cmdProject, _ = app.GetLocalProject()
}
if cmdProject.Name != "" && cmdProjectName == "" {
cmdProjectName = cmdProject.Name
}
if cmdProject.Environment != "" && cmdProjectEnvironment == "" {
cmdProjectEnvironment = cmdProject.Environment
}
}
func yesNo(message string) bool {
if !forceAction {
prompt := promptui.Select{
Label: message + "; Select[Yes/No]",
Items: []string{"No", "Yes"},
}
_, result, err := prompt.Run()
if err != nil {
output.RenderError(err.Error(), outputOptions)
os.Exit(1)
}
return result == "Yes"
}
return true
}
// GetInput reads input from an input buffer and returns the result as a string.
func GetInput() string {
inputScanner.Scan()
return strings.TrimSpace(inputScanner.Text())
}
// Prompt gets input with a prompt and returns the input
func Prompt(prompt string) string {
fullPrompt := prompt
fmt.Print(fullPrompt + ": ")
return GetInput()
}
// global the clients
var eClient environments.Client
var uClient users.Client
var pClient projects.Client
// FormatType .
type FormatType string
// . .
const (
JSON FormatType = "JSON"
YAML FormatType = "YAML"
STDOUT FormatType = "STDOUT"
)
func validateToken(lagoon string) {
var err error
if err = checkContextExists(&lagoonCLIConfig); err != nil {
fmt.Println(err)
os.Exit(1)
}
valid := graphql.VerifyTokenExpiry(&lagoonCLIConfig, lagoon)
if !valid {
loginErr := loginToken()
if loginErr != nil {
fmt.Println("couldn't refresh token:", loginErr.Error())
os.Exit(1)
}
}
// set up the clients
eClient, err = environments.New(&lagoonCLIConfig, debugEnable)
if err != nil {
output.RenderError(err.Error(), outputOptions)
os.Exit(1)
}
uClient, err = users.New(&lagoonCLIConfig, debugEnable)
if err != nil {
output.RenderError(err.Error(), outputOptions)
os.Exit(1)
}
pClient, err = projects.New(&lagoonCLIConfig, debugEnable)
if err != nil {
output.RenderError(err.Error(), outputOptions)
os.Exit(1)
}
outputOptions.Debug = debugEnable
}
// validateTokenE does the same thing as validateToken, it just returns an
// error instead of exiting on error.
func validateTokenE(lagoon string) error {
var err error
if err = checkContextExists(&lagoonCLIConfig); err != nil {
return err
}
if graphql.VerifyTokenExpiry(&lagoonCLIConfig, lagoon) {
// check the API for the version of lagoon if we haven't got one set
// otherwise return nil, nothing to do
return nil
}
if err = loginToken(); err != nil {
return fmt.Errorf("couldn't refresh token: %w", err)
}
// set up the clients
eClient, err = environments.New(&lagoonCLIConfig, debugEnable)
if err != nil {
output.RenderError(err.Error(), outputOptions)
return err
}
uClient, err = users.New(&lagoonCLIConfig, debugEnable)
if err != nil {
output.RenderError(err.Error(), outputOptions)
return err
}
pClient, err = projects.New(&lagoonCLIConfig, debugEnable)
if err != nil {
output.RenderError(err.Error(), outputOptions)
return err
}
outputOptions.Debug = debugEnable
// fallback if token is expired or there was no token to begin with
return nil
}
// check if we have a version set in config, if not get the version.
// this checks whenever a token is refreshed
func versionCheck(lagoon string) error {
lc := client.New(
lagoonCLIConfig.Lagoons[lagoon].GraphQL,
lagoonCLIConfig.Lagoons[lagoon].Token,
lagoonCLIConfig.Lagoons[lagoon].Version,
lagoonCLIVersion,
debugEnable)
lagoonVersion, err := lagooncli.GetLagoonAPIVersion(context.TODO(), lc)
if err != nil {
return err
}
l := lagoonCLIConfig.Lagoons[lagoon]
l.Version = lagoonVersion.LagoonVersion
lagoonCLIConfig.Lagoons[lagoon] = l
if err = writeLagoonConfig(&lagoonCLIConfig, filepath.Join(configFilePath, configName+configExtension)); err != nil {
return fmt.Errorf("couldn't write config: %v", err)
}
return nil
}
func getLagoonConfigFile(configPath *string, configName *string, configExtension *string, createConfig bool, cmd *cobra.Command) error {
// check if we have an envvar or flag to define our confg file
var configFilePath string
configFilePath, err := cmd.Flags().GetString("config-file")
if err != nil {
return fmt.Errorf("error reading flag `config-file`: %v", err)
}
if configFilePath == "" {
if lagoonConfigEnvar, ok := os.LookupEnv("LAGOONCONFIG"); ok {
configFilePath = lagoonConfigEnvar
}
// prefer LAGOON_CONFIG_FILE
if lagoonConfigEnvar, ok := os.LookupEnv("LAGOON_CONFIG_FILE"); ok {
configFilePath = lagoonConfigEnvar
}
}
if configFilePath != "" {
if fileExists(configFilePath) || createConfig {
*configPath = filepath.Dir(configFilePath)
*configExtension = filepath.Ext(configFilePath)
*configName = strings.TrimSuffix(filepath.Base(configFilePath), *configExtension)
return nil
}
return fmt.Errorf("%s/%s File doesn't exist", *configPath, configFilePath)
}
// no config file found
return nil
}
func getLagoonContext(lagoonCLIConfig *lagooncli.Config, lagoon *string, cmd *cobra.Command) error {
// check if we have an envvar or flag to define our lagoon context
var lagoonContext string
lagoonContext, err := cmd.Flags().GetString("lagoon")
if err != nil {
return fmt.Errorf("error reading flag `lagoon`: %v", err)
}
if lagoonContext == "" {
if lagoonContextEnvar, ok := os.LookupEnv("LAGOONCONTEXT"); ok {
lagoonContext = lagoonContextEnvar
}
// prefer LAGOON_CONTEXT
if lagoonContextEnvar, ok := os.LookupEnv("LAGOON_CONTEXT"); ok {
configFilePath = lagoonContextEnvar
}
}
if lagoonContext != "" {
*lagoon = lagoonContext
} else {
if lagoonCLIConfig.Default == "" {
*lagoon = "amazeeio"
} else {
*lagoon = lagoonCLIConfig.Default
}
}
// set the Current lagoon to the one we've determined it needs to be
lagoonCLIConfig.Current = strings.TrimSpace(*lagoon)
return nil
}
func checkContextExists(lagoonCLIConfig *lagooncli.Config) error {
contextExists := false
for l := range lagoonCLIConfig.Lagoons {
if l == lagoonCLIConfig.Current {
contextExists = true
}
}
if !contextExists {
return fmt.Errorf("chosen context '%s' doesn't exist in config file", lagoonCLIConfig.Current)
}
return nil
}