github.com/AliyunContainerService/cli@v0.0.0-20181009023821-814ced4b30d0/kubernetes/check.go (about)

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