/
tar.go
324 lines (249 loc) · 8.02 KB
/
tar.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package sync
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"time"
"github.com/juju/errors"
)
func untarAll(reader io.Reader, destPath, prefix string, config *SyncConfig) error {
fileCounter := 0
gzr, err := gzip.NewReader(reader)
if err != nil {
return fmt.Errorf("Error decompressing: %v", err)
}
defer gzr.Close()
tarReader := tar.NewReader(gzr)
for {
shouldContinue, err := untarNext(tarReader, destPath, prefix, config)
if err != nil {
return errors.Trace(err)
} else if shouldContinue == false {
return nil
}
fileCounter++
if fileCounter%500 == 0 {
config.Logf("[Downstream] Untared %d files...\n", fileCounter)
}
}
}
func untarNext(tarReader *tar.Reader, destPath, prefix string, config *SyncConfig) (bool, error) {
config.fileIndex.fileMapMutex.Lock()
defer config.fileIndex.fileMapMutex.Unlock()
header, err := tarReader.Next()
if err != nil {
if err != io.EOF {
return false, errors.Trace(err)
}
return false, nil
}
relativePath := getRelativeFromFullPath("/"+header.Name, prefix)
outFileName := path.Join(destPath, relativePath)
baseName := path.Dir(outFileName)
// Check if newer file is there and then don't override?
stat, err := os.Stat(outFileName)
if err == nil {
if roundMtime(stat.ModTime()) > header.FileInfo().ModTime().Unix() {
// Update filemap otherwise we download and download again
config.fileIndex.fileMap[relativePath] = &fileInformation{
Name: relativePath,
Mtime: roundMtime(stat.ModTime()),
Size: stat.Size(),
IsDirectory: stat.IsDir(),
}
config.Logf("[Downstream] Don't override %s because file has newer mTime timestamp", relativePath)
return true, nil
}
}
if err := os.MkdirAll(baseName, 0755); err != nil {
return false, errors.Trace(err)
}
if header.FileInfo().IsDir() {
if err := os.MkdirAll(outFileName, 0755); err != nil {
return false, errors.Trace(err)
}
config.fileIndex.CreateDirInFileMap(relativePath)
return true, nil
}
// Create base dir in file map if it not already exists
config.fileIndex.CreateDirInFileMap(getRelativeFromFullPath(baseName, destPath))
// Create / Override file
outFile, err := os.Create(outFileName)
if err != nil {
// Try again after 5 seconds
time.Sleep(time.Second * 5)
outFile, err = os.Create(outFileName)
if err != nil {
return false, errors.Trace(err)
}
}
defer outFile.Close()
if _, err := io.Copy(outFile, tarReader); err != nil {
return false, errors.Trace(err)
}
if err := outFile.Close(); err != nil {
return false, errors.Trace(err)
}
if stat != nil {
// Set old permissions correctly
_ = os.Chmod(outFileName, stat.Mode())
// Set owner & group correctly
// TODO: Enable this on supported platforms
// _ = os.Chown(outFileName, stat.Sys().(*syscall.Stat).Uid, stat.Sys().(*syscall.Stat_t).Gid)
}
// Set mod time correctly
err = os.Chtimes(outFileName, time.Now(), header.FileInfo().ModTime())
if err != nil {
return false, errors.Trace(err)
}
// Update fileMap so that upstream does not upload the file
config.fileIndex.fileMap[relativePath] = &fileInformation{
Name: relativePath,
Mtime: header.FileInfo().ModTime().Unix(),
Size: header.FileInfo().Size(),
IsDirectory: false,
}
return true, nil
}
func writeTar(files []*fileInformation, config *SyncConfig) (string, map[string]*fileInformation, error) {
f, err := ioutil.TempFile("", "")
if err != nil {
return "", nil, errors.Trace(err)
}
defer f.Close()
// Use compression
gw := gzip.NewWriter(f)
defer gw.Close()
tarWriter := tar.NewWriter(gw)
defer tarWriter.Close()
writtenFiles := make(map[string]*fileInformation)
for _, element := range files {
relativePath := element.Name
if writtenFiles[relativePath] == nil {
err := recursiveTar(config.WatchPath, relativePath, writtenFiles, tarWriter, config)
if err != nil {
config.Logf("[Upstream] Tar failed: %s. Will retry in 4 seconds...\n", err.Error())
os.Remove(f.Name())
time.Sleep(time.Second * 4)
return writeTar(files, config)
}
}
}
return f.Name(), writtenFiles, nil
}
// TODO: Error handling if files are not there
func recursiveTar(basePath, relativePath string, writtenFiles map[string]*fileInformation, tw *tar.Writer, config *SyncConfig) error {
absFilepath := path.Join(basePath, relativePath)
if writtenFiles[relativePath] != nil {
return nil
}
config.fileIndex.fileMapMutex.Lock()
isExcluded := false
// Exclude files on the exclude list
if config.ignoreMatcher != nil {
if config.ignoreMatcher.MatchesPath(relativePath) {
isExcluded = true
}
}
// Exclude files on the upload exclude list
if config.uploadIgnoreMatcher != nil {
if config.uploadIgnoreMatcher.MatchesPath(relativePath) {
isExcluded = true
}
}
config.fileIndex.fileMapMutex.Unlock()
if isExcluded {
return nil
}
stat, err := os.Stat(absFilepath)
// We skip files that are suddenly not there anymore
if err != nil {
config.Logf("[Upstream] Couldn't stat file %s: %s\n", absFilepath, err.Error())
return nil
}
fileInformation := createFileInformationFromStat(relativePath, stat, config)
if stat.IsDir() {
// Recursively tar folder
return tarFolder(basePath, fileInformation, writtenFiles, stat, tw, config)
}
return tarFile(basePath, fileInformation, writtenFiles, stat, tw, config)
}
func tarFolder(basePath string, fileInformation *fileInformation, writtenFiles map[string]*fileInformation, stat os.FileInfo, tw *tar.Writer, config *SyncConfig) error {
filepath := path.Join(basePath, fileInformation.Name)
files, err := ioutil.ReadDir(filepath)
if err != nil {
config.Logf("[Upstream] Couldn't read dir %s: %s\n", filepath, err.Error())
return nil
}
if len(files) == 0 && fileInformation.Name != "" {
// Case empty directory
hdr, _ := tar.FileInfoHeader(stat, filepath)
hdr.Name = fileInformation.Name
config.fileIndex.fileMapMutex.Lock()
if config.fileIndex.fileMap[fileInformation.Name] != nil {
hdr.Mode = fileInformation.RemoteMode
hdr.Uid = fileInformation.RemoteUID
hdr.Gid = fileInformation.RemoteGID
}
config.fileIndex.fileMapMutex.Unlock()
if err := tw.WriteHeader(hdr); err != nil {
return errors.Trace(err)
}
writtenFiles[fileInformation.Name] = fileInformation
}
for _, f := range files {
if err := recursiveTar(basePath, path.Join(fileInformation.Name, f.Name()), writtenFiles, tw, config); err != nil {
return errors.Trace(err)
}
}
return nil
}
func tarFile(basePath string, fileInformation *fileInformation, writtenFiles map[string]*fileInformation, stat os.FileInfo, tw *tar.Writer, config *SyncConfig) error {
filepath := path.Join(basePath, fileInformation.Name)
// Case regular file
f, err := os.Open(filepath)
if err != nil {
return errors.Trace(err)
}
defer f.Close()
hdr, err := tar.FileInfoHeader(stat, filepath)
if err != nil {
return errors.Trace(err)
}
hdr.Name = fileInformation.Name
config.fileIndex.fileMapMutex.Lock()
if config.fileIndex.fileMap[fileInformation.Name] != nil {
hdr.Mode = fileInformation.RemoteMode
hdr.Uid = fileInformation.RemoteUID
hdr.Gid = fileInformation.RemoteGID
}
config.fileIndex.fileMapMutex.Unlock()
if err := tw.WriteHeader(hdr); err != nil {
return errors.Trace(err)
}
if _, err := io.Copy(tw, f); err != nil {
return errors.Trace(err)
}
writtenFiles[fileInformation.Name] = fileInformation
return f.Close()
}
func createFileInformationFromStat(relativePath string, stat os.FileInfo, config *SyncConfig) *fileInformation {
config.fileIndex.fileMapMutex.Lock()
defer config.fileIndex.fileMapMutex.Unlock()
fileInformation := &fileInformation{
Name: relativePath,
Size: stat.Size(),
Mtime: roundMtime(stat.ModTime()),
IsDirectory: stat.IsDir(),
}
if config.fileIndex.fileMap[relativePath] != nil {
fileInformation.RemoteMode = config.fileIndex.fileMap[relativePath].RemoteMode
fileInformation.RemoteGID = config.fileIndex.fileMap[relativePath].RemoteGID
fileInformation.RemoteUID = config.fileIndex.fileMap[relativePath].RemoteUID
}
return fileInformation
}