From d4bf2b956ce3ed2b467b7d73d10255e5dbe4af5e Mon Sep 17 00:00:00 2001 From: Daniel Hilgarth Date: Fri, 13 Dec 2024 18:02:35 +0100 Subject: [PATCH] Don't panic upon shutdown when running in standalone mode Fixes #2135 --- pkg/subnet/subnet.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/pkg/subnet/subnet.go b/pkg/subnet/subnet.go index a60c5744d..d3a2a67d6 100644 --- a/pkg/subnet/subnet.go +++ b/pkg/subnet/subnet.go @@ -166,18 +166,26 @@ func WatchLeases(ctx context.Context, sm Manager, ownLease *lease.Lease, receive // and it needs to diff the latest snapshot with its saved state and generate events func WatchLease(ctx context.Context, sm Manager, sn ip.IP4Net, sn6 ip.IP6Net, receiver chan lease.Event) { leaseWatchChan := make(chan []lease.LeaseWatchResult) + var closeOnce sync.Once + + // Helper function to close the receiver channel safely + closeReceiver := func() { + closeOnce.Do(func() { + close(receiver) + }) + } go func() { err := sm.WatchLease(ctx, sn, sn6, leaseWatchChan) if err != nil { if err == context.Canceled || err == context.DeadlineExceeded { log.Infof("%v, close receiver chan", err) - close(receiver) + closeReceiver() return } log.Errorf("Subnet watch failed: %v", err) - close(receiver) + closeReceiver() return } @@ -199,5 +207,5 @@ func WatchLease(ctx context.Context, sm Manager, sn ip.IP4Net, sn6 ip.IP6Net, re } log.Info("leaseWatchChan channel closed") - close(receiver) + closeReceiver() }