Here's how to handle the Author controller and implement proper error handling in the Book controller when the referenced Author is not found:
1. Author Controller
The Author controller is simpler since it doesn't need to reference other resources. It can track the number of books published by the author.
controllers/author_controller.go
package controllers
import (
"context"
"fmt"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
bookstorev1 "example.com/bookstore/api/v1"
)
// AuthorReconciler reconciles an Author object
type AuthorReconciler struct {
client.Client
Scheme *runtime.Scheme
}
//+kubebuilder:rbac:groups=bookstore.example.com,resources=authors,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=bookstore.example.com,resources=authors/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=bookstore.example.com,resources=authors/finalizers,verbs=update
func (r *AuthorReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := log.FromContext(ctx)
// Fetch the Author instance
author := &bookstorev1.Author{}
if err := r.Get(ctx, req.NamespacedName, author); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// Example: Count books by this author (optional)
// You can implement this later if needed.
// Update status (e.g., booksPublished)
author.Status.BooksPublished = 0 // Replace with actual logic
if err := r.Status().Update(ctx, author); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update author status: %w", err)
}
return ctrl.Result{}, nil
}
func (r *AuthorReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&bookstorev1.Author{}).
Complete(r)
}
2. Book Controller (Handling Missing Author)
If the Author referenced in a Book does not exist, the Book controller should:
- Log an error (for debugging).
- Set a condition in the
Book status (to indicate the issue).
- Requeue the request (to retry later).
controllers/book_controller.go
package controllers
import (
"context"
"fmt"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
bookstorev1 "example.com/bookstore/api/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// BookReconciler reconciles a Book object
type BookReconciler struct {
client.Client
Scheme *runtime.Scheme
}
//+kubebuilder:rbac:groups=bookstore.example.com,resources=books,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=bookstore.example.com,resources=books/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=bookstore.example.com,resources=books/finalizers,verbs=update
//+kubebuilder:rbac:groups=bookstore.example.com,resources=authors,verbs=get;list;watch
func (r *BookReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := log.FromContext(ctx)
// Fetch the Book instance
book := &bookstorev1.Book{}
if err := r.Get(ctx, req.NamespacedName, book); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// Check if the referenced Author exists
author := &bookstorev1.Author{}
authorKey := types.NamespacedName{
Namespace: book.Namespace, // Same namespace as the Book
Name: book.Spec.AuthorRef.Name,
}
if err := r.Get(ctx, authorKey, author); err != nil {
if errors.IsNotFound(err) {
// Author does not exist
log.Error(err, "Author not found", "author", book.Spec.AuthorRef.Name)
// Update Book status to reflect the missing author
book.Status.Published = false
book.Status.Conditions = []metav1.Condition{
{
Type: "AuthorMissing",
Status: metav1.ConditionFalse,
Reason: "AuthorNotFound",
Message: fmt.Sprintf("Author %s not found", book.Spec.AuthorRef.Name),
},
}
if err := r.Status().Update(ctx, book); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update book status: %w", err)
}
// Requeue after a delay to retry later
return ctrl.Result{RequeueAfter: 10 * time.Second}, nil
}
return ctrl.Result{}, fmt.Errorf("failed to get author: %w", err)
}
// If Author exists, proceed with normal reconciliation
log.Info("Author found", "author", author.Name)
book.Status.Published = true
book.Status.Conditions = []metav1.Condition{
{
Type: "AuthorFound",
Status: metav1.ConditionTrue,
Reason: "AuthorExists",
Message: "Author reference is valid",
},
}
if err := r.Status().Update(ctx, book); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update book status: %w", err)
}
return ctrl.Result{}, nil
}
func (r *BookReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&bookstorev1.Book{}).
Complete(r)
}
Key Improvements:
-
Error Handling in Book Controller
- If the
Author is not found, the controller:
- Logs the error.
- Updates the
Book status with a Condition indicating the missing Author.
- Requeues the request to retry later.
-
Status Conditions
- Uses Kubernetes-style
Conditions to track whether the Author reference is valid.
-
RBAC Permissions
- The
Book controller needs get permissions on authors to check references.
-
Requeue Logic
- If the
Author is missing, the controller requeues after a delay (10s) to retry later.
Testing the Behavior
-
Apply an Author and a Book referencing it:
kubectl apply -f config/samples/bookstore_v1_author.yaml
kubectl apply -f config/samples/bookstore_v1_book.yaml
-
Delete the Author and observe the Book status:
kubectl delete author jk-rowling
The Book controller will log an error and update the Book status to reflect the missing Author.
-
Check the Book status:
kubectl get book harry-potter -o yaml
You should see:
status:
conditions:
- message: "Author jk-rowling not found"
reason: AuthorNotFound
status: "False"
type: AuthorMissing
published: false
Summary
- The
Author controller is straightforward and mainly updates status.
- The
Book controller handles missing Author references gracefully by:
- Logging errors.
- Updating
Book status.
- Requeuing for retries.
- This ensures robustness in cases where dependencies (
Author) are missing.