watcher: Clean up properly on exiting event loop
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Rob Watson 2022-06-14 09:56:59 +02:00
parent 969b0db9fc
commit a0949b2bde
2 changed files with 14 additions and 1 deletions

View File

@ -100,7 +100,7 @@ const tickerInterval = time.Millisecond * 250
// Close terminates the PodWatcher. // Close terminates the PodWatcher.
func (pw *PodWatcher) Close() { func (pw *PodWatcher) Close() {
pw.closeChan <- struct{}{} close(pw.closeChan)
} }
func (pw *PodWatcher) watchPods(ctx context.Context, wg *sync.WaitGroup) error { func (pw *PodWatcher) watchPods(ctx context.Context, wg *sync.WaitGroup) error {

View File

@ -54,6 +54,7 @@ type Watcher struct {
podSelector labels.Selector podSelector labels.Selector
podWatcher PodWatcherInterface podWatcher PodWatcherInterface
podWatcherFunc PodWatcherFunc podWatcherFunc PodWatcherFunc
closeChan chan struct{}
errChan chan error errChan chan error
dst io.Writer dst io.Writer
logger *log.Logger logger *log.Logger
@ -65,14 +66,24 @@ func NewWatcher(params WatcherParams, client KubernetesClient, podWatcherFunc Po
params: params, params: params,
client: client, client: client,
podWatcherFunc: podWatcherFunc, podWatcherFunc: podWatcherFunc,
closeChan: make(chan struct{}),
errChan: make(chan error), errChan: make(chan error),
dst: dst, dst: dst,
logger: logger, logger: logger,
} }
} }
// Close blocks until any actively monitored resource has been released, and
// exits.
func (w *Watcher) Close() {
close(w.closeChan)
}
// Watch watches a deployment. // Watch watches a deployment.
func (w *Watcher) Watch(ctx context.Context) error { func (w *Watcher) Watch(ctx context.Context) error {
// ensure any actively monitored resource is cleaned up on exit.
defer w.removeDeployment()
ns := w.params.Namespace ns := w.params.Namespace
if ns == "" { if ns == "" {
ns = corev1.NamespaceDefault ns = corev1.NamespaceDefault
@ -127,6 +138,8 @@ func (w *Watcher) Watch(ctx context.Context) error {
// errChan is never closed. // errChan is never closed.
case err := <-w.errChan: case err := <-w.errChan:
return err return err
case <-w.closeChan:
return nil
case <-ctx.Done(): case <-ctx.Done():
return ctx.Err() return ctx.Err()
} }