github.com/sdbaiguanghe/helm@v2.16.7+incompatible/pkg/kube/namespace.go (about)

     1  /*
     2  Copyright The Helm 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 kube // import "k8s.io/helm/pkg/kube"
    18  
    19  import (
    20  	"k8s.io/api/core/v1"
    21  	"k8s.io/apimachinery/pkg/api/errors"
    22  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    23  	"k8s.io/client-go/kubernetes"
    24  )
    25  
    26  func createNamespace(client kubernetes.Interface, namespace string) error {
    27  	ns := &v1.Namespace{
    28  		ObjectMeta: metav1.ObjectMeta{
    29  			Name: namespace,
    30  			Labels: map[string]string{
    31  				"name": namespace,
    32  			},
    33  		},
    34  	}
    35  	_, err := client.CoreV1().Namespaces().Create(ns)
    36  	return err
    37  }
    38  
    39  func getNamespace(client kubernetes.Interface, namespace string) (*v1.Namespace, error) {
    40  	return client.CoreV1().Namespaces().Get(namespace, metav1.GetOptions{})
    41  }
    42  
    43  func ensureNamespace(client kubernetes.Interface, namespace string) error {
    44  	_, err := getNamespace(client, namespace)
    45  	if err != nil && errors.IsNotFound(err) {
    46  		err = createNamespace(client, namespace)
    47  
    48  		// If multiple commands which run `ensureNamespace` are run in
    49  		// parallel, then protect against the race condition in which
    50  		// the namespace did not exist when `getNamespace` was executed,
    51  		// but did exist when `createNamespace` was executed. If that
    52  		// happens, we can just proceed as normal.
    53  		if errors.IsAlreadyExists(err) {
    54  			return nil
    55  		}
    56  	}
    57  	return err
    58  }