/
main.go
3057 lines (2665 loc) · 88.5 KB
/
main.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 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 cli
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/maruel/subcommands"
"go.chromium.org/luci/auth"
"go.chromium.org/luci/client/versioncli"
"go.chromium.org/luci/common/cli"
"go.chromium.org/luci/common/data/stringset"
"go.chromium.org/luci/common/errors"
"go.chromium.org/luci/common/flag/fixflagpos"
"go.chromium.org/luci/common/logging"
"go.chromium.org/luci/common/logging/gologger"
"go.chromium.org/luci/common/retry/transient"
"go.chromium.org/luci/auth/client/authcli"
api "go.chromium.org/luci/cipd/api/cipd/v1"
"go.chromium.org/luci/cipd/client/cipd"
"go.chromium.org/luci/cipd/client/cipd/builder"
"go.chromium.org/luci/cipd/client/cipd/deployer"
"go.chromium.org/luci/cipd/client/cipd/digests"
"go.chromium.org/luci/cipd/client/cipd/ensure"
"go.chromium.org/luci/cipd/client/cipd/fs"
"go.chromium.org/luci/cipd/client/cipd/pkg"
"go.chromium.org/luci/cipd/client/cipd/reader"
"go.chromium.org/luci/cipd/client/cipd/template"
"go.chromium.org/luci/cipd/common"
)
// TODO(vadimsh): Add some tests.
func expandTemplate(tmpl string) (pkg string, err error) {
pkg, err = template.DefaultExpander().Expand(tmpl)
if err != nil {
err = commandLineError{err}
}
return
}
// Parameters carry default configuration values for a CIPD CLI client.
type Parameters struct {
// DefaultAuthOptions provide default values for authentication related
// options (most notably SecretsDir: a directory with token cache).
DefaultAuthOptions auth.Options
// ServiceURL is a backend URL to use by default.
ServiceURL string
}
////////////////////////////////////////////////////////////////////////////////
// Common subcommand functions.
// pinInfo contains information about single package pin inside some site root,
// or an error related to it. It is passed through channels when running batch
// operations and dumped to JSON results file in doneWithPins.
type pinInfo struct {
// Pkg is package name. Always set.
Pkg string `json:"package"`
// Pin is not nil if pin related operation succeeded. It contains instanceID.
Pin *common.Pin `json:"pin,omitempty"`
// Platform is set by 'ensure-file-verify' to a platform for this pin.
Platform string `json:"platform,omitempty"`
// Tracking is what ref is being tracked by that package in the site root.
Tracking string `json:"tracking,omitempty"`
// Err is not empty if pin related operation failed. Pin is nil in that case.
Err string `json:"error,omitempty"`
}
type instanceInfoWithRefs struct {
cipd.InstanceInfo
Refs []string `json:"refs,omitempty"`
}
// instancesOutput defines JSON format of 'cipd instances' output.
type instancesOutput struct {
Instances []instanceInfoWithRefs `json:"instances"`
}
// cipdSubcommand is a base of all CIPD subcommands. It defines some common
// flags, such as logging and JSON output parameters.
type cipdSubcommand struct {
subcommands.CommandRunBase
jsonOutput string
logConfig logging.Config
// TODO(dnj): Remove "verbose" flag once all current invocations of it are
// cleaned up and rolled out, as it is now deprecated in favor of "logConfig".
verbose bool
}
// ModifyContext implements cli.ContextModificator.
func (c *cipdSubcommand) ModifyContext(ctx context.Context) context.Context {
if c.verbose {
ctx = logging.SetLevel(ctx, logging.Debug)
} else {
ctx = c.logConfig.Set(ctx)
}
return ctx
}
// registerBaseFlags registers common flags used by all subcommands.
func (c *cipdSubcommand) registerBaseFlags() {
// Minimum default logging level is Info. This accommodates subcommands that
// don't explicitly set the log level, resulting in the zero value (Debug).
if c.logConfig.Level < logging.Info {
c.logConfig.Level = logging.Info
}
c.Flags.StringVar(&c.jsonOutput, "json-output", "", "Path to write operation results to.")
c.Flags.BoolVar(&c.verbose, "verbose", false, "Enable more logging (deprecated, use -log-level=debug).")
c.logConfig.AddFlags(&c.Flags)
}
// checkArgs checks command line args.
//
// It ensures all required positional and flag-like parameters are set.
// Returns true if they are, or false (and prints to stderr) if not.
func (c *cipdSubcommand) checkArgs(args []string, minPosCount, maxPosCount int) bool {
// Check number of expected positional arguments.
if maxPosCount == 0 && len(args) != 0 {
c.printError(makeCLIError("unexpected arguments %v", args))
return false
}
if len(args) < minPosCount || (maxPosCount >= 0 && len(args) > maxPosCount) {
var err error
if minPosCount == maxPosCount {
err = makeCLIError("expecting %d positional argument, got %d instead", minPosCount, len(args))
} else {
if maxPosCount >= 0 {
err = makeCLIError(
"expecting from %d to %d positional arguments, got %d instead",
minPosCount, maxPosCount, len(args))
} else {
err = makeCLIError(
"expecting at least %d positional arguments, got %d instead",
minPosCount, len(args))
}
}
c.printError(err)
return false
}
// Check required unset flags.
unset := []*flag.Flag{}
c.Flags.VisitAll(func(f *flag.Flag) {
if strings.HasPrefix(f.DefValue, "<") && f.Value.String() == f.DefValue {
unset = append(unset, f)
}
})
if len(unset) != 0 {
missing := make([]string, len(unset))
for i, f := range unset {
missing[i] = f.Name
}
c.printError(makeCLIError("missing required flags: %v", missing))
return false
}
return true
}
// printError prints error to stderr (recognizing commandLineError).
func (c *cipdSubcommand) printError(err error) {
if _, ok := err.(commandLineError); ok {
fmt.Fprintf(os.Stderr, "Bad command line: %s.\n\n", err)
c.Flags.Usage()
return
}
if merr, _ := err.(errors.MultiError); len(merr) != 0 {
fmt.Fprintln(os.Stderr, "Errors:")
for _, err := range merr {
fmt.Fprintf(os.Stderr, " %s\n", err)
}
return
}
fmt.Fprintf(os.Stderr, "Error: %s.\n", err)
}
// writeJSONOutput writes result to JSON output file. It returns original error
// if it is non-nil.
func (c *cipdSubcommand) writeJSONOutput(result interface{}, err error) error {
// -json-output flag wasn't specified.
if c.jsonOutput == "" {
return err
}
// Prepare the body of the output file.
var body struct {
Error string `json:"error,omitempty"`
Result interface{} `json:"result,omitempty"`
}
if err != nil {
body.Error = err.Error()
}
body.Result = result
out, e := json.MarshalIndent(&body, "", " ")
if e != nil {
if err == nil {
err = e
} else {
fmt.Fprintf(os.Stderr, "Failed to serialize JSON output: %s\n", e)
}
return err
}
e = ioutil.WriteFile(c.jsonOutput, out, 0666)
if e != nil {
if err == nil {
err = e
} else {
fmt.Fprintf(os.Stderr, "Failed write JSON output to %s: %s\n", c.jsonOutput, e)
}
return err
}
return err
}
// done is called as a last step of processing a subcommand. It dumps command
// result (or error) to JSON output file, prints error message and generates
// process exit code.
func (c *cipdSubcommand) done(result interface{}, err error) int {
err = c.writeJSONOutput(result, err)
if err != nil {
c.printError(err)
return 1
}
return 0
}
// doneWithPins is a handy shortcut that prints a pinInfo slice and
// deduces process exit code based on presence of errors there.
//
// This just calls through to doneWithPinMap.
func (c *cipdSubcommand) doneWithPins(pins []pinInfo, err error) int {
return c.doneWithPinMap(map[string][]pinInfo{"": pins}, err)
}
// doneWithPinMap is a handy shortcut that prints the subdir->pinInfo map and
// deduces process exit code based on presence of errors there.
func (c *cipdSubcommand) doneWithPinMap(pins map[string][]pinInfo, err error) int {
if len(pins) == 0 {
if err == nil { // this error will be printed in c.done(...)
fmt.Println("No packages.")
}
} else {
printPinsAndError(pins)
}
if ret := c.done(pins, err); ret != 0 {
return ret
}
for _, infos := range pins {
if hasErrors(infos) {
return 1
}
}
return 0
}
// commandLineError is used to tag errors related to CLI.
type commandLineError struct {
error
}
// makeCLIError returns new commandLineError.
func makeCLIError(msg string, args ...interface{}) error {
return commandLineError{fmt.Errorf(msg, args...)}
}
////////////////////////////////////////////////////////////////////////////////
// clientOptions mixin.
type rootDirFlag bool
const (
withRootDir rootDirFlag = true
withoutRootDir rootDirFlag = false
)
// clientOptions defines command line arguments related to CIPD client creation.
// Subcommands that need a CIPD client embed it.
type clientOptions struct {
hardcoded Parameters // whatever was passed to registerFlags(...)
serviceURL string // also mutated by loadEnsureFile
cacheDir string
rootDir string // used only if registerFlags got withRootDir arg
versions ensure.VersionsFile // mutated by loadEnsureFile
authFlags authcli.Flags
}
func (opts *clientOptions) resolvedServiceURL() string {
if opts.serviceURL != "" {
return opts.serviceURL
}
return opts.hardcoded.ServiceURL
}
func (opts *clientOptions) registerFlags(f *flag.FlagSet, params Parameters, rootDir rootDirFlag) {
opts.hardcoded = params
f.StringVar(&opts.serviceURL, "service-url", "",
fmt.Sprintf(`Backend URL. If provided via an "ensure" file, the URL in the file takes precedence. `+
`(default %s)`, params.ServiceURL))
f.StringVar(&opts.cacheDir, "cache-dir", "",
fmt.Sprintf("Directory for the shared cache (can also be set by %s env var).", cipd.EnvCacheDir))
if rootDir {
f.StringVar(&opts.rootDir, "root", "<path>", "Path to an installation site root directory.")
}
opts.authFlags.Register(f, params.DefaultAuthOptions)
}
func (opts *clientOptions) toCIPDClientOpts(ctx context.Context) (cipd.ClientOptions, error) {
authOpts, err := opts.authFlags.Options()
if err != nil {
return cipd.ClientOptions{}, err
}
client, err := auth.NewAuthenticator(ctx, auth.OptionalLogin, authOpts).Client()
if err != nil {
return cipd.ClientOptions{}, err
}
realOpts := cipd.ClientOptions{
ServiceURL: opts.resolvedServiceURL(),
Root: opts.rootDir,
CacheDir: opts.cacheDir,
Versions: opts.versions,
AuthenticatedClient: client,
AnonymousClient: http.DefaultClient,
LoginInstructions: "run `cipd auth-login` to login or relogin",
}
if err := realOpts.LoadFromEnv(cli.MakeGetEnv(ctx)); err != nil {
return cipd.ClientOptions{}, err
}
return realOpts, nil
}
func (opts *clientOptions) makeCIPDClient(ctx context.Context) (cipd.Client, error) {
cipdOpts, err := opts.toCIPDClientOpts(ctx)
if err != nil {
return nil, err
}
return cipd.NewClient(cipdOpts)
}
////////////////////////////////////////////////////////////////////////////////
// inputOptions mixin.
// packageVars holds array of '-pkg-var' command line options.
type packageVars map[string]string
func (vars *packageVars) String() string {
// String() for empty vars used in -help output.
if len(*vars) == 0 {
return "key:value"
}
chunks := make([]string, 0, len(*vars))
for k, v := range *vars {
chunks = append(chunks, fmt.Sprintf("%s:%s", k, v))
}
sort.Strings(chunks)
return strings.Join(chunks, ", ")
}
// Set is called by 'flag' package when parsing command line options.
func (vars *packageVars) Set(value string) error {
// <key>:<value> pair.
chunks := strings.SplitN(value, ":", 2)
if len(chunks) != 2 {
return makeCLIError("expecting <key>:<value> pair, got %q", value)
}
(*vars)[chunks[0]] = chunks[1]
return nil
}
// inputOptions defines command line arguments that specify where to get data
// for a new package and how to build it.
//
// Subcommands that build packages embed it.
type inputOptions struct {
// Path to *.yaml file with package definition.
packageDef string
vars packageVars
// Alternative to 'pkg-def'.
packageName string
inputDir string
installMode pkg.InstallMode
preserveModTime bool
preserveWritable bool
// Deflate compression level (if [1-9]) or 0 to disable compression.
//
// Default is 5.
compressionLevel int
}
func (opts *inputOptions) registerFlags(f *flag.FlagSet) {
// Set default vars (e.g. ${platform}). They may be overridden through flags.
defVars := template.DefaultExpander()
opts.vars = make(packageVars, len(defVars))
for k, v := range defVars {
opts.vars[k] = v
}
// Interface to accept package definition file.
f.StringVar(&opts.packageDef, "pkg-def", "", "*.yaml file that defines what to put into the package.")
f.Var(&opts.vars, "pkg-var", "Variables accessible from package definition file.")
// Interface to accept a single directory (alternative to -pkg-def).
f.StringVar(&opts.packageName, "name", "", "Package name (unused with -pkg-def).")
f.StringVar(&opts.inputDir, "in", "", "Path to a directory with files to package (unused with -pkg-def).")
f.Var(&opts.installMode, "install-mode",
"How the package should be installed: \"copy\" or \"symlink\" (unused with -pkg-def).")
f.BoolVar(&opts.preserveModTime, "preserve-mtime", false,
"Preserve file's modification time (unused with -pkg-def).")
f.BoolVar(&opts.preserveWritable, "preserve-writable", false,
"Preserve file's writable permission bit (unused with -pkg-def).")
// Options for the builder.
f.IntVar(&opts.compressionLevel, "compression-level", 5,
"Deflate compression level [0-9]: 0 - disable, 1 - best speed, 9 - best compression.")
}
// prepareInput processes inputOptions by collecting all files to be added to
// a package and populating builder.Options. Caller is still responsible to fill
// out Output field of Options.
func (opts *inputOptions) prepareInput() (builder.Options, error) {
empty := builder.Options{}
if opts.compressionLevel < 0 || opts.compressionLevel > 9 {
return empty, makeCLIError("invalid -compression-level: must be in [0-9] set")
}
// Handle -name and -in if defined. Do not allow -pkg-def in that case, since
// it provides same information as -name and -in. Note that -pkg-var are
// ignored, even if defined. There's nothing to apply them to.
if opts.inputDir != "" {
if opts.packageName == "" {
return empty, makeCLIError("missing required flag: -name")
}
if opts.packageDef != "" {
return empty, makeCLIError("-pkg-def and -in can not be used together")
}
packageName, err := expandTemplate(opts.packageName)
if err != nil {
return empty, err
}
// Simply enumerate files in the directory.
files, err := fs.ScanFileSystem(opts.inputDir, opts.inputDir, nil, fs.ScanOptions{
PreserveModTime: opts.preserveModTime,
PreserveWritable: opts.preserveWritable,
})
if err != nil {
return empty, err
}
return builder.Options{
Input: files,
PackageName: packageName,
InstallMode: opts.installMode,
CompressionLevel: opts.compressionLevel,
}, nil
}
// Handle -pkg-def case. -in is "" (already checked), reject -name.
if opts.packageDef != "" {
if opts.packageName != "" {
return empty, makeCLIError("-pkg-def and -name can not be used together")
}
if opts.installMode != "" {
return empty, makeCLIError("-install-mode is ignored if -pkg-def is used")
}
if opts.preserveModTime {
return empty, makeCLIError("-preserve-mtime is ignored if -pkg-def is used")
}
if opts.preserveWritable {
return empty, makeCLIError("-preserve-writable is ignored if -pkg-def is used")
}
// Parse the file, perform variable substitution.
f, err := os.Open(opts.packageDef)
if err != nil {
return empty, err
}
defer f.Close()
pkgDef, err := builder.LoadPackageDef(f, opts.vars)
if err != nil {
return empty, err
}
// Scan the file system. Package definition may use path relative to the
// package definition file itself, so pass its location.
fmt.Println("Enumerating files to zip...")
files, err := pkgDef.FindFiles(filepath.Dir(opts.packageDef))
if err != nil {
return empty, err
}
return builder.Options{
Input: files,
PackageName: pkgDef.Package,
VersionFile: pkgDef.VersionFile(),
InstallMode: pkgDef.InstallMode,
CompressionLevel: opts.compressionLevel,
}, nil
}
// All command line options are missing.
return empty, makeCLIError("-pkg-def or -name/-in are required")
}
////////////////////////////////////////////////////////////////////////////////
// refsOptions mixin.
// refList holds an array of '-ref' command line options.
type refList []string
func (refs *refList) String() string {
// String() for empty vars used in -help output.
if len(*refs) == 0 {
return "ref"
}
return strings.Join(*refs, " ")
}
// Set is called by 'flag' package when parsing command line options.
func (refs *refList) Set(value string) error {
err := common.ValidatePackageRef(value)
if err != nil {
return commandLineError{err}
}
*refs = append(*refs, value)
return nil
}
// refsOptions defines command line arguments for commands that accept a set
// of refs.
type refsOptions struct {
refs refList
}
func (opts *refsOptions) registerFlags(f *flag.FlagSet) {
f.Var(&opts.refs, "ref", "A ref to point to the package instance (can be used multiple times).")
}
////////////////////////////////////////////////////////////////////////////////
// tagsOptions mixin.
// tagList holds an array of '-tag' command line options.
type tagList []string
func (tags *tagList) String() string {
// String() for empty vars used in -help output.
if len(*tags) == 0 {
return "key:value"
}
return strings.Join(*tags, " ")
}
// Set is called by 'flag' package when parsing command line options.
func (tags *tagList) Set(value string) error {
err := common.ValidateInstanceTag(value)
if err != nil {
return commandLineError{err}
}
*tags = append(*tags, value)
return nil
}
// tagsOptions defines command line arguments for commands that accept a set
// of tags.
type tagsOptions struct {
tags tagList
}
func (opts *tagsOptions) registerFlags(f *flag.FlagSet) {
f.Var(&opts.tags, "tag", "A tag to attach to the package instance (can be used multiple times).")
}
////////////////////////////////////////////////////////////////////////////////
// uploadOptions mixin.
// uploadOptions defines command line options for commands that upload packages.
type uploadOptions struct {
verificationTimeout time.Duration
}
func (opts *uploadOptions) registerFlags(f *flag.FlagSet) {
f.DurationVar(
&opts.verificationTimeout, "verification-timeout",
cipd.CASFinalizationTimeout, "Maximum time to wait for backend-side package hash verification.")
}
////////////////////////////////////////////////////////////////////////////////
// deployOptions mixin.
type deployOptions struct {
maxThreads int
}
func (opts *deployOptions) registerFlags(f *flag.FlagSet) {
f.IntVar(&opts.maxThreads, "max-threads", 1,
"Number of worker threads for extracting packages. If 0, uses CPU count.")
}
func (opts *deployOptions) loadMaxThreads(ctx context.Context) (int, error) {
if opts.maxThreads == 1 {
if v := cli.Getenv(ctx, cipd.EnvMaxThreads); v != "" {
maxThreads, err := strconv.Atoi(v)
if err != nil {
return opts.maxThreads, fmt.Errorf("bad %s: not an integer - %s", cipd.EnvMaxThreads, v)
}
opts.maxThreads = maxThreads
}
}
return opts.maxThreads, nil
}
////////////////////////////////////////////////////////////////////////////////
// hashOptions mixin.
// allAlgos is used in the flag help text, it is "sha256, sha1, ...".
var allAlgos string
func init() {
algos := make([]string, 0, len(api.HashAlgo_name)-1)
for i := len(api.HashAlgo_name) - 1; i > 0; i-- {
algos = append(algos, strings.ToLower(api.HashAlgo_name[int32(i)]))
}
allAlgos = strings.Join(algos, ", ")
}
// hashAlgoFlag adapts api.HashAlgo to flag.Value interface.
type hashAlgoFlag api.HashAlgo
// String is called by 'flag' package when displaying default value of a flag.
func (ha *hashAlgoFlag) String() string {
return strings.ToLower(api.HashAlgo(*ha).String())
}
// Set is called by 'flag' package when parsing command line options.
func (ha *hashAlgoFlag) Set(value string) error {
val := api.HashAlgo_value[strings.ToUpper(value)]
if val == 0 {
return fmt.Errorf("unknown hash algo %q, should be one of: %s", value, allAlgos)
}
*ha = hashAlgoFlag(val)
return nil
}
// hashOptions defines -hash-algo flag that specifies hash algo to use for
// constructing instance IDs.
//
// Default value is given by common.DefaultHashAlgo.
//
// Not all algos may be accepted by the server.
type hashOptions struct {
algo hashAlgoFlag
}
func (opts *hashOptions) registerFlags(f *flag.FlagSet) {
opts.algo = hashAlgoFlag(common.DefaultHashAlgo)
f.Var(&opts.algo, "hash-algo", fmt.Sprintf("Algorithm to use for deriving package instance ID, one of: %s", allAlgos))
}
func (opts *hashOptions) hashAlgo() api.HashAlgo {
return api.HashAlgo(opts.algo)
}
////////////////////////////////////////////////////////////////////////////////
// ensureFileOptions mixin.
type legacyListFlag bool
const (
withLegacyListFlag legacyListFlag = true
withoutLegacyListFlag legacyListFlag = false
)
type ensureOutFlag bool
const (
withEnsureOutFlag ensureOutFlag = true
withoutEnsureOutFlag ensureOutFlag = false
)
type verifyingEnsureFile bool
const (
requireVerifyPlatforms verifyingEnsureFile = true
ignoreVerifyPlatforms verifyingEnsureFile = false
)
type versionFileOpt bool
const (
parseVersionsFile versionFileOpt = true
ignoreVersionsFile versionFileOpt = false
)
// ensureFileOptions defines -ensure-file flag that specifies a location of the
// "ensure file", which is a manifest that describes what should be installed
// into a site root.
type ensureFileOptions struct {
ensureFile string
ensureFileOut string // used only if registerFlags got withEnsureOutFlag arg
}
func (opts *ensureFileOptions) registerFlags(f *flag.FlagSet, out ensureOutFlag, list legacyListFlag) {
f.StringVar(&opts.ensureFile, "ensure-file", "<path>",
`An "ensure" file. See syntax described here: `+
`https://godoc.org/go.chromium.org/luci/cipd/client/cipd/ensure.`+
` Providing '-' will read from stdin.`)
if out {
f.StringVar(&opts.ensureFileOut, "ensure-file-output", "",
`A path to write an "ensure" file which is the fully-resolved version `+
`of the input ensure file for the current platform. This output will `+
`not contain any ${params} or $Settings other than $ServiceURL.`)
}
if list {
f.StringVar(&opts.ensureFile, "list", "<path>", "(DEPRECATED) A synonym for -ensure-file.")
}
}
// loadEnsureFile parses the ensure file and mutates clientOpts to point to a
// service URL specified in the ensure file.
func (opts *ensureFileOptions) loadEnsureFile(ctx context.Context, clientOpts *clientOptions, verifying verifyingEnsureFile, parseVers versionFileOpt) (*ensure.File, error) {
parsedFile, err := ensure.LoadEnsureFile(opts.ensureFile)
if err != nil {
return nil, err
}
// Prefer the ServiceURL from the file (if set), and log a warning if the user
// provided one on the command line that doesn't match the one in the file.
if parsedFile.ServiceURL != "" {
if clientOpts.serviceURL != "" && clientOpts.serviceURL != parsedFile.ServiceURL {
logging.Warningf(ctx, "serviceURL in ensure file != serviceURL on CLI (%q v %q). Using %q from file.",
parsedFile.ServiceURL, clientOpts.serviceURL, parsedFile.ServiceURL)
}
clientOpts.serviceURL = parsedFile.ServiceURL
}
if verifying && len(parsedFile.VerifyPlatforms) == 0 {
logging.Errorf(ctx,
"For this feature to work, verification platforms must be specified in "+
"the ensure file using one or more $VerifiedPlatform directives.")
return nil, errors.New("no verification platforms configured")
}
if parseVers && parsedFile.ResolvedVersions != "" {
clientOpts.versions, err = loadVersionsFile(parsedFile.ResolvedVersions, opts.ensureFile)
if err != nil {
return nil, err
}
logging.Debugf(ctx, "Using the resolved version file %q", filepath.Base(parsedFile.ResolvedVersions))
}
return parsedFile, nil
}
////////////////////////////////////////////////////////////////////////////////
// Support for running operations concurrently.
// batchOperation defines what to do with a packages matching a prefix.
type batchOperation struct {
client cipd.Client
packagePrefix string // a package name or a prefix
packages []string // packages to operate on, overrides packagePrefix
callback func(pkg string) (common.Pin, error)
}
// expandPkgDir takes a package name or '<prefix>/' and returns a list
// of matching packages (asking backend if necessary). Doesn't recurse, returns
// only direct children.
func expandPkgDir(ctx context.Context, c cipd.Client, packagePrefix string) ([]string, error) {
if !strings.HasSuffix(packagePrefix, "/") {
return []string{packagePrefix}, nil
}
pkgs, err := c.ListPackages(ctx, packagePrefix, false, false)
if err != nil {
return nil, err
}
// Skip directories.
var out []string
for _, p := range pkgs {
if !strings.HasSuffix(p, "/") {
out = append(out, p)
}
}
if len(out) == 0 {
return nil, fmt.Errorf("no packages under %s", packagePrefix)
}
return out, nil
}
// performBatchOperation expands a package prefix into a list of packages and
// calls callback for each of them (concurrently) gathering the results.
//
// Returns an error only if the prefix expansion fails. Errors from individual
// operations are returned through []pinInfo, use hasErrors to check them.
func performBatchOperation(ctx context.Context, op batchOperation) ([]pinInfo, error) {
op.client.BeginBatch(ctx)
defer op.client.EndBatch(ctx)
pkgs := op.packages
if len(pkgs) == 0 {
var err error
pkgs, err = expandPkgDir(ctx, op.client, op.packagePrefix)
if err != nil {
return nil, err
}
}
return callConcurrently(pkgs, func(pkg string) pinInfo {
pin, err := op.callback(pkg)
if err != nil {
return pinInfo{Pkg: pkg, Err: err.Error()}
}
return pinInfo{Pkg: pkg, Pin: &pin}
}), nil
}
func callConcurrently(pkgs []string, callback func(pkg string) pinInfo) []pinInfo {
// Push index through channel to make results ordered as 'pkgs'.
ch := make(chan struct {
int
pinInfo
})
for idx, pkg := range pkgs {
go func(idx int, pkg string) {
ch <- struct {
int
pinInfo
}{idx, callback(pkg)}
}(idx, pkg)
}
pins := make([]pinInfo, len(pkgs))
for i := 0; i < len(pkgs); i++ {
res := <-ch
pins[res.int] = res.pinInfo
}
return pins
}
func printPinsAndError(pinMap map[string][]pinInfo) {
for subdir, pins := range pinMap {
hasPins := false
hasErrors := false
for _, p := range pins {
if p.Err != "" {
hasErrors = true
} else if p.Pin != nil {
hasPins = true
}
}
subdirString := ""
if (hasPins || hasErrors) && (len(pinMap) > 1 || subdir != "") {
// only print this if it's not the root subdir, or there's more than one
// subdir in pinMap.
subdirString = fmt.Sprintf(" (subdir %q)", subdir)
}
if hasPins {
fmt.Printf("Packages%s:\n", subdirString)
for _, p := range pins {
if p.Err != "" || p.Pin == nil {
continue
}
plat := ""
if p.Platform != "" {
plat = fmt.Sprintf(" (for %s)", p.Platform)
}
tracking := ""
if p.Tracking != "" {
tracking = fmt.Sprintf(" (tracking %q)", p.Tracking)
}
fmt.Printf(" %s%s%s\n", p.Pin, plat, tracking)
}
}
if hasErrors {
fmt.Fprintf(os.Stderr, "Errors%s:\n", subdirString)
for _, p := range pins {
if p.Err != "" {
fmt.Fprintf(os.Stderr, " %s: %s.\n", p.Pkg, p.Err)
}
}
}
}
}
func hasErrors(pins []pinInfo) bool {
for _, p := range pins {
if p.Err != "" {
return true
}
}
return false
}
////////////////////////////////////////////////////////////////////////////////
// Ensure-file related helpers.
func resolveEnsureFile(ctx context.Context, f *ensure.File, clientOpts clientOptions) (map[string][]pinInfo, ensure.VersionsFile, error) {
client, err := clientOpts.makeCIPDClient(ctx)
if err != nil {
return nil, nil, err
}
out := ensure.VersionsFile{}
mu := sync.Mutex{}
resolver := cipd.Resolver{
Client: client,
VerifyPresence: true,
Visitor: func(pkg, ver, iid string) {
mu.Lock()
out.AddVersion(pkg, ver, iid)
mu.Unlock()
},
}
results, err := resolver.ResolveAllPlatforms(ctx, f)
if err != nil {
return nil, nil, err
}
return resolvedFilesToPinMap(results), out, nil
}
func resolvedFilesToPinMap(res map[template.Platform]*ensure.ResolvedFile) map[string][]pinInfo {
pinMap := map[string][]pinInfo{}
for plat, resolved := range res {
for subdir, resolvedPins := range resolved.PackagesBySubdir {
pins := pinMap[subdir]
for _, pin := range resolvedPins {
// Put a copy into 'pins', otherwise they all end up pointing to the
// same variable living in the outer scope.
pin := pin
pins = append(pins, pinInfo{
Pkg: pin.PackageName,
Pin: &pin,
Platform: plat.String(),
})
}
pinMap[subdir] = pins
}
}
// Sort pins by (package name, platform) for deterministic output.
for _, v := range pinMap {
sort.Slice(v, func(i, j int) bool {
if v[i].Pkg == v[j].Pkg {
return v[i].Platform < v[j].Platform
}
return v[i].Pkg < v[j].Pkg
})
}
return pinMap
}
func loadVersionsFile(path, ensureFile string) (ensure.VersionsFile, error) {
switch f, err := os.Open(path); {
case os.IsNotExist(err):
return nil, fmt.Errorf("the resolved versions file doesn't exist, "+
"use 'cipd ensure-file-resolve -ensure-file %q' to generate it", ensureFile)
case err != nil:
return nil, err