-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
241 lines (212 loc) · 6.48 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
// Backup tool for Grafana.
// Copyright (C) 2016-2017 Alexander I.Grafov <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// ॐ तारे तुत्तारे तुरे स्व
package main
import (
"errors"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/grafana-tools/sdk"
)
var (
// Connection flags.
flagServerURL = flag.String("url", "", "URL of Grafana server")
flagServerKey = flag.String("key", "", "API key of Grafana server")
flagTimeout = flag.Duration("timeout", 6*time.Minute, "read flagTimeout for interacting with Grafana in seconds")
// Dashboard matching flags.
flagTags = flag.String("tag", "", "dashboard should match all these tags")
flagBoardTitle = flag.String("title", "", "dashboard title should match name")
flagStarred = flag.Bool("starred", false, "only match starred dashboards")
// Common flags.
flagApplyFor = flag.String("apply-for", "auto", `apply operation only for some kind of objects, available values are "auto", "all", "dashboards", "datasources", "users"`)
flagForce = flag.Bool("force", false, "force overwrite of existing objects")
flagVerbose = flag.Bool("verbose", false, "verbose output")
flagDir = flag.String("dir", "backup", "A directory to write backup files to or read them from.")
// The args after flags.
argCommand string
argPath = "*"
// Environment variables to read from
tokenKey = "GRAFANA_TOKEN" // Becomes flagServerKey
urlKey = "GRAFANA_URL" // Becomes flagServerURL
)
var cancel = make(chan os.Signal, 1)
// TODO use first $XDG_CONFIG_HOME then try $XDG_CONFIG_DIRS
var tryConfigDirs = []string{"~/.config/grafana+", ".grafana+"}
func main() {
// TODO parse config here
flag.Parse()
// We need at minimum a command to execute so throw the printUsage if we don't have > 0 args
if flag.NArg() == 0 {
printUsage()
os.Exit(2)
}
// Set Token and URL from environment variables if they are present.
varToken := os.Getenv(tokenKey)
varURL := os.Getenv(urlKey)
if varToken != "" {
*flagServerKey = varToken
}
if varURL != "" {
*flagServerURL = varURL
}
var args = flag.Args()
// First mandatory argument is command.
argCommand = args[0]
// Second optional argument is file path.
if flag.NArg() > 1 {
argPath = args[1]
}
signal.Notify(cancel, os.Interrupt, syscall.SIGTERM)
switch argCommand {
case "backup":
// TODO fix logic accordingly with apply-for
doBackup(serverInstance, applyFor, matchDashboard)
case "restore":
// TODO fix logic accordingly with apply-for
doRestore(serverInstance, applyFor, matchFilename)
case "ls":
// TODO fix logic accordingly with apply-for
doObjectList(serverInstance, applyFor, matchDashboard)
case "ls-files":
// TODO merge this command with ls
doFileList(matchFilename, applyFor, matchDashboard)
case "config-set":
// TBD
// doConfigSet()
fmt.Fprintln(os.Stderr, "Command config-set not yet implemented!")
case "config-get":
// TBD
// doConfigGet()
fmt.Fprintln(os.Stderr, "Command config-get not yet implemented!")
default:
fmt.Fprintf(os.Stderr, fmt.Sprintf("unknown command: %s\n\n", args[0]))
printUsage()
os.Exit(1)
}
}
type command struct {
grafana *sdk.Client
applyHierarchically bool
applyForBoards bool
applyForDs bool
applyForUsers bool
boardTitle string
tags []string
starred bool
filenames []string
force bool
verbose bool
directory string
}
type option func(*command) error
func serverInstance(c *command) error {
if *flagServerURL == "" {
return errors.New("you should provide the server URL")
}
if *flagServerKey == "" {
return errors.New("you should provide the server API key")
}
c.grafana = sdk.NewClient(*flagServerURL, *flagServerKey, &http.Client{Timeout: *flagTimeout})
return nil
}
func applyFor(c *command) error {
if *flagApplyFor == "" {
return fmt.Errorf("flag '-apply-for' provided with empty argument")
}
for _, objectKind := range strings.Split(strings.ToLower(*flagApplyFor), ",") {
switch objectKind {
case "auto":
c.applyHierarchically = true
c.applyForBoards = true
c.applyForDs = true
case "all":
c.applyForBoards = true
c.applyForDs = true
c.applyForUsers = true
case "dashboards":
c.applyForBoards = true
case "datasources":
c.applyForDs = true
case "users":
c.applyForUsers = true
default:
return fmt.Errorf("unknown argument %s", objectKind)
}
}
return nil
}
func matchDashboard(c *command) error {
c.boardTitle = *flagBoardTitle
c.starred = *flagStarred
if *flagTags != "" {
for _, tag := range strings.Split(*flagTags, ",") {
c.tags = append(c.tags, strings.TrimSpace(tag))
}
}
return nil
}
func matchFilename(c *command) error {
var (
files []string
err error
)
if files, err = filepath.Glob(argPath); err != nil {
return err
}
if len(files) == 0 {
return errors.New("there are no files matching selected pattern found")
}
c.filenames = files
return nil
}
func initCommand(opts ...option) *command {
var (
cmd = &command{force: *flagForce, verbose: *flagVerbose, directory: *flagDir}
err error
)
for _, opt := range opts {
if err = opt(cmd); err != nil {
fmt.Fprintf(os.Stderr, fmt.Sprintf("Error: %s\n\n", err))
printUsage()
os.Exit(1)
}
}
return cmd
}
func printUsage() {
fmt.Println(`Backup tool for Grafana.
Copyright (C) 2016-2017 Alexander I.Grafov <[email protected]>
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under conditions of GNU GPL license v3.
Usage: $ grafana-backup [flags] <command>
Available commands are: backup, restore, ls, ls-files, info, config, help.
Call 'grafana-backup help <command>' for details about the command.
`)
flag.PrintDefaults()
}
func exitBySignal() {
fmt.Fprintf(os.Stderr, "Execution was cancelled.\n")
os.Exit(1)
}