Welcome to mirror list, hosted at ThFree Co, Russian Federation.

archive.go « archive « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4667f9ae001bad439fee1c3b566596876cd3299f (plain)
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
package archive

import (
	"archive/tar"
	"context"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"runtime"
	"strings"

	"gitlab.com/gitlab-org/gitaly/v16/internal/command"
	"golang.org/x/exp/slices"
)

const (
	// readDirEntriesPageSize is an amount of fs.DirEntry(s) to read
	// from the opened file descriptor of the directory.
	readDirEntriesPageSize = 32

	// Below is a set of flags used to decide what to do with the file/directory
	// found on the disk.
	// decisionWrite means that the file/directory needs to be added to the archive
	decisionWrite = iota
	// decisionSkip means that the file/directory shouldn't be added to the archive
	decisionSkip
	// decisionStop means that nothing else left to be added to the archive
	decisionStop

	// tarFormat is a format to use for the archived files/directories/etc.
	// The decision is made to use it as it is the latest version of the format.
	// It allows sparse files, long file names, etc. that older formats doesn't support.
	tarFormat = tar.FormatPAX
)

type decider func(string) int

// WriteTarball writes a tarball to an `io.Writer` for the provided path
// containing the specified archive members. Members should be specified
// relative to `path`.
func WriteTarball(ctx context.Context, writer io.Writer, path string, members ...string) error {
	cmdArgs := []string{"-c", "-f", "-", "-C", path}

	if runtime.GOOS == "darwin" {
		cmdArgs = append(cmdArgs, "--no-mac-metadata")
	}

	cmdArgs = append(cmdArgs, members...)

	cmd, err := command.New(ctx, append([]string{"tar"}, cmdArgs...), command.WithStdout(writer))
	if err != nil {
		return fmt.Errorf("executing tar command: %w", err)
	}

	if err := cmd.Wait(); err != nil {
		return fmt.Errorf("waiting for tar command completion: %w", err)
	}

	return nil
}

// writeTarball creates a tar archive by flushing data into writer.
// Files and folders to be included into archive needs to be provided as members.
// If entry from members slice points to a folder all content inside it will be archived.
// The empty folders will be archived as well.
// It doesn't support sparse files efficiently, see https://github.com/golang/go/issues/22735
func writeTarball(ctx context.Context, writer io.Writer, path string, members ...string) error {
	// The function decides what to do with the entry: write, skip or finish archive
	// creation if all members are added.
	decide := func(candidate string) int {
		if len(members) == 0 {
			return decisionStop
		}

		idx := slices.Index(members, candidate)
		if idx < 0 {
			return decisionSkip
		}

		members = slices.Delete(members, idx, idx+1)
		return decisionWrite
	}

	archWriter := tar.NewWriter(writer)
	if err := walkDir(ctx, archWriter, path, "", decide); err != nil {
		return fmt.Errorf("walk dir: %w", err)
	}

	if err := archWriter.Close(); err != nil {
		return fmt.Errorf("closing archive writer: %w", err)
	}

	return nil
}

func walkDir(ctx context.Context, archWriter *tar.Writer, path, currentPrefix string, decide decider) error {
	if cancelled(ctx) {
		return ctx.Err()
	}

	dir, err := os.Open(path)
	if err != nil {
		return fmt.Errorf("open dir: %w", err)
	}
	defer func() { _ = dir.Close() }()

	dirStat, err := dir.Stat()
	if err != nil {
		return fmt.Errorf("dir description: %w", err)
	}

	if dirStat.Mode().Type() != fs.ModeDir {
		return errors.New("is not a dir")
	}

	for {
		// Own implementation of the directory walker is used for optimization.
		// fs.WalkDir() reads all the entries into memory at once and does the sorting.
		// If there are a lot of files in the nested directories all that info will remain
		// in the memory while the leaf is reached. In other words if there is 1000 files
		// in the root and 1000 file in the nested directory of the root in one moment
		// 2000 entries will remain in the memory for no reason.
		dirEntries, err := dir.ReadDir(readDirEntriesPageSize)
		if err != nil {
			if errors.Is(err, io.EOF) {
				return nil
			}

			return fmt.Errorf("chunked dir read: %w", err)
		}

		for _, dirEntry := range dirEntries {
			if cancelled(ctx) {
				return ctx.Err()
			}

			entryName := dirEntry.Name()
			entryRelativePath := filepath.Join(currentPrefix, entryName)

			decision := decide(entryRelativePath)
			switch decision {
			case decisionStop:
				// Nothing needs to be added to the archive.
				return nil
			case decisionSkip:
				// Current entry doesn't need to be added, but we need travers it if it is a directory.
				if dirEntry.IsDir() {
					if err := walkDir(ctx, archWriter, filepath.Join(path, entryName), entryRelativePath, decide); err != nil {
						return fmt.Errorf("walk dir: %w", err)
					}
				}
			case decisionWrite:
				if dirEntry.IsDir() {
					// As this is a dir we add all its content to the archive.
					if err := tarDir(ctx, archWriter, filepath.Join(path, entryName), entryRelativePath, func(string) int { return decisionWrite }); err != nil {
						return fmt.Errorf("write dir: %w", err)
					}
					continue
				}

				if err := tarFile(archWriter, path, entryRelativePath); err != nil {
					return fmt.Errorf("write file: %w", err)
				}
			default:
				return fmt.Errorf("unhandled decision: %d", decision)
			}
		}
	}
}

func tarDir(ctx context.Context, archWriter *tar.Writer, path, currentPrefix string, decide decider) error {
	// The current entry is a directory that needs to be added to the archive.
	stat, err := os.Lstat(path)
	if err != nil {
		return err
	}

	link := ""
	if stat.Mode()&fs.ModeSymlink != 0 {
		link, err = os.Readlink(path)
		if err != nil {
			return fmt.Errorf("read link destination: %w", err)
		}
	}

	header, err := tar.FileInfoHeader(stat, link)
	if err != nil {
		return fmt.Errorf("file info header: %w", err)
	}
	header.Name = strings.TrimSuffix(currentPrefix, "/") + "/"
	header.Format = tarFormat

	if err := archWriter.WriteHeader(header); err != nil {
		return fmt.Errorf("write file info header: %w", err)
	}

	if err := walkDir(ctx, archWriter, path, currentPrefix, decide); err != nil {
		return fmt.Errorf("walk dir: %w", err)
	}

	return nil
}

func tarFile(archWriter *tar.Writer, path, entryRelativePath string) error {
	entryPath := filepath.Join(path, filepath.Base(entryRelativePath))

	entryStat, err := os.Lstat(entryPath)
	if err != nil {
		return fmt.Errorf("file/link description: %w", err)
	}

	if entryStat.Mode()&fs.ModeSymlink != 0 {
		targetPath, err := os.Readlink(entryPath)
		if err != nil {
			return fmt.Errorf("read link destination: %w", err)
		}

		header := &tar.Header{
			Typeflag: tar.TypeSymlink,
			Name:     entryRelativePath,
			Linkname: targetPath,
			Format:   tarFormat,
			Mode:     int64(entryStat.Mode().Perm()),
		}

		if err := archWriter.WriteHeader(header); err != nil {
			return fmt.Errorf("write symlink file info header: %w", err)
		}

		return nil
	}

	curFile, err := os.Open(entryPath)
	if err != nil {
		return fmt.Errorf("open file: %w", err)
	}
	defer func() { _ = curFile.Close() }()

	curFileStat, err := curFile.Stat()
	if err != nil {
		return fmt.Errorf("file description: %w", err)
	}

	header, err := tar.FileInfoHeader(curFileStat, curFileStat.Name())
	if err != nil {
		return fmt.Errorf("file info header: %w", err)
	}
	header.Name = entryRelativePath
	header.Format = tarFormat

	if err := archWriter.WriteHeader(header); err != nil {
		return fmt.Errorf("write file info header: %w", err)
	}

	if _, err := io.Copy(archWriter, curFile); err != nil {
		return fmt.Errorf("copy file: %w", err)
	}

	return nil
}

func cancelled(ctx context.Context) bool {
	select {
	case <-ctx.Done():
		return true
	default:
		return false
	}
}