github.com/oam-dev/cluster-gateway@v1.9.0/pkg/event/resync.go (about) 1 package event 2 3 import ( 4 "context" 5 "time" 6 7 "k8s.io/apimachinery/pkg/types" 8 "k8s.io/client-go/util/workqueue" 9 "k8s.io/klog/v2" 10 addonv1alpha1 "open-cluster-management.io/api/addon/v1alpha1" 11 "sigs.k8s.io/controller-runtime/pkg/client" 12 "sigs.k8s.io/controller-runtime/pkg/event" 13 "sigs.k8s.io/controller-runtime/pkg/handler" 14 "sigs.k8s.io/controller-runtime/pkg/reconcile" 15 "sigs.k8s.io/controller-runtime/pkg/source" 16 17 "github.com/oam-dev/cluster-gateway/pkg/common" 18 ) 19 20 func AddOnHealthResyncHandler(c client.Client, interval time.Duration) (*source.Channel, handler.EventHandler) { 21 ch := StartBackgroundExternalTimerResync(func() ([]event.GenericEvent, error) { 22 addonList := &addonv1alpha1.ManagedClusterAddOnList{} 23 if err := c.List(context.TODO(), addonList); err != nil { 24 return nil, err 25 } 26 evs := make([]event.GenericEvent, 0) 27 for _, addon := range addonList.Items { 28 if addon.Name != common.AddonName { 29 continue 30 } 31 addon := addon 32 evs = append(evs, event.GenericEvent{ 33 Object: &addon, 34 }) 35 } 36 return evs, nil 37 }, interval) 38 return ch, AddonHealthHandler{} 39 } 40 41 type GeneratorFunc func() ([]event.GenericEvent, error) 42 43 func StartBackgroundExternalTimerResync(g GeneratorFunc, interval time.Duration) *source.Channel { 44 events := make(chan event.GenericEvent) // unbuffered 45 ch := &source.Channel{Source: events} 46 ticker := time.NewTicker(interval) 47 go func() { 48 for { 49 _, ok := <-ticker.C 50 if !ok { 51 return 52 } 53 evs, err := g() 54 if err != nil { 55 klog.Errorf("Encountered an error when getting periodic events: %v", err) 56 continue 57 } 58 for _, ev := range evs { 59 events <- ev 60 } 61 } 62 }() 63 return ch 64 } 65 66 var _ handler.EventHandler = &AddonHealthHandler{} 67 68 type AddonHealthHandler struct { 69 } 70 71 func (a AddonHealthHandler) Generic(_ context.Context, genericEvent event.GenericEvent, limitingInterface workqueue.RateLimitingInterface) { 72 limitingInterface.Add(reconcile.Request{ 73 NamespacedName: types.NamespacedName{ 74 Namespace: genericEvent.Object.GetNamespace(), 75 Name: genericEvent.Object.GetName(), 76 }, 77 }) 78 } 79 80 func (a AddonHealthHandler) Create(_ context.Context, createEvent event.CreateEvent, limitingInterface workqueue.RateLimitingInterface) { 81 panic("implement me") // unreachable 82 } 83 84 func (a AddonHealthHandler) Update(_ context.Context, updateEvent event.UpdateEvent, limitingInterface workqueue.RateLimitingInterface) { 85 panic("implement me") // unreachable 86 } 87 88 func (a AddonHealthHandler) Delete(_ context.Context, deleteEvent event.DeleteEvent, limitingInterface workqueue.RateLimitingInterface) { 89 panic("implement me") // unreachable 90 }