github.com/kubeshop/testkube@v1.17.23/cmd/kubectl-testkube/commands/common/validator/version.go (about) 1 package validator 2 3 import ( 4 "fmt" 5 "regexp" 6 7 "github.com/Masterminds/semver" 8 "github.com/spf13/cobra" 9 10 "github.com/kubeshop/testkube/cmd/kubectl-testkube/commands/common" 11 "github.com/kubeshop/testkube/pkg/ui" 12 ) 13 14 var ErrOldClientVersion = fmt.Errorf("client version is older than api version, please upgrade") 15 16 // PersistentPreRunVersionCheck will check versions based on commands client 17 func PersistentPreRunVersionCheck(cmd *cobra.Command, clientVersion string) { 18 // version validation 19 // if client version is less than server version show warning 20 client, _, err := common.GetClient(cmd) 21 if err != nil { 22 return 23 } 24 25 info, err := client.GetServerInfo() 26 if err != nil { 27 // omit check of versions if we can't get server info 28 // e.g. when there is not cloud token yet 29 ui.Debug(err.Error()) 30 return 31 } 32 33 err = ValidateVersions(info.Version, clientVersion) 34 if err != nil { 35 ui.Warn(err.Error()) 36 } else if err == ErrOldClientVersion { 37 ui.Warn("Your Testkube API version is newer than your `kubectl testkube` plugin") 38 ui.Info("Testkube API version", info.Version) 39 ui.Info("Testkube kubectl plugin client", clientVersion) 40 ui.Info("It's recommended to upgrade client to version close to API server version") 41 ui.NL() 42 } 43 } 44 45 // ValidateVersions will check if kubectl plugins MINOR version is greater or equal Testkube API version 46 func ValidateVersions(apiVersionString, clientVersionString string) error { 47 if apiVersionString == "" { 48 return fmt.Errorf("server version not set") 49 } 50 51 apiMinorVersion := TrimPatchVersion(apiVersionString) 52 apiVersion, err := semver.NewVersion(apiMinorVersion) 53 if err != nil { 54 return fmt.Errorf("parsing server version '%s': %w", apiVersionString, err) 55 } 56 57 if clientVersionString == "" { 58 return fmt.Errorf("client version not set") 59 } 60 61 clientMinorVersion := TrimPatchVersion(clientVersionString) 62 clientVersion, err := semver.NewVersion(clientMinorVersion) 63 if err != nil { 64 return fmt.Errorf("parsing client version %s: %w", clientVersionString, err) 65 } 66 67 if clientVersion.LessThan(apiVersion) { 68 return ErrOldClientVersion 69 } 70 71 return nil 72 } 73 74 // TrimPatchVersion will trim 75 func TrimPatchVersion(version string) string { 76 re := regexp.MustCompile("([0-9]+).([0-9]+).([0-9]+)(.*)") 77 parts := re.FindStringSubmatch(version) 78 if len(parts) == 5 { 79 return fmt.Sprintf("%s.%s.%s", parts[1], parts[2], "0") 80 } 81 82 return version 83 }