diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go index 6652b85..c4c502c 100644 --- a/internal/metrics/metrics.go +++ b/internal/metrics/metrics.go @@ -13,6 +13,8 @@ import ( "github.com/shirou/gopsutil/v4/disk" "github.com/shirou/gopsutil/v4/mem" "github.com/veertuinc/anklet/internal/config" + "github.com/veertuinc/anklet/internal/database" + "github.com/veertuinc/anklet/internal/logging" ) // Server defines the structure for the API server @@ -754,3 +756,15 @@ func GetMetricsDataFromContext(ctx context.Context) (*MetricsDataLock, error) { } return metricsData, nil } + +func Cleanup(ctx context.Context, logger *slog.Logger, owner string, name string) { + databaseContainer, err := database.GetDatabaseFromContext(ctx) + if err != nil { + logger.ErrorContext(ctx, "error getting database client from context", "error", err.Error()) + } + result := databaseContainer.Client.Del(context.Background(), "anklet/metrics/"+owner+"/"+name) + if result.Err() != nil { + logger.ErrorContext(ctx, "error deleting metrics data from Redis", "error", result.Err().Error()) + } + logging.DevContext(ctx, "successfully deleted metrics data from Redis, key: anklet/metrics/"+owner+"/"+name) +} diff --git a/main.go b/main.go index d2c0e2e..15ab6a3 100644 --- a/main.go +++ b/main.go @@ -466,6 +466,10 @@ func worker( return } pluginCtx = context.WithValue(pluginCtx, config.ContextKey("database"), databaseClient) + // cleanup metrics data when the plugin is stopped (otherwise it's orphaned in the aggregator) + if index == 0 { // only cleanup the first plugin's metrics data (they're aggregated by the first plugin's name) + defer metrics.Cleanup(pluginCtx, pluginLogger, plugin.Owner, plugin.Name) + } logging.DevContext(pluginCtx, "connected to database") }