-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathmanager.go
More file actions
1689 lines (1480 loc) · 61.5 KB
/
Copy pathmanager.go
File metadata and controls
1689 lines (1480 loc) · 61.5 KB
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 2021 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package pluginmanager is responsible for plugin discovery and installation
package pluginmanager
import (
"crypto/sha256"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"github.com/Masterminds/semver"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kerrors "k8s.io/apimachinery/pkg/util/errors"
"github.com/vmware-tanzu/tanzu-plugin-runtime/component"
configlib "github.com/vmware-tanzu/tanzu-plugin-runtime/config"
configtypes "github.com/vmware-tanzu/tanzu-plugin-runtime/config/types"
cliv1alpha1 "github.com/vmware-tanzu/tanzu-cli/apis/cli/v1alpha1"
"github.com/vmware-tanzu/tanzu-cli/pkg/artifact"
"github.com/vmware-tanzu/tanzu-cli/pkg/catalog"
"github.com/vmware-tanzu/tanzu-cli/pkg/cli"
"github.com/vmware-tanzu/tanzu-cli/pkg/common"
"github.com/vmware-tanzu/tanzu-cli/pkg/config"
"github.com/vmware-tanzu/tanzu-cli/pkg/discovery"
"github.com/vmware-tanzu/tanzu-cli/pkg/distribution"
"github.com/vmware-tanzu/tanzu-cli/pkg/plugincmdtree"
"github.com/vmware-tanzu/tanzu-cli/pkg/plugininventory"
"github.com/vmware-tanzu/tanzu-cli/pkg/pluginsupplier"
"github.com/vmware-tanzu/tanzu-cli/pkg/telemetry"
"github.com/vmware-tanzu/tanzu-cli/pkg/utils"
"github.com/vmware-tanzu/tanzu-plugin-runtime/log"
)
const (
// exe is an executable file extension
exe = ".exe"
// ManifestFileName is the file name for the manifest.
ManifestFileName = "manifest.yaml"
// PluginManifestFileName is the file name for the manifest.
PluginManifestFileName = "plugin_manifest.yaml"
// PluginFileName is the file name for the plugin info.
PluginFileName = "plugin.yaml"
// String used to request the user to use the --target flag
missingTargetStr = "unable to uniquely identify plugin '%v'. Please specify the target (" + common.TargetList + ") of the plugin using the `--target` flag"
errorWhileDiscoveringPlugins = "there was an error while discovering plugins, error information: '%v'"
errorNoDiscoverySourcesFound = "there are no plugin discovery sources available. Please run 'tanzu plugin source init'"
errorNoActiveContexForGivenContextType = "there is no active context for the given context type `%v`"
)
var totalPluginsToInstall = 0
var pluginNumberBeingInstalled = 1
var execCommand = exec.Command
var spinner component.OutputWriterSpinner
func init() {
// Initialize global spinner
spinner = component.NewOutputWriterSpinner(component.WithOutputStream(os.Stderr))
runtime.SetFinalizer(spinner, func(s component.OutputWriterSpinner) {
if s != nil {
s.StopSpinner()
}
})
}
func StopSpinner() {
if spinner != nil {
spinner.StopSpinner()
}
}
// ResetPluginInstallationCounts resets the total number of plugins to install and the number of plugins installed
func ResetPluginInstallationCounts() {
SetTotalPluginsToInstall(0)
SetPluginBeingInstalledCount(1)
}
type DeletePluginOptions struct {
Target configtypes.Target
PluginName string
ForceDelete bool
}
// discoverSpecificPlugins returns all plugins that match the specified criteria from all PluginDiscovery sources,
// along with an aggregated error (if any) that occurred while creating the plugin discovery source or fetching plugins.
func discoverSpecificPlugins(pd []configtypes.PluginDiscovery, options ...discovery.DiscoveryOptions) ([]discovery.Discovered, error) {
allPlugins := make([]discovery.Discovered, 0)
errorList := make([]error, 0)
for _, d := range pd {
discObject, err := discovery.CreateDiscoveryFromV1alpha1(d, options...)
if err != nil {
errorList = append(errorList, errors.Wrapf(err, "unable to create discovery"))
continue
}
plugins, err := discObject.List()
if err != nil {
errorList = append(errorList, errors.Wrapf(err, "unable to list plugins from discovery source '%v'", discObject.Name()))
continue
}
allPlugins = append(allPlugins, plugins...)
}
return allPlugins, kerrors.NewAggregate(errorList)
}
// discoverSpecificPluginGroups returns all the plugin groups found in the discoveries
func discoverSpecificPluginGroups(pd []configtypes.PluginDiscovery, options ...discovery.DiscoveryOptions) ([]*plugininventory.PluginGroup, error) {
var allGroups []*plugininventory.PluginGroup
for _, d := range pd {
groupDisc, err := discovery.CreateGroupDiscovery(d, options...)
if err != nil {
return nil, errors.Wrapf(err, "unable to create group discovery")
}
groups, err := groupDisc.GetGroups()
if err != nil {
log.Warningf("unable to list groups from discovery '%v': %v", groupDisc.Name(), err.Error())
continue
}
if len(groups) > 0 {
allGroups = append(allGroups, groups...)
}
}
return mergeDuplicateGroups(allGroups), nil
}
// DiscoverStandalonePlugins returns the available standalone plugins
func DiscoverStandalonePlugins(options ...discovery.DiscoveryOptions) ([]discovery.Discovered, error) {
discoveries, err := getPluginDiscoveries()
if err != nil {
return nil, err
} else if len(discoveries) == 0 {
return nil, errors.New(errorNoDiscoverySourcesFound)
}
plugins, err := discoverSpecificPlugins(discoveries, options...)
for i := range plugins {
plugins[i].Scope = common.PluginScopeStandalone
plugins[i].Status = common.PluginStatusNotInstalled
}
return mergeDuplicatePlugins(plugins), err
}
// DiscoverPluginGroups returns the available plugin groups
func DiscoverPluginGroups(options ...discovery.DiscoveryOptions) ([]*plugininventory.PluginGroup, error) {
discoveries, err := getPluginDiscoveries()
if err != nil {
return nil, err
}
if len(discoveries) == 0 {
return nil, errors.New(errorNoDiscoverySourcesFound)
}
groups, err := discoverSpecificPluginGroups(discoveries, options...)
if err != nil {
return nil, err
}
return groups, err
}
// GetAdditionalTestPluginDiscoveries returns an array of plugin discoveries that
// are meant to be used for testing new plugin version. The comma-separated list of
// such discoveries can be specified through the environment variable
// "TANZU_CLI_ADDITIONAL_PLUGIN_DISCOVERY_IMAGES_TEST_ONLY".
// Each entry in the variable should be the URI of an OCI image of the DB of the
// discovery in question.
func GetAdditionalTestPluginDiscoveries() []configtypes.PluginDiscovery {
var testDiscoveries []configtypes.PluginDiscovery
testDiscoveryImages := config.GetAdditionalTestDiscoveryImages()
for idx, image := range testDiscoveryImages {
testDiscoveries = append(testDiscoveries, configtypes.PluginDiscovery{
OCI: &configtypes.OCIDiscovery{
Name: fmt.Sprintf("disc_%d", idx),
Image: image,
},
})
}
return testDiscoveries
}
// DiscoverServerPlugins returns the available discovered plugins associated with all active contexts
func DiscoverServerPlugins() ([]discovery.Discovered, error) {
currentContextMap, err := configlib.GetAllActiveContextsMap()
if err != nil {
return nil, err
}
contexts := make([]*configtypes.Context, 0)
for _, context := range currentContextMap {
contexts = append(contexts, context)
}
return discoverServerPluginsForGivenContexts(contexts)
}
// discoverServerPluginsForGivenContexts returns the available discovered plugins associated with specific contexts
func discoverServerPluginsForGivenContexts(contexts []*configtypes.Context) ([]discovery.Discovered, error) {
var plugins []discovery.Discovered
var errList []error
if len(contexts) == 0 {
return plugins, nil
}
for _, context := range contexts {
var discoverySources []configtypes.PluginDiscovery
discoverySources = append(discoverySources, context.DiscoverySources...)
discoverySources = append(discoverySources, defaultDiscoverySourceBasedOnContext(context)...)
discoveredPlugins, err := discoverSpecificPlugins(discoverySources)
// If there is an error while discovering plugins from all of the given plugin sources,
// append the error to the error list and continue processing the discoveredPlugins,
// as there may still be plugins that were successfully discovered from some of the discovery sources.
if err != nil {
errList = append(errList, err)
}
for i := range discoveredPlugins {
discoveredPlugins[i].Scope = common.PluginScopeContext
discoveredPlugins[i].Status = common.PluginStatusNotInstalled
discoveredPlugins[i].ContextName = context.Name
// Associate Target of the plugin based on the Context Type of the Context
switch context.ContextType {
case configtypes.ContextTypeTMC:
discoveredPlugins[i].Target = configtypes.TargetTMC
default:
// All other context types are associated with the kubernetes target
discoveredPlugins[i].Target = configtypes.TargetK8s
}
// It is possible that server recommends shortened plugin version of format vMAJOR or vMAJOR.MINOR
// in that case, try to find the latest available version of the plugin that matches with the given recommended version
matchedRecommendedVersion := getMatchingRecommendedVersionOfPlugin(discoveredPlugins[i].Name, discoveredPlugins[i].Target, discoveredPlugins[i].RecommendedVersion)
if matchedRecommendedVersion != "" {
discoveredPlugins[i].RecommendedVersion = matchedRecommendedVersion
}
}
// Remove older plugins from the discoveredPlugins list when there are duplicates
// this can be possible if a same plugin gets discovered from different kubernetes namespaces
discoveredPlugins = removeOldPluginsWhenDuplicates(discoveredPlugins)
plugins = append(plugins, discoveredPlugins...)
}
return plugins, kerrors.NewAggregate(errList)
}
func getMatchingRecommendedVersionOfPlugin(pluginName string, pluginTarget configtypes.Target, version string) string {
criteria := &discovery.PluginDiscoveryCriteria{
Name: pluginName,
Target: pluginTarget,
Version: version,
}
// Considering the performance is of importance for this function, We are using `WithUseLocalCacheOnly` option
// here as we do not want to fetch the database (or even validate the digest) all the time.
// Using local cache should be fine as cache gets updated with any plugin installation or search commands
// Also we are planning to implement scheduling of auto sync of database cache in future releases
matchedPlugins, err := DiscoverStandalonePlugins(discovery.WithPluginDiscoveryCriteria(criteria), discovery.WithUseLocalCacheOnly())
if err != nil {
return ""
}
if len(matchedPlugins) != 1 {
return ""
}
return matchedPlugins[0].RecommendedVersion
}
func mergePluginEntries(plugin1, plugin2 *discovery.Discovered) *discovery.Discovered {
// Plugins with the same name having `k8s` and `none` targets are also considered the same for
// backward compatibility reasons, considering, we are adding `k8s` targeted plugins as root level commands.
if plugin1.Target == configtypes.TargetUnknown {
plugin1.Target = plugin2.Target
}
// Combine the installation status and installedVersion result when combining plugins
if plugin2.Status == common.PluginStatusInstalled {
plugin1.Status = common.PluginStatusInstalled
}
if plugin2.InstalledVersion != "" {
plugin1.InstalledVersion = plugin2.InstalledVersion
}
// Build a combined Source string
if plugin1.Source != plugin2.Source {
plugin1.Source = fmt.Sprintf("%s/%s", plugin1.Source, plugin2.Source)
}
// The discovery type could be OCI or Local.
// When dealing with different discovery types, unset it
if plugin1.DiscoveryType != plugin2.DiscoveryType {
plugin1.DiscoveryType = ""
}
artifacts1, ok := plugin1.Distribution.(distribution.Artifacts)
if !ok {
// This should not happened
log.Warningf("Plugin '%s' has an unexpected distribution type", plugin1.Name)
return plugin1
}
artifacts2, ok := plugin2.Distribution.(distribution.Artifacts)
if !ok {
// This should not happened
log.Warningf("Plugin '%s' has an unexpected distribution type", plugin2.Name)
return plugin1
}
// For every version in the second plugin, if it doesn't already exist
// in the first plugin, add it.
// Also build the new list of supported versions
for version := range artifacts2 {
_, exists := artifacts1[version]
if !exists {
artifacts1[version] = artifacts2[version]
plugin1.SupportedVersions = append(plugin1.SupportedVersions, version)
}
}
plugin1.Distribution = artifacts1
_ = utils.SortVersions(plugin1.SupportedVersions)
// Set the recommended version to the highest version
if len(plugin1.SupportedVersions) > 0 {
plugin1.RecommendedVersion = plugin1.SupportedVersions[len(plugin1.SupportedVersions)-1]
}
// Keep the following fields from the first plugin found
// - Optional
// - ContextName
// - Scope
return plugin1
}
// mergeDuplicatePlugins combines the same plugins to eliminate duplicates by merging the information
// of multiple entries of the same plugin into a single entry. For example, the Central Repository can
// provide details about a plugin, but an additional test discovery can provide other versions of the
// same plugin. This function will join all the information into one.
// A plugin is determined by its name-target combination.
// Note that if two versions of the same plugin are found more than once, it will be the first one
// found that will be kept. The order of the array "plugins" therefore matters.
// This merge operation is deterministic due to the sequence of sources/plugins that we process always
// being the same.
func mergeDuplicatePlugins(plugins []discovery.Discovered) []discovery.Discovered {
mapOfSelectedPlugins := make(map[string]*discovery.Discovered)
for i := range plugins {
target := plugins[i].Target
if target == configtypes.TargetUnknown {
// Two plugins with the same name having `k8s` and `none` as targets are also considered the same for
// backward compatibility reasons. This is because we are adding `k8s`-targeted plugins as root-level commands.
target = configtypes.TargetK8s
}
// If plugin doesn't exist in the map then add the plugin to the map
// else merge the two entries, giving priority to the first one found
key := fmt.Sprintf("%s_%s", plugins[i].Name, target)
dp, exists := mapOfSelectedPlugins[key]
if !exists {
mapOfSelectedPlugins[key] = &plugins[i]
} else {
mapOfSelectedPlugins[key] = mergePluginEntries(dp, &plugins[i])
}
}
var mergedPlugins []discovery.Discovered
for key := range mapOfSelectedPlugins {
mergedPlugins = append(mergedPlugins, *mapOfSelectedPlugins[key])
}
return mergedPlugins
}
func mergeGroupEntries(group1, group2 *plugininventory.PluginGroup) *plugininventory.PluginGroup {
// For every version in the second group, if it doesn't already exist
// in the first group, add it.
for version := range group2.Versions {
_, exists := group1.Versions[version]
if !exists {
group1.Versions[version] = group2.Versions[version]
}
}
// Find the latest version
if len(group1.Versions) > 0 {
latestVersions := []string{group1.RecommendedVersion, group2.RecommendedVersion}
_ = utils.SortVersions(latestVersions)
// Set the recommended version and the description to the ones from the highest version group
if group2.RecommendedVersion == latestVersions[1] {
// If it is group2 that has the highest version, replace the RecommendedVersion and Description
group1.RecommendedVersion = group2.RecommendedVersion
group1.Description = group2.Description
}
}
return group1
}
// mergeDuplicateGroups combines the same plugin groups to eliminate duplicates by merging the information
// of multiple entries of the same group into a single entry. For example, the Central Repository can
// provide details about a plugin group, but an additional test discovery can provide other versions of the
// same group. This function will join all the information into one.
// A group is determined by its vendor-publisher/name combination.
// Note that if two versions of the same group are found more than once, it will be the first one
// found that will be kept. The order of the array "groups" therefore matters.
// This merge operation is deterministic due to the sequence of sources/groups that we process always
// being the same.
func mergeDuplicateGroups(groups []*plugininventory.PluginGroup) []*plugininventory.PluginGroup {
mapOfSelectedGroups := make(map[string]*plugininventory.PluginGroup)
for _, newGroup := range groups {
// If group doesn't exist in the map then add it.
// Otherwise merge the two entries, giving priority to the first one found.
key := plugininventory.PluginGroupToID(newGroup)
existingGroup, exists := mapOfSelectedGroups[key]
if !exists {
mapOfSelectedGroups[key] = newGroup
} else {
mapOfSelectedGroups[key] = mergeGroupEntries(existingGroup, newGroup)
}
}
var mergedGroups []*plugininventory.PluginGroup
for key := range mapOfSelectedGroups {
mergedGroups = append(mergedGroups, mapOfSelectedGroups[key])
}
return mergedGroups
}
func setAvailablePluginsStatus(availablePlugins []discovery.Discovered, installedPlugins []cli.PluginInfo) {
for i := range installedPlugins {
for j := range availablePlugins {
if installedPlugins[i].Name == availablePlugins[j].Name && installedPlugins[i].Target == availablePlugins[j].Target {
// Match found, Check for update available and update status
if installedPlugins[i].DiscoveredRecommendedVersion == availablePlugins[j].RecommendedVersion {
availablePlugins[j].Status = common.PluginStatusInstalled
} else {
availablePlugins[j].Status = common.PluginStatusUpdateAvailable
}
availablePlugins[j].InstalledVersion = installedPlugins[i].Version
}
}
}
}
// DescribePlugin describes a plugin.
func DescribePlugin(pluginName string, target configtypes.Target) (info *cli.PluginInfo, err error) {
plugins, err := pluginsupplier.GetInstalledPlugins()
if err != nil {
return nil, err
}
var matchedPlugins []cli.PluginInfo
for i := range plugins {
if plugins[i].Name == pluginName &&
(target == configtypes.TargetUnknown || target == plugins[i].Target) {
matchedPlugins = append(matchedPlugins, plugins[i])
}
}
if len(matchedPlugins) == 0 {
if target != configtypes.TargetUnknown {
return nil, errors.Errorf("unable to find plugin '%v' for target '%s'", pluginName, string(target))
}
return nil, errors.Errorf("unable to find plugin '%v'", pluginName)
}
if len(matchedPlugins) == 1 {
return &matchedPlugins[0], nil
}
for i := range matchedPlugins {
if matchedPlugins[i].Target == target {
return &matchedPlugins[i], nil
}
}
return nil, errors.Errorf(missingTargetStr, pluginName)
}
// InitializePlugin initializes the plugin configuration
func InitializePlugin(plugin *cli.PluginInfo) error {
if plugin == nil {
return fmt.Errorf("could not get plugin information")
}
b, err := execCommand(plugin.InstallationPath, "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", plugin.Name, string(b))
}
return nil
}
// InstallStandalonePlugin installs a plugin by name, version and target as a standalone plugin.
func InstallStandalonePlugin(pluginName, version string, target configtypes.Target) error {
defer StopSpinner()
return installPlugin(pluginName, version, target, "")
}
// SetTotalPluginsToInstall sets the total number of plugins to install
func SetTotalPluginsToInstall(total int) {
totalPluginsToInstall = total
}
// SetPluginBeingInstalledCount sets the number of plugins installed already
func SetPluginBeingInstalledCount(count int) {
pluginNumberBeingInstalled = count
}
// GetPluginBeingInstalledCount returns the number of plugin being installed
func GetPluginBeingInstalledCount() int {
return pluginNumberBeingInstalled
}
// IncrementPluginsInstalledCount increments the number of plugins installed
func IncrementPluginsInstalledCount(count int) {
pluginNumberBeingInstalled += count
}
// installs a plugin by name, version and target.
// If the contextName is not empty, it implies the plugin is a context-scope plugin, otherwise
// we are installing a standalone plugin.
//
//nolint:gocyclo
func installPlugin(pluginName, version string, target configtypes.Target, contextName string) error {
discoveries, err := getPluginDiscoveries()
if err != nil {
return err
}
if len(discoveries) == 0 {
return errors.New(errorNoDiscoverySourcesFound)
}
criteria := &discovery.PluginDiscoveryCriteria{
Name: pluginName,
Target: target,
Version: version,
OS: cli.GOOS,
Arch: cli.GOARCH,
}
errorList := make([]error, 0)
availablePlugins, err := discoverSpecificPlugins(discoveries, discovery.WithPluginDiscoveryCriteria(criteria))
if err != nil {
errorList = append(errorList, err)
}
// If we cannot find the plugin for ARM64, let's fallback to AMD64 for Darwin and Windows.
// This leverages Apples Rosetta emulator and Windows 11 emulator until plugins
// are all available for ARM64. Note that this approach cannot be used on Linux since there
// is no such emulator.
if len(availablePlugins) == 0 &&
(cli.BuildArch() == cli.DarwinARM64 || cli.BuildArch() == cli.WinARM64) {
// Pretend we are on a AMD64 machine so that we can find the plugin.
switch cli.BuildArch() {
case cli.DarwinARM64:
cli.SetArch(cli.DarwinAMD64)
criteria.Arch = cli.DarwinAMD64.Arch()
defer cli.SetArch(cli.DarwinARM64) // Go back to ARM64 once the plugin is installed
case cli.WinARM64:
cli.SetArch(cli.WinAMD64)
criteria.Arch = cli.WinAMD64.Arch()
defer cli.SetArch(cli.WinARM64) // Go back to ARM64 once the plugin is installed
}
availablePlugins, err = discoverSpecificPlugins(discoveries, discovery.WithPluginDiscoveryCriteria(criteria))
if err != nil {
errorList = append(errorList, err)
}
}
if len(availablePlugins) == 0 {
if target != configtypes.TargetUnknown {
errorList = append(errorList, errors.Errorf("unable to find plugin '%v' matching version '%v' for target '%s'", pluginName, version, string(target)))
return kerrors.NewAggregate(errorList)
}
errorList = append(errorList, errors.Errorf("unable to find plugin '%v' matching version '%v'", pluginName, version))
return kerrors.NewAggregate(errorList)
}
// Deal with duplicates from different plugin discovery sources
availablePlugins = mergeDuplicatePlugins(availablePlugins)
var matchedPlugins []discovery.Discovered
for i := range availablePlugins {
if availablePlugins[i].Name == pluginName &&
(target == configtypes.TargetUnknown || target == availablePlugins[i].Target) {
// If the plugin was recommended by a context, lets store that info
if contextName != "" {
availablePlugins[i].ContextName = contextName
}
matchedPlugins = append(matchedPlugins, availablePlugins[i])
}
}
if len(matchedPlugins) == 0 {
if target != configtypes.TargetUnknown {
errorList = append(errorList, errors.Errorf("unable to find plugin '%v' matching version '%v' for target '%s'", pluginName, version, string(target)))
return kerrors.NewAggregate(errorList)
}
errorList = append(errorList, errors.Errorf("unable to find plugin '%v' matching version '%v'", pluginName, version))
return kerrors.NewAggregate(errorList)
}
if len(matchedPlugins) == 1 {
return installOrUpgradePlugin(&matchedPlugins[0], matchedPlugins[0].RecommendedVersion, false)
}
// there can be only one plugin with the same name and target, so we can safely return the first one
for i := range matchedPlugins {
if matchedPlugins[i].Target == target {
return installOrUpgradePlugin(&matchedPlugins[i], matchedPlugins[i].RecommendedVersion, false)
}
}
errorList = append(errorList, errors.Errorf(missingTargetStr, pluginName))
return kerrors.NewAggregate(errorList)
}
// UpgradePlugin upgrades a plugin from the given repository.
func UpgradePlugin(pluginName, version string, target configtypes.Target) error {
// Upgrade is only triggered from a manual user operation.
// This means a plugin is installed manually, which means it is installed as a standalone plugin.
return InstallStandalonePlugin(pluginName, version, target)
}
// InstallPluginsFromGroup installs either the specified plugin or all plugins from the specified group version.
// If the group version is not specified, the latest available version will be used.
// The group identifier including the version used is returned.
func InstallPluginsFromGroup(pluginName, groupIDAndVersion string, options ...PluginManagerOptions) (string, error) {
// get plugins from the specific plugin group
pg, err := GetPluginGroup(groupIDAndVersion, options...)
if err != nil {
return "", err
}
// It is possible that user has provided plugin group version in form of vMAJOR or vMAJOR.MINOR
// So always update the groupIdentifier and groupIDAndVersion to the recommendedVersion we got
// from the database
groupIDAndVersion = fmt.Sprintf("%s-%s/%s:%s", pg.Vendor, pg.Publisher, pg.Name, pg.RecommendedVersion)
log.Infof("Installing plugins from plugin group '%s'", groupIDAndVersion)
return InstallPluginsFromGivenPluginGroup(pluginName, groupIDAndVersion, pg)
}
// InstallPluginsFromGivenPluginGroup installs either the specified plugin or all plugins from given plugin group plugins.
func InstallPluginsFromGivenPluginGroup(pluginName, groupIDAndVersion string, pg *plugininventory.PluginGroup) (string, error) {
numErrors := 0
mandatoryPluginsExist := false
pluginExist := false
pluginsToInstall := make([]*plugininventory.PluginGroupPluginEntry, 0)
for _, plugin := range pg.Versions[pg.RecommendedVersion] {
if pluginName == cli.AllPlugins || pluginName == plugin.Name {
pluginExist = true
if plugin.Mandatory {
mandatoryPluginsExist = true
pluginsToInstall = append(pluginsToInstall, plugin) // Add mandatory plugin to the slice
}
}
}
SetTotalPluginsToInstall(len(pluginsToInstall))
SetPluginBeingInstalledCount(1)
defer StopSpinner()
defer ResetPluginInstallationCounts()
for _, plugin := range pluginsToInstall {
err := InstallStandalonePlugin(plugin.Name, plugin.Version, plugin.Target)
if err != nil {
numErrors++
} else {
IncrementPluginsInstalledCount(1)
}
}
if !pluginExist {
return groupIDAndVersion, fmt.Errorf("plugin '%s' is not part of the group '%s'", pluginName, groupIDAndVersion)
}
if !mandatoryPluginsExist {
if pluginName == cli.AllPlugins {
return groupIDAndVersion, fmt.Errorf("plugin group '%s' has no mandatory plugins to install", groupIDAndVersion)
}
return groupIDAndVersion, fmt.Errorf("plugin '%s' from group '%s' is not mandatory to install", pluginName, groupIDAndVersion)
}
if numErrors > 0 {
return groupIDAndVersion, fmt.Errorf("could not install %d plugin(s) from group '%s'", numErrors, groupIDAndVersion)
}
if GetPluginBeingInstalledCount() == 0 {
return groupIDAndVersion, fmt.Errorf("plugin '%s' is not part of the group '%s'", pluginName, groupIDAndVersion)
}
return groupIDAndVersion, nil
}
// GetPluginGroup returns the plugin group for the specified groupIDAndVersion.
func GetPluginGroup(groupIDAndVersion string, options ...PluginManagerOptions) (*plugininventory.PluginGroup, error) {
// Initialize plugin manager options and enable logs by default
opts := NewPluginManagerOpts()
for _, option := range options {
option(opts)
}
// Enable or Disable logs
opts.SetLogMode()
defer opts.ResetLogMode()
discoveries, err := getPluginDiscoveries()
if err != nil {
return nil, err
}
if len(discoveries) == 0 {
return nil, errors.New(errorNoDiscoverySourcesFound)
}
groupIdentifier := plugininventory.PluginGroupIdentifierFromID(groupIDAndVersion)
if groupIdentifier == nil {
return nil, fmt.Errorf("could not find group '%s'", groupIDAndVersion)
}
if groupIdentifier.Version == "" {
// If the version is not specified to install from, we use the latest
groupIdentifier.Version = cli.VersionLatest
}
criteria := &discovery.GroupDiscoveryCriteria{
Vendor: groupIdentifier.Vendor,
Publisher: groupIdentifier.Publisher,
Name: groupIdentifier.Name,
Version: groupIdentifier.Version,
}
groups, err := discoverSpecificPluginGroups(discoveries, discovery.WithGroupDiscoveryCriteria(criteria))
if err != nil {
return nil, err
}
if len(groups) == 0 {
return nil, errors.Errorf("unable to find plugin group with name '%s-%s/%s' matching version '%s'", groupIdentifier.Vendor, groupIdentifier.Publisher, groupIdentifier.Name, groupIdentifier.Version)
}
if len(groups) > 1 {
log.Warningf("unexpected: group '%s' was found more than once. Using the first one.", groupIDAndVersion)
}
pg := groups[0]
return pg, nil
}
func getPluginInstallationMessage(p *discovery.Discovered, version string, isPluginInCache, isPluginAlreadyInstalled bool) (installingMsg, installedMsg, errorMsg string) {
withTarget := ""
if p.Target != configtypes.TargetUnknown {
withTarget = fmt.Sprintf("with target '%v' ", p.Target)
}
if isPluginInCache {
if !isPluginAlreadyInstalled {
installingMsg = fmt.Sprintf("Installing plugin '%v:%v' %v(from cache)", p.Name, version, withTarget)
installedMsg = fmt.Sprintf("Installed plugin '%v:%v' %v(from cache)", p.Name, version, withTarget)
} else {
installingMsg = fmt.Sprintf("Already installed : Plugin '%v:%v' %v", p.Name, version, withTarget)
installedMsg = fmt.Sprintf("Reinitialized plugin '%v:%v' %v", p.Name, version, withTarget)
}
} else {
installingMsg = fmt.Sprintf("Installing plugin '%v:%v' %v", p.Name, version, withTarget)
installedMsg = fmt.Sprintf("Installed plugin '%v:%v' %v", p.Name, version, withTarget)
}
errorMsg = fmt.Sprintf("Failed to install plugin '%v:%v' %v", p.Name, version, withTarget)
return installingMsg, installedMsg, errorMsg
}
func installOrUpgradePlugin(p *discovery.Discovered, version string, installTestPlugin bool) error {
// If the version requested was the RecommendedVersion, we should set it explicitly
if version == "" || version == cli.VersionLatest {
version = p.RecommendedVersion
}
var isPluginAlreadyInstalled bool
var plugin *cli.PluginInfo
if !installTestPlugin {
// If we need to install the test plugin we know we are doing a local
// installation. In that case, we don't use the cache as the binary is
// already local to the machine.
plugin = getPluginFromCache(p, version)
if p.ContextName == "" {
isPluginAlreadyInstalled = pluginsupplier.IsPluginInstalled(p.Name, p.Target, version)
}
}
// Log message based on different installation conditions
installingMsg, _, errMsg := getPluginInstallationMessage(p, version, plugin != nil, isPluginAlreadyInstalled)
installingMsg = fmt.Sprintf("[%v/%v] %v", pluginNumberBeingInstalled, totalPluginsToInstall, installingMsg)
errMsg = fmt.Sprintf("[%v/%v] %v", pluginNumberBeingInstalled, totalPluginsToInstall, errMsg)
numPluginsInstalled := fmt.Sprintf("%d plugins installed out of %d", pluginNumberBeingInstalled, totalPluginsToInstall)
numPluginsInstalledWithLog := fmt.Sprintf("%s%s", log.GetLogTypeIndicator(log.LogTypeERROR), numPluginsInstalled)
errMsg = fmt.Sprintf("%s\n%s", errMsg, numPluginsInstalledWithLog)
// Initialize the spinner if the spinner is allowed
if component.IsTTYEnabled() && spinner != nil {
spinner.SetText(installingMsg)
spinner.SetFinalText(errMsg, log.LogTypeERROR)
spinner.StartSpinner()
} else {
log.Info(installingMsg)
}
pluginErr := verifyInstallAndInitializePlugin(plugin, p, version, installTestPlugin)
if pluginErr == nil && spinner != nil {
// unset the final text to avoid the spinner from showing the final text
spinner.SetFinalText("", "")
}
return pluginErr
}
func verifyInstallAndInitializePlugin(plugin *cli.PluginInfo, p *discovery.Discovered, version string, installTestPlugin bool) error {
if plugin == nil {
binary, err := fetchAndVerifyPlugin(p, version)
if err != nil {
return err
}
plugin, err = installAndDescribePlugin(p, version, binary)
if err != nil {
return err
}
}
if installTestPlugin {
if err := doInstallTestPlugin(p, plugin.InstallationPath, version); err != nil {
return err
}
}
return updatePluginInfoAndInitializePlugin(p, plugin)
}
func getPluginFromCache(p *discovery.Discovered, version string) *cli.PluginInfo {
pluginArtifact, err := p.Distribution.DescribeArtifact(version, cli.GOOS, cli.GOARCH)
if err != nil {
return nil
}
// TODO(khouzam): We should not be checking the presence of the binary directly here,
// as it bypasses the plugin catalog abstraction. Instead, we should ask the plugin
// catalog to know if the plugin binary is present already.
pluginFileName := fmt.Sprintf("%s_%s_%s", version, pluginArtifact.Digest, p.Target)
pluginPath := filepath.Join(common.DefaultPluginRoot, p.Name, pluginFileName)
if cli.BuildArch().IsWindows() {
pluginPath += exe
}
if _, err = os.Stat(pluginPath); err != nil {
return nil
}
plugin, err := describePlugin(p, pluginPath)
if err != nil {
return nil
}
return plugin
}
func fetchAndVerifyPlugin(p *discovery.Discovered, version string) ([]byte, error) {
// verify plugin before download
err := verifyPluginPreDownload(p, version)
if err != nil {
return nil, errors.Wrapf(err, "%q plugin pre-download verification failed", p.Name)
}
b, err := p.Distribution.Fetch(version, cli.GOOS, cli.GOARCH)
if err != nil {
return nil, errors.Wrapf(err, "unable to fetch the plugin metadata for plugin %q", p.Name)
}
// verify plugin after download but before installation
d, err := p.Distribution.GetDigest(version, cli.GOOS, cli.GOARCH)
if err != nil {
return nil, err
}
err = verifyPluginPostDownload(p, d, b)
if err != nil {
return nil, errors.Wrapf(err, "%q plugin post-download verification failed", p.Name)
}
return b, nil
}
func installAndDescribePlugin(p *discovery.Discovered, version string, binary []byte) (*cli.PluginInfo, error) {
pluginFileName := fmt.Sprintf("%s_%x_%s", version, sha256.Sum256(binary), p.Target)
pluginPath := filepath.Join(common.DefaultPluginRoot, p.Name, pluginFileName)
if err := os.MkdirAll(filepath.Dir(pluginPath), os.ModePerm); err != nil {
return nil, err
}
if cli.BuildArch().IsWindows() {
pluginPath += exe
}
if err := os.WriteFile(pluginPath, binary, 0755); err != nil {
return nil, errors.Wrap(err, "could not write file")
}
return describePlugin(p, pluginPath)
}
func describePlugin(p *discovery.Discovered, pluginPath string) (*cli.PluginInfo, error) {
bytesInfo, err := execCommand(pluginPath, "info").Output()
if err != nil {
return nil, errors.Wrapf(err, "could not describe plugin %q", p.Name)
}
var plugin cli.PluginInfo
if err = json.Unmarshal(bytesInfo, &plugin); err != nil {
return nil, errors.Wrapf(err, "could not unmarshal plugin %q description", p.Name)
}
plugin.InstallationPath = pluginPath
plugin.Discovery = p.Source
plugin.DiscoveredRecommendedVersion = p.RecommendedVersion
plugin.Target = p.Target
plugin.Scope = p.Scope
if plugin.Version == p.RecommendedVersion {
plugin.Status = common.PluginStatusInstalled
} else {
plugin.Status = common.PluginStatusUpdateAvailable
}
return &plugin, nil
}
func doInstallTestPlugin(p *discovery.Discovered, pluginPath, version string) error {
log.Infof("Installing test plugin for '%v:%v'", p.Name, version)
binary, err := p.Distribution.FetchTest(version, cli.GOOS, cli.GOARCH)
if err != nil {
if os.Getenv("TZ_ENFORCE_TEST_PLUGIN") == "1" {
return errors.Wrapf(err, "unable to install test plugin for '%v:%v'", p.Name, version)
}
log.Infof(" ... skipped: %s", err.Error())
return nil
}
testPluginPath := cli.TestPluginPathFromPluginPath(pluginPath)
err = os.WriteFile(testPluginPath, binary, 0755)
if err != nil {
return errors.Wrap(err, "error while saving test plugin binary")
}
return nil
}
func updatePluginInfoAndInitializePlugin(p *discovery.Discovered, plugin *cli.PluginInfo) error {
c, err := catalog.NewContextCatalogUpdater(p.ContextName)
if err != nil {
return err
}
if err := c.Upsert(plugin); err != nil {
log.Info("Plugin Info could not be updated in cache")
}
// We are not using defer `c.Unlock()` to release the lock here because we want to unlock the lock as soon as possible
// Using `defer` here will release the lock after `InitializePlugin`, `ConfigureDefaultFeatureFlagsIfMissing`,
// `addPluginToCommandTreeCache` invocations which is not what we want.
c.Unlock()
if err := InitializePlugin(plugin); err != nil {
log.Infof("could not initialize plugin after installing: %v", err.Error())
}
if err := configlib.ConfigureFeatureFlags(plugin.DefaultFeatureFlags, configlib.SkipIfExists()); err != nil {
log.Infof("could not configure default featureflags for the plugin: %v", err.Error())
}
// add plugin to the plugin command tree cache for telemetry to consume later for plugin command chain parsing
addPluginToCommandTreeCache(plugin)
return nil
}
// addPluginToCommandTreeCache would construct and add the plugin command tree to the command tree cache
// which would be consumed by telemetry for plugin command chain parsing
func addPluginToCommandTreeCache(plugin *cli.PluginInfo) {
// update the plugin command tree cache
ctr, err := plugincmdtree.NewCache()
if err != nil {
telemetry.LogError(err, "")
return
}
err = ctr.ConstructAndAddTree(plugin)
if err != nil {
telemetry.LogError(err, "")
}
}
// deletePluginFromCommandTreeCache deletes the plugin command tree from the command tree cache
// which would be consumed by telemetry
func deletePluginFromCommandTreeCache(plugin *cli.PluginInfo) {
// delete the plugin command tree from the plugin command tree cache
ctr, err := plugincmdtree.NewCache()
if err != nil {
telemetry.LogError(err, "")
return
}
err = ctr.DeleteTree(plugin)
if err != nil {
telemetry.LogError(err, "")
}
}