github.com/operator-framework/operator-lifecycle-manager@v0.30.0/pkg/lib/operatorclient/service.go (about)

     1  package operatorclient
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	v1 "k8s.io/api/core/v1"
     8  	apierrors "k8s.io/apimachinery/pkg/api/errors"
     9  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    10  	"k8s.io/apimachinery/pkg/types"
    11  	acv1 "k8s.io/client-go/applyconfigurations/core/v1"
    12  	"k8s.io/klog"
    13  )
    14  
    15  // ApplyService applies the Service.
    16  func (c *Client) ApplyService(applyConfig *acv1.ServiceApplyConfiguration, applyOptions metav1.ApplyOptions) (*v1.Service, error) {
    17  	return c.CoreV1().Services(*applyConfig.Namespace).Apply(context.TODO(), applyConfig, applyOptions)
    18  }
    19  
    20  // CreateService creates the Service or Updates if it already exists.
    21  func (c *Client) CreateService(ig *v1.Service) (*v1.Service, error) {
    22  	createdService, err := c.CoreV1().Services(ig.GetNamespace()).Create(context.TODO(), ig, metav1.CreateOptions{})
    23  	if apierrors.IsAlreadyExists(err) {
    24  		return c.UpdateService(ig)
    25  	}
    26  	return createdService, err
    27  }
    28  
    29  // GetService returns the existing Service.
    30  func (c *Client) GetService(namespace, name string) (*v1.Service, error) {
    31  	return c.CoreV1().Services(namespace).Get(context.TODO(), name, metav1.GetOptions{})
    32  }
    33  
    34  // DeleteService deletes the Service.
    35  func (c *Client) DeleteService(namespace, name string, options *metav1.DeleteOptions) error {
    36  	return c.CoreV1().Services(namespace).Delete(context.TODO(), name, *options)
    37  }
    38  
    39  // UpdateService will update the given Service resource.
    40  func (c *Client) UpdateService(service *v1.Service) (*v1.Service, error) {
    41  	klog.V(4).Infof("[UPDATE Service]: %s", service.GetName())
    42  	old, err := c.GetService(service.GetNamespace(), service.GetName())
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	normalized, err := cloneAndNormalizeObject(old)
    47  	if err != nil {
    48  		return nil, fmt.Errorf("failed to normalize existing Service resource for patch: %w", err)
    49  	}
    50  	if service.Spec.ClusterIP == old.Spec.ClusterIP {
    51  		// Support updating to manifests that specify a
    52  		// ClusterIP when its value is the same as that of the
    53  		// existing Service.
    54  		service = service.DeepCopy()
    55  		service.Spec.ClusterIP = ""
    56  	}
    57  	patchBytes, err := createPatch(normalized, service)
    58  	if err != nil {
    59  		return nil, fmt.Errorf("error creating patch for Service: %v", err)
    60  	}
    61  	return c.CoreV1().Services(service.GetNamespace()).Patch(context.TODO(), service.GetName(), types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{})
    62  }