Skip to content

Commit 8477886

Browse files
committed
enhance: start worker goroutines on demand
Instead of having a bunch of waiting goroutines, this change will introduce one goroutine per type that waits for new tasks. That goroutine will spin up new goroutines, up to the desired limit, to handle tasks as they come in. Signed-off-by: Donnie Adams <[email protected]>
1 parent 3b7c581 commit 8477886

File tree

1 file changed

+31
-22
lines changed

1 file changed

+31
-22
lines changed

pkg/runtime/controller.go

Lines changed: 31 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import (
1414
"k8s.io/apimachinery/pkg/runtime"
1515
"k8s.io/apimachinery/pkg/runtime/schema"
1616
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
17-
"k8s.io/apimachinery/pkg/util/wait"
1817
clientgocache "k8s.io/client-go/tools/cache"
1918
"k8s.io/client-go/util/workqueue"
2019
"sigs.k8s.io/controller-runtime/pkg/cache"
@@ -155,13 +154,8 @@ func (c *controller) run(ctx context.Context, workers int) {
155154
// Start the informer factories to begin populating the informer caches
156155
log.Infof("Starting %s controller", c.name)
157156

158-
for i := 0; i < workers; i++ {
159-
go wait.Until(func() {
160-
c.runWorker(ctx)
161-
}, time.Second, ctx.Done())
162-
}
157+
c.runWorkers(ctx, workers)
163158

164-
<-ctx.Done()
165159
c.startLock.Lock()
166160
defer c.startLock.Unlock()
167161
c.started = false
@@ -217,26 +211,41 @@ func (c *controller) Start(ctx context.Context, workers int) error {
217211
return nil
218212
}
219213

220-
func (c *controller) runWorker(ctx context.Context) {
221-
for c.processNextWorkItem(ctx) {
222-
}
223-
}
214+
func (c *controller) runWorkers(ctx context.Context, workers int) {
215+
wait := sync.WaitGroup{}
216+
running := make(chan struct{}, workers)
217+
218+
defer func() {
219+
defer wait.Wait()
220+
}()
224221

225-
func (c *controller) processNextWorkItem(ctx context.Context) bool {
226-
obj, shutdown := c.workqueue.Get()
222+
defer close(running)
227223

228-
if shutdown {
229-
return false
230-
}
224+
go func() {
225+
<-ctx.Done()
226+
c.workqueue.ShutDown()
227+
}()
228+
229+
for {
230+
obj, shutdown := c.workqueue.Get()
231231

232-
if err := c.processSingleItem(ctx, obj); err != nil {
233-
if !strings.Contains(err.Error(), "please apply your changes to the latest version and try again") {
234-
log.Errorf("%v", err)
232+
if shutdown {
233+
return
235234
}
236-
return true
237-
}
238235

239-
return true
236+
running <- struct{}{}
237+
wait.Add(1)
238+
239+
go func() {
240+
if err := c.processSingleItem(ctx, obj); err != nil {
241+
if !strings.Contains(err.Error(), "please apply your changes to the latest version and try again") {
242+
log.Errorf("%v", err)
243+
}
244+
}
245+
<-running
246+
wait.Done()
247+
}()
248+
}
240249
}
241250

242251
func (c *controller) processSingleItem(ctx context.Context, obj interface{}) error {

0 commit comments

Comments
 (0)