This repository has been archived by the owner on Mar 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
interactive.go
546 lines (510 loc) · 13.7 KB
/
interactive.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
package route
import (
"fmt"
"os"
"strconv"
"github.com/gogo/protobuf/types"
"github.com/olekukonko/tablewriter"
"github.com/pkg/errors"
"github.com/solo-io/gloo/pkg/api/types/v1"
"github.com/solo-io/gloo/pkg/storage"
"gopkg.in/AlecAivazis/survey.v1"
"gopkg.in/AlecAivazis/survey.v1/core"
)
// SelectionResult groups routes into selected and not selected list
type SelectionResult struct {
Selected []*v1.Route
NotSelected []*v1.Route
}
// SelectInteractive selectes one or more routes interactively. If multi is true
// it enables selecting multiple routess
func SelectInteractive(routes []*v1.Route, multi bool) (*SelectionResult, error) {
// group routes by upstream so that selection list is smaller
routesByUpstream := make(map[string][]*v1.Route)
for _, r := range routes {
for _, d := range Destinations(r) {
routesByUpstream[d.Upstream] = append(routesByUpstream[d.Upstream], r)
}
}
upstreams := make([]string, len(routesByUpstream))
i := 0
for k := range routesByUpstream {
upstreams[i] = k
i++
}
var upstream string
if err := survey.AskOne(&survey.Select{
Message: "Please select the upstream for the route:",
Options: upstreams}, &upstream, survey.Required); err != nil {
return nil, err
}
routesByName := make(map[string]*v1.Route)
routeOptions := []string{}
for _, r := range routesByUpstream[upstream] {
name := toSelectionOption(r)
routeOptions = append(routeOptions, name)
routesByName[name] = r
}
if multi {
core.MarkedOptionIcon = "☑"
core.UnmarkedOptionIcon = "☐"
var selections []string
if err := survey.AskOne(&survey.MultiSelect{
Message: "Please select routes:",
Options: routeOptions,
}, &selections, survey.Required); err != nil {
return nil, err
}
selected := make([]*v1.Route, len(selections))
for i, r := range selections {
selected[i] = routesByName[r]
}
return &SelectionResult{
Selected: selected,
NotSelected: notSelected(routes, selected),
}, nil
}
// single
var selection string
if err := survey.AskOne(&survey.Select{
Message: "Please select a route:",
Options: routeOptions,
}, &selection, survey.Required); err != nil {
return nil, err
}
selected := []*v1.Route{routesByName[selection]}
return &SelectionResult{
Selected: selected,
NotSelected: notSelected(routes, selected),
}, nil
}
func toSelectionOption(r *v1.Route) string {
matcher, rType, verb, header := Matcher(r)
hasExtensions := r.Extensions != nil && len(r.Extensions.Fields) != 0
return fmt.Sprintf("%s: %s. Verb: %s Headers: %s Has Extensions: %v",
rType, matcher, verb, header, hasExtensions)
}
// TODO use a map if this is too slow
func notSelected(routes []*v1.Route, selected []*v1.Route) []*v1.Route {
var filtered []*v1.Route
Route:
for _, r := range routes {
for _, s := range selected {
if r == s {
continue Route
}
}
filtered = append(filtered, r)
}
return filtered
}
// Interactive allows user to create/update a route definition interactively
func Interactive(sc storage.Interface, r *v1.Route) error {
upstreams, err := sc.V1().Upstreams().List()
if err != nil {
return errors.Wrap(err, "unable to get upstreams")
}
if err := matcher(r); err != nil {
return err
}
if err := destination(r, upstreams); err != nil {
return err
}
if err := extensions(r); err != nil {
return err
}
return nil
}
type request struct {
path string
verbs []string
headers map[string]string
}
func matcher(r *v1.Route) error {
oldValues := getMatcherValues(r)
prompt := &survey.Select{
Message: "Please select the type of matcher for the route:",
Options: []string{"event", "path-prefix", "path-regex", "path-exact"},
Default: oldValues.matcherType,
}
var mType string
if err := survey.AskOne(prompt, &mType, survey.Required); err != nil {
return err
}
switch mType {
case "event":
prompt := &survey.Input{
Message: "Please enter the event type:",
Default: oldValues.matcher,
}
var event string
if err := survey.AskOne(prompt, &event, survey.Required); err != nil {
return err
}
r.Matcher = &v1.Route_EventMatcher{
EventMatcher: &v1.EventMatcher{EventType: event},
}
case "path-prefix":
request, err := requestMatcher(oldValues)
if err != nil {
return err
}
r.Matcher = &v1.Route_RequestMatcher{
RequestMatcher: &v1.RequestMatcher{
Path: &v1.RequestMatcher_PathPrefix{PathPrefix: request.path},
Verbs: request.verbs,
Headers: request.headers,
},
}
case "path-regex":
request, err := requestMatcher(oldValues)
if err != nil {
return err
}
r.Matcher = &v1.Route_RequestMatcher{
RequestMatcher: &v1.RequestMatcher{
Path: &v1.RequestMatcher_PathRegex{PathRegex: request.path},
Verbs: request.verbs,
Headers: request.headers,
},
}
case "path-exact":
request, err := requestMatcher(oldValues)
if err != nil {
return err
}
r.Matcher = &v1.Route_RequestMatcher{
RequestMatcher: &v1.RequestMatcher{
Path: &v1.RequestMatcher_PathExact{PathExact: request.path},
Verbs: request.verbs,
Headers: request.headers,
},
}
}
if mType != "event" {
if err := prefixRewrite(r); err != nil {
return err
}
}
return nil
}
type matcherValues struct {
matcherType string
matcher string
verbs []string
headers map[string]string
}
func getMatcherValues(r *v1.Route) matcherValues {
switch m := r.GetMatcher().(type) {
case *v1.Route_EventMatcher:
return matcherValues{
matcherType: "event",
matcher: m.EventMatcher.EventType,
}
case *v1.Route_RequestMatcher:
switch p := m.RequestMatcher.GetPath().(type) {
case *v1.RequestMatcher_PathExact:
return matcherValues{
matcherType: "path-exact",
matcher: p.PathExact,
verbs: m.RequestMatcher.Verbs,
headers: m.RequestMatcher.Headers,
}
case *v1.RequestMatcher_PathPrefix:
return matcherValues{
matcherType: "path-prefix",
matcher: p.PathPrefix,
verbs: m.RequestMatcher.Verbs,
headers: m.RequestMatcher.Headers,
}
case *v1.RequestMatcher_PathRegex:
return matcherValues{
matcherType: "path-regex",
matcher: p.PathRegex,
verbs: m.RequestMatcher.Verbs,
headers: m.RequestMatcher.Headers,
}
}
}
return matcherValues{
matcherType: "path-prefix",
matcher: "",
}
}
func requestMatcher(oldValues matcherValues) (*request, error) {
core.MarkedOptionIcon = "☑"
core.UnmarkedOptionIcon = "☐"
httpMethods := []string{"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"}
var questions = []*survey.Question{
{
Name: "path",
Prompt: &survey.Input{
Message: "Please enter the path for the matcher:",
Default: oldValues.matcher,
},
Validate: survey.Required,
},
{
Name: "verb",
Prompt: &survey.MultiSelect{
Message: "Please select all the HTTP requests methods that are applicable:",
Options: httpMethods,
Default: oldValues.verbs,
},
},
}
answers := struct {
Path string
Verb []string
}{}
if err := survey.Ask(questions, &answers); err != nil {
return nil, err
}
// handle case for all
if len(answers.Verb) == 0 || len(answers.Verb) == len(httpMethods) {
answers.Verb = nil
}
// headers
// TODO better editing instead of just replacing
headers := make(map[string]string)
hasHeaders := false
if len(oldValues.headers) != 0 {
// print headers
printHeaders(oldValues.headers)
replaceHeaders := false
if err := survey.AskOne(&survey.Confirm{Message: "Do you want to replace existing HTTP headers?"}, &replaceHeaders, nil); err != nil {
return nil, err
}
if !replaceHeaders {
headers = oldValues.headers
hasHeaders = false
} else {
hasHeaders = true
}
} else {
if err := survey.AskOne(&survey.Confirm{Message: "Do you want to set HTTP headers?"}, &hasHeaders, nil); err != nil {
return nil, err
}
}
for hasHeaders {
questions = []*survey.Question{
{
Name: "key",
Prompt: &survey.Input{Message: "Please enter HTTP header name:"},
Validate: survey.Required,
},
{
Name: "value",
Prompt: &survey.Input{Message: "Please enter HTTP header value:"},
},
}
header := struct {
Key string
Value string
}{}
if err := survey.Ask(questions, &header); err != nil {
return nil, err
}
headers[header.Key] = header.Value
if err := survey.AskOne(&survey.Confirm{Message: "Do you want to more HTTP headers?"}, &hasHeaders, nil); err != nil {
return nil, err
}
}
return &request{path: answers.Path, verbs: answers.Verb, headers: headers}, nil
}
func printHeaders(m map[string]string) {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Header", "Value"})
for k, v := range m {
table.Append([]string{k, v})
}
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.Render()
fmt.Printf("\n\n\n") // keep survey happy
}
func prefixRewrite(r *v1.Route) error {
if r.PrefixRewrite != "" {
fmt.Printf("Current prefix rewrite: %s\n\n\n", r.PrefixRewrite)
}
var prefix string
if err := survey.AskOne(&survey.Input{
Message: "Please enter the rewrite prefix (leave empty if you don't want rewrite):",
}, &prefix, nil); err != nil {
return err
}
r.PrefixRewrite = prefix
return nil
}
func destination(r *v1.Route, upstreams []*v1.Upstream) error {
replace, err := askReplaceDestination(r)
if err != nil {
return err
}
if !replace {
return nil
}
var destinations []*Destination
ask := true
for ask {
d, err := askDestination(upstreams)
if err != nil {
return err
}
destinations = append(destinations, d)
err = survey.AskOne(&survey.Confirm{Message: "Does the route have more destinations?"}, &ask, nil)
if err != nil {
return err
}
}
switch len(destinations) {
case 0:
return errors.New("expected at least one destination for the route")
case 1:
r.SingleDestination = toAPIDestination(destinations[0])
default:
wd := make([]*v1.WeightedDestination, len(destinations))
for i, d := range destinations {
var weight int
q := fmt.Sprintf("Please enter a weight for destination '%s' >", d)
err := survey.AskOne(&survey.Input{Message: q}, &weight, func(val interface{}) error {
w, err := strconv.Atoi(val.(string))
if err != nil {
return errors.New("weight must be an integer greather than 0")
}
if w <= 0 {
return errors.New("weight must be an integer greater than 0")
}
return nil
})
if err != nil {
return err
}
wd[i] = &v1.WeightedDestination{
Destination: toAPIDestination(d),
Weight: uint32(weight),
}
}
r.MultipleDestinations = wd
}
return nil
}
func askReplaceDestination(r *v1.Route) (bool, error) {
// check if we want to update destinations
old := Destinations(r)
if len(old) != 0 {
printDestination(old)
replace := false
if err := survey.AskOne(&survey.Confirm{Message: "Do you want to replace existing destination?"}, &replace, nil); err != nil {
return false, err
}
return replace, nil
}
// if we don't have any existing destination we always replace
return true, nil
}
func askDestination(upstreams []*v1.Upstream) (*Destination, error) {
upstreamNames := make([]string, len(upstreams))
for i, u := range upstreams {
upstreamNames[i] = u.Name
}
var name string
err := survey.AskOne(&survey.Select{
Message: "Please select an upstream:",
Options: upstreamNames,
}, &name, survey.Required)
if err != nil {
return nil, err
}
var selectedUpstream *v1.Upstream
for _, u := range upstreams {
if u.Name == name {
selectedUpstream = u
break
}
}
if len(selectedUpstream.Functions) == 0 {
return &Destination{Upstream: name}, nil
}
functionNames := make([]string, len(selectedUpstream.Functions))
for i, f := range selectedUpstream.Functions {
functionNames[i] = f.Name
}
var fname string
err = survey.AskOne(&survey.Select{
Message: "Please select a function:",
Options: functionNames,
}, &fname, survey.Required)
if err != nil {
return nil, err
}
return &Destination{Upstream: name, Function: fname}, nil
}
func printDestination(list []Destination) {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Upstream", "Function"})
for _, d := range list {
table.Append([]string{d.Upstream, d.Function})
}
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.Render()
fmt.Printf("\n\n\n") // keep survey happy
}
func toAPIDestination(d *Destination) *v1.Destination {
if d.Function != "" {
return &v1.Destination{
DestinationType: &v1.Destination_Function{
Function: &v1.FunctionDestination{
UpstreamName: d.Upstream,
FunctionName: d.Function},
},
}
}
return &v1.Destination{
DestinationType: &v1.Destination_Upstream{
Upstream: &v1.UpstreamDestination{Name: d.Upstream},
},
}
}
// TODO better editing of existing extensions instead of just replacing
func extensions(r *v1.Route) error {
if r.Extensions != nil && len(r.Extensions.Fields) != 0 {
printExtensions(r)
replace := false
if err := survey.AskOne(&survey.Confirm{Message: "Do you want to replace existing extensions?"}, &replace, nil); err != nil {
return err
}
if !replace {
return nil
}
}
extensionOptions := make([]string, len(availableExtensions)+1)
extensionOptions[0] = "None"
for i, e := range availableExtensions {
extensionOptions[i+1] = e.name
}
question := &survey.Select{
Message: "Select the route extension you want to set:",
Options: extensionOptions,
}
r.Extensions = &types.Struct{}
var choice string
for choice != "None" {
if err := survey.AskOne(question, &choice, survey.Required); err != nil {
return err
}
for _, e := range availableExtensions {
if e.name == choice {
if err := e.handler(r.Extensions); err != nil {
return err
}
break
}
}
printExtensions(r)
}
return nil
}
func printExtensions(r *v1.Route) {
// additional newlines at the end necessary to make it work with survey
fmt.Printf("\nCurrent extensions:\n%s\n\n\n", Extension(r))
}