This repository was archived by the owner on Jan 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathget.go
85 lines (75 loc) · 1.89 KB
/
get.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
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
log "github.com/Sirupsen/logrus"
"github.com/retzkek/grafanactl/gapi"
)
var getCmd = &Command{
Name: "get",
Usage: "[OPTIONS] [DASHBOARD...]",
Summary: "Retrieve dashboards and save to file.",
Help: `The get command retrieves dashboards and saves them to file.
If no dashboards are specified, retrieve all available dashboards.`,
}
func getFunc(client *gapi.Client, cmd *Command, args []string) error {
var dashboards []string
if len(args) == 0 {
dashboards = make([]string, 0)
dl, err := client.ListDashboards()
if err != nil {
log.Error(err)
return fmt.Errorf("error getting dashboard list")
}
for _, d := range *dl {
dashboards = append(dashboards, d.URI)
}
} else {
dashboards = args
}
for _, d := range dashboards {
dash, err := client.Dashboard(d)
if err != nil {
log.WithField("dashboard", d).Error(err)
return fmt.Errorf("error getting dashboard")
}
filename := filepath.Join(*path, d) + ".json"
log.WithFields(log.Fields{
"dashboard": d,
"file": filename,
}).Info("saving dashboard")
if err := writeDashboard(dash, filename); err != nil {
log.WithField("dashboard", d).Error(err)
return fmt.Errorf("error saving dashboard to file")
}
}
return nil
}
func writeDashboard(dash *gapi.Dashboard, filename string) error {
ll := log.WithFields(log.Fields{
"dashboard": dash.Meta.Slug,
"file": filename,
"where": "writeDashboard",
})
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
d, err := json.MarshalIndent(dash.Model, "", "\t")
if err != nil {
ll.Error(err)
return fmt.Errorf("error marshalling dashboard to JSON")
}
if _, err = f.Write(d); err != nil {
ll.Error(err)
return fmt.Errorf("error writing JSON to file")
}
ll.Debug("successfully wrote file")
return nil
}
func init() {
getCmd.Function = getFunc
}