@@ -11,6 +11,7 @@ import (
1111 "time"
1212
1313 "github.com/go-logr/logr"
14+ "github.com/robfig/cron/v3"
1415 corev1 "k8s.io/api/core/v1"
1516 "sigs.k8s.io/controller-runtime/pkg/client"
1617
@@ -19,7 +20,10 @@ import (
1920 "go.mondoo.com/mondoo-operator/pkg/constants"
2021)
2122
22- const defaultGCOlderThan = 2 * time .Hour
23+ const (
24+ defaultGCOlderThan = 2 * time .Hour
25+ gcMultiplier = 2
26+ )
2327
2428// ManagedByLabel returns the ManagedBy value for assets owned by this operator instance.
2529// The cluster UID uniquely identifies which operator instance manages the assets.
@@ -30,19 +34,41 @@ func ManagedByLabel(clusterUID string) string {
3034 return "mondoo-operator-" + clusterUID
3135}
3236
33- // GCOlderThan returns the duration threshold for garbage collection.
34- // It defaults to 2h but can be overridden via the MONDOO_GC_OLDER_THAN env var
35- // (accepts any value parseable by time.ParseDuration, e.g. "5m", "30s").
36- func GCOlderThan () time.Duration {
37+ // GCOlderThan returns the duration threshold for garbage collection based on
38+ // the scan schedule. It computes 2x the interval between consecutive cron runs
39+ // so that assets are only GC'd after missing at least one full scan cycle.
40+ // The MONDOO_GC_OLDER_THAN env var overrides the computed value.
41+ func GCOlderThan (schedule string ) time.Duration {
3742 if v := os .Getenv ("MONDOO_GC_OLDER_THAN" ); v != "" {
3843 d , err := time .ParseDuration (v )
3944 if err != nil {
40- fmt .Fprintf (os .Stderr , "WARNING: invalid MONDOO_GC_OLDER_THAN=%q, using default %s : %v\n " , v , defaultGCOlderThan , err )
45+ fmt .Fprintf (os .Stderr , "WARNING: invalid MONDOO_GC_OLDER_THAN=%q, falling back to schedule-based computation : %v\n " , v , err )
4146 } else {
4247 return d
4348 }
4449 }
45- return defaultGCOlderThan
50+ return gcOlderThanFromSchedule (schedule )
51+ }
52+
53+ // gcOlderThanFromSchedule parses a cron schedule and returns 2x the interval
54+ // between consecutive runs. Falls back to defaultGCOlderThan if parsing fails.
55+ func gcOlderThanFromSchedule (schedule string ) time.Duration {
56+ if schedule == "" {
57+ return defaultGCOlderThan
58+ }
59+
60+ sched , err := cron .ParseStandard (schedule )
61+ if err != nil {
62+ fmt .Fprintf (os .Stderr , "WARNING: failed to parse cron schedule %q, using default %s: %v\n " , schedule , defaultGCOlderThan , err )
63+ return defaultGCOlderThan
64+ }
65+
66+ now := time .Now ()
67+ next1 := sched .Next (now )
68+ next2 := sched .Next (next1 )
69+ interval := next2 .Sub (next1 )
70+
71+ return time .Duration (gcMultiplier ) * interval
4672}
4773
4874// DeleteStaleAssets builds a Mondoo API client from the operator's credentials and
0 commit comments