/
backups.go
233 lines (202 loc) · 6.63 KB
/
backups.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
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package backups
import (
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/utils/v3/du"
)
const (
// FilenamePrefix is the prefix used for backup archive files.
FilenamePrefix = "juju-backup-"
// FilenameTemplate is used with time.Time.Format to generate a filename.
FilenameTemplate = FilenamePrefix + "20060102-150405.tar.gz"
)
var logger = loggo.GetLogger("juju.state.backups")
var (
getFilesToBackUp = GetFilesToBackUp
getDBDumper = NewDBDumper
runCreate = create
finishMeta = func(meta *Metadata, result *createResult) error {
return meta.MarkComplete(result.size, result.checksum)
}
availableDisk = func(path string) uint64 {
return du.NewDiskUsage(path).Available()
}
totalDisk = func(path string) uint64 {
return du.NewDiskUsage(path).Size()
}
dirSize = totalDirSize
)
// Backups is an abstraction around all juju backup-related functionality.
type Backups interface {
// Create creates a new juju backup archive. It updates
// the provided metadata.
Create(meta *Metadata, dbInfo *DBInfo) (string, error)
// Get returns the metadata and specified archive file.
Get(fileName string) (*Metadata, io.ReadCloser, error)
}
type backups struct {
paths *Paths
}
// NewBackups creates a new Backups value using the FileStorage provided.
func NewBackups(paths *Paths) Backups {
return &backups{
paths: paths,
}
}
func totalDirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
}
return err
})
return size, err
}
// Create creates and stores a new juju backup archive (based on arguments)
// and updates the provided metadata. A filename to download the backup is provided.
func (b *backups) Create(meta *Metadata, dbInfo *DBInfo) (string, error) {
// TODO(fwereade): 2016-03-17 lp:1558657
meta.Started = time.Now().UTC()
// The metadata file will not contain the ID or the "finished" data.
// However, that information is not as critical. The alternatives
// are either adding the metadata file to the archive after the fact
// or adding placeholders here for the finished data and filling
// them in afterward. Neither is particularly trivial.
metadataFile, err := meta.AsJSONBuffer()
if err != nil {
return "", errors.Annotate(err, "while preparing the metadata")
}
// Create the archive.
filesToBackUp, err := getFilesToBackUp("", b.paths)
if err != nil {
return "", errors.Annotate(err, "while listing files to back up")
}
var totalFileSizes int64
for _, f := range filesToBackUp {
size, err := dirSize(f)
if err != nil {
return "", errors.Trace(err)
}
totalFileSizes += size
}
totalFizeSizesMiB := int64(dbInfo.ApproxSizeMB) + totalFileSizes/humanize.MiByte
logger.Infof("backing up %dMiB (files) and %dMiB (database) = %dMiB",
totalFizeSizesMiB, dbInfo.ApproxSizeMB, int(totalFizeSizesMiB)+dbInfo.ApproxSizeMB)
destinationDir := b.paths.BackupDir
if _, err := os.Stat(destinationDir); err != nil {
if os.IsNotExist(err) {
return "", errors.Errorf("backup destination directory %q does not exist", destinationDir)
}
return "", errors.NewNotValid(nil, fmt.Sprintf("invalid backup destination directory %q: %v", destinationDir, err))
}
if !filepath.IsAbs(destinationDir) {
return "", errors.Errorf("cannot use relative backup destination directory %q", destinationDir)
}
// We require space equal to the larger of:
// - smaller of 5GB or 10% of the total disk size
// - 20% of the backup size
// on top of the approximate backup size to be available.
const minFreeAbsolute = 5 * humanize.GiByte
diskSizeMargin := float64(totalDisk(destinationDir)) * 0.10
if diskSizeMargin > minFreeAbsolute {
diskSizeMargin = minFreeAbsolute
}
backupSizeMargin := float64(totalFizeSizesMiB) * 0.20 * humanize.MiByte
if backupSizeMargin < diskSizeMargin {
backupSizeMargin = diskSizeMargin
}
wantFree := uint64(totalFizeSizesMiB) + uint64(backupSizeMargin/humanize.MiByte)
available := availableDisk(destinationDir) / humanize.MiByte
logger.Infof("free disk on volume hosting %q: %dMiB", destinationDir, available)
if available < wantFree {
return "", errors.Errorf("not enough free space in %q; want %dMiB, have %dMiB", destinationDir, wantFree, available)
}
dumper, err := getDBDumper(dbInfo)
if err != nil {
return "", errors.Annotate(err, "while preparing for DB dump")
}
args := createArgs{
destinationDir: destinationDir,
filesToBackUp: filesToBackUp,
db: dumper,
metadataReader: metadataFile,
}
result, err := runCreate(&args)
if err != nil {
return "", errors.Annotate(err, "while creating backup archive")
}
defer func() { _ = result.archiveFile.Close() }()
// Finalize the metadata.
err = finishMeta(meta, result)
if err != nil {
return "", errors.Annotate(err, "while updating metadata")
}
return result.filename, nil
}
func isValidFilepath(root string, filePath string) (bool, error) {
if !filepath.IsAbs(filePath) {
return false, nil
}
if !strings.HasPrefix(filepath.Base(filePath), FilenamePrefix) {
return false, nil
}
result := false
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if d.IsDir() {
return nil
}
if path == filePath {
result = true
return nil
}
return nil
})
return result, err
}
// Get retrieves the associated metadata and archive file a file on the machine.
func (b *backups) Get(fileName string) (_ *Metadata, _ io.ReadCloser, err error) {
valid, err := isValidFilepath(b.paths.BackupDir, fileName)
if err != nil {
return nil, nil, errors.Trace(err)
}
if !valid {
return nil, nil, errors.NotValidf("backup file %q", fileName)
}
defer func() {
// On success, remove the retrieved file.
if err != nil {
return
}
if err2 := os.Remove(fileName); err2 != nil && !os.IsNotExist(err2) {
logger.Errorf("error removing backup archive: %v", err2.Error())
}
}()
readCloser, err := os.Open(fileName)
if err != nil {
return nil, nil, errors.Annotate(err, "while opening archive file for download")
}
meta, err := BuildMetadata(readCloser)
if err != nil {
return nil, nil, errors.Annotate(err, "while creating metadata for archive file to download")
}
// BuildMetadata copied readCloser, so reset handle to beginning of the file
_, err = readCloser.Seek(0, io.SeekStart)
if err != nil {
return nil, nil, errors.Annotate(err, "while resetting archive file to download")
}
return meta, readCloser, nil
}