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
|
package zip
import (
"archive/zip"
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
log "github.com/sirupsen/logrus"
"gitlab.com/gitlab-org/gitlab-pages/internal/httprange"
"gitlab.com/gitlab-org/gitlab-pages/internal/vfs"
"gitlab.com/gitlab-org/gitlab-pages/metrics"
)
const (
dirPrefix = "public/"
maxSymlinkSize = 256
)
var (
errNotSymlink = errors.New("not a symlink")
errSymlinkSize = errors.New("symlink too long")
errNotFile = errors.New("not a file")
)
type archiveStatus int
const (
archiveOpening archiveStatus = iota
archiveOpenError
archiveOpened
archiveCorrupted
)
// zipArchive implements the vfs.Root interface.
// It represents a zip archive saving all its files in memory.
// It holds an httprange.Resource that can be read with httprange.RangedReader in chunks.
type zipArchive struct {
fs *zipVFS
once sync.Once
done chan struct{}
openTimeout time.Duration
cacheNamespace string
resource *httprange.Resource
reader *httprange.RangedReader
archive *zip.Reader
err error
files map[string]*zip.File
directories map[string]*zip.FileHeader
}
func newArchive(fs *zipVFS, openTimeout time.Duration) *zipArchive {
return &zipArchive{
fs: fs,
done: make(chan struct{}),
files: make(map[string]*zip.File),
directories: make(map[string]*zip.FileHeader),
openTimeout: openTimeout,
cacheNamespace: strconv.FormatInt(atomic.AddInt64(&fs.archiveCount, 1), 10) + ":",
}
}
func (a *zipArchive) openArchive(parentCtx context.Context, url string) (err error) {
// always try to update URL on resource
if a.resource != nil {
a.resource.SetURL(url)
}
// return early if openArchive was done already in a concurrent request
if status, err := a.openStatus(); status != archiveOpening {
return err
}
ctx, cancel := context.WithTimeout(parentCtx, a.openTimeout)
defer cancel()
a.once.Do(func() {
// read archive once in its own routine with its own timeout
// if parentCtx is canceled, readArchive will continue regardless and will be cached in memory
go a.readArchive(url)
})
// wait for readArchive to be done or return if the parent context is canceled
select {
case <-a.done:
return a.err
case <-ctx.Done():
err := ctx.Err()
switch err {
case context.Canceled:
log.WithError(err).Traceln("open zip archive request canceled")
case context.DeadlineExceeded:
log.WithError(err).Traceln("open zip archive timed out")
}
return err
}
}
// readArchive creates an httprange.Resource that can read the archive's contents and stores a slice of *zip.Files
// that can be accessed later when calling any of th vfs.VFS operations
func (a *zipArchive) readArchive(url string) {
defer close(a.done)
// readArchive with a timeout separate from openArchive's
ctx, cancel := context.WithTimeout(context.Background(), a.openTimeout)
defer cancel()
a.resource, a.err = httprange.NewResource(ctx, url)
if a.err != nil {
metrics.ZipOpened.WithLabelValues("error").Inc()
return
}
// load all archive files into memory using a cached ranged reader
a.reader = httprange.NewRangedReader(a.resource)
a.reader.WithCachedReader(ctx, func() {
a.archive, a.err = zip.NewReader(a.reader, a.resource.Size)
})
if a.archive == nil || a.err != nil {
metrics.ZipOpened.WithLabelValues("error").Inc()
return
}
// TODO: Improve preprocessing of zip archives https://gitlab.com/gitlab-org/gitlab-pages/-/issues/432
for _, file := range a.archive.File {
if !strings.HasPrefix(file.Name, dirPrefix) {
continue
}
if file.Mode().IsDir() {
a.directories[file.Name] = &file.FileHeader
} else {
a.files[file.Name] = file
}
a.addPathDirectory(file.Name)
}
// recycle memory
a.archive.File = nil
fileCount := float64(len(a.files))
metrics.ZipOpened.WithLabelValues("ok").Inc()
metrics.ZipOpenedEntriesCount.Add(fileCount)
metrics.ZipArchiveEntriesCached.Add(fileCount)
}
// addPathDirectory adds a directory for a given path
func (a *zipArchive) addPathDirectory(path string) {
// Split dir and file from `path`
path, _ = filepath.Split(path)
if path == "" {
return
}
if a.directories[path] != nil {
return
}
a.directories[path] = &zip.FileHeader{
Name: path,
}
}
func (a *zipArchive) findFile(name string) *zip.File {
name = filepath.Join(dirPrefix, name)
if file := a.files[name]; file != nil {
return file
}
return nil
}
func (a *zipArchive) findDirectory(name string) *zip.FileHeader {
name = filepath.Join(dirPrefix, name)
return a.directories[name+"/"]
}
// Open finds the file by name inside the zipArchive and returns a reader that can be served by the VFS
func (a *zipArchive) Open(ctx context.Context, name string) (vfs.File, error) {
file := a.findFile(name)
if file == nil {
if a.findDirectory(name) != nil {
return nil, errNotFile
}
return nil, os.ErrNotExist
}
if !file.Mode().IsRegular() {
return nil, errNotFile
}
dataOffset, err := a.fs.dataOffsetCache.findOrFetch(a.cacheNamespace, name, func() (interface{}, error) {
return file.DataOffset()
})
if err != nil {
return nil, err
}
// only read from dataOffset up to the size of the compressed file
reader := a.reader.SectionReader(ctx, dataOffset.(int64), int64(file.CompressedSize64))
switch file.Method {
case zip.Deflate:
return newDeflateReader(reader), nil
case zip.Store:
return reader, nil
default:
return nil, fmt.Errorf("unsupported compression method: %x", file.Method)
}
}
// Lstat finds the file by name inside the zipArchive and returns its FileInfo
func (a *zipArchive) Lstat(ctx context.Context, name string) (os.FileInfo, error) {
file := a.findFile(name)
if file != nil {
return file.FileInfo(), nil
}
directory := a.findDirectory(name)
if directory != nil {
return directory.FileInfo(), nil
}
return nil, os.ErrNotExist
}
// ReadLink finds the file by name inside the zipArchive and returns the contents of the symlink
func (a *zipArchive) Readlink(ctx context.Context, name string) (string, error) {
file := a.findFile(name)
if file == nil {
if a.findDirectory(name) != nil {
return "", errNotSymlink
}
return "", os.ErrNotExist
}
if file.FileInfo().Mode()&os.ModeSymlink != os.ModeSymlink {
return "", errNotSymlink
}
symlinkValue, err := a.fs.readlinkCache.findOrFetch(a.cacheNamespace, name, func() (interface{}, error) {
rc, err := file.Open()
if err != nil {
return nil, err
}
defer rc.Close()
var link [maxSymlinkSize + 1]byte
// read up to len(symlink) bytes from the link file
n, err := io.ReadFull(rc, link[:])
if err != nil && err != io.ErrUnexpectedEOF {
// if err == io.ErrUnexpectedEOF the link is smaller than len(symlink) so it's OK to not return it
return nil, err
}
return string(link[:n]), nil
})
if err != nil {
return "", err
}
symlink := symlinkValue.(string)
// return errSymlinkSize if the number of bytes read from the link is too big
if len(symlink) > maxSymlinkSize {
return "", errSymlinkSize
}
return symlink, nil
}
// onEvicted called by the zipVFS.cache when an archive is removed from the cache
func (a *zipArchive) onEvicted() {
metrics.ZipArchiveEntriesCached.Sub(float64(len(a.files)))
}
func (a *zipArchive) openStatus() (archiveStatus, error) {
select {
case <-a.done:
if a.err != nil {
return archiveOpenError, a.err
}
if a.resource != nil && a.resource.Err() != nil {
return archiveCorrupted, a.resource.Err()
}
return archiveOpened, nil
default:
return archiveOpening, nil
}
}
|