-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
backup.go
231 lines (200 loc) · 6.18 KB
/
backup.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
package periodicbackup
import (
"context"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"time"
"github.com/pkg/errors"
"github.com/smartcontractkit/chainlink/v2/core/config"
"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/services"
"github.com/smartcontractkit/chainlink/v2/core/static"
"github.com/smartcontractkit/chainlink/v2/core/utils"
)
var (
filePattern = "cl_backup_%s.dump"
minBackupFrequency = time.Minute
excludedDataFromTables = []string{
"pipeline_runs",
"pipeline_task_runs",
}
)
type backupResult struct {
size int64
path string
maskedArguments []string
pgDumpArguments []string
}
type (
DatabaseBackup interface {
services.ServiceCtx
RunBackup(version string) error
}
databaseBackup struct {
logger logger.Logger
databaseURL url.URL
mode config.DatabaseBackupMode
frequency time.Duration
outputParentDir string
done chan bool
utils.StartStopOnce
}
BackupConfig interface {
URL() *url.URL
Dir() string
Mode() config.DatabaseBackupMode
Frequency() time.Duration
}
)
// NewDatabaseBackup instantiates a *databaseBackup
func NewDatabaseBackup(dbUrl url.URL, rootDir string, backupConfig BackupConfig, lggr logger.Logger) (DatabaseBackup, error) {
lggr = lggr.Named("DatabaseBackup")
dbBackupUrl := backupConfig.URL()
if dbBackupUrl != nil {
dbUrl = *dbBackupUrl
}
outputParentDir := filepath.Join(rootDir, "backup")
if backupConfig.Dir() != "" {
dir, err := filepath.Abs(backupConfig.Dir())
if err != nil {
return nil, errors.Errorf("failed to get path for Database.Backup.Dir (%s) - please set it to a valid directory path", backupConfig.Dir())
}
outputParentDir = dir
}
return &databaseBackup{
lggr,
dbUrl,
backupConfig.Mode(),
backupConfig.Frequency(),
outputParentDir,
make(chan bool),
utils.StartStopOnce{},
}, nil
}
// Start starts DatabaseBackup.
func (backup *databaseBackup) Start(context.Context) error {
return backup.StartOnce("DatabaseBackup", func() (err error) {
ticker := time.NewTicker(backup.frequency)
if backup.frequency == 0 {
backup.logger.Info("Periodic database backups are disabled; Database.Backup.Frequency was set to 0")
// Stopping the ticker means it will never fire, effectively disabling periodic backups
ticker.Stop()
} else if backup.frequencyIsTooSmall() {
return errors.Errorf("Database backup frequency (%s=%v) is too small. Please set it to at least %s (or set to 0 to disable periodic backups)", "Database.Backup.Frequency", backup.frequency, minBackupFrequency)
}
go func() {
for {
select {
case <-backup.done:
ticker.Stop()
return
case <-ticker.C:
backup.logger.Infow("Starting automatic database backup, this can take a while. To disable periodic backups, set Database.Backup.Frequency=0. To disable database backups entirely, set Database.Backup.Mode=none.")
//nolint:errcheck
backup.RunBackup(static.Version)
}
}
}()
return nil
})
}
func (backup *databaseBackup) Close() error {
return backup.StopOnce("DatabaseBackup", func() (err error) {
backup.done <- true
return nil
})
}
func (backup *databaseBackup) Name() string {
return backup.logger.Name()
}
func (backup *databaseBackup) HealthReport() map[string]error {
return map[string]error{backup.Name(): backup.StartStopOnce.Healthy()}
}
func (backup *databaseBackup) frequencyIsTooSmall() bool {
return backup.frequency < minBackupFrequency
}
func (backup *databaseBackup) RunBackup(version string) error {
backup.logger.Debugw("Starting backup", "mode", backup.mode, "directory", backup.outputParentDir)
startAt := time.Now()
result, err := backup.runBackup(version)
duration := time.Since(startAt)
if err != nil {
backup.logger.Criticalw("Backup failed", "duration", duration, "err", err)
backup.SvcErrBuffer.Append(err)
return err
}
backup.logger.Infow("Backup completed successfully.", "duration", duration, "fileSize", result.size, "filePath", result.path)
return nil
}
func (backup *databaseBackup) runBackup(version string) (*backupResult, error) {
err := os.MkdirAll(backup.outputParentDir, os.ModePerm)
if err != nil {
return nil, errors.Wrapf(err, "Failed to create directories on the path: %s", backup.outputParentDir)
}
tmpFile, err := os.CreateTemp(backup.outputParentDir, "cl_backup_tmp_")
if err != nil {
return nil, errors.Wrap(err, "Failed to create a tmp file")
}
err = os.Remove(tmpFile.Name())
if err != nil {
return nil, errors.Wrap(err, "Failed to remove the tmp file before running backup")
}
args := []string{
backup.databaseURL.String(),
"-f", tmpFile.Name(),
"-F", "c", // format: custom (zipped)
}
if backup.mode == config.DatabaseBackupModeLite {
for _, table := range excludedDataFromTables {
args = append(args, fmt.Sprintf("--exclude-table-data=%s", table))
}
}
maskArgs := func(args []string) []string {
masked := make([]string, len(args))
copy(masked, args)
masked[0] = backup.databaseURL.Redacted()
return masked
}
maskedArgs := maskArgs(args)
backup.logger.Debugf("Running pg_dump with: %v", maskedArgs)
cmd := exec.Command(
"pg_dump", args...,
)
_, err = cmd.Output()
if err != nil {
partialResult := &backupResult{
size: 0,
path: "",
maskedArguments: maskedArgs,
pgDumpArguments: args,
}
var ee *exec.ExitError
if errors.As(err, &ee) {
return partialResult, errors.Wrapf(err, "pg_dump failed with output: %s", string(ee.Stderr))
}
return partialResult, errors.Wrap(err, "pg_dump failed")
}
if version == "" {
version = "unknown"
}
finalFilePath := filepath.Join(backup.outputParentDir, fmt.Sprintf(filePattern, version))
_ = os.Remove(finalFilePath)
err = os.Rename(tmpFile.Name(), finalFilePath)
if err != nil {
_ = os.Remove(tmpFile.Name())
return nil, errors.Wrap(err, "Failed to rename the temp file to the final backup file")
}
file, err := os.Stat(finalFilePath)
if err != nil {
return nil, errors.Wrap(err, "Failed to access the final backup file")
}
return &backupResult{
size: file.Size(),
path: finalFilePath,
maskedArguments: maskedArgs,
pgDumpArguments: args,
}, nil
}