-
Notifications
You must be signed in to change notification settings - Fork 239
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(reset): add cleanup volumes and cleanup-load-balancers flag #3507
Open
rajaSahil
wants to merge
2
commits into
kubermatic:main
Choose a base branch
from
rajaSahil:destroy-volumes-svc
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+458
−18
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
/* | ||
Copyright 2025 The KubeOne Authors. | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package clientutil | ||
|
||
import ( | ||
"context" | ||
"time" | ||
|
||
"github.com/sirupsen/logrus" | ||
|
||
"k8c.io/kubeone/pkg/fail" | ||
|
||
corev1 "k8s.io/api/core/v1" | ||
"k8s.io/apimachinery/pkg/util/wait" | ||
"sigs.k8s.io/controller-runtime/pkg/client" | ||
) | ||
|
||
func CleanupLBs(ctx context.Context, logger logrus.FieldLogger, c client.Client) error { | ||
serviceList := &corev1.ServiceList{} | ||
if err := c.List(ctx, serviceList); err != nil { | ||
return fail.KubeClient(err, "listing services") | ||
} | ||
|
||
for _, service := range serviceList.Items { | ||
// This service is already in deletion, nothing further needs to happen. | ||
if service.DeletionTimestamp != nil { | ||
continue | ||
} | ||
logger.Infof("Cleaning up LoadBalancer Services...") | ||
// Only LoadBalancer services incur charges on cloud providers | ||
if service.Spec.Type == corev1.ServiceTypeLoadBalancer { | ||
logger.Debugf("Deleting LoadBalancer Service \"%s/%s\"", service.Namespace, service.Name) | ||
if err := DeleteIfExists(ctx, c, &service); err != nil { | ||
return err | ||
} | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func WaitCleanupLbs(ctx context.Context, logger logrus.FieldLogger, c client.Client) error { | ||
logger.Infoln("Waiting for all LoadBalancer Services to get deleted...") | ||
|
||
return wait.PollUntilContextTimeout(ctx, 5*time.Second, 5*time.Minute, false, func(ctx context.Context) (bool, error) { | ||
serviceList := &corev1.ServiceList{} | ||
if err := c.List(ctx, serviceList); err != nil { | ||
logger.Errorf("failed to list services, error: %v", err.Error()) | ||
|
||
return false, nil | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let's still log an error so that user has some idea that there's something wrong. |
||
} | ||
for _, service := range serviceList.Items { | ||
// Only LoadBalancer services incur charges on cloud providers | ||
if service.Spec.Type == corev1.ServiceTypeLoadBalancer { | ||
return false, nil | ||
} | ||
} | ||
|
||
return true, nil | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
/* | ||
Copyright 2025 The KubeOne Authors. | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package clientutil | ||
|
||
import ( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same here, please properly sort imports. |
||
"context" | ||
"fmt" | ||
"time" | ||
|
||
"github.com/sirupsen/logrus" | ||
|
||
"k8c.io/kubeone/pkg/fail" | ||
"k8c.io/reconciler/pkg/reconciling" | ||
|
||
corev1 "k8s.io/api/core/v1" | ||
"k8s.io/apimachinery/pkg/util/wait" | ||
"sigs.k8s.io/controller-runtime/pkg/client" | ||
) | ||
|
||
const ( | ||
annotationKeyDescription = "description" | ||
|
||
// AnnDynamicallyProvisioned is added to a PV that is dynamically provisioned by kubernetes | ||
// Because the annotation is defined only at k8s.io/kubernetes, copying the content instead of vendoring | ||
// https://github.com/kubernetes/kubernetes/blob/v1.21.0/pkg/controller/volume/persistentvolume/util/util.go#L65 | ||
AnnDynamicallyProvisioned = "pv.kubernetes.io/provisioned-by" | ||
) | ||
|
||
var VolumeResources = []string{"persistentvolumes", "persistentvolumeclaims"} | ||
|
||
func CleanupUnretainedVolumes(ctx context.Context, logger logrus.FieldLogger, c client.Client) error { | ||
// We disable the PV & PVC creation so nothing creates new PV's while we delete them | ||
logger.Infoln("Creating ValidatingWebhookConfiguration to disable future PV & PVC creation...") | ||
if err := disablePVCreation(ctx, c); err != nil { | ||
return fail.KubeClient(err, "failed to disable future PV & PVC creation.") | ||
} | ||
|
||
pvcList, pvList, err := getDynamicallyProvisionedUnretainedPvs(ctx, c) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
// Do not attempt to delete any pods when there are no PVs and PVCs | ||
if (pvcList != nil && pvList != nil) && len(pvcList.Items) == 0 && len(pvList.Items) == 0 { | ||
return nil | ||
} | ||
|
||
// Delete all Pods that use PVs. We must keep the remaining pods, otherwise | ||
// we end up in a deadlock when CSI is used | ||
if err := cleanupPVCUsingPods(ctx, c); err != nil { | ||
return fail.KubeClient(err, "failed to clean up PV using pod from user cluster.") | ||
} | ||
|
||
// Delete PVC's | ||
logger.Infoln("Deleting persistent volume claims...") | ||
for _, pvc := range pvcList.Items { | ||
if pvc.DeletionTimestamp == nil { | ||
identifier := fmt.Sprintf("%s/%s", pvc.Namespace, pvc.Name) | ||
logger.Infoln("Deleting PVC...", identifier) | ||
|
||
if err := DeleteIfExists(ctx, c, &pvc); err != nil { | ||
return fail.KubeClient(err, "failed to delete PVC from user cluster.") | ||
} | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func disablePVCreation(ctx context.Context, c client.Client) error { | ||
// Prevent re-creation of PVs and PVCs by using an intentionally defunct admissionWebhook | ||
creatorGetters := []reconciling.NamedValidatingWebhookConfigurationReconcilerFactory{ | ||
creationPreventingWebhook("", VolumeResources), | ||
} | ||
if err := reconciling.ReconcileValidatingWebhookConfigurations(ctx, creatorGetters, "", c); err != nil { | ||
return fail.KubeClient(err, "failed to create ValidatingWebhookConfiguration to prevent creation of PVs/PVCs.") | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func cleanupPVCUsingPods(ctx context.Context, c client.Client) error { | ||
podList := &corev1.PodList{} | ||
if err := c.List(ctx, podList); err != nil { | ||
return fail.KubeClient(err, "failed to list Pods from user cluster.") | ||
} | ||
|
||
var pvUsingPods []*corev1.Pod | ||
for idx := range podList.Items { | ||
pod := &podList.Items[idx] | ||
if podUsesPV(pod) { | ||
pvUsingPods = append(pvUsingPods, pod) | ||
} | ||
} | ||
|
||
for _, pod := range pvUsingPods { | ||
if pod.DeletionTimestamp == nil { | ||
if err := DeleteIfExists(ctx, c, pod); err != nil { | ||
return fail.KubeClient(err, "failed to delete Pod.") | ||
} | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func podUsesPV(p *corev1.Pod) bool { | ||
for _, volume := range p.Spec.Volumes { | ||
if volume.VolumeSource.PersistentVolumeClaim != nil { | ||
return true | ||
} | ||
} | ||
|
||
return false | ||
} | ||
|
||
func getDynamicallyProvisionedUnretainedPvs(ctx context.Context, c client.Client) (*corev1.PersistentVolumeClaimList, *corev1.PersistentVolumeList, error) { | ||
pvcList := &corev1.PersistentVolumeClaimList{} | ||
if err := c.List(ctx, pvcList); err != nil { | ||
return nil, nil, fail.KubeClient(err, "failed to list PVCs from user cluster.") | ||
} | ||
allPVList := &corev1.PersistentVolumeList{} | ||
if err := c.List(ctx, allPVList); err != nil { | ||
return nil, nil, fail.KubeClient(err, "failed to list PVs from user cluster.") | ||
} | ||
pvList := &corev1.PersistentVolumeList{} | ||
for _, pv := range allPVList.Items { | ||
// Check only dynamically provisioned PVs with delete reclaim policy to verify provisioner has done the cleanup | ||
// this filters out everything else because we leave those be | ||
if pv.Annotations[AnnDynamicallyProvisioned] != "" && pv.Spec.PersistentVolumeReclaimPolicy == corev1.PersistentVolumeReclaimDelete { | ||
pvList.Items = append(pvList.Items, pv) | ||
} | ||
} | ||
|
||
return pvcList, pvList, nil | ||
} | ||
|
||
func WaitCleanUpVolumes(ctx context.Context, logger logrus.FieldLogger, c client.Client) error { | ||
logger.Infoln("Waiting for all dynamically provisioned and unretained volumes to get deleted...") | ||
|
||
return wait.PollUntilContextTimeout(ctx, 5*time.Second, 5*time.Minute, false, func(ctx context.Context) (bool, error) { | ||
pvcList, pvList, err := getDynamicallyProvisionedUnretainedPvs(ctx, c) | ||
if err != nil { | ||
return false, nil | ||
} | ||
|
||
if (pvcList != nil && pvList != nil) && len(pvcList.Items) == 0 && len(pvList.Items) == 0 { | ||
return true, nil | ||
} | ||
|
||
return false, nil | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
/* | ||
Copyright 2025 The KubeOne Authors. | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package clientutil | ||
|
||
import ( | ||
"context" | ||
"strings" | ||
|
||
"k8c.io/kubeone/pkg/fail" | ||
"k8c.io/reconciler/pkg/reconciling" | ||
|
||
admissionregistrationv1 "k8s.io/api/admissionregistration/v1" | ||
"k8s.io/apimachinery/pkg/types" | ||
"k8s.io/utils/ptr" | ||
"sigs.k8s.io/controller-runtime/pkg/client" | ||
) | ||
|
||
// creationPreventingWebhook returns a ValidatingWebhookConfiguration that is intentionally defunct | ||
// and will prevent all creation requests from succeeding. | ||
func creationPreventingWebhook(apiGroup string, resources []string) reconciling.NamedValidatingWebhookConfigurationReconcilerFactory { | ||
failurePolicy := admissionregistrationv1.Fail | ||
sideEffects := admissionregistrationv1.SideEffectClassNone | ||
|
||
return func() (string, reconciling.ValidatingWebhookConfigurationReconciler) { | ||
return "kubernetes-cluster-cleanup-" + strings.Join(resources, "-"), | ||
func(vwc *admissionregistrationv1.ValidatingWebhookConfiguration) (*admissionregistrationv1.ValidatingWebhookConfiguration, error) { | ||
if vwc.Annotations == nil { | ||
vwc.Annotations = map[string]string{} | ||
} | ||
vwc.Annotations[annotationKeyDescription] = "This webhook configuration exists to prevent creation of any new stateful resources in a cluster that is currently being terminated" | ||
|
||
// This only gets set when the APIServer supports it, so carry it over | ||
var scope *admissionregistrationv1.ScopeType | ||
if len(vwc.Webhooks) != 1 { | ||
vwc.Webhooks = []admissionregistrationv1.ValidatingWebhook{{}} | ||
} else if len(vwc.Webhooks[0].Rules) > 0 { | ||
scope = vwc.Webhooks[0].Rules[0].Scope | ||
} | ||
// Must be a domain with at least three segments separated by dots | ||
vwc.Webhooks[0].Name = "kubernetes.cluster.cleanup" | ||
vwc.Webhooks[0].ClientConfig = admissionregistrationv1.WebhookClientConfig{ | ||
URL: ptr.To("https://127.0.0.1:1"), | ||
} | ||
vwc.Webhooks[0].Rules = []admissionregistrationv1.RuleWithOperations{ | ||
{ | ||
Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create}, | ||
Rule: admissionregistrationv1.Rule{ | ||
APIGroups: []string{apiGroup}, | ||
APIVersions: []string{"*"}, | ||
Resources: resources, | ||
Scope: scope, | ||
}, | ||
}, | ||
} | ||
vwc.Webhooks[0].FailurePolicy = &failurePolicy | ||
vwc.Webhooks[0].SideEffects = &sideEffects | ||
vwc.Webhooks[0].AdmissionReviewVersions = []string{"v1"} | ||
|
||
return vwc, nil | ||
} | ||
} | ||
} | ||
|
||
func DeletePreventingWebhook(ctx context.Context, c client.Client, resourceName string) error { | ||
vwc := admissionregistrationv1.ValidatingWebhookConfiguration{} | ||
if err := c.Get(ctx, types.NamespacedName{Name: resourceName}, &vwc); err != nil { | ||
return fail.KubeClient(err, "failed to get ValidatingWebhookConfiguration") | ||
} | ||
if err := DeleteIfExists(ctx, c, &vwc); err != nil { | ||
return err | ||
} | ||
|
||
return nil | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Take a look here how we order imports:
kubeone/pkg/nodeutils/drain.go
Lines 19 to 31 in 8b8d794
It should be stdlib -> external dependencies -> k8c.io -> k8s.io
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This will fix all the imports