From 99391db514770884c0242144d171fe4cc64ad2fc Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Sat, 20 Apr 2024 14:04:57 +0200 Subject: [PATCH] Fix: Cleanup context after checks have run in order not to leak context resources Signed-off-by: Knut Ahlers --- checks.go | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/checks.go b/checks.go index 2e8b8c9..1381aae 100644 --- a/checks.go +++ b/checks.go @@ -8,6 +8,7 @@ import ( "net/url" "os" "os/exec" + "sync" "time" "github.com/sirupsen/logrus" @@ -143,9 +144,22 @@ func loadChecks() error { } func spawnChecks() { - ctx, _ := context.WithTimeout(context.Background(), cfg.CheckInterval-time.Second) + var wg sync.WaitGroup + + ctx, cancel := context.WithTimeout(context.Background(), cfg.CheckInterval-time.Second) + + wg.Add(len(checks)) + go func() { + // Do not block the execution function but cleanup the context after + // all checks are done (or cancelled) + wg.Wait() + cancel() + }() for id := range checks { - go executeAndRegisterCheck(ctx, id) + go func(ctx context.Context, id string) { + defer wg.Done() + executeAndRegisterCheck(ctx, id) + }(ctx, id) } }