github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/cli/kubernetes/check.go (about)

     1  package kubernetes
     2  
     3  import (
     4  	apiv1alpha3 "github.com/docker/compose-on-kubernetes/api/compose/v1alpha3"
     5  	apiv1beta1 "github.com/docker/compose-on-kubernetes/api/compose/v1beta1"
     6  	apiv1beta2 "github.com/docker/compose-on-kubernetes/api/compose/v1beta2"
     7  	"github.com/pkg/errors"
     8  	apimachinerymetav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
     9  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    10  	"k8s.io/apimachinery/pkg/runtime/schema"
    11  	"k8s.io/client-go/discovery"
    12  )
    13  
    14  // StackVersion represents the detected Compose Component on Kubernetes side.
    15  type StackVersion string
    16  
    17  const (
    18  	// StackAPIV1Beta1 is returned if it's the most recent version available.
    19  	StackAPIV1Beta1 = StackVersion("v1beta1")
    20  	// StackAPIV1Beta2 is returned if it's the most recent version available.
    21  	StackAPIV1Beta2 = StackVersion("v1beta2")
    22  	// StackAPIV1Alpha3 is returned if it's the most recent version available, and experimental flag is on.
    23  	StackAPIV1Alpha3 = StackVersion("v1alpha3")
    24  )
    25  
    26  // GetStackAPIVersion returns the most appropriate stack API version installed.
    27  func GetStackAPIVersion(serverGroups discovery.ServerGroupsInterface) (StackVersion, error) {
    28  	groups, err := serverGroups.ServerGroups()
    29  	if err != nil {
    30  		return "", err
    31  	}
    32  
    33  	return getAPIVersion(groups)
    34  }
    35  
    36  func getAPIVersion(groups *metav1.APIGroupList) (StackVersion, error) {
    37  	switch {
    38  	case findVersion(apiv1alpha3.SchemeGroupVersion, groups.Groups):
    39  		return StackAPIV1Alpha3, nil
    40  	case findVersion(apiv1beta2.SchemeGroupVersion, groups.Groups):
    41  		return StackAPIV1Beta2, nil
    42  	case findVersion(apiv1beta1.SchemeGroupVersion, groups.Groups):
    43  		return StackAPIV1Beta1, nil
    44  	default:
    45  		return "", errors.New("failed to find a Stack API version")
    46  	}
    47  }
    48  
    49  func findVersion(stackAPI schema.GroupVersion, groups []apimachinerymetav1.APIGroup) bool {
    50  	for _, group := range groups {
    51  		if group.Name == stackAPI.Group {
    52  			for _, version := range group.Versions {
    53  				if version.Version == stackAPI.Version {
    54  					return true
    55  				}
    56  			}
    57  		}
    58  	}
    59  	return false
    60  }