-
Notifications
You must be signed in to change notification settings - Fork 3
/
upstream.go
96 lines (91 loc) · 2.67 KB
/
upstream.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
package cmd
import (
"fmt"
"net/url"
"os"
"strings"
"github.com/octago/sflags/gen/gpflag"
"github.com/spf13/cobra"
"github.com/whitewater-guide/gorge/core"
"github.com/whitewater-guide/gorge/scripts"
)
func init() {
upstreamCmd := &cobra.Command{
Use: "upstream <script> <command> [arguments]",
Short: "Proxies commands to upstream data sources",
}
for _, descriptor := range scripts.Registry.List() {
scriptCmd := &cobra.Command{
Use: fmt.Sprintf("%s <command> <arguments>", descriptor.Name),
Short: fmt.Sprintf("Proxies commands to %s data source", descriptor.Name),
}
gaugesCmd := createGaugesCmd(descriptor)
measurementsCmd := createMeasurementsCmd(descriptor)
scriptCmd.AddCommand(gaugesCmd)
scriptCmd.AddCommand(measurementsCmd)
upstreamCmd.AddCommand(scriptCmd)
}
rootCmd.AddCommand(upstreamCmd)
}
func createGaugesCmd(descriptor core.ScriptDescriptor) *cobra.Command {
cfg := descriptor.DefaultOptions()
noTruncURLs := false
cmd := &cobra.Command{
Use: "gauges [flags]",
Short: fmt.Sprintf("Lists all available gauges for script %s", descriptor.Name),
Run: func(cmd *cobra.Command, args []string) {
var result []core.Gauge
err := Client.PostTo(fmt.Sprintf("upstream/%s/gauges", descriptor.Name), cfg, &result)
if err != nil {
fmt.Printf("Error: %v", err)
os.Exit(1)
} else {
printGauges(result, !noTruncURLs)
}
},
}
gFlags, err := gpflag.Parse(cfg)
if err != nil {
fmt.Printf("Failed to setup flags for script %s: %v\n", descriptor.Name, err)
os.Exit(1)
}
cmd.Flags().AddFlagSet(gFlags)
cmd.Flags().BoolVar(&noTruncURLs, "no-trunc", false, "Do not truncate URLs")
return cmd
}
func createMeasurementsCmd(descriptor core.ScriptDescriptor) *cobra.Command {
cfg := descriptor.DefaultOptions()
use := "measurements {codes}... [flags]"
var args cobra.PositionalArgs
if descriptor.Mode == core.OneByOne {
use = "measurements <code> [flags]"
args = cobra.ExactArgs(1)
}
cmd := &cobra.Command{
Use: use,
Args: args,
Short: fmt.Sprintf("Gets latest measurements from upstream of script %s", descriptor.Name),
Run: func(cmd *cobra.Command, args []string) {
var result []core.Measurement
q := url.Values{}
if len(args) > 0 {
q.Set("codes", strings.Join(args, ","))
}
url := fmt.Sprintf("upstream/%s/measurements?%s", descriptor.Name, q.Encode())
err := Client.PostTo(url, cfg, &result)
if err != nil {
fmt.Printf("Error: %v", err)
os.Exit(1)
} else {
printMeasurements(result)
}
},
}
gFlags, err := gpflag.Parse(cfg)
if err != nil {
fmt.Printf("Failed to setup flags for script %s: %v\n", descriptor.Name, err)
os.Exit(1)
}
cmd.Flags().AddFlagSet(gFlags)
return cmd
}