...

Source file src/sigs.k8s.io/cli-utils/pkg/apply/filter/local-namespaces-filter.go

Documentation: sigs.k8s.io/cli-utils/pkg/apply/filter

     1  // Copyright 2021 The Kubernetes Authors.
     2  // SPDX-License-Identifier: Apache-2.0
     3  
     4  package filter
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
    10  	"k8s.io/apimachinery/pkg/runtime/schema"
    11  	"k8s.io/apimachinery/pkg/util/sets"
    12  	"sigs.k8s.io/cli-utils/pkg/object"
    13  )
    14  
    15  var (
    16  	namespaceGK = schema.GroupKind{Group: "", Kind: "Namespace"}
    17  )
    18  
    19  // LocalNamespacesFilter encapsulates the set of namespaces
    20  // that are currently in use. Used to ensure we do not delete
    21  // namespaces with currently applied objects in them.
    22  type LocalNamespacesFilter struct {
    23  	LocalNamespaces sets.String
    24  }
    25  
    26  // Name returns a filter identifier for logging.
    27  func (lnf LocalNamespacesFilter) Name() string {
    28  	return "LocalNamespacesFilter"
    29  }
    30  
    31  // Filter returns a NamespaceInUseError if the object prune/delete should be
    32  // skipped.
    33  func (lnf LocalNamespacesFilter) Filter(obj *unstructured.Unstructured) error {
    34  	id := object.UnstructuredToObjMetadata(obj)
    35  	if id.GroupKind == namespaceGK &&
    36  		lnf.LocalNamespaces.Has(id.Name) {
    37  		return &NamespaceInUseError{
    38  			Namespace: id.Name,
    39  		}
    40  	}
    41  	return nil
    42  }
    43  
    44  type NamespaceInUseError struct {
    45  	Namespace string
    46  }
    47  
    48  func (e *NamespaceInUseError) Error() string {
    49  	return fmt.Sprintf("namespace still in use: %s", e.Namespace)
    50  }
    51  
    52  func (e *NamespaceInUseError) Is(err error) bool {
    53  	if err == nil {
    54  		return false
    55  	}
    56  	tErr, ok := err.(*NamespaceInUseError)
    57  	if !ok {
    58  		return false
    59  	}
    60  	return e.Namespace == tErr.Namespace
    61  }
    62  

View as plain text