Skip to content

Commit

Permalink
fix: Handle MySQL deletion before finalizer addition
Browse files Browse the repository at this point in the history
- Move finalizer handling to beginning of reconciliation loop
- Add early check for deletion without finalizer
- Ensure atomic finalizer addition with requeue
- Separate finalizer addition from other operations

Fixes #209
  • Loading branch information
devloai[bot] committed Dec 16, 2024
1 parent ea56e2a commit 6a070eb
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 3 deletions.
26 changes: 23 additions & 3 deletions internal/controller/mysql_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,33 @@ func (r *MySQLReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl
return ctrl.Result{}, err
}

// Add a finalizer if not exists
if controllerutil.AddFinalizer(mysql, mysqlFinalizer) {
if err := r.Update(ctx, mysql); err != nil {
// Handle deletion first
if !mysql.GetDeletionTimestamp().IsZero() {
if !controllerutil.ContainsFinalizer(mysql, mysqlFinalizer) {
// If being deleted and no finalizer, nothing to do
return ctrl.Result{}, nil
}
if r.finalizeMySQL(ctx, mysql) {
if controllerutil.RemoveFinalizer(mysql, mysqlFinalizer) {
if err := r.Update(ctx, mysql); err != nil {
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
log.Info("Could not complete finalizer. waiting another second")
return ctrl.Result{RequeueAfter: time.Second}, nil
}

// Add finalizer first if it doesn't exist
if !controllerutil.ContainsFinalizer(mysql, mysqlFinalizer) {
controllerutil.AddFinalizer(mysql, mysqlFinalizer)
if err := r.Update(ctx, mysql); err != nil {
log.Error(err, "Failed to update MySQL after adding finalizer")
return ctrl.Result{}, err
}
// Requeue to continue with other operations after finalizer is added
return ctrl.Result{Requeue: true}, nil
}

// Get referenced number
Expand Down
38 changes: 38 additions & 0 deletions reproduce-issue-209.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#!/bin/bash

# Create MySQL object
cat <<EOF | kubectl apply -f -
apiVersion: mysql.nakamasato.com/v1alpha1
kind: MySQL
metadata:
name: test-mysql
spec:
host: localhost
port: 3306
adminUser:
name: root
type: raw
adminPassword:
name: password
type: raw
EOF

# Create MySQLUser immediately
cat <<EOF | kubectl apply -f -
apiVersion: mysql.nakamasato.com/v1alpha1
kind: MySQLUser
metadata:
name: test-user
spec:
mysqlName: test-mysql
username: testuser
password:
name: userpass
type: raw
EOF

# Delete MySQL object immediately
kubectl delete mysql test-mysql

# Check if MySQLUser is orphaned
kubectl get mysqluser test-user -o yaml

0 comments on commit 6a070eb

Please sign in to comment.