-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.go
400 lines (351 loc) · 9.66 KB
/
main.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
/*
* Copyright 2023 RapidLoop, Inc.
*
* 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 main
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
"strings"
"time"
"github.com/rapidloop/pgdash/api"
"github.com/rapidloop/pgmetrics"
"github.com/pborman/getopt"
)
const usage = `pgdash is a command-line tool for talking to the pgDash application.
Usage:
pgdash [OPTION]... COMMAND [ARGS]...
General options:
--timeout=SECS individual operation timeout in seconds (default: 60)
--retries=COUNT retry these many times on network or server errors (default: 5)
-i, --input=FILE read from this JSON file instead of stdin
-a, --api-key=APIKEY the API key for your pgDash account
--base-url=URL for use with self-hosted version of pgDash, see docs
-V, --version output version information, then exit
--debug output debugging information
-h, --help[=options] show this help, then exit
--help=variables list environment variables, then exit
Commands:
report SERVERNAME send report for PostgreSQL server SERVERNAME
report-pgbouncer SERVERNAME PGBOUNCERNAME
send PgBouncer report for PgBouncer instance PGBOUNCERNAME
pooling connections for PostgreSQL server SERVERNAME
report-pgpool PGPOOLNAME send report for Pgpool server PGPOOLNAME
For more information, visit <https://pgdash.io>.
`
const variables = `Environment variables:
Usage:
NAME=VALUE [NAME=VALUE] pgdash ...
PDAPIKEY API key for your pgdash account
`
var version string // set during build
var client *api.RestV1Client
const baseURL = "https://app.pgdash.io/api/v1"
type options struct {
// general
timeoutSec uint
retries uint
input string
apiKey string
version bool
help string
helpShort bool
baseURL string
debug bool
}
func (o *options) defaults() {
// general
o.timeoutSec = 60
o.retries = 5
o.input = ""
o.apiKey = ""
o.version = false
o.help = ""
o.helpShort = false
o.baseURL = baseURL
o.debug = false
}
func (o *options) usage(code int) {
fp := os.Stdout
if code != 0 {
fp = os.Stderr
}
if o.helpShort || code != 0 || o.help == "short" {
fmt.Fprint(fp, usage)
} else if o.help == "variables" {
fmt.Fprint(fp, variables)
}
os.Exit(code)
}
func printTry() {
fmt.Fprint(os.Stderr, "Try \"pgdash --help\" for more information.\n")
}
func (o *options) parse() (args []string) {
// make getopt
s := getopt.New()
s.SetUsage(printTry)
s.SetProgram("pgdash")
// general
s.UintVarLong(&o.timeoutSec, "timeout", 0, "")
s.UintVarLong(&o.retries, "retries", 0, "")
s.StringVarLong(&o.input, "input", 'i', "")
s.StringVarLong(&o.apiKey, "api-key", 'a', "")
help := s.StringVarLong(&o.help, "help", 'h', "").SetOptional()
s.BoolVarLong(&o.version, "version", 'V', "").SetFlag()
s.StringVarLong(&o.baseURL, "base-url", 0, "")
s.BoolVarLong(&o.debug, "debug", 0, "").SetFlag()
// parse
s.Parse(os.Args)
if help.Seen() && o.help == "" {
o.help = "short"
}
// check environment variables
if o.apiKey == "" {
if v := os.Getenv("PDAPIKEY"); v != "" {
o.apiKey = v
}
}
// check values
if o.help != "" && o.help != "short" && o.help != "variables" {
printTry()
os.Exit(2)
}
if o.timeoutSec == 0 {
fmt.Fprintln(os.Stderr, "timeout must be greater than 0")
printTry()
os.Exit(2)
}
if o.retries <= 1 {
fmt.Fprintln(os.Stderr, "retries must be greater than 1")
printTry()
os.Exit(2)
}
// help action
if o.helpShort || o.help == "short" || o.help == "variables" {
o.usage(0)
}
// version action
if o.version {
if len(version) == 0 {
version = "devel"
}
fmt.Println("pgdash", version)
os.Exit(0)
}
// check the command
args = s.Args()
if len(args) == 0 {
fmt.Fprintln(os.Stderr, "a command must be specified")
printTry()
os.Exit(2)
}
command := args[0]
if command != "report" && command != "report-pgbouncer" && command != "report-pgpool" {
fmt.Fprintf(os.Stderr, "unknown command '%s'\n", command)
printTry()
os.Exit(2)
}
return args
}
const sixMonths = time.Duration(180 * 24 * time.Hour)
func getReport(o options) *pgmetrics.Model {
// read input file
var data []byte
var err error
if len(o.input) > 0 {
data, err = os.ReadFile(o.input)
} else {
data, err = io.ReadAll(os.Stdin)
}
if err != nil {
log.Fatalf("failed to read input: %v", err)
}
if o.debug {
log.Printf("read input: %d bytes", len(data))
}
// unmarshal json
var model pgmetrics.Model
if err := json.Unmarshal(data, &model); err != nil {
log.Fatalf("invalid input: %v", err)
}
if o.debug {
log.Print("decoded input JSON successfully")
}
// validate the data a bit
ver := model.Metadata.Version
if !strings.HasPrefix(ver, "1.") { // we currently know only about major version 1
log.Fatalf("invalid input: bad schema version '%s' in pgmetrics json",
ver)
}
at := time.Unix(model.Metadata.At, 0)
now := time.Now()
if at.Before(now.Add(-sixMonths)) || at.After(now.Add(sixMonths)) {
log.Fatalf("invalid input: bad collection timestamp in pgmetrics json: %v", at)
}
// append our user agent info into the model
if len(model.Metadata.UserAgent) > 0 {
model.Metadata.UserAgent += " "
}
model.Metadata.UserAgent += "pgdash/"
if len(version) > 0 {
model.Metadata.UserAgent += version
} else {
model.Metadata.UserAgent += "devel"
}
return &model
}
func checkAPIKey(o options) {
if len(o.apiKey) == 0 {
log.Fatal("API key must be specified using the '-a' option for reporting.")
}
if !api.RxAPIKey.MatchString(o.apiKey) {
log.Fatalf("invalid API key format '%s'", o.apiKey)
}
}
func cmdReport(o options, args []string) {
// check API key
checkAPIKey(o)
// check server
if len(args) == 0 {
log.Fatal("Server name needs to be specified, try --help for help.")
}
if len(args) != 1 {
log.Fatal("invalid syntax for report command, try --help for help.")
}
if !api.RxServer.MatchString(args[0]) {
log.Fatal(`bad server name, must be 1-64 chars A-Z, a-z, 0-9, "-", "_", and ".".`)
}
// check the model (must not have pgbouncer info)
model := getReport(o)
if model.PgBouncer != nil {
log.Fatal("use report-pgbouncer to send PgBouncer information")
}
// call the api
_, err := client.Report(api.ReqReport{
APIKey: o.apiKey,
Server: args[0],
Data: *model,
})
if errh, ok := err.(*api.RestV1ClientError); ok {
if errh.Code() == 400 {
log.Fatal("invalid API key or account limit reached")
}
if errh.Code() == 500 {
log.Fatal("internal server error")
}
}
if err != nil {
log.Fatalf("API request failed: %v", err)
}
}
func cmdReportPgBouncer(o options, args []string) {
// check API key
checkAPIKey(o)
// check args
if len(args) != 2 {
log.Fatal("invalid syntax for report-pgbouncer command, try --help for help.")
}
if !api.RxServer.MatchString(args[0]) {
log.Fatal(`bad server name, must be 1-64 chars A-Z, a-z, 0-9, "-", "_", and ".".`)
}
if !api.RxServer.MatchString(args[1]) {
log.Fatal(`bad PgBouncer name, must be 1-64 chars A-Z, a-z, 0-9, "-", "_", and ".".`)
}
// check the model (must have pgbouncer info)
model := getReport(o)
if model == nil || model.PgBouncer == nil {
log.Fatal("pgmetrics report does not contain PgBouncer information")
}
// call the api
_, err := client.ReportPgBouncer(api.ReqReportPgBouncer{
APIKey: o.apiKey,
Server: args[0],
PgBouncer: args[1],
Data: *model,
})
if errh, ok := err.(*api.RestV1ClientError); ok {
if errh.Code() == 400 {
log.Fatalf("invalid API key or server %q not found", args[0])
}
if errh.Code() == 500 {
log.Fatal("internal server error")
}
}
if err != nil {
log.Fatalf("API request failed: %v", err)
}
}
func cmdReportPgpool(o options, args []string) {
// check API key
checkAPIKey(o)
// check args
if len(args) == 0 {
log.Fatal("pgpool name needs to be specified, try --help for help.")
}
if len(args) != 1 {
log.Fatal("invalid syntax for report-pgpool command, try --help for help.")
}
if !api.RxServer.MatchString(args[0]) {
log.Fatal(`bad pgpool name, must be 1-64 chars A-Z, a-z, 0-9, "-", "_", and ".".`)
}
// check the model (must have pgbouncer info)
model := getReport(o)
if model == nil || model.Pgpool == nil {
log.Fatal("pgmetrics report does not contain Pgpool information")
}
// call the api
_, err := client.ReportPgpool(api.ReqReportPgpool{
APIKey: o.apiKey,
Pgpool: args[0],
Data: *model,
})
if errh, ok := err.(*api.RestV1ClientError); ok {
if errh.Code() == 400 {
log.Fatalf("invalid API key or server %q not found", args[0])
}
if errh.Code() == 500 {
log.Fatal("internal server error")
}
}
if err != nil {
log.Fatalf("API request failed: %v", err)
}
}
func main() {
var o options
o.defaults()
args := o.parse()
command := args[0]
log.SetPrefix("pgdash: ")
if o.debug {
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
} else {
log.SetFlags(0)
}
// create the client
tout := time.Duration(o.timeoutSec) * time.Second
client = api.NewRestV1Client(o.baseURL, tout, int(o.retries))
client.SetDebug(o.debug)
switch command {
case "report":
cmdReport(o, args[1:])
case "report-pgbouncer":
cmdReportPgBouncer(o, args[1:])
case "report-pgpool":
cmdReportPgpool(o, args[1:])
}
}