1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2024-12-15 17:51:20 +00:00
kyverno/pkg/utils/kube/version.go
Charles-Edouard Brétéché 94abfaf13e
refactor: move util funcs in sub packages (#5754)
* refactor: move util func in sub packages

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>

* fix

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>

* Update pkg/utils/kube/crd.go

Signed-off-by: shuting <shutting06@gmail.com>

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
Signed-off-by: shuting <shutting06@gmail.com>
Co-authored-by: shuting <shutting06@gmail.com>
2022-12-22 06:39:54 +00:00

53 lines
1.6 KiB
Go

package kube
import (
"fmt"
"regexp"
"strconv"
"github.com/go-logr/logr"
"k8s.io/client-go/discovery"
)
var regexVersion = regexp.MustCompile(`v(\d+).(\d+).(\d+)\.*`)
// HigherThanKubernetesVersion compare Kubernetes client version to user given version
func HigherThanKubernetesVersion(client discovery.ServerVersionInterface, log logr.Logger, major, minor, patch int) bool {
logger := log.WithName("CompareKubernetesVersion")
serverVersion, err := client.ServerVersion()
if err != nil {
logger.Error(err, "Failed to get kubernetes server version")
return false
}
b, err := isVersionHigher(serverVersion.String(), major, minor, patch)
if err != nil {
logger.Error(err, "serverVersion", serverVersion.String())
return false
}
return b
}
func isVersionHigher(version string, major int, minor int, patch int) (bool, error) {
groups := regexVersion.FindStringSubmatch(version)
if len(groups) != 4 {
return false, fmt.Errorf("invalid version %s. Expected {major}.{minor}.{patch}", version)
}
currentMajor, err := strconv.Atoi(groups[1])
if err != nil {
return false, fmt.Errorf("failed to extract major version from %s", version)
}
currentMinor, err := strconv.Atoi(groups[2])
if err != nil {
return false, fmt.Errorf("failed to extract minor version from %s", version)
}
currentPatch, err := strconv.Atoi(groups[3])
if err != nil {
return false, fmt.Errorf("failed to extract minor version from %s", version)
}
if currentMajor < major ||
(currentMajor == major && currentMinor < minor) ||
(currentMajor == major && currentMinor == minor && currentPatch <= patch) {
return false, nil
}
return true, nil
}