-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
local.go
257 lines (232 loc) · 6.53 KB
/
local.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
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package storage
import (
"bufio"
"context"
"io"
"os"
"path/filepath"
"strings"
"github.com/google/uuid"
"github.com/pingcap/errors"
"github.com/pingcap/log"
"go.uber.org/zap"
)
const (
localDirPerm os.FileMode = 0o777
localFilePerm os.FileMode = 0o644
// LocalURIPrefix represents the local storage prefix.
LocalURIPrefix = "file://"
)
// LocalStorage represents local file system storage.
//
// export for using in tests.
type LocalStorage struct {
base string
}
// DeleteFile deletes the file.
func (l *LocalStorage) DeleteFile(_ context.Context, name string) error {
path := filepath.Join(l.base, name)
return os.Remove(path)
}
// DeleteFiles deletes the files.
func (l *LocalStorage) DeleteFiles(ctx context.Context, names []string) error {
for _, name := range names {
err := l.DeleteFile(ctx, name)
if err != nil {
return err
}
}
return nil
}
// WriteFile writes data to a file to storage.
func (l *LocalStorage) WriteFile(_ context.Context, name string, data []byte) error {
// because `os.WriteFile` is not atomic, directly write into it may reset the file
// to an empty file if write is not finished.
tmpPath := filepath.Join(l.base, name) + ".tmp." + uuid.NewString()
if err := os.WriteFile(tmpPath, data, localFilePerm); err != nil {
path := filepath.Dir(tmpPath)
log.Info("failed to write file, try to mkdir the path", zap.String("path", path))
exists, existErr := pathExists(path)
if existErr != nil {
return errors.Annotatef(err, "after failed to write file, failed to check path exists : %v", existErr)
}
if exists {
return errors.Trace(err)
}
if mkdirErr := mkdirAll(path); mkdirErr != nil {
return errors.Annotatef(err, "after failed to write file, failed to mkdir : %v", mkdirErr)
}
if err := os.WriteFile(tmpPath, data, localFilePerm); err != nil {
return errors.Trace(err)
}
}
if err := os.Rename(tmpPath, filepath.Join(l.base, name)); err != nil {
return errors.Trace(err)
}
return nil
}
// ReadFile reads the file from the storage and returns the contents.
func (l *LocalStorage) ReadFile(_ context.Context, name string) ([]byte, error) {
path := filepath.Join(l.base, name)
return os.ReadFile(path)
}
// FileExists implement ExternalStorage.FileExists.
func (l *LocalStorage) FileExists(_ context.Context, name string) (bool, error) {
path := filepath.Join(l.base, name)
return pathExists(path)
}
// WalkDir traverse all the files in a dir.
//
// fn is the function called for each regular file visited by WalkDir.
// The first argument is the file path that can be used in `Open`
// function; the second argument is the size in byte of the file determined
// by path.
func (l *LocalStorage) WalkDir(_ context.Context, opt *WalkOption, fn func(string, int64) error) error {
if opt == nil {
opt = &WalkOption{}
}
base := filepath.Join(l.base, opt.SubDir)
return filepath.Walk(base, func(path string, f os.FileInfo, err error) error {
if os.IsNotExist(err) {
// if path not exists, we should return nil to continue.
return nil
}
if err != nil {
return errors.Trace(err)
}
if f == nil {
return nil
}
if f.IsDir() {
// walk will call this for base itself.
if path != base && opt.SkipSubDir {
return filepath.SkipDir
}
return nil
}
// in mac osx, the path parameter is absolute path; in linux, the path is relative path to execution base dir,
// so use Rel to convert to relative path to l.base
path, _ = filepath.Rel(l.base, path)
if !strings.HasPrefix(path, opt.ObjPrefix) {
return nil
}
size := f.Size()
// if not a regular file, we need to use os.stat to get the real file size
if !f.Mode().IsRegular() {
stat, err := os.Stat(filepath.Join(l.base, path))
if err != nil {
return errors.Trace(err)
}
size = stat.Size()
}
return fn(path, size)
})
}
// URI returns the base path as an URI with a file:/// prefix.
func (l *LocalStorage) URI() string {
return LocalURIPrefix + l.base
}
// Open a Reader by file path, path is a relative path to base path.
func (l *LocalStorage) Open(_ context.Context, path string, o *ReaderOption) (ExternalFileReader, error) {
//nolint: gosec
f, err := os.Open(filepath.Join(l.base, path))
if err != nil {
return nil, errors.Trace(err)
}
pos, endPos := int64(0), int64(-1)
if o != nil {
if o.EndOffset != nil {
endPos = *o.EndOffset
}
if o.StartOffset != nil {
_, err = f.Seek(*o.StartOffset, io.SeekStart)
if err != nil {
return nil, errors.Trace(err)
}
pos = *o.StartOffset
}
}
return &localFile{File: f, pos: pos, endPos: endPos}, nil
}
type localFile struct {
*os.File
pos int64
endPos int64
}
func (f *localFile) Read(p []byte) (n int, err error) {
if f.endPos == -1 {
return f.File.Read(p)
}
pEnd := f.endPos - f.pos
if pEnd <= 0 {
return 0, io.EOF
}
if pEnd > int64(len(p)) {
pEnd = int64(len(p))
}
p = p[:pEnd]
n, err = f.File.Read(p)
f.pos += int64(n)
return n, err
}
func (f *localFile) Seek(offset int64, whence int) (int64, error) {
n, err := f.File.Seek(offset, whence)
if err != nil {
return 0, errors.Trace(err)
}
f.pos, _ = f.File.Seek(0, io.SeekCurrent)
return n, nil
}
func (f *localFile) GetFileSize() (int64, error) {
stat, err := f.Stat()
if err != nil {
return 0, errors.Trace(err)
}
return stat.Size(), nil
}
// Create implements ExternalStorage interface.
func (l *LocalStorage) Create(_ context.Context, name string, _ *WriterOption) (ExternalFileWriter, error) {
filename := filepath.Join(l.base, name)
dir := filepath.Dir(filename)
err := os.MkdirAll(dir, 0750)
if err != nil {
return nil, errors.Trace(err)
}
file, err := os.Create(filename)
if err != nil {
return nil, errors.Trace(err)
}
buf := bufio.NewWriter(file)
return newFlushStorageWriter(buf, buf, file), nil
}
// Rename implements ExternalStorage interface.
func (l *LocalStorage) Rename(_ context.Context, oldFileName, newFileName string) error {
return errors.Trace(os.Rename(filepath.Join(l.base, oldFileName), filepath.Join(l.base, newFileName)))
}
func pathExists(_path string) (bool, error) {
_, err := os.Stat(_path)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, errors.Trace(err)
}
return true, nil
}
// NewLocalStorage return a LocalStorage at directory `base`.
//
// export for test.
func NewLocalStorage(base string) (*LocalStorage, error) {
ok, err := pathExists(base)
if err != nil {
return nil, errors.Trace(err)
}
if !ok {
err := mkdirAll(base)
if err != nil {
return nil, errors.Trace(err)
}
}
return &LocalStorage{base: base}, nil
}