Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/flow/internal/testcomponents/tick.go
4096 views
1
package testcomponents
2
3
import (
4
"context"
5
"fmt"
6
"sync"
7
"time"
8
9
"github.com/go-kit/log"
10
"github.com/go-kit/log/level"
11
"github.com/grafana/agent/component"
12
)
13
14
func init() {
15
component.Register(component.Registration{
16
Name: "testcomponents.tick",
17
Args: TickConfig{},
18
Exports: TickExports{},
19
20
Build: func(opts component.Options, args component.Arguments) (component.Component, error) {
21
return NewTick(opts, args.(TickConfig))
22
},
23
})
24
}
25
26
// TickConfig configures the testcomponents.tick component.
27
type TickConfig struct {
28
Frequency time.Duration `river:"frequency,attr"`
29
}
30
31
// TickExports describes exported fields for the testcomponents.tick component.
32
type TickExports struct {
33
Time time.Time `river:"tick_time,attr,optional"`
34
}
35
36
// Tick implements the testcomponents.tick component, where the wallclock time
37
// will be emitted on a given frequency.
38
type Tick struct {
39
opts component.Options
40
log log.Logger
41
42
cfgMut sync.Mutex
43
cfg TickConfig
44
}
45
46
// NewTick creates a new testcomponents.tick component.
47
func NewTick(o component.Options, cfg TickConfig) (*Tick, error) {
48
t := &Tick{opts: o, log: o.Logger}
49
if err := t.Update(cfg); err != nil {
50
return nil, err
51
}
52
return t, nil
53
}
54
55
var (
56
_ component.Component = (*Tick)(nil)
57
)
58
59
// Run implements Component.
60
func (t *Tick) Run(ctx context.Context) error {
61
for {
62
select {
63
case <-ctx.Done():
64
return nil
65
case <-time.After(t.getNextTick()):
66
level.Info(t.log).Log("msg", "ticked")
67
t.opts.OnStateChange(TickExports{Time: time.Now()})
68
}
69
}
70
}
71
72
func (t *Tick) getNextTick() time.Duration {
73
t.cfgMut.Lock()
74
defer t.cfgMut.Unlock()
75
return t.cfg.Frequency
76
}
77
78
// Update implements Component.
79
func (t *Tick) Update(args component.Arguments) error {
80
t.cfgMut.Lock()
81
defer t.cfgMut.Unlock()
82
83
cfg := args.(TickConfig)
84
if cfg.Frequency == 0 {
85
return fmt.Errorf("frequency must not be 0")
86
}
87
88
level.Info(t.log).Log("msg", "setting tick frequency", "freq", cfg.Frequency)
89
t.cfg = cfg
90
return nil
91
}
92
93