Skip to content

Commit 09954f4

Browse files
committed
update internal controller for more clean code and metrics
1 parent 38483b2 commit 09954f4

File tree

1 file changed

+18
-20
lines changed

1 file changed

+18
-20
lines changed

pkg/internal/controller/controller.go

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -154,10 +154,7 @@ func (c *Controller) Start(stop <-chan struct{}) error {
154154
log.Info("Starting workers", "controller", c.Name, "worker count", c.MaxConcurrentReconciles)
155155
for i := 0; i < c.MaxConcurrentReconciles; i++ {
156156
// Process work items
157-
go wait.Until(func() {
158-
for c.processNextWorkItem() {
159-
}
160-
}, c.JitterPeriod, stop)
157+
go wait.Until(c.worker, c.JitterPeriod, stop)
161158
}
162159

163160
c.Started = true
@@ -168,30 +165,32 @@ func (c *Controller) Start(stop <-chan struct{}) error {
168165
return nil
169166
}
170167

168+
// worker runs a worker thread that just dequeues items, processes them, and marks them done.
169+
// It enforces that the reconcileHandler is never invoked concurrently with the same object.
170+
func (c *Controller) worker() {
171+
for c.processNextWorkItem() {
172+
}
173+
}
174+
171175
// processNextWorkItem will read a single work item off the workqueue and
172-
// attempt to process it, by calling the syncHandler.
176+
// attempt to process it, by calling the reconcileHandler.
173177
func (c *Controller) processNextWorkItem() bool {
174-
// This code copy-pasted from the sample-Controller.
178+
obj, shutdown := c.Queue.Get()
179+
if shutdown {
180+
return false
181+
}
182+
defer c.Queue.Done(obj)
175183

184+
return c.reconcileHandler(obj)
185+
}
186+
187+
func (c *Controller) reconcileHandler(obj interface{}) bool {
176188
// Update metrics after processing each item
177189
reconcileStartTS := time.Now()
178190
defer func() {
179191
c.updateMetrics(time.Now().Sub(reconcileStartTS))
180192
}()
181193

182-
obj, shutdown := c.Queue.Get()
183-
if shutdown {
184-
// Stop working
185-
return false
186-
}
187-
188-
// We call Done here so the workqueue knows we have finished
189-
// processing this item. We also must remember to call Forget if we
190-
// do not want this work item being re-queued. For example, we do
191-
// not call Forget if a transient error occurs, instead the item is
192-
// put back on the workqueue and attempted again after a back-off
193-
// period.
194-
defer c.Queue.Done(obj)
195194
var req reconcile.Request
196195
var ok bool
197196
if req, ok = obj.(reconcile.Request); !ok {
@@ -204,7 +203,6 @@ func (c *Controller) processNextWorkItem() bool {
204203
// Return true, don't take a break
205204
return true
206205
}
207-
208206
// RunInformersAndControllers the syncHandler, passing it the namespace/Name string of the
209207
// resource to be synced.
210208
if result, err := c.Do.Reconcile(req); err != nil {

0 commit comments

Comments
 (0)