-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
269 lines (213 loc) · 8.49 KB
/
Copy pathconfig.go
File metadata and controls
269 lines (213 loc) · 8.49 KB
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
package main
import (
"flag"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"time"
"go.uber.org/zap"
)
// LumoConfig is the global application configuration derived from CLI flags
type LumoConfig struct {
Endpoint string
Service string
Node string
ClusterName string
Database string
ReplSet string
Groups map[string]struct{}
OutDir string
Interval string
Start time.Time
End time.Time
Token string
DipperToken string
DipperProjectID string
Hostname string
SyncDir string
Debug bool
InsecureTLS bool
}
const (
timeFormat = "2006-01-02 15:04:05"
getGraphsCommand = "get-graphs"
listGroupsCommand = "list-groups"
listServicesCommand = "list-services"
dipperSyncCommand = "dipper-sync"
)
// lastDurationRe is a regular expression to parse the last duration flag
var lastDurationRe = regexp.MustCompile(`^([1-9]\d*)([mhd])$`)
func parseFlags() (string, LumoConfig) {
if len(os.Args) < 2 {
printUsage()
os.Exit(0)
}
command := os.Args[1]
var cfg LumoConfig
var startStr, endStr, lastStr, groupsStr string
getCmd, listCmd, listServicesCmd, dipperSyncCmd := setupFlagSets(&cfg, &startStr, &endStr, &lastStr, &groupsStr)
var activeCmd *flag.FlagSet
switch command {
case getGraphsCommand:
activeCmd = getCmd
case listGroupsCommand:
activeCmd = listCmd
case listServicesCommand:
activeCmd = listServicesCmd
case dipperSyncCommand:
activeCmd = dipperSyncCmd
default:
printUsage()
os.Exit(1)
}
if err := activeCmd.Parse(os.Args[2:]); err != nil {
fmt.Fprintf(os.Stderr, "error parsing flags: %v\n", err)
os.Exit(1)
}
initLogger(cfg.Debug)
configureHTTPClient(cfg.InsecureTLS)
if command == getGraphsCommand || command == listServicesCommand {
cfg.Token = resolveToken(cfg.Token, "PMM_TOKEN")
}
if command == getGraphsCommand {
cfg.Start, cfg.End = resolveTimeRanges(startStr, endStr, lastStr)
cfg.Groups = parseGroups(groupsStr)
}
if command == dipperSyncCommand {
cfg.DipperToken = resolveToken(cfg.DipperToken, "DIPPER_TOKEN")
// The sole positional argument is the directory of images to upload
cfg.SyncDir = activeCmd.Arg(0)
}
return command, cfg
}
func setupFlagSets(cfg *LumoConfig, startStr, endStr, lastStr, groupsStr *string) (*flag.FlagSet, *flag.FlagSet, *flag.FlagSet, *flag.FlagSet) {
getGraphsCmd := flag.NewFlagSet(getGraphsCommand, flag.ExitOnError)
listGroupsCmd := flag.NewFlagSet(listGroupsCommand, flag.ExitOnError)
listServicesCmd := flag.NewFlagSet(listServicesCommand, flag.ExitOnError)
dipperSyncCmd := flag.NewFlagSet(dipperSyncCommand, flag.ExitOnError)
getGraphsCmd.StringVar(&cfg.Endpoint, "endpoint", "", "PMM URL (required)")
getGraphsCmd.StringVar(&cfg.Service, "service", "", "PMM Service name (required)")
getGraphsCmd.StringVar(&cfg.Node, "node", "", "PMM Node name (optional)")
getGraphsCmd.StringVar(&cfg.ClusterName, "cluster-name", "", "For cluster-based graphs (ie: PXC, Mongo, etc) (optional)")
getGraphsCmd.StringVar(&cfg.Database, "database", "", "Filter for PostgreSQL databases (optional)")
getGraphsCmd.StringVar(&cfg.ReplSet, "replset", "", "MongoDB replica set name (optional)")
getGraphsCmd.StringVar(groupsStr, "groups", "", "Comma-separated list of graph groups render (required)")
getGraphsCmd.StringVar(&cfg.OutDir, "outdir", "", "Output directory for graphs (optional, defaults to service name)")
getGraphsCmd.StringVar(&cfg.Interval, "interval", "5m", "Interval duration for graphs (e.g., 5m, 1h)")
getGraphsCmd.StringVar(startStr, "start", "", "Start time (YYYY-MM-DD HH:MM:SS, defaults to 24h ago)")
getGraphsCmd.StringVar(endStr, "end", "", "End time (YYYY-MM-DD HH:MM:SS, defaults to now)")
getGraphsCmd.StringVar(lastStr, "last", "", "Relative lookback window (e.g., 30m, 12h, 7d); mutually exclusive with -start/-end")
getGraphsCmd.StringVar(&cfg.Token, "token", "", "PMM API token (can also use PMM_TOKEN env var)")
getGraphsCmd.BoolVar(&cfg.Debug, "debug", false, "Print detailed HTTP request and response information")
getGraphsCmd.BoolVar(&cfg.InsecureTLS, "insecure-tls", false, "Disable TLS certificate verification (for self-signed certs)")
listGroupsCmd.BoolVar(&cfg.Debug, "debug", false, "Print detailed HTTP request and response information")
listGroupsCmd.BoolVar(&cfg.InsecureTLS, "insecure-tls", false, "Disable TLS certificate verification (for self-signed certs)")
listServicesCmd.StringVar(&cfg.Endpoint, "endpoint", "", "PMM endpoint URL (required)")
listServicesCmd.StringVar(&cfg.Token, "token", "", "Service account PMM API token (can also use PMM_TOKEN env var)")
listServicesCmd.BoolVar(&cfg.Debug, "debug", false, "Print detailed HTTP request and response information")
listServicesCmd.BoolVar(&cfg.InsecureTLS, "insecure-tls", false, "Disable TLS certificate verification (for self-signed certs)")
dipperSyncCmd.StringVar(&cfg.DipperToken, "token", "", "Dipper API token (required, can also use DIPPER_TOKEN env var)")
dipperSyncCmd.StringVar(&cfg.DipperProjectID, "projectid", "", "Dipper project ID (required)")
dipperSyncCmd.StringVar(&cfg.Hostname, "hostname", "", "Hostname associated with the images (required)")
dipperSyncCmd.Usage = dipperSyncUsage(dipperSyncCmd)
return getGraphsCmd, listGroupsCmd, listServicesCmd, dipperSyncCmd
}
// dipperSyncUsage returns a usage function that documents the positional argument.
func dipperSyncUsage(fs *flag.FlagSet) func() {
return func() {
fmt.Fprintf(os.Stderr, "Usage: %s dipper-sync [flags] <image-directory>\n\n", os.Args[0])
fmt.Fprintf(os.Stderr, "Compresses the images in <image-directory> and uploads them to Dipper.\n\n")
fmt.Fprintf(os.Stderr, "Flags:\n")
fs.PrintDefaults()
}
}
// resolveToken returns the token from the -token flag, falling back to the
// named environment variable. Providing both is an error.
func resolveToken(cliToken, envVar string) string {
envToken := os.Getenv(envVar)
if cliToken != "" && envToken != "" {
zap.S().Fatalf("error: both -token flag and %s environment variable are set. Please provide only one.", envVar)
}
if cliToken == "" {
return envToken
}
return cliToken
}
func resolveTimeRanges(startStr, endStr, lastStr string) (time.Time, time.Time) {
if lastStr != "" {
if startStr != "" || endStr != "" {
zap.S().Fatalf("%v", ErrConflictingTimeFlags)
}
dur, err := parseLastDuration(lastStr)
if err != nil {
zap.S().Fatalf("%v", err)
}
end := time.Now()
return end.Add(-dur), end
}
var start, end time.Time
var err error
if startStr == "" {
start = time.Now().Add(-24 * time.Hour)
} else {
start, err = time.ParseInLocation(timeFormat, startStr, time.Local)
if err != nil {
zap.S().Fatalf("error parsing -start time: %v", err)
}
}
if endStr == "" {
end = time.Now()
} else {
end, err = time.ParseInLocation(timeFormat, endStr, time.Local)
if err != nil {
zap.S().Fatalf("error parsing -end time: %v", err)
}
}
return start, end
}
// parseLastDuration parses a relative duration like "30m", "12h", or "7d".
func parseLastDuration(s string) (time.Duration, error) {
matches := lastDurationRe.FindStringSubmatch(s)
if matches == nil {
return 0, ErrInvalidLastDuration
}
n, err := strconv.Atoi(matches[1])
if err != nil {
return 0, fmt.Errorf("%w: %w", ErrInvalidLastDuration, err)
}
switch matches[2] {
case "m":
return time.Duration(n) * time.Minute, nil
case "h":
return time.Duration(n) * time.Hour, nil
case "d":
return time.Duration(n) * 24 * time.Hour, nil
default:
return 0, ErrInvalidLastDuration
}
}
// parseGroups splits the comma-separated -groups flag into a set, trimming
// whitespace and discarding empty entries.
func parseGroups(s string) map[string]struct{} {
groups := make(map[string]struct{})
for g := range strings.SplitSeq(s, ",") {
g = strings.TrimSpace(g)
if g == "" {
continue
}
groups[g] = struct{}{}
}
return groups
}
func printUsage() {
fmt.Fprintf(os.Stderr, "--- Lumograph %s ---\n", Version)
fmt.Fprintf(os.Stderr, "Usage of %s:\n\n", os.Args[0])
fmt.Fprintf(os.Stderr, "Commands:\n")
fmt.Fprintf(os.Stderr, " get-graphs\t\tGenerates charts by querying a PMM endpoint.\n")
fmt.Fprintf(os.Stderr, " list-groups\t\tLists all available graph groups.\n")
fmt.Fprintf(os.Stderr, " list-services\t\tLists all available services from the PMM inventory API.\n")
fmt.Fprintf(os.Stderr, " dipper-sync\t\tCompresses a directory of images and uploads them to Dipper.\n\n")
fmt.Fprintf(os.Stderr, "Run '%s <command> -h' to see flags for a specific command.\n", os.Args[0])
}