github.com/oam-dev/kubevela@v1.9.11/pkg/utils/util/init.go (about)

     1  /*
     2  Copyright 2021 The KubeVela Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package util
    18  
    19  import (
    20  	"context"
    21  
    22  	corev1 "k8s.io/api/core/v1"
    23  	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
    24  	"k8s.io/apimachinery/pkg/api/errors"
    25  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    26  	"k8s.io/apimachinery/pkg/types"
    27  	"sigs.k8s.io/controller-runtime/pkg/client"
    28  )
    29  
    30  // OAMLabel defines the label of namespace automatically created by kubevela
    31  var OAMLabel = map[string]string{"app.kubernetes.io/part-of": "kubevela"}
    32  
    33  // DoesNamespaceExist check namespace exist
    34  func DoesNamespaceExist(c client.Client, namespace string) (bool, error) {
    35  	var ns corev1.Namespace
    36  	err := c.Get(context.Background(), types.NamespacedName{Name: namespace}, &ns)
    37  	if err != nil {
    38  		return false, client.IgnoreNotFound(err)
    39  	}
    40  	return true, nil
    41  }
    42  
    43  // NewNamespace create namespace
    44  func NewNamespace(c client.Client, namespace string) error {
    45  	ns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace,
    46  		// marking a special label for prometheus monitoring.
    47  		Labels: OAMLabel}}
    48  	err := c.Create(context.Background(), ns)
    49  	if err != nil {
    50  		return err
    51  	}
    52  	return nil
    53  }
    54  
    55  // DoesCRDExist check CRD exist
    56  func DoesCRDExist(cxt context.Context, c client.Client, crdName string) (bool, error) {
    57  	err := c.Get(cxt, types.NamespacedName{Name: crdName}, &apiextensions.CustomResourceDefinition{})
    58  	if err != nil {
    59  		if errors.IsNotFound(err) {
    60  			return false, nil
    61  		}
    62  		return false, err
    63  	}
    64  	return true, nil
    65  }