From f13f0b2f8a3bd5733e3f839f588d4bdf579fc2dc Mon Sep 17 00:00:00 2001 From: Henry Dollman Date: Tue, 6 Aug 2024 14:44:31 -0400 Subject: [PATCH] make sure deletion of container stats is thread safe --- agent/main.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/agent/main.go b/agent/main.go index c95e3e1..33bafc8 100644 --- a/agent/main.go +++ b/agent/main.go @@ -175,7 +175,7 @@ func getDockerStats() ([]*ContainerStats, error) { // note: can't use Created field because it's not updated on restart if strings.HasSuffix(ctr.Status, "seconds") { // if so, remove old container data - delete(containerStatsMap, ctr.IdShort) + deleteContainerStatsSync(ctr.IdShort) } wg.Add(1) go func() { @@ -183,7 +183,7 @@ func getDockerStats() ([]*ContainerStats, error) { cstats, err := getContainerStats(ctr) if err != nil { // delete container from map and retry once - delete(containerStatsMap, ctr.IdShort) + deleteContainerStatsSync(ctr.IdShort) cstats, err = getContainerStats(ctr) if err != nil { log.Printf("Error getting container stats: %+v\n", err) @@ -277,6 +277,13 @@ func getContainerStats(ctr *Container) (*ContainerStats, error) { return cStats, nil } +// delete container stats from map using mutex +func deleteContainerStatsSync(id string) { + containerStatsMutex.Lock() + defer containerStatsMutex.Unlock() + delete(containerStatsMap, id) +} + func gatherStats() *SystemData { systemInfo, systemStats := getSystemStats() stats := &SystemData{