forked from digitalocean/doctl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
doit.go
577 lines (484 loc) · 15.8 KB
/
doit.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
/*
Copyright 2018 The Doctl Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package doctl
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"github.com/blang/semver"
"github.com/digitalocean/doctl/pkg/listen"
"github.com/digitalocean/doctl/pkg/runner"
"github.com/digitalocean/doctl/pkg/ssh"
"github.com/digitalocean/godo"
"github.com/docker/docker/client"
"github.com/spf13/viper"
"golang.org/x/oauth2"
"github.com/digitalocean/doctl/internal/apps/builder"
)
const (
// LatestReleaseURL is the latest release URL endpoint.
LatestReleaseURL = "https://api.github.com/repos/digitalocean/doctl/releases/latest"
)
// Version is the version info for doit.
type Version struct {
Major, Minor, Patch int
Name, Build, Label string
}
var (
// Build is set at build time. It defines the git SHA for the current
// build.
Build string
// Major is set at build time. It defines the major semantic version of
// doctl.
Major string
// Minor is set at build time. It defines the minor semantic version of
// doctl.
Minor string
// Patch is set at build time. It defines the patch semantic version of
// doctl.
Patch string
// Label is set at build time. It defines the string that comes after the
// version of doctl, ie, the "dev" in v1.0.0-dev.
Label string
// DoitVersion is doctl's version.
DoitVersion Version
// TraceHTTP traces http connections.
TraceHTTP bool
)
func init() {
if Build != "" {
DoitVersion.Build = Build
}
if Major != "" {
i, _ := strconv.Atoi(Major)
DoitVersion.Major = i
}
if Minor != "" {
i, _ := strconv.Atoi(Minor)
DoitVersion.Minor = i
}
if Patch != "" {
i, _ := strconv.Atoi(Patch)
DoitVersion.Patch = i
}
if Label == "" {
DoitVersion.Label = "dev"
} else {
DoitVersion.Label = Label
}
}
func (v Version) String() string {
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch))
if v.Label != "" {
buffer.WriteString("-" + v.Label)
}
return buffer.String()
}
// Complete is the complete version for doit.
func (v Version) Complete(lv LatestVersioner) string {
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("doctl version %s", v.String()))
if v.Build != "" {
buffer.WriteString(fmt.Sprintf("\nGit commit hash: %s", v.Build))
}
if tagName, err := lv.LatestVersion(); err == nil {
v0, err1 := semver.Make(tagName)
v1, err2 := semver.Make(v.String())
if len(v0.Build) == 0 {
v0, err1 = semver.Make(tagName + "-release")
}
if err1 == nil && err2 == nil && v0.GT(v1) {
buffer.WriteString(fmt.Sprintf("\nrelease %s is available, check it out! ", tagName))
}
}
return buffer.String()
}
// CompleteJSON is the complete version for doit, formatted as JSON.
func (v Version) CompleteJSON(lv LatestVersioner) string {
versionInfo := &struct {
Version string `json:"version,omitempty"`
Commit string `json:"commit,omitempty"`
LatestRelease string `json:"latestRelease"`
Notification string `json:"notification,omitempty"`
}{
Version: v.String(),
Commit: v.Build,
}
if tagName, err := lv.LatestVersion(); err == nil {
versionInfo.LatestRelease = tagName
v0, err1 := semver.Make(tagName)
v1, err2 := semver.Make(v.String())
if len(v0.Build) == 0 {
v0, err1 = semver.Make(tagName + "-release")
}
if err1 == nil && err2 == nil && v0.GT(v1) {
versionInfo.Notification = fmt.Sprintf("release %s is available, check it out!", tagName)
}
}
data, _ := json.MarshalIndent(versionInfo, "", " ")
return string(data)
}
// LatestVersioner an interface for detecting the latest version.
type LatestVersioner interface {
LatestVersion() (string, error)
}
// GithubLatestVersioner retrieves the latest version from GitHub.
type GithubLatestVersioner struct{}
var _ LatestVersioner = &GithubLatestVersioner{}
// LatestVersion retrieves the latest version from Github or returns
// an error.
func (glv *GithubLatestVersioner) LatestVersion() (string, error) {
u := LatestReleaseURL
res, err := http.Get(u)
if err != nil {
return "", err
}
defer res.Body.Close()
var m map[string]interface{}
if err = json.NewDecoder(res.Body).Decode(&m); err != nil {
return "", err
}
tn, ok := m["tag_name"]
if !ok {
return "", errors.New("could not find tag name in response")
}
tagName := tn.(string)
return strings.TrimPrefix(tagName, "v"), nil
}
// Config is an interface that represent doit's config.
type Config interface {
GetGodoClient(trace bool, accessToken string) (*godo.Client, error)
GetDockerEngineClient() (builder.DockerEngineClient, error)
SSH(user, host, keyPath string, port int, opts ssh.Options) runner.Runner
Listen(url *url.URL, token string, schemaFunc listen.SchemaFunc, out io.Writer) listen.ListenerService
Set(ns, key string, val interface{})
IsSet(key string) bool
GetString(ns, key string) (string, error)
GetBool(ns, key string) (bool, error)
GetBoolPtr(ns, key string) (*bool, error)
GetInt(ns, key string) (int, error)
GetIntPtr(ns, key string) (*int, error)
GetStringSlice(ns, key string) ([]string, error)
GetStringMapString(ns, key string) (map[string]string, error)
GetDuration(ns, key string) (time.Duration, error)
}
// LiveConfig is an implementation of Config for live values.
type LiveConfig struct {
cliArgs map[string]bool
}
var _ Config = &LiveConfig{}
// GetGodoClient returns a GodoClient.
func (c *LiveConfig) GetGodoClient(trace bool, accessToken string) (*godo.Client, error) {
if accessToken == "" {
return nil, fmt.Errorf("access token is required. (hint: run 'doctl auth init')")
}
tokenSource := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: accessToken})
oauthClient := oauth2.NewClient(context.Background(), tokenSource)
if trace {
r := newRecorder(oauthClient.Transport)
go func() {
for {
select {
case msg := <-r.req:
log.Println("->", strconv.Quote(msg))
case msg := <-r.resp:
log.Println("<-", strconv.Quote(msg))
}
}
}()
oauthClient.Transport = r
}
args := []godo.ClientOpt{godo.SetUserAgent(userAgent())}
apiURL := viper.GetString("api-url")
if apiURL != "" {
args = append(args, godo.SetBaseURL(apiURL))
}
return godo.New(oauthClient, args...)
}
// GetDockerEngineClient returns a container engine client.
func (c *LiveConfig) GetDockerEngineClient() (builder.DockerEngineClient, error) {
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
return nil, err
}
return cli, nil
}
func userAgent() string {
return fmt.Sprintf("doctl/%s (%s %s)", DoitVersion.String(), runtime.GOOS, runtime.GOARCH)
}
// SSH creates a ssh connection to a host.
func (c *LiveConfig) SSH(user, host, keyPath string, port int, opts ssh.Options) runner.Runner {
return &ssh.Runner{
User: user,
Host: host,
KeyPath: keyPath,
Port: port,
AgentForwarding: opts[ArgsSSHAgentForwarding].(bool),
Command: opts[ArgSSHCommand].(string),
}
}
// Listen creates a websocket connection
func (c *LiveConfig) Listen(url *url.URL, token string, schemaFunc listen.SchemaFunc, out io.Writer) listen.ListenerService {
return listen.NewListener(url, token, schemaFunc, out)
}
// Set sets a config key.
func (c *LiveConfig) Set(ns, key string, val interface{}) {
viper.Set(nskey(ns, key), val)
}
// IsSet checks if a config is set
func (c *LiveConfig) IsSet(key string) bool {
matches := regexp.MustCompile("\b*--([a-z-_]+)").FindAllStringSubmatch(strings.Join(os.Args, " "), -1)
if len(matches) == 0 {
return false
}
if len(c.cliArgs) == 0 {
args := make(map[string]bool)
for _, match := range matches {
args[match[1]] = true
}
c.cliArgs = args
}
return c.cliArgs[key]
}
// GetString returns a config value as a string.
func (c *LiveConfig) GetString(ns, key string) (string, error) {
nskey := nskey(ns, key)
str := viper.GetString(nskey)
if isRequired(nskey) && strings.TrimSpace(str) == "" {
return "", NewMissingArgsErr(nskey)
}
return str, nil
}
// GetBool returns a config value as a bool.
func (c *LiveConfig) GetBool(ns, key string) (bool, error) {
return viper.GetBool(nskey(ns, key)), nil
}
// GetBoolPtr returns a config value as a bool pointer.
func (c *LiveConfig) GetBoolPtr(ns, key string) (*bool, error) {
if !c.IsSet(key) {
return nil, nil
}
val := viper.GetBool(nskey(ns, key))
return &val, nil
}
// GetInt returns a config value as an int.
func (c *LiveConfig) GetInt(ns, key string) (int, error) {
nskey := nskey(ns, key)
val := viper.GetInt(nskey)
if isRequired(nskey) && val == 0 {
return 0, NewMissingArgsErr(nskey)
}
return val, nil
}
// GetIntPtr returns a config value as an int pointer.
func (c *LiveConfig) GetIntPtr(ns, key string) (*int, error) {
nskey := nskey(ns, key)
if !c.IsSet(key) {
if isRequired(nskey) {
return nil, NewMissingArgsErr(nskey)
}
return nil, nil
}
val := viper.GetInt(nskey)
return &val, nil
}
// GetStringSlice returns a config value as a string slice.
func (c *LiveConfig) GetStringSlice(ns, key string) ([]string, error) {
nskey := nskey(ns, key)
val := viper.GetStringSlice(nskey)
if isRequired(nskey) && emptyStringSlice(val) {
return nil, NewMissingArgsErr(nskey)
}
out := []string{}
for _, item := range viper.GetStringSlice(nskey) {
item = strings.TrimPrefix(item, "[")
item = strings.TrimSuffix(item, "]")
list := strings.Split(item, ",")
for _, str := range list {
if str == "" {
continue
}
out = append(out, str)
}
}
return out, nil
}
// GetStringMapString returns a config value as a string to string map.
func (c *LiveConfig) GetStringMapString(ns, key string) (map[string]string, error) {
nskey := nskey(ns, key)
if isRequired(nskey) && !c.IsSet(key) {
return nil, NewMissingArgsErr(nskey)
}
// We cannot call viper.GetStringMapString because it does not handle
// pflag's StringToStringP properly:
// https://github.com/spf13/viper/issues/608
// Re-implement the necessary pieces on our own instead.
vals := map[string]string{}
items := viper.GetStringSlice(nskey)
for _, item := range items {
parts := strings.SplitN(item, "=", 2)
if len(parts) < 2 {
return nil, fmt.Errorf("item %q does not adhere to form: key=value", item)
}
labelKey := parts[0]
labelValue := parts[1]
vals[labelKey] = labelValue
}
return vals, nil
}
// GetDuration returns a config value as a duration.
func (c *LiveConfig) GetDuration(ns, key string) (time.Duration, error) {
return viper.GetDuration(nskey(ns, key)), nil
}
func nskey(ns, key string) string {
if ns != "" {
key = fmt.Sprintf("%s.%s", ns, key)
}
return key
}
func isRequired(key string) bool {
return viper.GetBool(fmt.Sprintf("required.%s", key))
}
// TestConfig is an implementation of Config for testing.
type TestConfig struct {
SSHFn func(user, host, keyPath string, port int, opts ssh.Options) runner.Runner
ListenFn func(url *url.URL, token string, schemaFunc listen.SchemaFunc, out io.Writer) listen.ListenerService
v *viper.Viper
IsSetMap map[string]bool
DockerEngineClient builder.DockerEngineClient
}
var _ Config = &TestConfig{}
// NewTestConfig creates a new, ready-to-use instance of a TestConfig.
func NewTestConfig() *TestConfig {
return &TestConfig{
SSHFn: func(u, h, kp string, p int, opts ssh.Options) runner.Runner {
return &MockRunner{}
},
ListenFn: func(url *url.URL, token string, schemaFunc listen.SchemaFunc, out io.Writer) listen.ListenerService {
return &MockListener{}
},
v: viper.New(),
IsSetMap: make(map[string]bool),
}
}
// GetGodoClient mocks a GetGodoClient call. The returned godo client will
// be nil.
func (c *TestConfig) GetGodoClient(trace bool, accessToken string) (*godo.Client, error) {
return &godo.Client{}, nil
}
// GetDockerEngineClient mocks a GetDockerEngineClient call. The returned client will
// be nil unless configured in the test config.
func (c *TestConfig) GetDockerEngineClient() (builder.DockerEngineClient, error) {
return c.DockerEngineClient, nil
}
// SSH returns a mock SSH runner.
func (c *TestConfig) SSH(user, host, keyPath string, port int, opts ssh.Options) runner.Runner {
return c.SSHFn(user, host, keyPath, port, opts)
}
// Listen returns a mock websocket listener
func (c *TestConfig) Listen(url *url.URL, token string, schemaFunc listen.SchemaFunc, out io.Writer) listen.ListenerService {
return c.ListenFn(url, token, schemaFunc, out)
}
// Set sets a config key.
func (c *TestConfig) Set(ns, key string, val interface{}) {
nskey := nskey(ns, key)
c.v.Set(nskey, val)
c.IsSetMap[key] = true
}
// IsSet returns true if the given key is set on the config.
func (c *TestConfig) IsSet(key string) bool {
return c.IsSetMap[key]
}
// GetString returns the string value for the key in the given namespace. Because
// this is a mock implementation, and error will never be returned.
func (c *TestConfig) GetString(ns, key string) (string, error) {
nskey := nskey(ns, key)
return c.v.GetString(nskey), nil
}
// GetInt returns the int value for the key in the given namespace. Because
// this is a mock implementation, and error will never be returned.
func (c *TestConfig) GetInt(ns, key string) (int, error) {
nskey := nskey(ns, key)
return c.v.GetInt(nskey), nil
}
// GetIntPtr returns the int value for the key in the given namespace. Because
// this is a mock implementation, and error will never be returned.
func (c *TestConfig) GetIntPtr(ns, key string) (*int, error) {
nskey := nskey(ns, key)
if !c.v.IsSet(nskey) {
return nil, nil
}
val := c.v.GetInt(nskey)
return &val, nil
}
// GetStringSlice returns the string slice value for the key in the given
// namespace. Because this is a mock implementation, and error will never be
// returned.
func (c *TestConfig) GetStringSlice(ns, key string) ([]string, error) {
nskey := nskey(ns, key)
return c.v.GetStringSlice(nskey), nil
}
// GetStringMapString returns the string-to-string value for the key in the
// given namespace. Because this is a mock implementation, and error will never
// be returned.
func (c *TestConfig) GetStringMapString(ns, key string) (map[string]string, error) {
nskey := nskey(ns, key)
return c.v.GetStringMapString(nskey), nil
}
// GetBool returns the bool value for the key in the given namespace. Because
// this is a mock implementation, and error will never be returned.
func (c *TestConfig) GetBool(ns, key string) (bool, error) {
nskey := nskey(ns, key)
return c.v.GetBool(nskey), nil
}
// GetBoolPtr returns the bool value for the key in the given namespace. Because
// this is a mock implementation, and error will never be returned.
func (c *TestConfig) GetBoolPtr(ns, key string) (*bool, error) {
nskey := nskey(ns, key)
if !c.v.IsSet(nskey) {
return nil, nil
}
val := c.v.GetBool(nskey)
return &val, nil
}
// GetDuration returns the duration value for the key in the given namespace. Because
// this is a mock implementation, and error will never be returned.
func (c *TestConfig) GetDuration(ns, key string) (time.Duration, error) {
nskey := nskey(ns, key)
return c.v.GetDuration(nskey), nil
}
// This is needed because an empty StringSlice flag returns `"[]"`
func emptyStringSlice(s []string) bool {
return (len(s) == 1 && s[0] == "[]") || len(s) == 0
}
// CommandName returns the name by which doctl was invoked
func CommandName() string {
name, ok := os.LookupEnv("SNAP_NAME")
if !ok || name != "doctl" {
return os.Args[0]
}
return name
}