summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/agent/filestatus/manager.go
blob: 4f4f03f85e66b12a7285284a9f2f4ba748c00030 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// SPDX-License-Identifier: GPL-3.0-or-later

package filestatus

import (
	"context"
	"log/slog"
	"os"
	"time"

	"github.com/netdata/netdata/go/go.d.plugin/agent/confgroup"
	"github.com/netdata/netdata/go/go.d.plugin/logger"
)

func NewManager(path string) *Manager {
	return &Manager{
		Logger: logger.New().With(
			slog.String("component", "filestatus manager"),
		),
		path:       path,
		store:      &Store{},
		flushEvery: time.Second * 5,
		flushCh:    make(chan struct{}, 1),
	}
}

type Manager struct {
	*logger.Logger

	path string

	store *Store

	flushEvery time.Duration
	flushCh    chan struct{}
}

func (m *Manager) Run(ctx context.Context) {
	m.Info("instance is started")
	defer func() { m.Info("instance is stopped") }()

	tk := time.NewTicker(m.flushEvery)
	defer tk.Stop()
	defer m.flush()

	for {
		select {
		case <-ctx.Done():
			return
		case <-tk.C:
			m.tryFlush()
		}
	}
}

func (m *Manager) Save(cfg confgroup.Config, status string) {
	if v, ok := m.store.lookup(cfg); !ok || status != v {
		m.store.add(cfg, status)
		m.triggerFlush()
	}
}

func (m *Manager) Remove(cfg confgroup.Config) {
	if _, ok := m.store.lookup(cfg); ok {
		m.store.remove(cfg)
		m.triggerFlush()
	}
}

func (m *Manager) triggerFlush() {
	select {
	case m.flushCh <- struct{}{}:
	default:
	}
}

func (m *Manager) tryFlush() {
	select {
	case <-m.flushCh:
		m.flush()
	default:
	}
}

func (m *Manager) flush() {
	bs, err := m.store.bytes()
	if err != nil {
		return
	}

	f, err := os.Create(m.path)
	if err != nil {
		return
	}
	defer func() { _ = f.Close() }()

	_, _ = f.Write(bs)
}