-
Hi all! I've been working through the CronJob tutorial in the documentation. I've basically gotten things to work manually, but I'm trying to figure out the tests now. However, when I include the test code from Github (it's kind of hard to understand with the documentation breaks in the book), it doesn't work:
Basically, it looks like the testJob that is created to simulate an active job is never found by the CronJob controller's reconcile. I've set breakpoints and it looks like the reconcile runs twice before the test job is created and then never again. The test then fails because the controller's status has no reference to the test job. I should say that I have deviated from the controller implementation in the book, so this could be 100% my fault. The change I made was to pull out the inline func objects and some repeated code into separate private functions because the include github action for code linting kept failing because the code complexity of the example was too high. If I broke something after refactoring, that would be good to know when I write a real controller. I'm thinking perhaps I messed up the memory model of the controller or something. I've included a gist of my version of the tutorial controller, the test suite, and the actual test: https://gist.github.com/jwilkicki/b84ddaeb108a0a9bd181703abd28c929 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I found the answer by resetting back to the working code from the tutorial and then applying my refactorings one by one. It came down to this code: // SetupWithManager sets up the controller with the Manager.
func (r *CronJobReconciler) SetupWithManager(mgr ctrl.Manager) error {
// set up a real clock, since we're not in a test
if r.Clock == nil {
r.Clock = realClock{}
}
if err := mgr.GetFieldIndexer().IndexField(context.Background(), &kbatch.Job{}, jobOwnerKey, func(rawObj client.Object) []string {
// grab the job object, extract the owner...
job := rawObj.(*kbatch.Job)
owner := metav1.GetControllerOf(job)
if owner == nil {
return nil
}
// ...make sure it's a CronJob...
if owner.APIVersion != apiGVStr || owner.Kind != "CronJob" {
return nil
}
// ...and if so, return it
return []string{owner.Name}
}); err != nil {
return err
}
return ctrl.NewControllerManagedBy(mgr).
For(&batchv1.CronJob{}).
Owns(&kbatch.Job{}). // <-- I didn't copy this in my original edit
Named("cronjob").
Complete(r)
} In case it isn't apparent from the snippet, in The goof was definitely mine. It might be nicer if all of the Github Action flows provided by the framework worked when run by the example, but refactoring to get the cycolomatic complexity of the controller implementation to pass linting did teach me something valuable. |
Beta Was this translation helpful? Give feedback.
I found the answer by resetting back to the working code from the tutorial and then applying my refactorings one by one. It came down to this code: