helper.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. Copyright 2026 LocoStack.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package controller
  14. import (
  15. "context"
  16. "github.com/LocoStack/loco-operator/api/v1alpha1"
  17. corev1 "k8s.io/api/core/v1"
  18. "k8s.io/apimachinery/pkg/runtime/schema"
  19. "k8s.io/apimachinery/pkg/types"
  20. "sigs.k8s.io/controller-runtime/pkg/client"
  21. "sigs.k8s.io/controller-runtime/pkg/handler"
  22. "sigs.k8s.io/controller-runtime/pkg/reconcile"
  23. )
  24. func ComponentEventHandler(kind string) handler.EventHandler {
  25. mapFunc := func(ctx context.Context, obj client.Object) []reconcile.Request {
  26. comp, ok := obj.(*v1alpha1.Component)
  27. if !ok {
  28. return nil
  29. }
  30. var reqs []reconcile.Request
  31. for _, dep := range comp.Spec.Dependencies {
  32. if !dependencyRefMatches(dep, kind) {
  33. continue
  34. }
  35. namespace := dep.Namespace
  36. if namespace == "" {
  37. namespace = comp.GetNamespace()
  38. }
  39. reqs = append(reqs, reconcile.Request{
  40. NamespacedName: types.NamespacedName{
  41. Name: dep.Name,
  42. Namespace: namespace,
  43. },
  44. })
  45. }
  46. return reqs
  47. }
  48. return handler.EnqueueRequestsFromMapFunc(mapFunc)
  49. }
  50. func dependencyRefMatches(ref corev1.ObjectReference, kind string) bool {
  51. if ref.Kind != kind {
  52. return false
  53. }
  54. if ref.APIVersion == "" {
  55. return true
  56. }
  57. gv, err := schema.ParseGroupVersion(ref.APIVersion)
  58. return err == nil && gv.Group == v1alpha1.GroupVersion.Group
  59. }