-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconfig.go
267 lines (251 loc) · 7.05 KB
/
config.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
/* See the file "LICENSE.txt" for the full license governing this code. */
// Global configuration with disk caching
// Parsing of command line flags
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
const (
myName = "snaprd"
defaultSchedFileName = "/etc/" + myName + ".schedules"
dataSubdir = ".data"
defaultRepository = "/tmp/snaprd_dest"
)
type opts []string
// opts getter
func (o *opts) String() string {
return fmt.Sprintf("\"%s\"", strings.Join(*o, ""))
}
// opts setter
func (o *opts) Set(value string) error {
*o = strings.Split(value, " ")
return nil
}
// Config is used as a backing store for parsed flags
type Config struct {
RsyncPath string
RsyncOpts opts
Origin string
repository string
Schedule string
verbose bool
showAll bool
MaxKeep int
NoPurge bool
NoWait bool
NoLogDate bool
SchedFile string
MinPercSpace float64
MinGiBSpace int
Notify string
noColor bool
}
// WriteCache writes the global configuration to disk as a json file.
func (c *Config) WriteCache() error {
cacheFile := filepath.Join(c.repository, "."+myName+".settings")
debugf("trying to write cached settings to %s", cacheFile)
jsonConfig, err := json.MarshalIndent(c, "", " ")
if err != nil {
log.Println("could not write config:", err)
return err
}
err = ioutil.WriteFile(cacheFile, jsonConfig, 0644)
return err
}
// ReadCache reads from the json configuration cache and resets assorted global
// configuration values from it.
func (c *Config) ReadCache() error {
t := new(Config)
cacheFile := filepath.Join(c.repository, "."+myName+".settings")
debugf("trying to read cached settings from %s", cacheFile)
b, err := ioutil.ReadFile(filepath.Join(c.repository, "."+myName+".settings"))
if err != nil {
return err
}
err = json.Unmarshal(b, &t)
if err != nil {
return err
}
c.RsyncPath = t.RsyncPath
c.RsyncOpts = t.RsyncOpts
if t.SchedFile != "" {
c.SchedFile = t.SchedFile
schedules.addFromFile(c.SchedFile)
}
c.Origin = t.Origin
if _, ok := schedules[t.Schedule]; ok == false {
return fmt.Errorf("no such schedule: %s", t.Schedule)
}
c.Schedule = t.Schedule
c.MaxKeep = t.MaxKeep
c.NoPurge = t.NoPurge
c.MinPercSpace = t.MinPercSpace
c.MinGiBSpace = t.MinGiBSpace
return nil
}
var subcmd string
func usage() {
fmt.Printf("%s %s\n", myName, version)
fmt.Printf(`usage: %[1]s <command> <options>
Commands:
run Periodically create snapshots
list List snapshots
scheds List schedules
help Show usage instructions
Use <command> -h to show possible options for <command>.
Examples:
%[1]s run -origin=fileserver:/export/projects -repository=/snapshots/projects
%[1]s list -repository=/snapshots/projects
`, myName)
}
func loadConfig() (*Config, error) {
config := new(Config)
if len(os.Args) > 1 {
subcmd = os.Args[1]
} else {
return nil, errors.New("no subcommand given")
}
switch subcmd {
case "run":
{
flags := flag.NewFlagSet(subcmd, flag.ContinueOnError)
flags.StringVar(&(config.RsyncPath),
"rsyncPath", "/usr/bin/rsync",
"path to rsync binary")
flags.Var(&(config.RsyncOpts),
"rsyncOpts",
"additional options for rsync")
flags.StringVar(&(config.Origin),
"origin", "/tmp/snaprd_test/",
"data source")
flags.StringVar(&(config.repository),
"repository", defaultRepository,
"where to store snapshots")
flags.StringVar(&(config.repository),
"r", defaultRepository,
"(shorthand for -repository)")
flags.StringVar(&(config.Schedule),
"schedule", "longterm",
"one of "+schedules.String())
flags.IntVar(&(config.MaxKeep),
"maxKeep", 0,
"how many snapshots to keep in highest (oldest) interval. Use 0 to keep all")
flags.BoolVar(&(config.NoPurge),
"noPurge", false,
"if set, obsolete snapshots will not be deleted (minimum space requirements will still be honoured)")
flags.BoolVar(&(config.NoWait),
"noWait", false,
"if set, skip the initial waiting time before the first snapshot")
flags.BoolVar(&(config.NoLogDate),
"noLogDate", false,
"if set, does not print date and time in the log output. Useful if output is redirected to syslog")
flags.StringVar(&(config.SchedFile),
"schedFile", defaultSchedFileName,
"path to external schedules")
flags.Float64Var(&(config.MinPercSpace),
"minPercSpace", 0,
"if set, keep at least x% of the snapshots filesystem free")
flags.IntVar(&(config.MinGiBSpace),
"minGbSpace", 0,
"if set, keep at least x GiB of the snapshots filesystem free")
flags.StringVar(&(config.Notify),
"notify", "",
"specify an email address to send reports")
if err := flags.Parse(os.Args[2:]); err != nil {
return nil, err
}
if config.SchedFile != "" {
err := schedules.addFromFile(config.SchedFile)
if err != nil {
return nil, err
}
}
if _, ok := schedules[config.Schedule]; ok == false {
return nil, fmt.Errorf("no such schedule: %s\n", config.Schedule)
}
path := filepath.Join(config.repository, dataSubdir)
debugf("creating repository: %s", path)
err := os.MkdirAll(path, 00755)
if err != nil {
return nil, err
}
err = config.WriteCache()
if err != nil {
log.Print("could not write settings cache file:", err)
}
return config, nil
}
case "list":
{
flags := flag.NewFlagSet(subcmd, flag.ContinueOnError)
flags.StringVar(&(config.repository),
"repository", defaultRepository,
"where snapshots are located")
flags.StringVar(&(config.repository),
"r", defaultRepository,
"(shorthand for -repository)")
flags.BoolVar(&(config.verbose),
"v", false,
"show more information")
flags.BoolVar(&(config.showAll),
"a", false,
"show all snapshots. Otherwise only complete snapshots are shown")
flags.StringVar(&(config.Schedule),
"schedule", "longterm",
"one of "+schedules.String())
flags.StringVar(&(config.SchedFile),
"schedFile", defaultSchedFileName,
"path to external schedules")
flags.BoolVar(&(config.noColor),
"noColor", false,
"do not colorize list output")
if err := flags.Parse(os.Args[2:]); err != nil {
return nil, err
}
if config.SchedFile != "" {
err := schedules.addFromFile(config.SchedFile)
if err != nil {
return nil, err
}
}
err := config.ReadCache()
if err != nil {
return nil, fmt.Errorf("error reading repository settings: %s\n", err)
}
debugf("cached config: %v", config)
return config, nil
}
case "help", "-h", "--help":
{
usage()
os.Exit(0)
}
case "scheds":
{
flags := flag.NewFlagSet(subcmd, flag.ContinueOnError)
flags.StringVar(&(config.SchedFile),
"schedFile", defaultSchedFileName,
"path to external schedules")
if err := flags.Parse(os.Args[2:]); err != nil {
return nil, err
}
if config.SchedFile != "" {
schedules.addFromFile(config.SchedFile)
}
return config, nil
}
default:
{
return nil, fmt.Errorf("unknown subcommand: \"%s\". Try \"help\".", subcmd)
}
}
return nil, nil
}