This repository has been archived by the owner on Oct 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathcatalog.go
685 lines (614 loc) · 18 KB
/
catalog.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
// Copyright 2021 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cli
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"github.com/aunum/log"
"github.com/pkg/errors"
"go.uber.org/multierr"
"golang.org/x/mod/semver"
apimachineryjson "k8s.io/apimachinery/pkg/runtime/serializer/json"
cliv1alpha1 "github.com/vmware-tanzu/tanzu-framework/apis/cli/v1alpha1"
)
const (
// catalogCacheDirName is the name of the local directory in which tanzu state is stored.
catalogCacheDirName = ".cache/tanzu"
// catalogCacheFileName is the name of the file which holds Catalog cache
catalogCacheFileName = "catalog.yaml"
// exe is an executable file extension
exe = ".exe"
)
var (
minConcurrent = 2
// PluginRoot is the plugin root where plugins are installed
pluginRoot = DefaultPluginRoot
// Distro is set of plugins that should be included with the CLI.
distro = DefaultDistro
)
// getCatalogCacheDir returns the local directory in which tanzu state is stored.
func getCatalogCacheDir() (path string, err error) {
home, err := os.UserHomeDir()
if err != nil {
return path, errors.Wrap(err, "could not locate user home directory")
}
path = filepath.Join(home, catalogCacheDirName)
return
}
// ValidatePlugin validates the plugin descriptor.
func ValidatePlugin(p *cliv1alpha1.PluginDescriptor) (err error) {
// skip builder plugin for bootstrapping
if p.Name == "builder" {
return nil
}
if p.Name == "" {
err = multierr.Append(err, fmt.Errorf("plugin %q name cannot be empty", p.Name))
}
if p.Version == "" {
err = multierr.Append(err, fmt.Errorf("plugin %q version cannot be empty", p.Name))
}
if !semver.IsValid(p.Version) && p.Version != "dev" {
err = multierr.Append(err, fmt.Errorf("version %q %q is not a valid semantic version", p.Name, p.Version))
}
if p.Description == "" {
err = multierr.Append(err, fmt.Errorf("plugin %q description cannot be empty", p.Name))
}
if p.Group == "" {
err = multierr.Append(err, fmt.Errorf("plugin %q group cannot be empty", p.Name))
}
return
}
// HasPluginUpdateIn checks if the plugin has an update in any of the given repositories.
func HasPluginUpdateIn(repos *MultiRepo, p *cliv1alpha1.PluginDescriptor) (update bool, repo Repository, version string, err error) {
for _, repo := range repos.repositories {
versionSelector := repo.VersionSelector()
update, version, err := HasPluginUpdate(repo, versionSelector, p)
if err != nil {
log.Debugf("could not check for update for plugin %q in repo %q: %v", p.Name, repo.Name, err)
continue
}
if update {
return update, repo, version, err
}
}
return false, nil, "", nil
}
// HasPluginUpdate tells whether the plugin descriptor has an update available in the given repository.
func HasPluginUpdate(repo Repository, versionSelector VersionSelector, p *cliv1alpha1.PluginDescriptor) (update bool, version string, err error) {
if versionSelector == nil {
versionSelector = repo.VersionSelector()
}
plugin, err := repo.Describe(p.Name)
if err != nil {
return update, version, err
}
valid := semver.IsValid(p.Version)
if !valid {
err = fmt.Errorf("local plugin version %q is not a valid semantic version", p.Version)
return
}
latest := plugin.FindVersion(versionSelector)
valid = semver.IsValid(latest)
if !valid {
err = fmt.Errorf("remote plugin version %q is not a valid semantic version", latest)
return
}
compared := semver.Compare(latest, p.Version)
if compared == 1 {
return true, latest, nil
}
return false, version, nil
}
// ParsePluginDescriptor parses a plugin descriptor in yaml.
func ParsePluginDescriptor(path string) (desc cliv1alpha1.PluginDescriptor, err error) {
b, err := os.ReadFile(path)
if err != nil {
return desc, errors.Wrap(err, "could not read plugin descriptor")
}
err = json.Unmarshal(b, &desc)
if err != nil {
return desc, errors.Wrap(err, "could not unmarshal plugin descriptor")
}
return
}
// IsDistributionSatisfied tells if a distribution is satisfied by the plugin list.
func IsDistributionSatisfied(desc []*cliv1alpha1.PluginDescriptor) bool {
for _, dist := range distro {
var contains bool
for _, plugin := range desc {
if dist == plugin.Name {
contains = true
}
}
if !contains {
return false
}
}
return true
}
// NewCatalog creates an instance of Catalog.
func NewCatalog() (*cliv1alpha1.Catalog, error) {
c := &cliv1alpha1.Catalog{}
err := ensureRoot()
if err != nil {
return nil, err
}
return c, nil
}
// getCatalogCache retrieves the catalog from from the local directory.
func getCatalogCache() (catalog *cliv1alpha1.Catalog, err error) {
catalogCachePath, err := getCatalogCachePath()
if err != nil {
return nil, err
}
b, err := os.ReadFile(catalogCachePath)
if err != nil {
catalog, err = NewCatalog()
if err != nil {
return nil, err
}
return catalog, nil
}
scheme, err := cliv1alpha1.SchemeBuilder.Build()
if err != nil {
return nil, errors.Wrap(err, "failed to create scheme")
}
s := apimachineryjson.NewSerializerWithOptions(apimachineryjson.DefaultMetaFactory, scheme, scheme,
apimachineryjson.SerializerOptions{Yaml: true, Pretty: false, Strict: false})
var c cliv1alpha1.Catalog
_, _, err = s.Decode(b, nil, &c)
if err != nil {
return nil, errors.Wrap(err, "could not decode catalog file")
}
return &c, nil
}
// saveCatalogCache saves the catalog in the local directory.
func saveCatalogCache(catalog *cliv1alpha1.Catalog) error {
catalogCachePath, err := getCatalogCachePath()
if err != nil {
return err
}
_, err = os.Stat(catalogCachePath)
if os.IsNotExist(err) {
catalogCacheDir, err := getCatalogCacheDir()
if err != nil {
return errors.Wrap(err, "could not find tanzu cache dir for OS")
}
err = os.MkdirAll(catalogCacheDir, 0755)
if err != nil {
return errors.Wrap(err, "could not make tanzu cache directory")
}
} else if err != nil {
return errors.Wrap(err, "could not create catalog cache path")
}
scheme, err := cliv1alpha1.SchemeBuilder.Build()
if err != nil {
return errors.Wrap(err, "failed to create scheme")
}
s := apimachineryjson.NewSerializerWithOptions(apimachineryjson.DefaultMetaFactory, scheme, scheme,
apimachineryjson.SerializerOptions{Yaml: true, Pretty: false, Strict: false})
catalog.GetObjectKind().SetGroupVersionKind(cliv1alpha1.GroupVersionKindCatalog)
buf := new(bytes.Buffer)
if err := s.Encode(catalog, buf); err != nil {
return errors.Wrap(err, "failed to encode catalog cache file")
}
if err = os.WriteFile(catalogCachePath, buf.Bytes(), 0644); err != nil {
return errors.Wrap(err, "failed to write catalog cache file")
}
return nil
}
// ListPlugins returns the available plugins.
func ListPlugins(exclude ...string) (list []*cliv1alpha1.PluginDescriptor, err error) {
pluginDescriptors, err := getPluginsFromCatalogCache()
if err != nil {
log.Debugf("could not get plugin descriptors %v", err)
} else {
return pluginDescriptors, nil
}
infos, err := os.ReadDir(pluginRoot)
if err != nil {
log.Debug("no plugins currently found")
return list, nil
}
for _, info := range infos {
if info.IsDir() {
continue
}
if inExclude(PluginNameFromBin(info.Name()), exclude) {
continue
}
descriptor, err := DescribePlugin(PluginNameFromBin(info.Name()))
if err != nil {
return list, err
}
list = append(list, descriptor)
}
if err := savePluginsToCatalogCache(list); err != nil {
log.Debugf("Plugin descriptors could not be saved to cache", err)
}
return list, nil
}
// savePluginsToCatalogCache saves plugins to catalog cache
func savePluginsToCatalogCache(list []*cliv1alpha1.PluginDescriptor) error {
catalog, err := getCatalogCache()
if err != nil {
catalog, err = NewCatalog()
if err != nil {
return err
}
}
catalog.PluginDescriptors = list
if err := saveCatalogCache(catalog); err != nil {
return err
}
return nil
}
// getPluginsFromCatalogCache gets plugins from catalog cache
func getPluginsFromCatalogCache() (list []*cliv1alpha1.PluginDescriptor, err error) {
catalog, err := getCatalogCache()
if err != nil {
return nil, err
}
if len(catalog.PluginDescriptors) == 0 {
return nil, errors.New("could not retrieve plugin descriptors from catalog cache")
}
return catalog.PluginDescriptors, nil
}
// upsertPluginCacheEntry inserts or updates a plugin entry in catalog cache
func upsertPluginCacheEntry(name string) error {
list, err := getPluginsFromCatalogCache()
if err != nil {
return err
}
list = remove(list, name)
descriptor, err := DescribePlugin(PluginNameFromBin(name))
if err != nil {
return err
}
list = append(list, descriptor)
if err := savePluginsToCatalogCache(list); err != nil {
return err
}
return nil
}
// deletePluginCacheEntry deletes plugin entry in catalog cache
func deletePluginCacheEntry(name string) error {
list, err := getPluginsFromCatalogCache()
if err != nil {
return err
}
list = remove(list, name)
if err := savePluginsToCatalogCache(list); err != nil {
return err
}
return nil
}
// CleanCatalogCache cleans the catalog cache
func CleanCatalogCache() error {
catalogCachePath, err := getCatalogCachePath()
if err != nil {
return err
}
if err := os.Remove(catalogCachePath); err != nil {
return err
}
return nil
}
// getCatalogCachePath gets the catalog cache path
func getCatalogCachePath() (string, error) {
catalogCacheDir, err := getCatalogCacheDir()
if err != nil {
return "", errors.Wrap(err, "could not locate catalog cache directory")
}
return filepath.Join(catalogCacheDir, catalogCacheFileName), nil
}
func remove(list []*cliv1alpha1.PluginDescriptor, name string) []*cliv1alpha1.PluginDescriptor {
i := 0
for _, v := range list {
if v != nil && v.Name != name {
list[i] = v
i++
}
}
list = list[:i]
return list
}
func inExclude(name string, exclude []string) bool {
for _, e := range exclude {
if name == e {
return true
}
}
return false
}
// ListTestPlugins returns the available test plugins.
func ListTestPlugins() (list []*cliv1alpha1.PluginDescriptor, err error) {
infos, err := os.ReadDir(testPath())
if err != nil {
log.Debug("no plugins currently found")
return list, nil
}
for _, info := range infos {
if info.IsDir() {
continue
}
descriptor, err := DescribeTestPlugin(PluginNameFromTestBin(info.Name()))
if err != nil {
return list, err
}
list = append(list, descriptor)
}
return list, nil
}
// DescribePlugin describes a plugin.
func DescribePlugin(name string) (desc *cliv1alpha1.PluginDescriptor, err error) {
pluginPath := pluginPath(name)
b, err := exec.Command(pluginPath, "info").Output()
if err != nil {
err = fmt.Errorf("could not describe plugin %q", name)
return
}
var descriptor cliv1alpha1.PluginDescriptor
err = json.Unmarshal(b, &descriptor)
if err != nil {
err = fmt.Errorf("could not unmarshal plugin %q description", name)
}
return &descriptor, err
}
// DescribeTestPlugin describes a test plugin.
func DescribeTestPlugin(pluginName string) (desc *cliv1alpha1.PluginDescriptor, err error) {
pluginPath := testPluginPath(pluginName)
b, err := exec.Command(pluginPath, "info").Output()
if err != nil {
err = fmt.Errorf("could not describe test plugin %q", pluginName)
return
}
var descriptor cliv1alpha1.PluginDescriptor
err = json.Unmarshal(b, &descriptor)
if err != nil {
err = fmt.Errorf("could not unmarshal plugin %q description", pluginName)
}
return &descriptor, err
}
// InitializePlugin initializes the plugin configuration
func InitializePlugin(name string) error {
pluginPath := pluginPath(name)
b, err := exec.Command(pluginPath, "post-install").CombinedOutput()
// Note: If user is installing old version of plugin than it is possible that
// the plugin does not implement post-install command. Ignoring the
// errors if the command does not exist for a particular plugin.
if err != nil && !strings.Contains(string(b), "unknown command") {
log.Warningf("Warning: Failed to initialize plugin '%q' after installation. %v", name, string(b))
}
return nil
}
// InstallPlugin installs a plugin from the given repository.
func InstallPlugin(name, version string, repo Repository) error {
return installOrUpgradePlugin(name, version, repo)
}
// UpgradePlugin upgrades a plugin from the given repository.
func UpgradePlugin(name, version string, repo Repository) error {
return installOrUpgradePlugin(name, version, repo)
}
func installOrUpgradePlugin(name, version string, repo Repository) error {
if name == CoreName {
return fmt.Errorf("cannot install core as a plugin")
}
b, err := repo.Fetch(name, version, BuildArch())
if err != nil {
return err
}
pluginPath := pluginPath(name)
if BuildArch().IsWindows() {
pluginPath += exe
}
err = os.WriteFile(pluginPath, b, 0755)
if err != nil {
return errors.Wrap(err, "could not write file")
}
err = upsertPluginCacheEntry(name)
if err != nil {
log.Debug("Plugin descriptor could not be updated in cache")
}
err = InitializePlugin(name)
if err != nil {
log.Infof("could not initialize plugin after installing: %v", err.Error())
}
return nil
}
// InstallAllPlugins plugins with the given version finder.
func InstallAllPlugins(repo Repository) error {
versionSelector := repo.VersionSelector()
plugins, err := repo.List()
if err != nil {
return err
}
for _, plugin := range plugins {
// TODO (pbarker): there is likely a better way of doing this
if plugin.Name == CoreName {
continue
}
err := InstallPlugin(plugin.Name, plugin.FindVersion(versionSelector), repo)
if err != nil {
return err
}
}
return nil
}
// InstallAllMulti installs all the plugins at the latest version in all the given repositories.
func InstallAllMulti(repos *MultiRepo) error {
pluginMap, err := repos.ListPlugins()
if err != nil {
return err
}
for repoName, descs := range pluginMap {
repo, err := repos.GetRepository(repoName)
if err != nil {
return err
}
versionSelector := repo.VersionSelector()
for _, plugin := range descs {
if plugin.Name == CoreName {
continue
}
err := InstallPlugin(plugin.Name, plugin.FindVersion(versionSelector), repo)
if err != nil {
return err
}
}
}
return nil
}
// DeletePlugin deletes a plugin.
func DeletePlugin(name string) error {
err := deletePluginCacheEntry(name)
if err != nil {
log.Debugf("Plugin descriptor could not be deleted from cache %v", err)
}
return os.Remove(pluginPath(name))
}
// Clean deletes all plugins and tests.
func Clean() error {
if err := CleanCatalogCache(); err != nil {
log.Debugf("Failed to clean the catalog cache %v", err)
}
return os.RemoveAll(pluginRoot)
}
// EnsureDistro ensures that all the distro plugins are installed.
func EnsureDistro(repos *MultiRepo) error {
fatalErrors := make(chan error, len(distro))
// Limit the number of concurrent operations we perform so we don't
// overwhelm the system.
maxConcurrent := runtime.NumCPU() / 2
if maxConcurrent < minConcurrent {
maxConcurrent = 2
}
guard := make(chan struct{}, maxConcurrent)
// capture list of already installed plugins
installedPlugins, err := ListPlugins()
if err != nil {
return err
}
var wg sync.WaitGroup
for _, pluginName := range distro {
// if plugin exists on user's system, do not (re)install
if isPluginInstalled(installedPlugins, pluginName) {
continue
}
wg.Add(1)
guard <- struct{}{}
go func(pluginName string) {
repo, err := repos.Find(pluginName)
if err != nil {
fatalErrors <- err
} else {
err = InstallPlugin(pluginName, VersionLatest, repo)
if err != nil {
fatalErrors <- err
}
log.Debugf("done installing: %s", pluginName)
}
wg.Done()
<-guard
}(pluginName)
}
wg.Wait()
select {
case err := <-fatalErrors:
close(fatalErrors)
return err
default:
break
}
return nil
}
// InstallTest installs the test for the given plugin name
func InstallTest(pluginName, version string, repo Repository) error {
b, err := repo.FetchTest(pluginName, version, BuildArch())
if err != nil {
return err
}
pluginPath := testPluginPath(pluginName)
if BuildArch().IsWindows() {
pluginPath += exe
}
err = os.WriteFile(pluginPath, b, 0755)
if err != nil {
return errors.Wrap(err, "could not write file")
}
return nil
}
// EnsureTest ensures the right version of the test is present for the plugin.
func EnsureTest(plugin *cliv1alpha1.PluginDescriptor, repos *MultiRepo) error {
testDesc, err := DescribeTestPlugin(plugin.Name)
if err == nil {
if testDesc.BuildSHA == plugin.BuildSHA {
return nil
}
}
repo, err := repos.Find(plugin.Name)
if err != nil {
return err
}
log.Infof("installing test for plugin %q", plugin.Name)
err = InstallTest(plugin.Name, plugin.Version, repo)
if err != nil {
log.Debugf("could not install test for plugin %q", plugin.Name)
}
return nil
}
// EnsureTests ensures the plugin tests are installed.
func EnsureTests(repos *MultiRepo, exclude ...string) error {
descs, err := ListPlugins(exclude...)
if err != nil {
return err
}
for _, desc := range descs {
err = EnsureTest(desc, repos)
if err != nil {
return err
}
}
return nil
}
// Returns the local path for a plugin.
func pluginPath(name string) string {
binName := BinFromPluginName(name)
return filepath.Join(pluginRoot, binName)
}
// Returns the local path for a plugin.
func testPluginPath(name string) string {
binName := BinTestFromPluginName(name)
return filepath.Join(pluginRoot, "test", binName)
}
// Returns the test path relative to the plugin root
func testPath() string {
return filepath.Join(pluginRoot, "test")
}
// Ensure the root directory exists.
func ensureRoot() error {
_, err := os.Stat(testPath())
if os.IsNotExist(err) {
err := os.MkdirAll(testPath(), 0755)
return errors.Wrap(err, "could not make root plugin directory")
}
return err
}
// isPluginInstalled takes a list of PluginDescriptors representing installed plugins.
// When the pluginName entered matches a plugin in the descriptor list, true is returned
// A list of installed plugins can be captured by calling Catalog's List method.
func isPluginInstalled(installedPlugin []*cliv1alpha1.PluginDescriptor, pluginName string) bool {
for _, p := range installedPlugin {
if p.Name == pluginName {
return true
}
}
return false
}