forked from grafana/loki
/
multi.go
73 lines (62 loc) · 1.35 KB
/
multi.go
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
package client
import (
"errors"
"sync"
"github.com/go-kit/log"
"github.com/pao214/loki/v2/clients/pkg/promtail/api"
)
// MultiClient is client pushing to one or more loki instances.
type MultiClient struct {
clients []Client
entries chan api.Entry
wg sync.WaitGroup
once sync.Once
}
// NewMulti creates a new client
func NewMulti(metrics *Metrics, streamLagLabels []string, logger log.Logger, cfgs ...Config) (Client, error) {
if len(cfgs) == 0 {
return nil, errors.New("at least one client config should be provided")
}
clients := make([]Client, 0, len(cfgs))
for _, cfg := range cfgs {
client, err := New(metrics, cfg, streamLagLabels, logger)
if err != nil {
return nil, err
}
clients = append(clients, client)
}
multi := &MultiClient{
clients: clients,
entries: make(chan api.Entry),
}
multi.start()
return multi, nil
}
func (m *MultiClient) start() {
m.wg.Add(1)
go func() {
defer m.wg.Done()
for e := range m.entries {
for _, c := range m.clients {
c.Chan() <- e
}
}
}()
}
func (m *MultiClient) Chan() chan<- api.Entry {
return m.entries
}
// Stop implements Client
func (m *MultiClient) Stop() {
m.once.Do(func() { close(m.entries) })
m.wg.Wait()
for _, c := range m.clients {
c.Stop()
}
}
// StopNow implements Client
func (m *MultiClient) StopNow() {
for _, c := range m.clients {
c.StopNow()
}
}