-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
loki.go
209 lines (171 loc) · 4.59 KB
/
loki.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
//go:generate ../../../tools/readme_config_includer/generator
package loki
import (
"bytes"
"context"
_ "embed"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"sort"
"strconv"
"strings"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/outputs"
)
//go:embed sample.conf
var sampleConfig string
const (
defaultEndpoint = "/loki/api/v1/push"
defaultClientTimeout = 5 * time.Second
)
type Loki struct {
Domain string `toml:"domain"`
Endpoint string `toml:"endpoint"`
Timeout config.Duration `toml:"timeout"`
Username config.Secret `toml:"username"`
Password config.Secret `toml:"password"`
Headers map[string]string `toml:"http_headers"`
ClientID string `toml:"client_id"`
ClientSecret string `toml:"client_secret"`
TokenURL string `toml:"token_url"`
Scopes []string `toml:"scopes"`
GZipRequest bool `toml:"gzip_request"`
MetricNameLabel string `toml:"metric_name_label"`
url string
client *http.Client
tls.ClientConfig
}
func (l *Loki) createClient(ctx context.Context) (*http.Client, error) {
tlsCfg, err := l.ClientConfig.TLSConfig()
if err != nil {
return nil, fmt.Errorf("tls config fail: %w", err)
}
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
Proxy: http.ProxyFromEnvironment,
},
Timeout: time.Duration(l.Timeout),
}
if l.ClientID != "" && l.ClientSecret != "" && l.TokenURL != "" {
oauthConfig := clientcredentials.Config{
ClientID: l.ClientID,
ClientSecret: l.ClientSecret,
TokenURL: l.TokenURL,
Scopes: l.Scopes,
}
ctx = context.WithValue(ctx, oauth2.HTTPClient, client)
client = oauthConfig.Client(ctx)
}
return client, nil
}
func (*Loki) SampleConfig() string {
return sampleConfig
}
func (l *Loki) Connect() (err error) {
if l.Domain == "" {
return errors.New("domain is required")
}
if l.Endpoint == "" {
l.Endpoint = defaultEndpoint
}
l.url = fmt.Sprintf("%s%s", l.Domain, l.Endpoint)
if l.Timeout == 0 {
l.Timeout = config.Duration(defaultClientTimeout)
}
ctx := context.Background()
l.client, err = l.createClient(ctx)
if err != nil {
return fmt.Errorf("http client fail: %w", err)
}
return nil
}
func (l *Loki) Close() error {
l.client.CloseIdleConnections()
return nil
}
func (l *Loki) Write(metrics []telegraf.Metric) error {
s := Streams{}
sort.SliceStable(metrics, func(i, j int) bool {
return metrics[i].Time().Before(metrics[j].Time())
})
for _, m := range metrics {
if l.MetricNameLabel != "" {
m.AddTag(l.MetricNameLabel, m.Name())
}
tags := m.TagList()
var line string
for _, f := range m.FieldList() {
line += fmt.Sprintf("%s=\"%v\" ", f.Key, f.Value)
}
s.insertLog(tags, Log{strconv.FormatInt(m.Time().UnixNano(), 10), line})
}
return l.writeMetrics(s)
}
func (l *Loki) writeMetrics(s Streams) error {
bs, err := json.Marshal(s)
if err != nil {
return fmt.Errorf("json.Marshal: %w", err)
}
var reqBodyBuffer io.Reader = bytes.NewBuffer(bs)
if l.GZipRequest {
rc := internal.CompressWithGzip(reqBodyBuffer)
defer rc.Close()
reqBodyBuffer = rc
}
req, err := http.NewRequest(http.MethodPost, l.url, reqBodyBuffer)
if err != nil {
return err
}
if !l.Username.Empty() {
username, err := l.Username.Get()
if err != nil {
return fmt.Errorf("getting username failed: %w", err)
}
password, err := l.Password.Get()
if err != nil {
username.Destroy()
return fmt.Errorf("getting password failed: %w", err)
}
req.SetBasicAuth(username.String(), password.String())
username.Destroy()
password.Destroy()
}
for k, v := range l.Headers {
if strings.EqualFold(k, "host") {
req.Host = v
}
req.Header.Set(k, v)
}
req.Header.Set("User-Agent", internal.ProductToken())
req.Header.Set("Content-Type", "application/json")
if l.GZipRequest {
req.Header.Set("Content-Encoding", "gzip")
}
resp, err := l.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("when writing to [%s] received status code, %d: %s", l.url, resp.StatusCode, body)
}
return nil
}
func init() {
outputs.Add("loki", func() telegraf.Output {
return &Loki{
MetricNameLabel: "__name",
}
})
}