forked from vmware-tanzu/tanzu-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli_compile.go
660 lines (572 loc) · 15.6 KB
/
cli_compile.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
// Copyright 2022 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package command provides handling to generate new scaffolding, compile, and
// publish CLI plugins.
package command
import (
"encoding/json"
"errors"
"fmt"
"math/rand"
"os"
"os/exec"
"path/filepath"
"runtime"
"sync"
"time"
"github.com/gobwas/glob"
"gopkg.in/yaml.v3"
configtypes "github.com/vmware-tanzu/tanzu-plugin-runtime/config/types"
rtplugin "github.com/vmware-tanzu/tanzu-plugin-runtime/plugin"
"github.com/vmware-tanzu/tanzu-cli/cmd/plugin/builder/types"
"github.com/vmware-tanzu/tanzu-cli/pkg/cli"
"github.com/vmware-tanzu/tanzu-plugin-runtime/log"
)
func init() {
// Show timestamp as part of the logs
log.ShowTimestamp(true)
// Redirect the logs to stdout for the user to consume
log.SetStderr(os.Stdout)
}
var (
version, artifactsDir, ldflags string
tags, goprivate string
targetArch []string
groupByOSArch bool
)
type plugin struct {
rtplugin.PluginDescriptor
path string
testPath string
docPath string
modPath string
buildID string
target string
}
// PluginCompileArgs contains the values to use for compiling plugins.
type PluginCompileArgs struct {
Version string
SourcePath string
ArtifactsDir string
LDFlags string
Tags string
Match string
Description string
GoPrivate string
PluginScopeAssociationFile string
TargetArch []string
GroupByOSArch bool
}
const local = "local"
var minConcurrent = 2
var identifiers = []string{
string('\U0001F435'),
string('\U0001F43C'),
string('\U0001F436'),
string('\U0001F430'),
string('\U0001F98A'),
string('\U0001F431'),
string('\U0001F981'),
string('\U0001F42F'),
string('\U0001F42E'),
string('\U0001F437'),
string('\U0001F42D'),
string('\U0001F428'),
}
func getID(i int) string {
index := i
if i >= len(identifiers) {
// Well aren't you lucky
index = i % len(identifiers)
}
return identifiers[index]
}
func getBuildArch(arch []string) []cli.Arch {
var arrArch []cli.Arch
for _, buildArch := range arch {
if buildArch == string(AllTargets) {
for arch := range archMap {
arrArch = append(arrArch, arch)
}
} else if buildArch == local {
arrArch = append(arrArch, cli.BuildArch())
} else {
arrArch = append(arrArch, cli.Arch(buildArch))
}
}
return arrArch
}
func getMaxParallelism() int {
maxConcurrent := runtime.NumCPU() - 2
if maxConcurrent < minConcurrent {
maxConcurrent = minConcurrent
}
return maxConcurrent
}
type errInfo struct {
Err error
Path string
ID string
}
// setGlobals initializes a set of global variables used throughout the compile
// process, based on the arguments passed in.
func setGlobals(compileArgs *PluginCompileArgs) {
version = compileArgs.Version
artifactsDir = compileArgs.ArtifactsDir
ldflags = compileArgs.LDFlags
tags = compileArgs.Tags
goprivate = compileArgs.GoPrivate
targetArch = compileArgs.TargetArch
groupByOSArch = compileArgs.GroupByOSArch
// Append version specific ldflag by default so that user doesn't need to pass this ldflag always.
ldflags = fmt.Sprintf("%s -X 'github.com/vmware-tanzu/tanzu-plugin-runtime/plugin/buildinfo.Version=%s'", ldflags, version)
}
func Compile(compileArgs *PluginCompileArgs) error {
// Set our global values based on the passed args
setGlobals(compileArgs)
log.Infof("building local repository at %s, %v, %v", compileArgs.ArtifactsDir, compileArgs.Version, compileArgs.TargetArch)
manifest := cli.Manifest{
CreatedTime: time.Now(),
Plugins: []cli.Plugin{},
}
files, err := os.ReadDir(compileArgs.SourcePath)
if err != nil {
return err
}
// Limit the number of concurrent operations we perform so we don't overwhelm the system.
maxConcurrent := getMaxParallelism()
guard := make(chan struct{}, maxConcurrent)
// Mix up IDs so we don't always get the same set.
randSkew := rand.Intn(len(identifiers)) //nolint:gosec
var wg sync.WaitGroup
plugins := make(chan cli.Plugin, len(files))
fatalErrors := make(chan errInfo, len(files))
g := glob.MustCompile(compileArgs.Match)
for i, f := range files {
if f.IsDir() {
if g.Match(f.Name()) {
wg.Add(1)
guard <- struct{}{}
go func(fullPath, id string) {
defer wg.Done()
p, err := buildPlugin(fullPath, id)
if err != nil {
fatalErrors <- errInfo{Err: err, Path: fullPath, ID: id}
} else {
plug := cli.Plugin{
Name: p.Name,
Description: p.Description,
Target: p.target,
Versions: []string{p.Version},
}
plugins <- plug
}
<-guard
}(filepath.Join(compileArgs.SourcePath, f.Name()), getID(i+randSkew))
}
}
}
wg.Wait()
close(plugins)
close(fatalErrors)
log.Info("========")
hasFailed := false
var exerr *exec.ExitError
for err := range fatalErrors {
hasFailed = true
if errors.As(err.Err, &exerr) {
log.Errorf("%s - building plugin %q failed - %v:\n%s", err.ID, err.Path, err.Err, exerr.Stderr)
} else {
log.Errorf("%s - building plugin %q failed - %v", err.ID, err.Path, err.Err)
}
}
if hasFailed {
os.Exit(1)
}
for plug := range plugins {
manifest.Plugins = append(manifest.Plugins, plug)
}
err = savePluginManifest(manifest, compileArgs.ArtifactsDir, compileArgs.GroupByOSArch)
if err != nil {
return err
}
err = savePluginGroupManifest(manifest.Plugins, compileArgs.ArtifactsDir, compileArgs.PluginScopeAssociationFile, compileArgs.GroupByOSArch)
if err != nil {
return err
}
log.Success("successfully built local repository")
return nil
}
func buildPlugin(path, id string) (plugin, error) {
log.Infof("%s - building plugin at path %q", id, path)
var modPath string
cmd := goCommand("run", "-ldflags", ldflags, "-tags", tags)
if isLocalGoModFileExists(path) {
modPath = path
cmd.Dir = modPath
cmd.Args = append(cmd.Args, "./.")
log.Infof("%s - running godep path %q", id, path)
err := runDownloadGoDep(path, id)
if err != nil {
log.Errorf("%s - cannot download go dependencies in path: %s - error: %v", id, path, err)
return plugin{}, err
}
} else {
modPath = ""
cmd.Args = append(cmd.Args, fmt.Sprintf("./%s", path))
}
cmd.Args = append(cmd.Args, "info")
b, err := cmd.Output()
if err != nil {
log.Errorf("%s - error: %v", id, err)
log.Errorf("%s - output: (%v)", id, string(b))
return plugin{}, err
}
var desc rtplugin.PluginDescriptor
err = json.Unmarshal(b, &desc)
if err != nil {
log.Errorf("%s - error unmarshalling plugin descriptor: %v", id, err)
return plugin{}, err
}
testPath := filepath.Join(path, "test")
_, err = os.Stat(testPath)
if err != nil {
if os.Getenv("TZ_ENFORCE_TEST_PLUGIN") == "1" {
log.Errorf("%s - plugin %q must implement test", id, desc.Name)
return plugin{}, err
}
testPath = ""
}
docPath := filepath.Join(path, "README.md")
_, err = os.Stat(docPath)
if err != nil {
log.Errorf("%s - plugin %q requires a README.md file", id, desc.Name)
return plugin{}, err
}
target, err := getPluginTarget(&desc, path, id)
if err != nil {
return plugin{}, err
}
p := plugin{
PluginDescriptor: desc,
docPath: docPath,
buildID: id,
target: target,
}
if modPath != "" {
p.path = "."
if testPath == "" {
p.testPath = ""
} else {
p.testPath = "test"
}
p.modPath = modPath
} else {
p.path = path
p.testPath = testPath
p.modPath = ""
}
log.V(4).Infof("plugin %v", p)
err = p.compile()
if err != nil {
log.Errorf("%s - error compiling plugin %s", id, desc.Name)
return plugin{}, err
}
return p, nil
}
type target struct {
env []string
args []string
}
func (t target) build(targetPath, prefix, modPath, ldflags, tags string) error {
cmd := goCommand("build")
var commonArgs = []string{
"-ldflags", ldflags,
"-tags", tags,
}
cmd.Args = append(cmd.Args, t.args...)
cmd.Args = append(cmd.Args, commonArgs...)
cmd.Env = append(cmd.Env, os.Environ()...)
cmd.Env = append(cmd.Env, t.env...)
if modPath != "" {
cmd.Dir = modPath
}
cmd.Args = append(cmd.Args, fmt.Sprintf("./%s", targetPath))
log.Infof("%s$ %s", prefix, cmd.String())
output, err := cmd.CombinedOutput()
if err != nil {
log.Errorf("%serror: %v", prefix, err)
log.Errorf("%soutput: %v", prefix, string(output))
return err
}
return nil
}
// AllTargets are all the known targets.
const AllTargets cli.Arch = "all"
type targetBuilder func(pluginName, outPath string) target
var archMap = map[cli.Arch]targetBuilder{
cli.Linux386: func(pluginName, outPath string) target {
return target{
env: []string{
"CGO_ENABLED=0",
"GOARCH=386",
"GOOS=linux",
},
args: []string{
"-o", filepath.Join(outPath, cli.MakeArtifactName(pluginName, cli.Linux386)),
},
}
},
cli.LinuxAMD64: func(pluginName, outPath string) target {
return target{
env: []string{
"CGO_ENABLED=0",
"GOARCH=amd64",
"GOOS=linux",
},
args: []string{
"-o", filepath.Join(outPath, cli.MakeArtifactName(pluginName, cli.LinuxAMD64)),
},
}
},
cli.LinuxARM64: func(pluginName, outPath string) target {
return target{
env: []string{
"CGO_ENABLED=0",
"GOARCH=arm64",
"GOOS=linux",
},
args: []string{
"-o", filepath.Join(outPath, cli.MakeArtifactName(pluginName, cli.LinuxARM64)),
},
}
},
cli.DarwinAMD64: func(pluginName, outPath string) target {
return target{
env: []string{
"GOARCH=amd64",
"GOOS=darwin",
},
args: []string{
"-o", filepath.Join(outPath, cli.MakeArtifactName(pluginName, cli.DarwinAMD64)),
},
}
},
cli.DarwinARM64: func(pluginName, outPath string) target {
return target{
env: []string{
"GOARCH=arm64",
"GOOS=darwin",
},
args: []string{
"-o", filepath.Join(outPath, cli.MakeArtifactName(pluginName, cli.DarwinARM64)),
},
}
},
cli.Win386: func(pluginName, outPath string) target {
return target{
env: []string{
"GOARCH=386",
"GOOS=windows",
},
args: []string{
"-o", filepath.Join(outPath, cli.MakeArtifactName(pluginName, cli.Win386)),
},
}
},
cli.WinAMD64: func(pluginName, outPath string) target {
return target{
env: []string{
"GOARCH=amd64",
"GOOS=windows",
},
args: []string{
"-o", filepath.Join(outPath, cli.MakeArtifactName(pluginName, cli.WinAMD64)),
},
}
},
}
func (p *plugin) compile() error {
absArtifactsDir, err := filepath.Abs(artifactsDir)
if err != nil {
return err
}
err = buildTargets(p.path, absArtifactsDir, p.Name, p.target, p.buildID, p.modPath, false)
if err != nil {
return err
}
if p.testPath != "" {
err = buildTargets(p.testPath, absArtifactsDir, p.Name, p.target, p.buildID, p.modPath, true)
if err != nil {
return err
}
}
if !groupByOSArch {
b, err := yaml.Marshal(p.PluginDescriptor)
if err != nil {
return err
}
configPath := filepath.Join(absArtifactsDir, p.Name, cli.PluginDescriptorFileName)
err = os.WriteFile(configPath, b, 0644)
if err != nil {
return err
}
}
return nil
}
func buildTargets(targetPath, artifactsDir, pluginName, target, id, modPath string, isTest bool) error {
if id != "" {
id = fmt.Sprintf("%s - ", id)
}
targets := map[cli.Arch]targetBuilder{}
for _, buildArch := range targetArch {
if buildArch == string(AllTargets) {
targets = archMap
} else if buildArch == local {
localArch := cli.BuildArch()
targets[localArch] = archMap[localArch]
} else {
bArch := cli.Arch(buildArch)
if val, ok := archMap[bArch]; !ok {
log.Errorf("%q build architecture is not supported", buildArch)
} else {
targets[cli.Arch(buildArch)] = val
}
}
}
for arch, targetBuilder := range targets {
pn := pluginName
outputDir := artifactsDir
if groupByOSArch {
outputDir = filepath.Join(outputDir, arch.OS(), arch.Arch(), target)
}
outputDir = filepath.Join(outputDir, pn, version)
if isTest {
outputDir = filepath.Join(outputDir, "test")
pn = fmt.Sprintf("%s-test", pn)
}
tgt := targetBuilder(pn, outputDir)
err := tgt.build(targetPath, id, modPath, ldflags, tags)
if err != nil {
return err
}
}
return nil
}
func runDownloadGoDep(targetPath, prefix string) error {
cmdgomoddownload := goCommand("mod", "download")
cmdgomoddownload.Dir = targetPath
log.Infof("%s$ %s", prefix, cmdgomoddownload.String())
output, err := cmdgomoddownload.CombinedOutput()
if err != nil {
log.Errorf("%serror: %v", prefix, err)
log.Errorf("%soutput: %v", prefix, string(output))
return err
}
return nil
}
func isLocalGoModFileExists(path string) bool {
_, err := os.Stat(filepath.Join(path, "go.mod"))
return err == nil
}
func goCommand(arg ...string) *exec.Cmd {
cmd := exec.Command("go", arg...)
if goprivate != "" {
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, fmt.Sprintf("GOPRIVATE=%s", goprivate))
}
return cmd
}
func getPluginTarget(pd *rtplugin.PluginDescriptor, pluginPath, id string) (string, error) {
if !groupByOSArch || pd == nil {
return "", nil
}
// If target is specified in the plugin descriptor use it
if configtypes.IsValidTarget(string(pd.Target), true, false) {
return string(pd.Target), nil
}
// If target is not specified in the plugin descriptor check `metadata.yaml` in the
// plugin directory to get the target of the plugin
metadataFilePath := filepath.Join(pluginPath, "metadata.yaml")
b, err := os.ReadFile(metadataFilePath)
if err != nil {
log.Errorf("%s - plugin %q requires a metadata.yaml file", id, pd.Name)
return "", err
}
var metadata types.Metadata
err = yaml.Unmarshal(b, &metadata)
if err != nil {
log.Errorf("%s - error unmarshalling plugin metadata.yaml file: %v", id, err)
return "", err
}
return metadata.Target, nil
}
func savePluginManifest(manifest cli.Manifest, artifactsDir string, groupByOSArch bool) error {
b, err := yaml.Marshal(manifest)
if err != nil {
return err
}
if groupByOSArch {
arrTargetArch := getBuildArch(targetArch)
arrTargetArch = append(arrTargetArch, "")
for _, osarch := range arrTargetArch {
manifestPath := filepath.Join(artifactsDir, osarch.OS(), osarch.Arch(), cli.PluginManifestFileName)
err := os.WriteFile(manifestPath, b, 0644)
if err != nil {
return err
}
}
} else {
manifestPath := filepath.Join(artifactsDir, cli.ManifestFileName)
err = os.WriteFile(manifestPath, b, 0644)
if err != nil {
return err
}
}
return nil
}
func savePluginGroupManifest(plugins []cli.Plugin, artifactsDir, pluginScopeAssociationFile string, groupByOSArch bool) error {
if !groupByOSArch || pluginScopeAssociationFile == "" {
return nil
}
log.Info("saving plugin group manifest...")
b, err := os.ReadFile(pluginScopeAssociationFile)
if err != nil {
return err
}
psm := &cli.PluginScopeMetadata{}
err = yaml.Unmarshal(b, psm)
if err != nil {
return err
}
getPluginScope := func(name, target string) bool {
for _, p := range psm.Plugins {
if p.Name == name && p.Target == target {
return p.IsContextScoped
}
}
return false
}
pgManifest := cli.PluginGroupManifest{
CreatedTime: time.Now(),
Plugins: []cli.PluginNameTargetScopeVersion{},
}
for _, plug := range plugins {
pluginNTSV := cli.PluginNameTargetScopeVersion{}
pluginNTSV.Name = plug.Name
pluginNTSV.Target = plug.Target
pluginNTSV.IsContextScoped = getPluginScope(plug.Name, plug.Target)
pluginNTSV.Version = plug.Versions[0]
pgManifest.Plugins = append(pgManifest.Plugins, pluginNTSV)
}
b, err = yaml.Marshal(pgManifest)
if err != nil {
return err
}
manifestPath := filepath.Join(artifactsDir, cli.PluginGroupManifestFileName)
err = os.WriteFile(manifestPath, b, 0644)
if err != nil {
return err
}
return nil
}