aboutsummaryrefslogtreecommitdiffstats
path: root/client/go/cmd/root.go
blob: 0557248cedfe857e632ce2ed4e342b53fd2b0407 (plain) (blame)
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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package cmd

import (
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"

	"github.com/fatih/color"
	"github.com/mattn/go-colorable"
	"github.com/mattn/go-isatty"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"github.com/vespa-engine/vespa/client/go/build"
	"github.com/vespa-engine/vespa/client/go/util"
	"github.com/vespa-engine/vespa/client/go/version"
	"github.com/vespa-engine/vespa/client/go/vespa"
)

const (
	applicationFlag = "application"
	instanceFlag    = "instance"
	zoneFlag        = "zone"
	targetFlag      = "target"
	waitFlag        = "wait"
	colorFlag       = "color"
	quietFlag       = "quiet"
)

// CLI holds the Vespa CLI command tree, configuration and dependencies.
type CLI struct {
	// Environment holds the process environment.
	Environment map[string]string
	Stdin       io.ReadWriter
	Stdout      io.Writer
	Stderr      io.Writer

	cmd     *cobra.Command
	config  *Config
	version version.Version

	httpClient util.HTTPClient
	exec       executor
	isTerminal func() bool
	spinner    func(w io.Writer, message string, fn func() error) error
}

// ErrCLI is an error returned to the user. It wraps an exit status, a regular error and optional hints for resolving
// the error.
type ErrCLI struct {
	Status int
	quiet  bool
	hints  []string
	error
}

type targetOptions struct {
	// logLevel sets the log level to use for this target. If empty, it defaults to "info".
	logLevel string
	// noCertificate declares that no client certificate should be required when using this target.
	noCertificate bool
}

// errHint creates a new CLI error, with optional hints that will be printed after the error
func errHint(err error, hints ...string) ErrCLI { return ErrCLI{Status: 1, hints: hints, error: err} }

type executor interface {
	LookPath(name string) (string, error)
	Run(name string, args ...string) ([]byte, error)
}

type execSubprocess struct{}

func (c *execSubprocess) LookPath(name string) (string, error) { return exec.LookPath(name) }
func (c *execSubprocess) Run(name string, args ...string) ([]byte, error) {
	return exec.Command(name, args...).Output()
}

// New creates the Vespa CLI, writing output to stdout and stderr, and reading environment variables from environment.
func New(stdout, stderr io.Writer, environment []string) (*CLI, error) {
	cmd := &cobra.Command{
		Use:   "vespa command-name",
		Short: "The command-line tool for Vespa.ai",
		Long: `The command-line tool for Vespa.ai.

Use it on Vespa instances running locally, remotely or in the cloud.
Prefer web service API's to this in production.

Vespa documentation: https://docs.vespa.ai

For detailed description of flags and configuration, see 'vespa help config'.
`,
		DisableAutoGenTag: true,
		SilenceErrors:     true, // We have our own error printing
		SilenceUsage:      false,
		Args:              cobra.MinimumNArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			return fmt.Errorf("invalid command: %s", args[0])
		},
	}
	env := make(map[string]string)
	for _, entry := range environment {
		parts := strings.SplitN(entry, "=", 2)
		env[parts[0]] = parts[1]
	}
	version, err := version.Parse(build.Version)
	if err != nil {
		return nil, err
	}
	cli := CLI{
		Environment: env,
		Stdin:       os.Stdin,
		Stdout:      stdout,
		Stderr:      stderr,

		version:    version,
		cmd:        cmd,
		httpClient: util.CreateClient(time.Second * 10),
		exec:       &execSubprocess{},
	}
	cli.isTerminal = func() bool { return isTerminal(cli.Stdout) && isTerminal(cli.Stderr) }
	if err := cli.loadConfig(); err != nil {
		return nil, err
	}
	cli.configureSpinner()
	cli.configureCommands()
	cmd.PersistentPreRunE = cli.configureOutput
	return &cli, nil
}

func (c *CLI) loadConfig() error {
	config, err := loadConfig(c.Environment, c.configureFlags())
	if err != nil {
		return err
	}
	c.config = config
	return nil
}

func (c *CLI) configureOutput(cmd *cobra.Command, args []string) error {
	if f, ok := c.Stdout.(*os.File); ok {
		c.Stdout = colorable.NewColorable(f)
	}
	if f, ok := c.Stderr.(*os.File); ok {
		c.Stderr = colorable.NewColorable(f)
	}
	if c.config.isQuiet() {
		c.Stdout = io.Discard
	}
	log.SetFlags(0) // No timestamps
	log.SetOutput(c.Stdout)
	colorValue, _ := c.config.get(colorFlag)
	colorize := false
	switch colorValue {
	case "auto":
		_, nocolor := c.Environment["NO_COLOR"] // https://no-color.org
		colorize = !nocolor && c.isTerminal()
	case "always":
		colorize = true
	case "never":
	default:
		return fmt.Errorf("invalid color option: %s", colorValue)
	}
	color.NoColor = !colorize
	return nil
}

func (c *CLI) configureFlags() map[string]*pflag.Flag {
	var (
		target      string
		application string
		instance    string
		zone        string
		waitSecs    int
		color       string
		quiet       bool
	)
	c.cmd.PersistentFlags().StringVarP(&target, targetFlag, "t", "local", `The target platform to use. Must be "local", "cloud", "hosted" or an URL`)
	c.cmd.PersistentFlags().StringVarP(&application, applicationFlag, "a", "", "The application to manage")
	c.cmd.PersistentFlags().StringVarP(&instance, instanceFlag, "i", "", "The instance of the application to manage")
	c.cmd.PersistentFlags().StringVarP(&zone, zoneFlag, "z", "", "The zone to use. This defaults to a dev zone")
	c.cmd.PersistentFlags().IntVarP(&waitSecs, waitFlag, "w", 0, "Number of seconds to wait for a service to become ready")
	c.cmd.PersistentFlags().StringVarP(&color, colorFlag, "c", "auto", `Whether to use colors in output. Must be "auto", "never", or "always"`)
	c.cmd.PersistentFlags().BoolVarP(&quiet, quietFlag, "q", false, "Print only errors")
	flags := make(map[string]*pflag.Flag)
	c.cmd.PersistentFlags().VisitAll(func(flag *pflag.Flag) {
		flags[flag.Name] = flag
	})
	return flags
}

func (c *CLI) configureSpinner() {
	// Explicitly disable spinner for Screwdriver. It emulates a tty but
	// \r result in a newline, and output gets truncated.
	_, screwdriver := c.Environment["SCREWDRIVER"]
	if c.config.isQuiet() || !c.isTerminal() || screwdriver {
		c.spinner = func(w io.Writer, message string, fn func() error) error {
			return fn()
		}
	} else {
		c.spinner = util.Spinner
	}
}

func (c *CLI) configureCommands() {
	rootCmd := c.cmd
	authCmd := newAuthCmd()
	certCmd := newCertCmd(c, false)
	configCmd := newConfigCmd()
	documentCmd := newDocumentCmd(c)
	prodCmd := newProdCmd()
	statusCmd := newStatusCmd(c)
	certCmd.AddCommand(newCertAddCmd(c))            // auth cert add
	authCmd.AddCommand(certCmd)                     // auth cert
	authCmd.AddCommand(newAPIKeyCmd(c, false))      // auth api-key
	authCmd.AddCommand(newLoginCmd(c))              // auth login
	authCmd.AddCommand(newLogoutCmd(c))             // auth logout
	rootCmd.AddCommand(authCmd)                     // auth
	rootCmd.AddCommand(newCertCmd(c, true))         // cert     TODO: Remove this after 2022-06-01
	rootCmd.AddCommand(newAPIKeyCmd(c, true))       // api-key  TODO: Remove this after 2022-06-01
	rootCmd.AddCommand(newCloneCmd(c))              // clone
	configCmd.AddCommand(newConfigGetCmd(c))        // config get
	configCmd.AddCommand(newConfigSetCmd(c))        // config set
	configCmd.AddCommand(newConfigUnsetCmd(c))      // config unset
	rootCmd.AddCommand(configCmd)                   // config
	rootCmd.AddCommand(newCurlCmd(c))               // curl
	rootCmd.AddCommand(newDeployCmd(c))             // deploy
	rootCmd.AddCommand(newPrepareCmd(c))            // prepare
	rootCmd.AddCommand(newActivateCmd(c))           // activate
	documentCmd.AddCommand(newDocumentPutCmd(c))    // document put
	documentCmd.AddCommand(newDocumentUpdateCmd(c)) // document update
	documentCmd.AddCommand(newDocumentRemoveCmd(c)) // document remove
	documentCmd.AddCommand(newDocumentGetCmd(c))    // document get
	rootCmd.AddCommand(documentCmd)                 // document
	rootCmd.AddCommand(newLogCmd(c))                // log
	rootCmd.AddCommand(newManCmd(c))                // man
	prodCmd.AddCommand(newProdInitCmd(c))           // prod init
	prodCmd.AddCommand(newProdSubmitCmd(c))         // prod submit
	rootCmd.AddCommand(prodCmd)                     // prod
	rootCmd.AddCommand(newQueryCmd(c))              // query
	statusCmd.AddCommand(newStatusQueryCmd(c))      // status query
	statusCmd.AddCommand(newStatusDocumentCmd(c))   // status document
	statusCmd.AddCommand(newStatusDeployCmd(c))     // status deploy
	rootCmd.AddCommand(statusCmd)                   // status
	rootCmd.AddCommand(newTestCmd(c))               // test
	rootCmd.AddCommand(newVersionCmd(c))            // version
}

func (c *CLI) printErr(err error, hints ...string) {
	fmt.Fprintln(c.Stderr, color.RedString("Error:"), err)
	for _, hint := range hints {
		fmt.Fprintln(c.Stderr, color.CyanString("Hint:"), hint)
	}
}

func (c *CLI) printSuccess(msg ...interface{}) {
	fmt.Fprintln(c.Stdout, color.GreenString("Success:"), fmt.Sprint(msg...))
}

func (c *CLI) printWarning(msg interface{}, hints ...string) {
	fmt.Fprintln(c.Stderr, color.YellowString("Warning:"), msg)
	for _, hint := range hints {
		fmt.Fprintln(c.Stderr, color.CyanString("Hint:"), hint)
	}
}

// target creates a target according the configuration of this CLI and given opts.
func (c *CLI) target(opts targetOptions) (vespa.Target, error) {
	target, err := c.createTarget(opts)
	if err != nil {
		return nil, err
	}
	if !c.isCloudCI() { // Vespa Cloud always runs an up-to-date version
		if err := target.CheckVersion(c.version); err != nil {
			c.printWarning(err, "This version may not work as expected", "Try 'vespa version' to check for a new version")
		}
	}
	return target, nil
}

func (c *CLI) createTarget(opts targetOptions) (vespa.Target, error) {
	targetType, err := c.config.targetType()
	if err != nil {
		return nil, err
	}
	if strings.HasPrefix(targetType, "http") {
		return vespa.CustomTarget(c.httpClient, targetType), nil
	}
	switch targetType {
	case vespa.TargetLocal:
		return vespa.LocalTarget(c.httpClient), nil
	case vespa.TargetCloud, vespa.TargetHosted:
		return c.createCloudTarget(targetType, opts)
	}
	return nil, errHint(fmt.Errorf("invalid target: %s", targetType), "Valid targets are 'local', 'cloud', 'hosted' or an URL")
}

func (c *CLI) createCloudTarget(targetType string, opts targetOptions) (vespa.Target, error) {
	system, err := c.system(targetType)
	if err != nil {
		return nil, err
	}
	deployment, err := c.config.deploymentIn(system)
	if err != nil {
		return nil, err
	}
	endpoints, err := c.endpointsFromEnv()
	if err != nil {
		return nil, err
	}
	var (
		apiKey               []byte
		authConfigPath       string
		apiTLSOptions        vespa.TLSOptions
		deploymentTLSOptions vespa.TLSOptions
	)
	switch targetType {
	case vespa.TargetCloud:
		apiKey, err = c.config.readAPIKey(c, system, deployment.Application.Tenant)
		if err != nil {
			return nil, err
		}
		authConfigPath = c.config.authConfigPath()
		deploymentTLSOptions = vespa.TLSOptions{}
		if !opts.noCertificate {
			kp, err := c.config.x509KeyPair(deployment.Application)
			if err != nil {
				return nil, errHint(err, "Deployment to cloud requires a certificate. Try 'vespa auth cert'")
			}
			deploymentTLSOptions = vespa.TLSOptions{
				KeyPair:         kp.KeyPair,
				CertificateFile: kp.CertificateFile,
				PrivateKeyFile:  kp.PrivateKeyFile,
			}
		}
	case vespa.TargetHosted:
		kp, err := athenzKeyPair()
		if err != nil {
			return nil, err
		}
		apiTLSOptions = vespa.TLSOptions{
			KeyPair:         kp.KeyPair,
			CertificateFile: kp.CertificateFile,
			PrivateKeyFile:  kp.PrivateKeyFile,
		}
		deploymentTLSOptions = apiTLSOptions
	default:
		return nil, fmt.Errorf("invalid cloud target: %s", targetType)
	}
	apiOptions := vespa.APIOptions{
		System:         system,
		TLSOptions:     apiTLSOptions,
		APIKey:         apiKey,
		AuthConfigPath: authConfigPath,
	}
	deploymentOptions := vespa.CloudDeploymentOptions{
		Deployment:  deployment,
		TLSOptions:  deploymentTLSOptions,
		ClusterURLs: endpoints,
	}
	logLevel := opts.logLevel
	if logLevel == "" {
		logLevel = "info"
	}
	logOptions := vespa.LogOptions{
		Writer: c.Stdout,
		Level:  vespa.LogLevel(logLevel),
	}
	return vespa.CloudTarget(c.httpClient, apiOptions, deploymentOptions, logOptions)
}

// system returns the appropiate system for the target configured in this CLI.
func (c *CLI) system(targetType string) (vespa.System, error) {
	name := c.Environment["VESPA_CLI_CLOUD_SYSTEM"]
	if name != "" {
		return vespa.GetSystem(name)
	}
	switch targetType {
	case vespa.TargetHosted:
		return vespa.MainSystem, nil
	case vespa.TargetCloud:
		return vespa.PublicSystem, nil
	}
	return vespa.System{}, fmt.Errorf("no default system found for %s target", targetType)
}

// service returns the service of given name located at target. If non-empty, cluster specifies a cluster to query. This
// function blocks according to the wait period configured in this CLI. The parameter sessionOrRunID specifies either
// the session ID (local target) or run ID (cloud target) to wait for.
func (c *CLI) service(target vespa.Target, name string, sessionOrRunID int64, cluster string) (*vespa.Service, error) {
	timeout, err := c.config.timeout()
	if err != nil {
		return nil, err
	}
	if timeout > 0 {
		log.Printf("Waiting up to %s for %s service to become available ...", color.CyanString(timeout.String()), color.CyanString(name))
	}
	s, err := target.Service(name, timeout, sessionOrRunID, cluster)
	if err != nil {
		return nil, fmt.Errorf("service '%s' is unavailable: %w", name, err)
	}
	return s, nil
}

func (c *CLI) createDeploymentOptions(pkg vespa.ApplicationPackage, target vespa.Target) (vespa.DeploymentOptions, error) {
	timeout, err := c.config.timeout()
	if err != nil {
		return vespa.DeploymentOptions{}, err
	}
	return vespa.DeploymentOptions{
		ApplicationPackage: pkg,
		Target:             target,
		Timeout:            timeout,
		HTTPClient:         c.httpClient,
	}, nil
}

// isCI returns true if running inside a continuous integration environment.
func (c *CLI) isCI() bool {
	_, ok := c.Environment["CI"]
	return ok
}

// isCloudCI returns true if running inside a Vespa Cloud deployment job.
func (c *CLI) isCloudCI() bool {
	_, ok := c.Environment["VESPA_CLI_CLOUD_CI"]
	return ok
}

func (c *CLI) endpointsFromEnv() (map[string]string, error) {
	endpointsString := c.Environment["VESPA_CLI_ENDPOINTS"]
	if endpointsString == "" {
		return nil, nil
	}
	var endpoints endpoints
	urlsByCluster := make(map[string]string)
	if err := json.Unmarshal([]byte(endpointsString), &endpoints); err != nil {
		return nil, fmt.Errorf("endpoints must be valid json: %w", err)
	}
	if len(endpoints.Endpoints) == 0 {
		return nil, fmt.Errorf("endpoints must be non-empty")
	}
	for _, endpoint := range endpoints.Endpoints {
		urlsByCluster[endpoint.Cluster] = endpoint.URL
	}
	return urlsByCluster, nil
}

// Run executes the CLI with given args. If args is nil, it defaults to os.Args[1:].
func (c *CLI) Run(args ...string) error {
	c.cmd.SetArgs(args)
	err := c.cmd.Execute()
	if err != nil {
		if cliErr, ok := err.(ErrCLI); ok {
			if !cliErr.quiet {
				c.printErr(cliErr, cliErr.hints...)
			}
		} else {
			c.printErr(err)
		}
	}
	return err
}

type endpoints struct {
	Endpoints []endpoint `json:"endpoints"`
}

type endpoint struct {
	Cluster string `json:"cluster"`
	URL     string `json:"url"`
}

func isTerminal(w io.Writer) bool {
	if f, ok := w.(*os.File); ok {
		return isatty.IsTerminal(f.Fd())
	}
	return false
}

func athenzPath(filename string) (string, error) {
	userHome, err := os.UserHomeDir()
	if err != nil {
		return "", err
	}
	return filepath.Join(userHome, ".athenz", filename), nil
}

func athenzKeyPair() (KeyPair, error) {
	certFile, err := athenzPath("cert")
	if err != nil {
		return KeyPair{}, err
	}
	keyFile, err := athenzPath("key")
	if err != nil {
		return KeyPair{}, err
	}
	kp, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		return KeyPair{}, err
	}
	cert, err := x509.ParseCertificate(kp.Certificate[0])
	if err != nil {
		return KeyPair{}, err
	}
	now := time.Now()
	expiredAt := cert.NotAfter
	if expiredAt.Before(now) {
		delta := now.Sub(expiredAt).Truncate(time.Second)
		return KeyPair{}, errHint(fmt.Errorf("certificate %s expired at %s (%s ago)", certFile, cert.NotAfter, delta), "Try renewing certificate with 'athenz-user-cert'")
	}
	return KeyPair{KeyPair: kp, CertificateFile: certFile, PrivateKeyFile: keyFile}, nil
}

// applicationPackageFrom returns an application loaded from args. If args is empty, the application package is loaded
// from the working directory. If requirePackaging is true, the application package is required to be packaged with mvn
// package.
func (c *CLI) applicationPackageFrom(args []string, requirePackaging bool) (vespa.ApplicationPackage, error) {
	path := "."
	if len(args) == 1 {
		path = args[0]
		stat, err := os.Stat(path)
		if err != nil {
			return vespa.ApplicationPackage{}, err
		}
		if stat.IsDir() {
			// Using an explicit application directory, look for local config in that directory too
			if err := c.config.loadLocalConfigFrom(path); err != nil {
				return vespa.ApplicationPackage{}, err
			}
		}
	} else if len(args) > 1 {
		return vespa.ApplicationPackage{}, fmt.Errorf("expected 0 or 1 arguments, got %d", len(args))
	}
	return vespa.FindApplicationPackage(path, requirePackaging)
}