/
middleware.go
367 lines (301 loc) · 8.28 KB
/
middleware.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
package cmd
import (
"context"
"os"
"reflect"
"strings"
"time"
"github.com/urfave/cli"
"gopkg.in/oleiade/reflections.v1"
"github.com/manifoldco/torus-cli/api"
"github.com/manifoldco/torus-cli/apitypes"
"github.com/manifoldco/torus-cli/config"
"github.com/manifoldco/torus-cli/dirprefs"
"github.com/manifoldco/torus-cli/errs"
"github.com/manifoldco/torus-cli/prefs"
"github.com/manifoldco/torus-cli/ui"
)
const downloadURL = "https://www.torus.sh/install"
type actionFunc func(ctx *cli.Context) error
// chain allows easy sequential calling of BeforeFuncs and AfterFuncs.
// chain will exit on the first error seen.
func chain(funcs ...actionFunc) func(*cli.Context) error {
return wrap(func(ctx *cli.Context) error {
for _, f := range funcs {
err := f(ctx)
if err != nil {
return err
}
}
return nil
})
}
// wrap wraps the given actionfunc and converts any of the received errors into
// cli.ExitErrors ensuring that we never have a silent failure.
func wrap(cmd actionFunc) actionFunc {
return func(ctx *cli.Context) error {
return errs.ToError(cmd(ctx))
}
}
// ensureDaemon ensures that the daemon is running, and is the correct version,
// before a command is exeucted.
// the daemon will be started/restarted once, to try and launch the latest
// version.
func ensureDaemon(ctx *cli.Context) error {
cfg, err := config.LoadConfig()
if err != nil {
return err
}
proc, err := findDaemon(cfg)
if err != nil {
return err
}
spawned := false
if proc == nil {
err := spawnDaemon()
if err != nil {
return err
}
spawned = true
}
client := api.NewClient(cfg)
var v *apitypes.Version
increment := 5 * time.Millisecond
for d := increment; d < 1*time.Second; d += increment {
v, err = client.Version.GetDaemon(context.Background())
if err == nil {
break
}
time.Sleep(d)
}
if err != nil {
return errs.NewErrorExitError("Could not communicate with daemon.", err)
}
if v.Version == cfg.Version {
return nil
}
if spawned {
return errs.NewExitError("The daemon version is incorrect. Check for stale processes.")
}
ui.Warn("The daemon version is out of date and is being restarted. You will need to login again.")
_, err = stopDaemon(proc)
if err != nil {
return err
}
return ensureDaemon(ctx)
}
// ensureSession ensures that the user is logged in with the daemon and has a
// valid session. If not, it will attempt to log the user in via environment
// variables. If they do not exist, of the login fails, it will abort the
// command.
func ensureSession(ctx *cli.Context) error {
cfg, err := config.LoadConfig()
if err != nil {
return err
}
bgCtx := context.Background()
client := api.NewClient(cfg)
_, err = client.Session.Get(bgCtx)
hasSession := true
if err != nil {
if cerr, ok := err.(*apitypes.Error); ok {
if cerr.Type == apitypes.UnauthorizedError {
hasSession = false
}
}
if hasSession {
return errs.NewErrorExitError("Could not communicate with daemon.", err)
}
}
if hasSession {
return nil
}
email, hasEmail := os.LookupEnv("TORUS_EMAIL")
password, hasPassword := os.LookupEnv("TORUS_PASSWORD")
tokenID, hasTokenID := os.LookupEnv("TORUS_TOKEN_ID")
tokenSecret, hasTokenSecret := os.LookupEnv("TORUS_TOKEN_SECRET")
if hasEmail && hasPassword {
ui.Info("Attempting to login as a user with email: %s", email)
err := client.Session.UserLogin(bgCtx, email, password)
if err != nil {
ui.Error("Could not log in, encountered an error: %s", err)
} else {
return nil
}
}
if hasTokenID && hasTokenSecret {
ui.Info("Attempting to login with machine token id: %s", tokenID)
err := client.Session.MachineLogin(bgCtx, tokenID, tokenSecret)
if err != nil {
ui.Error("Could not log in, encountered an error: %s", err)
} else {
return nil
}
}
msg := "\nYou must be logged in to run '" + ctx.Command.FullName() + "'.\n" +
"Login using 'login' or create an account using 'signup'."
return errs.NewExitError(msg)
}
// loadDirPrefs loads argument values from the .torus.json file
func loadDirPrefs(ctx *cli.Context) error {
p, err := prefs.NewPreferences()
if err != nil {
return err
}
d, err := dirprefs.Load(true)
if err != nil {
return err
}
return reflectArgs(ctx, p, d, "json")
}
// loadPrefDefaults loads default argument values from the .torusrc
// preferences file defaults section, inserting them into any unset flag values
func loadPrefDefaults(ctx *cli.Context) error {
p, err := prefs.NewPreferences()
if err != nil {
return err
}
return reflectArgs(ctx, p, p.Defaults, "ini")
}
func reflectArgs(ctx *cli.Context, p *prefs.Preferences, i interface{},
tagName string) error {
// The user has disabled reading arguments from prefs and .torus.json
if !p.Core.Context {
return nil
}
// tagged field names match the argument names
tags, err := reflections.Tags(i, tagName)
if err != nil {
return err
}
flags := make(map[string]bool)
for _, flagName := range ctx.FlagNames() {
// This value is already set via arguments or env vars. skip it.
if isSet(ctx, flagName) {
continue
}
flags[flagName] = true
}
for fieldName, tag := range tags {
name := strings.SplitN(tag, ",", 2)[0] // remove omitempty if its there
if _, ok := flags[name]; ok {
field, err := reflections.GetField(i, fieldName)
if err != nil {
return err
}
if f, ok := field.(string); ok && f != "" {
ctx.Set(name, field.(string))
}
}
}
return nil
}
// setUserEnv populates the env argument, if present and unset,
// with dev-USERNAME
func setUserEnv(ctx *cli.Context) error {
argName := "environment"
// Check for env flag, just in case this middleware is misused
hasEnvFlag := false
for _, name := range ctx.FlagNames() {
if name == argName {
hasEnvFlag = true
break
}
}
if !hasEnvFlag {
return nil
}
if isSet(ctx, argName) {
return nil
}
cfg, err := config.LoadConfig()
if err != nil {
return err
}
client := api.NewClient(cfg)
session, err := client.Session.Who(context.Background())
if err != nil {
return err
}
if session.Type() == apitypes.UserSession {
ctx.Set(argName, "dev-"+session.Username())
}
return nil
}
// setSliceDefaults populates any string slice flags with the default value
// if nothing else is set. This is different from the default urfave default
// Value, which will always be included in the string slice options.
func setSliceDefaults(ctx *cli.Context) error {
for _, f := range ctx.Command.Flags {
if psf, ok := f.(placeHolderStringSliceFlag); ok {
name := strings.SplitN(psf.GetName(), ",", 2)[0]
if psf.Default != "" && len(ctx.StringSlice(name)) == 0 {
ctx.Set(name, psf.Default)
}
}
}
return nil
}
func isSet(ctx *cli.Context, name string) bool {
value := ctx.Generic(name)
if value != nil {
v := reflect.Indirect(reflect.ValueOf(value))
switch v.Kind() {
case reflect.Array, reflect.Slice, reflect.String:
return v.Len() != 0
}
return true
}
return false
}
// CheckRequiredFlags ensures that any required flags have been set either on
// the command line, or through envvars/prefs files.
func checkRequiredFlags(ctx *cli.Context) error {
missing := []string{}
for _, f := range ctx.Command.Flags {
var name string
flagMissing := false
switch pf := f.(type) {
case placeHolderStringFlag:
name = strings.SplitN(pf.GetName(), ",", 2)[0]
if pf.Required && ctx.String(name) == "" {
flagMissing = true
}
case placeHolderStringSliceFlag:
name = strings.SplitN(pf.GetName(), ",", 2)[0]
if pf.Required && len(ctx.StringSlice(name)) == 0 {
flagMissing = true
}
}
if flagMissing {
prefix := "-"
if len(name) > 1 {
prefix = "--"
}
missing = append(missing, prefix+name)
}
}
if len(missing) > 0 {
msg := "Missing flags: " + strings.Join(missing, ", ")
return errs.NewUsageExitError(msg, ctx)
}
return nil
}
// checkUpdates checks if there's a torus update available. If so,
// it prints a message to the stdout with the download URL if so.
func checkUpdates(ctx *cli.Context) error {
cfg, err := config.LoadConfig()
if err != nil {
return err
}
client := api.NewClient(cfg)
c := context.Background()
updateInfo, err := client.Updates.Check(c)
if err != nil {
return err
}
if updateInfo.NeedsUpdate {
ui.Info("A new version of Torus is available (%s)! You can download it from %s.", updateInfo.Version, downloadURL)
}
return nil
}