Skip to content
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

K8SPS-367: delete-mysql-pvc finalizer #726

Merged
merged 17 commits into from
Aug 20, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions api/v1alpha1/perconaservermysql_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -840,6 +840,16 @@ func (cr *PerconaServerMySQL) CheckNSetDefaults(ctx context.Context, serverVersi
return nil
}

func (cr *PerconaServerMySQL) FinalizerApplied(finalizer string) bool {
for _, f := range cr.GetFinalizers() {
if f == finalizer {
return true
}
}

return false
}

inelpandzic marked this conversation as resolved.
Show resolved Hide resolved
const (
BinVolumeName = "bin"
BinVolumePath = "/opt/percona"
Expand Down
1 change: 1 addition & 0 deletions deploy/cr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ metadata:
finalizers:
- percona.com/delete-mysql-pods-in-order
# - percona.com/delete-ssl
# - percona.com/delete-mysql-pvc
spec:
# unsafeFlags:
# mysqlSize: false
Expand Down
65 changes: 65 additions & 0 deletions pkg/controller/ps/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
Expand Down Expand Up @@ -147,6 +148,8 @@ func (r *PerconaServerMySQLReconciler) applyFinalizers(ctx context.Context, cr *
err = r.deleteMySQLPods(ctx, cr)
case naming.FinalizerDeleteSSL:
err = r.deleteCerts(ctx, cr)
case naming.FinalizerDeleteMySQLPvc:
err = r.deleteMySQLPvc(ctx, cr)
}

if err != nil {
Expand Down Expand Up @@ -184,6 +187,21 @@ func (r *PerconaServerMySQLReconciler) deleteMySQLPods(ctx context.Context, cr *
if len(pods) <= 1 {
time.Sleep(time.Second * 3)
log.Info("Cluster deleted")

// If `delete-mysql-pvc` finalizer is also applied we need to remove all the secrets,
// but we need to do it here since there are needed to apply this finalizer.
if cr.FinalizerApplied(naming.FinalizerDeleteMySQLPvc) {
secretNames := []string{
cr.Spec.SecretsName,
"internal-" + cr.Name,
}

err := k8s.DeleteSecrets(ctx, r.Client, cr, secretNames)
if err != nil {
return errors.Wrap(err, "delete secrets")
}
log.Info("Removed secrets", "secrets", secretNames)
}
return nil
}

Expand Down Expand Up @@ -355,6 +373,53 @@ func (r *PerconaServerMySQLReconciler) deleteCerts(ctx context.Context, cr *apiv
return nil
}

func (r *PerconaServerMySQLReconciler) deleteMySQLPvc(ctx context.Context, cr *apiv1alpha1.PerconaServerMySQL) error {
log := logf.FromContext(ctx)

log.Info(fmt.Sprintf("Applying %s finalizer", naming.FinalizerDeleteMySQLPvc))

exposer := mysql.Exposer(*cr)

list := corev1.PersistentVolumeClaimList{}

err := r.Client.List(ctx,
&list,
&client.ListOptions{
Namespace: cr.Namespace,
LabelSelector: labels.SelectorFromSet(exposer.Labels()),
},
)
if err != nil {
return errors.Wrap(err, "get PVC list")
}

for _, pvc := range list.Items {
err := r.Client.Delete(ctx, &pvc, &client.DeleteOptions{Preconditions: &metav1.Preconditions{UID: &pvc.UID}})
if err != nil {
return errors.Wrapf(err, "delete PVC %s", pvc.Name)
}
log.Info("Removed MySQL PVC", "pvc", pvc.Name)
}

// If `delete-mysql-in-order` finalizer is applied, we will let that handler
// remove all the secrets, since they are needed to remove pods in order.
if cr.FinalizerApplied(naming.FinalizerDeletePodsInOrder) {
return nil
}

secretNames := []string{
cr.Spec.SecretsName,
"internal-" + cr.Name,
}
err = k8s.DeleteSecrets(ctx, r.Client, cr, secretNames)
if err != nil {
return errors.Wrap(err, "delete secrets")
}
log.Info("Removed secrets", "secrets", secretNames)

return nil
}

func (r *PerconaServerMySQLReconciler) doReconcile(
ctx context.Context,
cr *apiv1alpha1.PerconaServerMySQL,
Expand Down
150 changes: 150 additions & 0 deletions pkg/controller/ps/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ package ps

import (
"context"
"fmt"
"strconv"
"strings"
"time"

. "github.com/onsi/ginkgo/v2"
Expand All @@ -28,12 +31,14 @@ import (
k8serrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"

psv1alpha1 "github.com/percona/percona-server-mysql-operator/api/v1alpha1"
"github.com/percona/percona-server-mysql-operator/pkg/mysql"
"github.com/percona/percona-server-mysql-operator/pkg/naming"
//+kubebuilder:scaffold:imports
)

Expand Down Expand Up @@ -518,3 +523,148 @@ var _ = Describe("Reconcile Binlog Server", Ordered, func() {
})
})
})

var _ = Describe("Finalizer delete-mysql-pvc", Ordered, func() {
ctx := context.Background()

const crName = "del-mysql-pvc-fnlz"
const ns = "del-mysql-pvc-fnlz"
crNamespacedName := types.NamespacedName{Name: crName, Namespace: ns}

namespace := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: ns,
Namespace: ns,
},
}

BeforeAll(func() {
By("Creating the Namespace to perform the tests")
err := k8sClient.Create(ctx, namespace)
Expect(err).To(Not(HaveOccurred()))

Expect(err).NotTo(HaveOccurred())
})

AfterAll(func() {
By("Deleting the Namespace to perform the tests")
_ = k8sClient.Delete(ctx, namespace)
})

Context("delete-mysql-pvc finalizer specified", Ordered, func() {

cr, err := readDefaultCR(crName, ns)

It("should read default cr.yaml", func() {
Expect(err).NotTo(HaveOccurred())
})
cr.Finalizers = append(cr.Finalizers, naming.FinalizerDeleteMySQLPvc)
cr.Spec.SecretsName = "cluster1-secrets"

sfsWithOwner := appsv1.StatefulSet{}
// stsApp := statefulset.NewNode(cr)
exposer := mysql.Exposer(*cr)

It("Should create PerconaXtraDBCluster", func() {
Expect(k8sClient.Create(ctx, cr)).Should(Succeed())
})

It("should reconcile once to create user secret", func() {
_, err := reconciler().Reconcile(ctx, ctrl.Request{NamespacedName: crNamespacedName})
Expect(err).NotTo(HaveOccurred())
})

It("Should create mysql sts", func() {

Expect(k8sClient.Get(ctx, types.NamespacedName{
Name: cr.Name + "-mysql",
Namespace: cr.Namespace,
}, &sfsWithOwner)).Should(Succeed())
})

It("Should create secrets", func() {
secret := &corev1.Secret{}
Expect(k8sClient.Get(ctx, types.NamespacedName{
Namespace: cr.Namespace,
Name: cr.Spec.SecretsName,
}, secret)).Should(Succeed())
})

It("should create mysql PVC", func() {
for _, claim := range sfsWithOwner.Spec.VolumeClaimTemplates {
for i := 0; i < int(*sfsWithOwner.Spec.Replicas); i++ {
pvc := claim.DeepCopy()
pvc.Labels = exposer.Labels()
pvc.Name = strings.Join([]string{pvc.Name, sfsWithOwner.Name, strconv.Itoa(i)}, "-")
pvc.Namespace = ns
Expect(k8sClient.Create(ctx, pvc)).Should(Succeed())
}
}
})

It("controller should have mysql pvc", func() {
pvcList := corev1.PersistentVolumeClaimList{}
Eventually(func() bool {
err := k8sClient.List(ctx,
&pvcList,
&client.ListOptions{
Namespace: cr.Namespace,
LabelSelector: labels.SelectorFromSet(map[string]string{
"app.kubernetes.io/component": "mysql",
}),
})
return err == nil
}, time.Second*25, time.Millisecond*250).Should(BeTrue())
Expect(len(pvcList.Items)).Should(Equal(3))
})

When("mysql cluster is deleted with delete-mysql-pvc finalizer sts, pvc, and secrets should be removed", func() {
It("should delete mysql cluster and reconcile changes", func() {
Expect(k8sClient.Delete(ctx, cr)).Should(Succeed())

_, err := reconciler().Reconcile(ctx, ctrl.Request{NamespacedName: crNamespacedName})
Expect(err).NotTo(HaveOccurred())
})

It("controller should remove pvc for mysql", func() {
pvcList := corev1.PersistentVolumeClaimList{}
Eventually(func() bool {
err := k8sClient.List(ctx, &pvcList, &client.ListOptions{
Namespace: cr.Namespace,
LabelSelector: labels.SelectorFromSet(map[string]string{
"app.kubernetes.io/component": "mysql",
}),
})
return err == nil
}, time.Second*15, time.Millisecond*250).Should(BeTrue())

for _, pvc := range pvcList.Items {
By(fmt.Sprintf("checking pvc/%s", pvc.Name))
Expect(pvc.DeletionTimestamp).ShouldNot(BeNil())
}
})

It("controller should delete secrets", func() {
secret := &corev1.Secret{}
Eventually(func() bool {
err := k8sClient.Get(ctx, types.NamespacedName{
Namespace: cr.Namespace,
Name: cr.Spec.SecretsName,
}, secret)

return k8serrors.IsNotFound(err)
}, time.Second*15, time.Millisecond*250).Should(BeTrue())

Eventually(func() bool {
err := k8sClient.Get(ctx, types.NamespacedName{
Namespace: cr.Namespace,
Name: "internal-" + cr.Name,
}, secret)

return k8serrors.IsNotFound(err)
}, time.Second*15, time.Millisecond*250).Should(BeTrue())

})
})
})
})
21 changes: 21 additions & 0 deletions pkg/k8s/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -428,3 +428,24 @@ func GetCRWithDefaults(

return cr, nil
}

func DeleteSecrets(ctx context.Context, cl client.Client, cr *apiv1alpha1.PerconaServerMySQL, secretNames []string) error {
for _, secretName := range secretNames {
secret := &corev1.Secret{}
err := cl.Get(ctx, types.NamespacedName{
Namespace: cr.Namespace,
Name: secretName,
}, secret)
if err != nil {
continue
}

err = cl.Delete(ctx, secret,
&client.DeleteOptions{Preconditions: &metav1.Preconditions{UID: &secret.UID}})
if err != nil {
return errors.Wrapf(err, "delete secret %s", secretName)
}
}

return nil
}
4 changes: 2 additions & 2 deletions pkg/naming/naming.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ const (
const (
FinalizerDeleteSSL = perconaPrefix + "delete-ssl"
FinalizerDeletePodsInOrder = perconaPrefix + "delete-mysql-pods-in-order"

FinalizerDeleteBackup = perconaPrefix + "delete-backup"
FinalizerDeleteBackup = perconaPrefix + "delete-backup"
FinalizerDeleteMySQLPvc = perconaPrefix + "delete-mysql-pvc"
)

type AnnotationKey string
Expand Down
Loading