forked from cirocosta/grafana-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpull.go
79 lines (63 loc) · 1.52 KB
/
pull.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
package main
import (
"context"
"os"
"path"
"github.com/cirocosta/grafana-sync/grafana"
"github.com/pkg/errors"
)
type pullCommand struct{}
func (p *pullCommand) Execute(args []string) (err error) {
ctx, cancel := context.WithCancel(context.Background())
go handleSignals(cancel)
client := grafana.NewClient(grafana.ClientConfig{
Address: config.Address,
Verbose: config.Verbose,
AccessToken: config.Auth.AccessToken,
Username: config.Auth.Username,
Password: config.Auth.Password,
})
refs, err := client.ListDashboardSearchEntries(ctx)
if err != nil {
return
}
var dashboard map[string]interface{}
for _, ref := range refs {
dashboardFolderInFs := path.Join(string(config.Directory), ref.Folder)
err = eventuallyCreateDirectory(dashboardFolderInFs)
if err != nil {
return
}
dashboard, err = client.GetDashboard(ctx, ref.Uid)
if err != nil {
return
}
err = grafana.SaveToDisk(path.Join(dashboardFolderInFs, ref.Title)+".json", dashboard)
if err != nil {
return
}
}
return
}
func eventuallyCreateDirectory(dir string) (err error) {
finfo, err := os.Stat(dir)
if err != nil {
if os.IsNotExist(err) {
err = os.MkdirAll(dir, 0755)
if err != nil {
err = errors.Wrapf(err,
"failed to create directory %s", dir)
return
}
return
}
err = errors.Wrapf(err,
"unexpected failure checking directory %s", dir)
return
}
if !finfo.IsDir() {
err = errors.Errorf("location %s already exists and is not a directory", dir)
return
}
return
}