-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathingester.go
More file actions
325 lines (255 loc) · 7.55 KB
/
ingester.go
File metadata and controls
325 lines (255 loc) · 7.55 KB
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package logpush
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net"
"net/http"
"strings"
"time"
"unicode"
"math/rand"
)
type StreamConfig struct {
Tag string `yaml:"tag" json:"tag"`
Token string `yaml:"token" json:"token"`
Labels map[string]string `yaml:"labels" json:"labels"`
}
type IngesterOptions struct {
BasicAuth map[string]string `yaml:"basic_auth" json:"basic_auth"`
MaxEntries int `yaml:"max_entries" json:"max_entries"`
MaxMessageSize int `yaml:"max_message_size" json:"max_message_size"`
MaxMetadataSize int `yaml:"max_metadata_size" json:"max_metadata_size"`
MaxLabelSize int `yaml:"max_label_size" json:"max_label_size"`
MaxFieldSize int `yaml:"max_field_size" json:"max_field_size"`
}
type LogIngester struct {
Writer LogWriter
Options IngesterOptions
Streams map[string]StreamConfig
optionsValid bool
}
func (this *LogIngester) validateOptions() {
if this.Options.MaxEntries <= 0 {
this.Options.MaxEntries = 1024
}
if this.Options.MaxMessageSize <= 0 {
this.Options.MaxMessageSize = 16 * 1024
}
if this.Options.MaxLabelSize <= 0 {
this.Options.MaxLabelSize = 64
}
if this.Options.MaxFieldSize <= 0 {
this.Options.MaxFieldSize = 1024
}
if this.Options.MaxMetadataSize <= 64 {
this.Options.MaxMetadataSize = 16 * 1024
}
this.optionsValid = true
}
func (this *LogIngester) ServeHTTP(wrt http.ResponseWriter, req *http.Request) {
if !this.optionsValid {
this.validateOptions()
}
clientIP := parseXff(req)
var respondError = func(message string, status int) {
if status < http.StatusOK {
status = http.StatusBadRequest
}
slog.Error("INGESTER http request",
slog.String("ip", clientIP),
slog.String("err", message))
wrt.Header().Set("content-type", "text/plain")
wrt.WriteHeader(http.StatusBadRequest)
wrt.Write([]byte(message + "\r\n"))
}
if this.Writer == nil {
respondError("no available writer", http.StatusInternalServerError)
return
}
if len(this.Options.BasicAuth) > 0 {
if user, pass, has := req.BasicAuth(); !has {
respondError("authorization required", http.StatusUnauthorized)
return
} else if expectPass, hasUser := this.Options.BasicAuth[user]; !hasUser || pass != expectPass {
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
respondError("invalid credentials", http.StatusForbidden)
return
}
}
streamKey := strings.ToLower(req.PathValue("stream_key"))
if streamKey == "" {
respondError("stream id required", http.StatusBadRequest)
return
}
stream, has := this.Streams[streamKey]
if !has {
respondError(fmt.Sprintf("stream '%s' not found", streamKey), http.StatusNotFound)
return
}
if stream.Token != "" {
const bearerPrefix = "bearer"
clientToken := req.Header.Get("Authorization")
if strings.HasPrefix(strings.ToLower(clientToken), bearerPrefix) {
clientToken = strings.TrimSpace(clientToken[len(bearerPrefix):])
} else {
clientToken = req.URL.Query().Get("token")
}
if clientToken == "" {
respondError(fmt.Sprintf("auth token required for stream '%s'", streamKey), http.StatusUnauthorized)
return
} else if clientToken != stream.Token {
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
respondError(fmt.Sprintf("auth token rejected for stream '%s'", streamKey), http.StatusForbidden)
return
}
}
contentType := req.Header.Get("content-type")
switch {
case strings.Contains(contentType, "json"):
var batch IngesterBatch
if err := json.NewDecoder(req.Body).Decode(&batch); err != nil {
respondError(fmt.Sprintf("failed to decode batch: %v", err), http.StatusBadRequest)
return
}
if len(batch.Entries) == 0 {
slog.Warn("INGESTER Empty payload",
slog.String("ip", clientIP),
slog.String("stream_id", streamKey))
break
}
slog.Debug("INGESTER Received",
slog.Int("entries", len(batch.Entries)),
slog.String("ip", clientIP),
slog.String("stream_id", streamKey))
if this.Options.MaxEntries > 0 && len(batch.Entries) > this.Options.MaxEntries {
slog.Warn("INGESTER Entries truncated",
slog.Int("entries", len(batch.Entries)),
slog.Int("trunc", this.Options.MaxEntries),
slog.String("ip", clientIP),
slog.String("stream_id", streamKey))
batch.Entries = batch.Entries[:this.Options.MaxEntries]
}
var entries []LogEntry
for _, entry := range batch.Entries {
var totalMetadataSize int
meta := map[string]string{}
var canAddField = func(key string, val string) bool {
totalMetadataSize += len(key) + len(val)
return totalMetadataSize < this.Options.MaxMetadataSize
}
var indexLabels = func(labels map[string]string) {
for key, val := range labels {
_ = canAddField(key, val)
}
}
var copyField = func(key string, val string) {
meta[stripLabel(truncateKey(key, this.Options.MaxLabelSize))] = stripLabel(truncateValue(val, this.Options.MaxFieldSize))
}
// index stream and batch labels first without adding them
indexLabels(stream.Labels)
indexLabels(batch.Meta)
// copy entry labels if still have space left
for key, val := range entry.Meta {
if canAddField(key, val) {
copyField(key, val)
}
}
// write batch labels over entry meta
for key, val := range batch.Meta {
copyField(key, val)
}
// write stream labels over everything else
for key, val := range stream.Labels {
copyField(key, val)
}
var timestamp time.Time
if entry.Date >= 0 {
timestamp = time.Unix(0, entry.Date*int64(time.Millisecond))
} else {
timestamp = time.Now()
}
if this.Options.MaxMessageSize > 0 && len(entry.Message) > this.Options.MaxMessageSize {
slog.Warn("INGESTER Message truncated",
slog.Int("len", len(entry.Message)),
slog.Int("trunc", this.Options.MaxMessageSize),
slog.String("ip", clientIP),
slog.String("stream_id", streamKey))
entry.Message = entry.Message[:this.Options.MaxMessageSize] + "..."
}
streamTag := stream.Tag
if streamTag == "" {
streamTag = streamKey
}
entries = append(entries, LogEntry{
Timestamp: timestamp,
StreamTag: streamTag,
LogLevel: LogLevel(entry.Level),
Message: entry.Message,
Metadata: meta,
})
}
go func() {
if err := this.Writer.WriteBatch(context.Background(), entries); err != nil {
slog.Error("INGESTER Writer.WriteBatch",
slog.String("writer_type", this.Writer.Type()),
slog.String("err", err.Error()))
}
}()
default:
respondError("unsupported content type", http.StatusNotAcceptable)
return
}
wrt.WriteHeader(http.StatusNoContent)
}
func parseXff(req *http.Request) string {
if xff := req.Header.Get("x-forwarded-for"); xff != "" {
return xff
} else if host, _, _ := net.SplitHostPort(req.RemoteAddr); host != "" {
return host
}
return req.RemoteAddr
}
type IngesterBatch struct {
Meta map[string]string `json:"meta"`
Entries []IngesterEntry `json:"entries"`
}
type IngesterEntry struct {
Date int64 `json:"date"`
Level string `json:"level"`
Message string `json:"message"`
Meta map[string]string `json:"meta"`
}
func stripLabel(val string) string {
var stripped string
for _, next := range val {
switch {
case next == '\\':
stripped += "/"
case unicode.IsPrint(next):
stripped += string(next)
default:
stripped += "?"
}
}
return stripped
}
func truncateValue(val string, n int) string {
if n <= 0 {
return val
}
if len(val) < n {
return val
}
return val[:n] + " ..."
}
func truncateKey(val string, n int) string {
if n <= 0 {
return val
}
if len(val) < n {
return val
}
return val[:n] + "___"
}