Path: blob/main/pkg/flow/internal/testcomponents/tick.go
4096 views
package testcomponents12import (3"context"4"fmt"5"sync"6"time"78"github.com/go-kit/log"9"github.com/go-kit/log/level"10"github.com/grafana/agent/component"11)1213func init() {14component.Register(component.Registration{15Name: "testcomponents.tick",16Args: TickConfig{},17Exports: TickExports{},1819Build: func(opts component.Options, args component.Arguments) (component.Component, error) {20return NewTick(opts, args.(TickConfig))21},22})23}2425// TickConfig configures the testcomponents.tick component.26type TickConfig struct {27Frequency time.Duration `river:"frequency,attr"`28}2930// TickExports describes exported fields for the testcomponents.tick component.31type TickExports struct {32Time time.Time `river:"tick_time,attr,optional"`33}3435// Tick implements the testcomponents.tick component, where the wallclock time36// will be emitted on a given frequency.37type Tick struct {38opts component.Options39log log.Logger4041cfgMut sync.Mutex42cfg TickConfig43}4445// NewTick creates a new testcomponents.tick component.46func NewTick(o component.Options, cfg TickConfig) (*Tick, error) {47t := &Tick{opts: o, log: o.Logger}48if err := t.Update(cfg); err != nil {49return nil, err50}51return t, nil52}5354var (55_ component.Component = (*Tick)(nil)56)5758// Run implements Component.59func (t *Tick) Run(ctx context.Context) error {60for {61select {62case <-ctx.Done():63return nil64case <-time.After(t.getNextTick()):65level.Info(t.log).Log("msg", "ticked")66t.opts.OnStateChange(TickExports{Time: time.Now()})67}68}69}7071func (t *Tick) getNextTick() time.Duration {72t.cfgMut.Lock()73defer t.cfgMut.Unlock()74return t.cfg.Frequency75}7677// Update implements Component.78func (t *Tick) Update(args component.Arguments) error {79t.cfgMut.Lock()80defer t.cfgMut.Unlock()8182cfg := args.(TickConfig)83if cfg.Frequency == 0 {84return fmt.Errorf("frequency must not be 0")85}8687level.Info(t.log).Log("msg", "setting tick frequency", "freq", cfg.Frequency)88t.cfg = cfg89return nil90}919293