github.com/IBM-Blockchain/fabric-operator@v1.0.4/pkg/k8s/clientset/client.go (about)

     1  /*
     2   * Copyright contributors to the Hyperledger Fabric Operator project
     3   *
     4   * SPDX-License-Identifier: Apache-2.0
     5   *
     6   * Licensed under the Apache License, Version 2.0 (the "License");
     7   * you may not use this file except in compliance with the License.
     8   * You may obtain a copy of the License at:
     9   *
    10   * 	  http://www.apache.org/licenses/LICENSE-2.0
    11   *
    12   * Unless required by applicable law or agreed to in writing, software
    13   * distributed under the License is distributed on an "AS IS" BASIS,
    14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    15   * See the License for the specific language governing permissions and
    16   * limitations under the License.
    17   */
    18  
    19  package clientset
    20  
    21  import (
    22  	"context"
    23  	"fmt"
    24  	"strings"
    25  
    26  	extv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
    27  	"k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
    28  	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    29  	"k8s.io/client-go/rest"
    30  	logf "sigs.k8s.io/controller-runtime/pkg/log"
    31  )
    32  
    33  var log = logf.Log.WithName("clientset")
    34  
    35  type Client struct {
    36  	clientset.Clientset
    37  }
    38  
    39  func New(config *rest.Config) (*Client, error) {
    40  	clientSet, err := clientset.NewForConfig(config)
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  	return &Client{*clientSet}, nil
    45  }
    46  
    47  func (c *Client) CreateCRD(crd *extv1.CustomResourceDefinition) (*extv1.CustomResourceDefinition, error) {
    48  	log.Info(fmt.Sprintf("Creating CRD '%s'", crd.Name))
    49  	result, err := c.ApiextensionsV1().CustomResourceDefinitions().Create(context.TODO(), crd, v1.CreateOptions{})
    50  	if err != nil {
    51  		if strings.Contains(err.Error(), "already exists") {
    52  			existingcrd, err := c.ApiextensionsV1().CustomResourceDefinitions().Get(context.TODO(), crd.Name, v1.GetOptions{})
    53  			if err != nil {
    54  				return nil, err
    55  			}
    56  
    57  			log.Info(fmt.Sprintf("Updating CRD '%s'", crd.Name))
    58  			existingcrd.Spec = crd.Spec
    59  			result, err = c.ApiextensionsV1().CustomResourceDefinitions().Update(context.TODO(), existingcrd, v1.UpdateOptions{})
    60  			if err != nil {
    61  				return nil, err
    62  			}
    63  		} else {
    64  			log.Error(err, "Error creating CRD", "CRD", crd.Name)
    65  		}
    66  	}
    67  	return result, nil
    68  }