|
| 1 | +// Package metricsjob |
| 2 | +package metricsjob |
| 3 | + |
| 4 | +import ( |
| 5 | + "context" |
| 6 | + "hostlink/app/services/metrics" |
| 7 | + "hostlink/domain/credential" |
| 8 | + "sync" |
| 9 | +) |
| 10 | + |
| 11 | +type TriggerFunc func(context.Context, func() error) |
| 12 | + |
| 13 | +type MetricsJobConfig struct { |
| 14 | + Trigger TriggerFunc |
| 15 | + // CredFetchInterval tells in what intervals to call the cred fetch API |
| 16 | + // When set to 0, it will call one and never calls it again |
| 17 | + CredFetchInterval int |
| 18 | +} |
| 19 | + |
| 20 | +type MetricsJob struct { |
| 21 | + config MetricsJobConfig |
| 22 | + cancel context.CancelFunc |
| 23 | + wg sync.WaitGroup |
| 24 | +} |
| 25 | + |
| 26 | +func New() MetricsJob { |
| 27 | + return NewJobWithConf(MetricsJobConfig{ |
| 28 | + Trigger: Trigger, |
| 29 | + CredFetchInterval: 2, |
| 30 | + }) |
| 31 | +} |
| 32 | + |
| 33 | +func NewJobWithConf(cfg MetricsJobConfig) MetricsJob { |
| 34 | + if cfg.Trigger == nil { |
| 35 | + cfg.Trigger = Trigger |
| 36 | + } |
| 37 | + |
| 38 | + return MetricsJob{ |
| 39 | + config: cfg, |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +func (mj *MetricsJob) Register(ctx context.Context, mp metrics.Pusher, mcred metrics.AuthGetter) context.CancelFunc { |
| 44 | + ctx, cancel := context.WithCancel(ctx) |
| 45 | + mj.cancel = cancel |
| 46 | + var creds []credential.Credential |
| 47 | + var beatCount int |
| 48 | + mj.wg.Add(1) |
| 49 | + go func() { |
| 50 | + defer mj.wg.Done() |
| 51 | + mj.config.Trigger(ctx, func() (err error) { |
| 52 | + beatCount++ |
| 53 | + |
| 54 | + // Determine if we should fetch credentials this beat |
| 55 | + shouldFetch := len(creds) == 0 || |
| 56 | + (mj.config.CredFetchInterval > 0 && beatCount%mj.config.CredFetchInterval == 0) |
| 57 | + |
| 58 | + if shouldFetch { |
| 59 | + creds, err = mcred.GetCreds() |
| 60 | + if err != nil { |
| 61 | + return err |
| 62 | + } |
| 63 | + |
| 64 | + if len(creds) == 0 { |
| 65 | + // no op, waiting for the creds to be available |
| 66 | + return nil |
| 67 | + } |
| 68 | + |
| 69 | + var pgcred credential.Credential |
| 70 | + for _, cred := range creds { |
| 71 | + // only support one db for now, first match will exit the finding of creds |
| 72 | + if cred.Dialect == "postgresql" { |
| 73 | + pgcred = cred |
| 74 | + break |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + // Only push when we actually fetch credentials |
| 79 | + return mp.Push(pgcred) |
| 80 | + } |
| 81 | + |
| 82 | + // If we didn't fetch this beat, return nil (no push) |
| 83 | + return nil |
| 84 | + }) |
| 85 | + }() |
| 86 | + return cancel |
| 87 | +} |
| 88 | + |
| 89 | +func (mj *MetricsJob) Shutdown() { |
| 90 | + if mj.cancel != nil { |
| 91 | + mj.cancel() |
| 92 | + } |
| 93 | + mj.wg.Wait() |
| 94 | +} |
0 commit comments