-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtsm.go
204 lines (181 loc) · 4.99 KB
/
tsm.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
package main
import (
"bytes"
"flag"
"fmt"
"log"
"os"
"os/exec"
"sort"
"strings"
"time"
"github.com/kylelemons/go-gypsy/yaml"
)
// Default configuration file
var conffile = flag.String("c", ".tsmrc", "config file")
var showAllBackups = flag.Bool("with-current", false, "list-expired: list current backups too")
// Config variables. Provide a default for tarsnap(1) path.
var cfgTarsnapBin = "/usr/local/bin/tarsnap"
var cfgTarsnapArgs []string
var cfgBackupDirs []string
var cfgExcludeFile string
// Templates for time.Parse()
const iso8601 = "2006-01-02"
const nightly = "nightly-2006-01-02"
const adhoc = "adhoc-2006-01-02_1504"
const day = time.Hour * 24
var info = log.New(os.Stdout, "", log.LstdFlags)
// Shamefully "borrowed" from src/cmd/go/main.go
// Flattens a mix of strings and slices of strings into a single slice.
func commandArgs(args ...interface{}) []string {
var x []string
for _, arg := range args {
switch arg := arg.(type) {
case []string:
x = append(x, arg...)
case string:
x = append(x, arg)
default:
panic("commandArgs: invalid argument")
}
}
return x
}
// Creates a new Tarsnap archive
func runBackup(archiveName string) {
info.Printf("Starting backup %s\n", archiveName)
args := commandArgs("-c", "-f", archiveName, cfgTarsnapArgs, cfgBackupDirs)
backup := exec.Command(cfgTarsnapBin, args...)
backup.Stdout = os.Stdout
backup.Stderr = os.Stderr
backuperr := backup.Run()
if backuperr != nil {
log.Fatal("Error running backup: ", backuperr)
}
info.Println("Backup finished")
}
// Deletes a Tarsnap archive
func deleteBackup(backup string) {
deletecmd := exec.Command(cfgTarsnapBin, "-d", "-f", backup)
deletecmd.Stdout = os.Stdout
deletecmd.Stderr = os.Stderr
err := deletecmd.Run()
if err != nil {
log.Fatal(err)
}
}
// Runs expiry against backup archives
func expireBackups(w, m time.Time, reallyExpire bool) {
listcmd := exec.Command(cfgTarsnapBin, "--list-archives")
var stdout bytes.Buffer
listcmd.Stdout = &stdout
listcmd.Stderr = os.Stderr
listerr := listcmd.Run()
if listerr != nil {
log.Fatal("Error running command: ", listerr)
}
backups := strings.Split(strings.TrimSuffix(stdout.String(), "\n"), "\n")
sort.Strings(backups)
for i := 0; i < len(backups); i++ {
// Don't expire adhoc backups
if strings.HasPrefix(backups[i], "adhoc-") {
continue
}
backup, _ := time.Parse(nightly, backups[i])
eom := time.Date(backup.Year(), backup.Month()+1, 0, 0, 0, 0, 0, backup.Location())
if (backup.Before(w) && backup.Day() != eom.Day()) || backup.Before(m) {
if reallyExpire {
info.Println("Expiring backup", backups[i])
deleteBackup(backups[i])
} else {
fmt.Println("Expired backup", backups[i])
}
} else {
if *showAllBackups && !reallyExpire {
fmt.Println("Current backup", backups[i])
}
}
}
}
func main() {
flag.Parse()
config, conferr := yaml.ReadFile(*conffile)
if conferr != nil {
log.Fatalf("Error reading config %q: %s", *conffile, conferr)
}
tmpTarsnapBin, _ := config.Get("TarsnapBin")
if tmpTarsnapBin != "" {
cfgTarsnapBin = tmpTarsnapBin
}
count, err := config.Count("TarsnapArgs")
for i := 0; i < count; i++ {
s := fmt.Sprintf("TarsnapArgs[%d]", i)
t, err := config.Get(s)
if err != nil {
log.Fatal(err)
}
// Remove any quotes from the arg - used to protect
// options (starting with a -)
t = strings.Replace(t, `"`, ``, -1)
cfgTarsnapArgs = append(cfgTarsnapArgs, t)
}
count, err = config.Count("BackupDirs")
if err != nil {
fmt.Println("No backup directories specified")
os.Exit(1)
}
for i := 0; i < count; i++ {
s := fmt.Sprintf("BackupDirs[%d]", i)
t, err := config.Get(s)
if err != nil {
log.Fatal(err)
}
cfgBackupDirs = append(cfgBackupDirs, t)
}
cfgExcludeFile, err := config.Get("ExcludeFile")
if err == nil {
cfgTarsnapArgs = append(cfgTarsnapArgs, "-X", cfgExcludeFile)
}
// GetInt() returns an int64. Convert this to an int.
tmpKeepWeeks, err := config.GetInt("KeepWeeks")
if err != nil {
fmt.Println("Missing config value KeepWeeks")
os.Exit(1)
}
tmpKeepMonths, err := config.GetInt("KeepMonths")
if err != nil {
fmt.Println("Missing config value KeepMonths")
os.Exit(1)
}
cfgKeepWeeks := int(tmpKeepWeeks)
cfgKeepMonths := int(tmpKeepMonths)
t := time.Now()
w := t.AddDate(0, 0, -(7 * cfgKeepWeeks))
m := t.AddDate(0, -cfgKeepMonths, 0)
fmt.Printf("Date: %s\nExpire week: %s\nExpire month: %s\n\n", t.Format(iso8601), w.Format(iso8601), m.Format(iso8601))
if len(flag.Args()) == 0 {
fmt.Println("Missing action")
os.Exit(1)
}
action := flag.Args()[0]
switch action {
case "nightly":
// Run nightly
runBackup(t.Format(nightly))
// TODO: Make w and m global?
cfgExpireBackups, _ := config.GetBool("ExpireBackups")
if cfgExpireBackups {
expireBackups(w, m, true)
} else {
info.Println("Backup expiration disabled")
}
info.Println("All done!")
case "adhoc":
// Run adhoc
runBackup(t.Format(adhoc))
case "list-expired":
expireBackups(w, m, false)
default:
log.Fatalf("Unknown action '%s'", action)
}
}