github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/cli/cmd/plugin/platform.go (about) 1 /* 2 Copyright (C) 2022-2023 ApeCloud Co., Ltd 3 4 This file is part of KubeBlocks project 5 6 This program is free software: you can redistribute it and/or modify 7 it under the terms of the GNU Affero General Public License as published by 8 the Free Software Foundation, either version 3 of the License, or 9 (at your option) any later version. 10 11 This program is distributed in the hope that it will be useful 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU Affero General Public License for more details. 15 16 You should have received a copy of the GNU Affero General Public License 17 along with this program. If not, see <http://www.gnu.org/licenses/>. 18 */ 19 20 package plugin 21 22 import ( 23 "fmt" 24 "os" 25 "runtime" 26 27 "github.com/pkg/errors" 28 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 29 "k8s.io/apimachinery/pkg/labels" 30 "k8s.io/klog/v2" 31 ) 32 33 // GetMatchingPlatform finds the platform spec in the specified plugin that 34 // matches the os/arch of the current machine (can be overridden via KREW_OS 35 // and/or KREW_ARCH). 36 func GetMatchingPlatform(platforms []Platform) (Platform, bool, error) { 37 return matchPlatform(platforms, OSArch()) 38 } 39 40 // matchPlatform returns the first matching platform to given os/arch. 41 func matchPlatform(platforms []Platform, env OSArchPair) (Platform, bool, error) { 42 envLabels := labels.Set{ 43 "os": env.OS, 44 "arch": env.Arch, 45 } 46 klog.V(2).Infof("Matching platform for labels(%v)", envLabels) 47 48 for i, platform := range platforms { 49 sel, err := metav1.LabelSelectorAsSelector(platform.Selector) 50 if err != nil { 51 return Platform{}, false, errors.Wrap(err, "failed to compile label selector") 52 } 53 if sel.Matches(envLabels) { 54 klog.V(2).Infof("Found matching platform with index (%d)", i) 55 return platform, true, nil 56 } 57 } 58 return Platform{}, false, nil 59 } 60 61 // OSArchPair is wrapper around operating system and architecture 62 type OSArchPair struct { 63 OS, Arch string 64 } 65 66 // String converts environment into a string 67 func (p OSArchPair) String() string { 68 return fmt.Sprintf("%s/%s", p.OS, p.Arch) 69 } 70 71 // OSArch returns the OS/arch combination to be used on the current system. It 72 // can be overridden by setting KREW_OS and/or KREW_ARCH environment variables. 73 func OSArch() OSArchPair { 74 return OSArchPair{ 75 OS: getEnvOrDefault("KBLCI_OS", runtime.GOOS), 76 Arch: getEnvOrDefault("KBCLI_ARCH", runtime.GOARCH), 77 } 78 } 79 80 func getEnvOrDefault(env, absent string) string { 81 v := os.Getenv(env) 82 if v != "" { 83 return v 84 } 85 return absent 86 }