-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
218 lines (186 loc) · 4.79 KB
/
main.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
210
211
212
213
214
215
216
217
218
package main
import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"flag"
"fmt"
"github.com/klauspost/compress/zstd"
"io"
"os"
"strings"
"time"
)
type LogData struct {
ResourceLogs []ResourceLogs `json:"resourceLogs"`
}
type ResourceLogs struct {
ScopeLogs []ScopeLogs `json:"scopeLogs"`
}
type ScopeLogs struct {
LogRecords []LogRecords `json:"logRecords"`
}
type LogRecords struct {
TimeUnixNano string `json:"timeUnixNano"`
Body map[string]any `json:"body"`
Attributes []Attribute `json:"attributes"`
}
type Attribute struct {
Key string
Value map[string]any
}
type flags struct {
matchBy
file string
since time.Duration
}
type matchBy struct {
namespace string
pod string
container string
}
func main() {
var fl flags
flag.StringVar(&fl.file, "file", "", "log file path")
flag.StringVar(&fl.namespace, "namespace", "", "namespace prefix to filter for")
flag.StringVar(&fl.pod, "pod", "", "pod prefix to filter for")
flag.StringVar(&fl.container, "container", "", "container prefix to filter for")
flag.DurationVar(&fl.since, "since", time.Duration(0), "only return logs newer than a relative duration like 5s, 2m, or 3h")
flag.Parse()
if err := validate(fl); err != nil {
fmt.Printf("Invalid flag: %v\n", err)
os.Exit(1)
}
if err := run(fl, os.Stdout); err != nil {
fmt.Printf("Error: %v\n", err)
os.Exit(1)
}
}
func validate(fl flags) error {
if fl.file == "" {
return errors.New("compressed path not provided")
}
return nil
}
func run(fl flags, out io.Writer) error {
compressed, err := os.Open(fl.file)
if err != nil {
return err
}
defer compressed.Close()
for {
logDataJSON, err := decompressChunk(compressed)
if err != nil {
if err == io.EOF {
break
}
return err
}
var logData LogData
if err := json.Unmarshal(logDataJSON, &logData); err != nil {
return fmt.Errorf("failed to unmarshal a log line: %v", err)
}
for _, resourceLog := range logData.ResourceLogs {
for _, scopeLog := range resourceLog.ScopeLogs {
for _, logRecord := range scopeLog.LogRecords {
message := logMessage(logRecord.Body)
rawTimestamp := stringAttributeByKey(logRecord.Attributes, "time")
timestamp, err := time.Parse(time.RFC3339, rawTimestamp)
if err != nil {
continue
}
if fl.since != time.Duration(0) {
fromTimestamp := time.Now().UTC().Add(-1 * fl.since)
if timestamp.Before(fromTimestamp) {
continue
}
}
rawTag := stringAttributeByKey(logRecord.Attributes, "fluent.tag")
tag, err := parseFluentTag(rawTag)
if err != nil {
continue
}
if matches(tag, fl.matchBy) {
fmt.Fprintf(out, "%v/%v\t%v\t%v\t%v\n", tag.namespace, tag.pod, tag.container, timestamp, message)
}
}
}
}
}
return nil
}
func decompressChunk(in io.Reader) ([]byte, error) {
sizeBuf := make([]byte, 4)
if err := binary.Read(in, binary.BigEndian, &sizeBuf); err != nil {
return nil, err
}
size := binary.BigEndian.Uint32(sizeBuf)
dataBuf := make([]byte, size)
if err := binary.Read(in, binary.BigEndian, &dataBuf); err != nil {
return nil, err
}
compressedChunk := bytes.NewBuffer(dataBuf)
var decompressedChunk bytes.Buffer
d, err := zstd.NewReader(compressedChunk)
if err != nil {
return nil, err
}
defer d.Close()
if _, err := io.Copy(&decompressedChunk, d); err != nil {
return nil, err
}
return decompressedChunk.Bytes(), nil
}
func logMessage(body map[string]any) string {
if val, hasStringVal := body["stringValue"]; hasStringVal {
if stringVal, ok := val.(string); ok {
return stringVal
}
}
return ""
}
func stringAttributeByKey(attributes []Attribute, key string) string {
for _, attr := range attributes {
if attr.Key != key {
continue
}
if val, hasStringVal := attr.Value["stringValue"]; hasStringVal {
if stringVal, ok := val.(string); ok {
return stringVal
}
}
}
return ""
}
type fluentTag struct {
namespace, pod, container string
}
func parseFluentTag(tag string) (fluentTag, error) {
_, tagWithoutPrefix, found := strings.Cut(tag, "kube.var.log.containers.")
if !found {
return fluentTag{}, errors.New("invalid fluent tag: prefix not found")
}
tokens := strings.Split(tagWithoutPrefix, "_")
if len(tokens) != 3 {
return fluentTag{}, errors.New("invalid fluent tag: must be 3 tokens")
}
containerEndIndex := strings.LastIndex(tokens[2], "-")
return fluentTag{
namespace: tokens[1],
pod: tokens[0],
container: tokens[2][:containerEndIndex],
}, nil
}
func matches(tag fluentTag, by matchBy) bool {
if by.namespace != "" && !strings.HasPrefix(tag.namespace, by.namespace) {
return false
}
if by.pod != "" && !strings.HasPrefix(tag.pod, by.pod) {
return false
}
if by.container != "" && !strings.HasPrefix(tag.container, by.container) {
return false
}
return true
}