forked from wal-g/wal-g
/
prefetch.go
239 lines (207 loc) · 6.84 KB
/
prefetch.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
package internal
import (
"archive/tar"
"github.com/pkg/errors"
"github.com/wal-g/storages/storage"
"github.com/tinsane/tracelog"
"github.com/wal-g/wal-g/utility"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"sync"
"time"
)
// TODO : unit tests
// HandleWALPrefetch is invoked by wal-fetch command to speed up database restoration
func HandleWALPrefetch(uploader *Uploader, walFileName string, location string) {
folder := uploader.UploadingFolder.GetSubFolder(utility.WalPath)
var fileName = walFileName
location = path.Dir(location)
waitGroup := &sync.WaitGroup{}
concurrency, err := GetMaxDownloadConcurrency()
tracelog.ErrorLogger.FatalOnError(err)
for i := 0; i < concurrency; i++ {
fileName, err = GetNextWalFilename(fileName)
if err != nil {
tracelog.ErrorLogger.Println("WAL-prefetch failed: ", err, " file: ", fileName)
}
waitGroup.Add(1)
go prefetchFile(location, folder, fileName, waitGroup)
prefaultStartLsn, shouldPrefault, timelineId, err := ShouldPrefault(fileName)
if err != nil {
tracelog.ErrorLogger.Println("ShouldPrefault failed: ", err, " file: ", fileName)
}
if shouldPrefault {
waitGroup.Add(1)
go prefaultData(prefaultStartLsn, timelineId, waitGroup, uploader)
}
time.Sleep(10 * time.Millisecond) // ramp up in order
}
go CleanupPrefetchDirectories(walFileName, location, FileSystemCleaner{})
waitGroup.Wait()
}
// TODO : unit tests
func prefaultData(prefaultStartLsn uint64, timelineId uint32, waitGroup *sync.WaitGroup, uploader *Uploader) {
defer func() {
if r := recover(); r != nil {
tracelog.ErrorLogger.Println("Prefault unsuccessful ", prefaultStartLsn)
}
waitGroup.Done()
}()
if !uploader.getUseWalDelta() {
return
}
archiveDirectory := uploader.deltaFileManager.dataFolder.(*DiskDataFolder).path
archiveDirectory = filepath.Dir(archiveDirectory)
archiveDirectory = filepath.Dir(archiveDirectory)
bundle := NewBundle(archiveDirectory, nil, &prefaultStartLsn, nil)
bundle.Timeline = timelineId
err := bundle.DownloadDeltaMap(uploader.UploadingFolder.GetSubFolder(utility.WalPath), prefaultStartLsn+WalSegmentSize*WalFileInDelta)
if err != nil {
tracelog.ErrorLogger.Printf("Error during loading delta map: '%+v'.", err)
return
}
bundle.TarBallMaker = NewNopTarBallMaker()
// Start a new tar bundle, walk the archiveDirectory and upload everything there.
bundle.StartQueue()
tracelog.InfoLogger.Println("Walking for prefault...")
err = filepath.Walk(archiveDirectory, bundle.PrefaultWalkedFSObject)
tracelog.ErrorLogger.FatalOnError(err)
err = bundle.FinishQueue()
}
// TODO : unit tests
func (bundle *Bundle) PrefaultWalkedFSObject(path string, info os.FileInfo, err error) error {
if err != nil {
if os.IsNotExist(err) {
tracelog.WarningLogger.Println(path, " deleted during filepath walk")
return nil
}
return err
}
if info.Name() != PgControl {
err = bundle.prefaultHandleTar(path, info)
if err != nil {
if err == filepath.SkipDir {
return err
}
return errors.Wrap(err, "HandleWalkedFSObject: handle tar failed")
}
}
return nil
}
// TODO : unit tests
func (bundle *Bundle) prefaultHandleTar(path string, info os.FileInfo) error {
fileName := info.Name()
_, excluded := ExcludedFilenames[fileName]
isDir := info.IsDir()
if excluded && !isDir {
return nil
}
fileInfoHeader, err := tar.FileInfoHeader(info, fileName)
if err != nil {
return errors.Wrap(err, "handleTar: could not grab header info")
}
fileInfoHeader.Name = bundle.GetFileRelPath(path)
if !excluded && info.Mode().IsRegular() {
tarBall := bundle.Deque()
tarBall.SetUp(nil)
go func() {
err := bundle.prefaultFile(path, info, fileInfoHeader)
if err != nil {
panic(err)
}
err = bundle.CheckSizeAndEnqueueBack(tarBall)
if err != nil {
panic(err)
}
}()
} else {
if excluded && isDir {
return filepath.SkipDir
}
}
return nil
}
// TODO : unit tests
func (bundle *Bundle) prefaultFile(path string, info os.FileInfo, fileInfoHeader *tar.Header) error {
incrementBaseLsn := bundle.GetIncrementBaseLsn()
isIncremented := isPagedFile(info, path)
var fileReader io.ReadCloser
if isIncremented {
bitmap, err := bundle.getDeltaBitmapFor(path)
if _, ok := err.(NoBitmapFoundError); !ok { // this file has changed after the start of backup, so just skip it
if err != nil {
return errors.Wrapf(err, "packFileIntoTar: failed to find corresponding bitmap '%s'\n", path)
}
tracelog.InfoLogger.Println("Prefaulting ", path)
fileReader, fileInfoHeader.Size, err = ReadIncrementalFile(path, info.Size(), *incrementBaseLsn, bitmap)
if _, ok := err.(InvalidBlockError); ok {
return nil
} else if err != nil {
return errors.Wrapf(err, "packFileIntoTar: failed reading incremental file '%s'\n", path)
}
_, err := io.Copy(ioutil.Discard, fileReader)
if err != nil {
return errors.Wrap(err, "packFileIntoTar: operation failed")
}
fileReader.Close()
}
}
return nil
}
// TODO : unit tests
func prefetchFile(location string, folder storage.Folder, walFileName string, waitGroup *sync.WaitGroup) {
defer func() {
if r := recover(); r != nil {
tracelog.ErrorLogger.Println("Prefetch unsuccessful ", walFileName, r)
}
waitGroup.Done()
}()
_, runningLocation, oldPath, newPath := GetPrefetchLocations(location, walFileName)
_, errO := os.Stat(oldPath)
_, errN := os.Stat(newPath)
if (errO == nil || !os.IsNotExist(errO)) || (errN == nil || !os.IsNotExist(errN)) {
// Seems someone is doing something about this file
return
}
tracelog.InfoLogger.Println("WAL-prefetch file: ", walFileName)
os.MkdirAll(runningLocation, 0755)
err := DownloadWALFileTo(folder, walFileName, oldPath)
tracelog.ErrorLogger.FatalOnError(err)
_, errO = os.Stat(oldPath)
_, errN = os.Stat(newPath)
if errO == nil && os.IsNotExist(errN) {
os.Rename(oldPath, newPath)
} else {
os.Remove(oldPath) // error is ignored
}
}
func GetPrefetchLocations(location string, walFileName string) (prefetchLocation string, runningLocation string, runningFile string, fetchedFile string) {
prefetchLocation = path.Join(location, ".wal-g", "prefetch")
runningLocation = path.Join(prefetchLocation, "running")
oldPath := path.Join(runningLocation, walFileName)
newPath := path.Join(prefetchLocation, walFileName)
return prefetchLocation, runningLocation, oldPath, newPath
}
// TODO : unit tests
func forkPrefetch(walFileName string, location string) {
concurrency, err := GetMaxDownloadConcurrency()
if err != nil {
tracelog.ErrorLogger.Println("WAL-prefetch failed: ", err)
}
if strings.Contains(walFileName, "history") ||
strings.Contains(walFileName, "partial") ||
concurrency == 1 {
return // There will be nothing ot prefetch anyway
}
cmd := exec.Command(os.Args[0], "wal-prefetch", walFileName, location)
cmd.Env = os.Environ()
err = cmd.Start()
if err != nil {
tracelog.ErrorLogger.Println("WAL-prefetch failed: ", err)
}
}