Skip to content

Commit

Permalink
Finalize namespace
Browse files Browse the repository at this point in the history
Finalize namespace when it is stuck in 'Terminating' after migration.
As controller-runtime client has yet support subresources like,
using client-go to invoke the Finalize API of Namespace.
  • Loading branch information
pliurh committed May 11, 2020
1 parent b7ab652 commit da6035d
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions pkg/apply/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,15 @@ import (

"github.com/pkg/errors"

v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
uns "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
k8sclient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"k8s.io/client-go/kubernetes"
kscheme "k8s.io/client-go/kubernetes/scheme"
)

// ApplyObject applies the desired object against the apiserver,
Expand Down Expand Up @@ -49,6 +53,30 @@ func ApplyObject(ctx context.Context, client k8sclient.Client, obj *uns.Unstruct
return errors.Wrapf(err, "could not retrieve existing %s", objDesc)
}

if obj.GetKind() == "Namespace" {
ns := &v1.Namespace{}
if err := kscheme.Scheme.Convert(existing, ns, nil); err != nil {
return errors.Wrapf(err, "could not convert namespace %s", objDesc)
}
if ns.Status.Phase == v1.NamespaceTerminating {
log.Printf("finalize Namespace %s", objDesc)
ns.Spec.Finalizers = []v1.FinalizerName{}
// Get a config to for client-go
cfg, err := config.GetConfig()
if err != nil {
return errors.Wrapf(err, "could not create rest config")
}
clientset, err := kubernetes.NewForConfig(cfg)
if err != nil {
return errors.Wrapf(err, "could not create clientset")
}
if _, err := clientset.CoreV1().Namespaces().Finalize(ns); err != nil {
return errors.Wrapf(err, "could not finalize namespace %s", objDesc)
}
return nil
}
}

// Merge the desired object with what actually exists
if err := MergeObjectForUpdate(existing, obj); err != nil {
return errors.Wrapf(err, "could not merge object %s with existing", objDesc)
Expand Down

0 comments on commit da6035d

Please sign in to comment.