-
Notifications
You must be signed in to change notification settings - Fork 0
/
batch_archive.go
324 lines (292 loc) · 10.6 KB
/
batch_archive.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
// Copyright 2015 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/maruel/subcommands"
"github.com/TriggerMail/luci-go/auth"
"github.com/TriggerMail/luci-go/client/archiver"
"github.com/TriggerMail/luci-go/client/internal/common"
"github.com/TriggerMail/luci-go/client/isolate"
"github.com/TriggerMail/luci-go/common/data/text/units"
"github.com/TriggerMail/luci-go/common/isolated"
"github.com/TriggerMail/luci-go/common/isolatedclient"
)
func cmdBatchArchive(defaultAuthOpts auth.Options) *subcommands.Command {
return &subcommands.Command{
UsageLine: "batcharchive <options> file1 file2 ...",
ShortDesc: "archives multiple isolated trees at once.",
LongDesc: `Archives multiple isolated trees at once.
Using single command instead of multiple sequential invocations allows to cut
redundant work when isolated trees share common files (e.g. file hashes are
checked only once, their presence on the server is checked only once, and
so on).
Takes a list of paths to *.isolated.gen.json files that describe what trees to
isolate. Format of files is:
{
"version": 1,
"dir": <absolute path to a directory all other paths are relative to>,
"args": [list of command line arguments for single 'archive' command]
}`,
CommandRun: func() subcommands.CommandRun {
c := batchArchiveRun{}
c.commonServerFlags.Init(defaultAuthOpts)
c.loggingFlags.Init(&c.Flags)
c.Flags.Var(&c.blacklist, "blacklist", "List of globs to use as blacklist filter when uploading directories")
c.Flags.StringVar(&c.dumpJSON, "dump-json", "", "Write isolated digests of archived trees to this file as JSON")
c.Flags.BoolVar(&c.expArchive, "exparchive", true, "IGNORED (deprecated) Whether to use the new exparchive implementation, which tars small files before uploading them.")
c.Flags.IntVar(&c.maxConcurrentChecks, "max-concurrent-checks", 1, "The maxiumum number of in-flight check requests.")
c.Flags.IntVar(&c.maxConcurrentUploads, "max-concurrent-uploads", 8, "The maximum number of in-flight uploads.")
return &c
},
}
}
type batchArchiveRun struct {
commonServerFlags
loggingFlags loggingFlags
dumpJSON string
expArchive bool // deprecated
maxConcurrentChecks int
maxConcurrentUploads int
// Blacklist is a list of filename regexes describing which files to
// ignore.
blacklist common.Strings
}
func (c *batchArchiveRun) Parse(a subcommands.Application, args []string) error {
if err := c.commonServerFlags.Parse(); err != nil {
return err
}
if len(args) == 0 {
return errors.New("at least one isolate file required")
}
return nil
}
func parseArchiveCMD(args []string, cwd string) (*isolate.ArchiveOptions, error) {
// Python isolate allows form "--XXXX-variable key value".
// Golang flag pkg doesn't consider value to be part of --XXXX-variable flag.
// Therefore, we convert all such "--XXXX-variable key value" to
// "--XXXX-variable key --XXXX-variable value" form.
// Note, that key doesn't have "=" in it in either case, but value might.
// TODO(tandrii): eventually, we want to retire this hack.
args = convertPyToGoArchiveCMDArgs(args)
base := subcommands.CommandRunBase{}
i := isolateFlags{}
i.Init(&base.Flags)
if err := base.GetFlags().Parse(args); err != nil {
return nil, err
}
if err := i.Parse(cwd, RequireIsolatedFile); err != nil {
return nil, err
}
if base.GetFlags().NArg() > 0 {
return nil, fmt.Errorf("no positional arguments expected")
}
i.PostProcess(cwd)
return &i.ArchiveOptions, nil
}
// convertPyToGoArchiveCMDArgs converts kv-args from old python isolate into go variants.
// Essentially converts "--X key value" into "--X key=value".
func convertPyToGoArchiveCMDArgs(args []string) []string {
kvars := map[string]bool{
"--path-variable": true, "--config-variable": true, "--extra-variable": true}
var newArgs []string
for i := 0; i < len(args); {
newArgs = append(newArgs, args[i])
kvar := args[i]
i++
if !kvars[kvar] {
continue
}
if i >= len(args) {
// Ignore unexpected behaviour, it'll be caught by flags.Parse() .
break
}
appendArg := args[i]
i++
if !strings.Contains(appendArg, "=") && i < len(args) {
// appendArg is key, and args[i] is value .
appendArg = fmt.Sprintf("%s=%s", appendArg, args[i])
i++
}
newArgs = append(newArgs, appendArg)
}
return newArgs
}
func (c *batchArchiveRun) main(a subcommands.Application, args []string) error {
start := time.Now()
ctx := c.defaultFlags.MakeLoggingContext(os.Stderr)
authClient, err := c.createAuthClient()
if err != nil {
return err
}
client := isolatedclient.New(nil, authClient, c.isolatedFlags.ServerURL, c.isolatedFlags.Namespace, nil, nil)
al := archiveLogger{
start: start,
quiet: c.defaultFlags.Quiet,
}
blacklistStrings := []string(c.blacklist)
return batchArchive(ctx, client, al, c.dumpJSON, c.maxConcurrentChecks, c.maxConcurrentUploads, args, blacklistStrings)
}
// batchArchive archives a series of isolates specified by genJSONPaths.
func batchArchive(ctx context.Context, client *isolatedclient.Client, al archiveLogger, dumpJSONPath string, concurrentChecks, concurrentUploads int, genJSONPaths []string, blacklistStrings []string) error {
// Set up a checker and uploader. We limit the uploader to one concurrent
// upload, since the uploads are all coming from disk (with the exception of
// the isolated JSON itself) and we only want a single goroutine reading from
// disk at once.
checker := archiver.NewChecker(ctx, client, concurrentChecks)
uploader := archiver.NewUploader(ctx, client, concurrentUploads)
a := archiver.NewTarringArchiver(checker, uploader)
var errArchive error
var isolSummaries []archiver.IsolatedSummary
for _, genJSONPath := range genJSONPaths {
opts, err := processGenJSON(genJSONPath)
if err != nil {
return err
}
// Parse the incoming isolate file.
deps, rootDir, isol, err := isolate.ProcessIsolate(opts)
if err != nil {
return fmt.Errorf("isolate %s: failed to process: %v", opts.Isolate, err)
}
log.Printf("Isolate %s referenced %d deps", opts.Isolate, len(deps))
// Use the explicit blacklist if it's provided.
if len(blacklistStrings) > 0 {
opts.Blacklist = blacklistStrings
}
isolSummary, err := a.Archive(deps, rootDir, isol, opts.Blacklist, opts.Isolated)
if err != nil && errArchive == nil {
errArchive = fmt.Errorf("isolate %s: %v", opts.Isolate, err)
} else {
printSummary(al, isolSummary)
isolSummaries = append(isolSummaries, isolSummary)
}
}
if errArchive != nil {
return errArchive
}
// Make sure that all pending items have been checked.
if err := checker.Close(); err != nil {
return err
}
// Make sure that all the uploads have completed successfully.
if err := uploader.Close(); err != nil {
return err
}
if err := dumpSummaryJSON(dumpJSONPath, isolSummaries...); err != nil {
return err
}
al.LogSummary(ctx, int64(checker.Hit.Count()), int64(checker.Miss.Count()), units.Size(checker.Hit.Bytes()), units.Size(checker.Miss.Bytes()), digests(isolSummaries))
return nil
}
// digests extracts the digests from the supplied IsolatedSummarys.
func digests(summaries []archiver.IsolatedSummary) []string {
var result []string
for _, summary := range summaries {
result = append(result, string(summary.Digest))
}
return result
}
// processGenJSON validates a genJSON file and returns the contents.
func processGenJSON(genJSONPath string) (*isolate.ArchiveOptions, error) {
f, err := os.Open(genJSONPath)
if err != nil {
return nil, fmt.Errorf("opening %s: %s", genJSONPath, err)
}
defer f.Close()
opts, err := processGenJSONData(f)
if err != nil {
return nil, fmt.Errorf("processing %s: %s", genJSONPath, err)
}
return opts, nil
}
// processGenJSONData performs the function of processGenJSON, but operates on an io.Reader.
func processGenJSONData(r io.Reader) (*isolate.ArchiveOptions, error) {
data := &struct {
Args []string
Dir string
Version int
}{}
if err := json.NewDecoder(r).Decode(data); err != nil {
return nil, fmt.Errorf("failed to decode: %s", err)
}
if data.Version != isolate.IsolatedGenJSONVersion {
return nil, fmt.Errorf("invalid version %d", data.Version)
}
if fileInfo, err := os.Stat(data.Dir); err != nil || !fileInfo.IsDir() {
return nil, fmt.Errorf("invalid dir %s", data.Dir)
}
opts, err := parseArchiveCMD(data.Args, data.Dir)
if err != nil {
return nil, fmt.Errorf("invalid archive command: %s", err)
}
return opts, nil
}
// strippedIsolatedName returns the base name of an isolated path, with the extension (if any) removed.
func strippedIsolatedName(isolated string) string {
name := filepath.Base(isolated)
// Strip the extension if there is one.
if dotIndex := strings.LastIndex(name, "."); dotIndex != -1 {
return name[0:dotIndex]
}
return name
}
func writeJSONDigestFile(filePath string, data map[string]isolated.HexDigest) error {
digestBytes, err := json.MarshalIndent(data, "", " ")
if err != nil {
return fmt.Errorf("encoding digest JSON: %s", err)
}
return writeFile(filePath, digestBytes)
}
// writeFile writes data to filePath. File permission is set to user only.
func writeFile(filePath string, data []byte) error {
f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return fmt.Errorf("opening %s: %s", filePath, err)
}
// NOTE: We don't defer f.Close here, because it may return an error.
_, writeErr := f.Write(data)
closeErr := f.Close()
if writeErr != nil {
return fmt.Errorf("writing %s: %s", filePath, writeErr)
} else if closeErr != nil {
return fmt.Errorf("closing %s: %s", filePath, closeErr)
}
return nil
}
func (c *batchArchiveRun) Run(a subcommands.Application, args []string, _ subcommands.Env) int {
if err := c.Parse(a, args); err != nil {
fmt.Fprintf(a.GetErr(), "%s: %s\n", a.GetName(), err)
return 1
}
cl, err := c.defaultFlags.StartTracing()
if err != nil {
fmt.Fprintf(a.GetErr(), "%s: %s\n", a.GetName(), err)
return 1
}
defer cl.Close()
if err := c.main(a, args); err != nil {
fmt.Fprintf(a.GetErr(), "%s: %s\n", a.GetName(), err)
return 1
}
return 0
}