forked from grafana/loki
/
head_wal.go
246 lines (206 loc) · 6.09 KB
/
head_wal.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
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
package tsdb
import (
"time"
"github.com/go-kit/log"
"github.com/pkg/errors"
"github.com/prometheus/prometheus/tsdb/record"
"github.com/prometheus/prometheus/tsdb/wlog"
"github.com/grafana/loki/pkg/storage/stores/tsdb/index"
"github.com/grafana/loki/pkg/util/encoding"
)
type WAL interface {
Start(time.Time) error
Log(*WALRecord) error
Stop() error
}
// TODO(owen-d): There are probably some performance gains to be had by utilizing
// pools here, but in the interest of implementation time and given chunks aren't
// flushed often (generally ~5/s), this seems fine.
// This may also be applicable to varint encoding.
// 128KB
// The segment sizes are kept small for the TSDB Head here because
// we only store chunk references
const walSegmentSize = 128 << 10
type RecordType byte
// By prefixing records with versions, we can easily update our wal schema
const (
// FirstWrite is a special record type written once
// at the beginning of every WAL. It records the system time
// when the WAL was created. This is used to determine when to rotate
// WALs and persists across restarts.
WalRecordSeries RecordType = iota
WalRecordChunks
WalRecordSeriesWithFingerprint
)
type WALRecord struct {
UserID string
Series record.RefSeries
Fingerprint uint64
Chks ChunkMetasRecord
}
type ChunkMetasRecord struct {
Chks index.ChunkMetas
Ref uint64
}
// NB(owen-d): unused since we started recording the fingerprint
// with the series, but left here for future understanding
func (r *WALRecord) encodeSeries(b []byte) []byte {
buf := encoding.EncWith(b)
buf.PutByte(byte(WalRecordSeries))
buf.PutUvarintStr(r.UserID)
var enc record.Encoder
// The 'encoded' already has the type header and userID here, hence re-using
// the remaining part of the slice (i.e. encoded[len(encoded):])) to encode the series.
encoded := buf.Get()
encoded = append(encoded, enc.Series([]record.RefSeries{r.Series}, encoded[len(encoded):])...)
return encoded
}
func (r *WALRecord) encodeSeriesWithFingerprint(b []byte) []byte {
buf := encoding.EncWith(b)
buf.PutByte(byte(WalRecordSeriesWithFingerprint))
buf.PutUvarintStr(r.UserID)
buf.PutBE64(r.Fingerprint)
var enc record.Encoder
// The 'encoded' already has the type header and userID here, hence re-using
// the remaining part of the slice (i.e. encoded[len(encoded):])) to encode the series.
encoded := buf.Get()
encoded = append(encoded, enc.Series([]record.RefSeries{r.Series}, encoded[len(encoded):])...)
return encoded
}
func (r *WALRecord) encodeChunks(b []byte) []byte {
buf := encoding.EncWith(b)
buf.PutByte(byte(WalRecordChunks))
buf.PutUvarintStr(r.UserID)
buf.PutBE64(r.Chks.Ref)
buf.PutUvarint(len(r.Chks.Chks))
for _, chk := range r.Chks.Chks {
buf.PutBE64(uint64(chk.MinTime))
buf.PutBE64(uint64(chk.MaxTime))
buf.PutBE32(chk.Checksum)
buf.PutBE32(chk.KB)
buf.PutBE32(chk.Entries)
}
return buf.Get()
}
func decodeChunks(b []byte, rec *WALRecord) error {
if len(b) == 0 {
return nil
}
dec := encoding.DecWith(b)
rec.Chks.Ref = dec.Be64()
if err := dec.Err(); err != nil {
return errors.Wrap(err, "decoding series ref")
}
ln := dec.Uvarint()
if err := dec.Err(); err != nil {
return errors.Wrap(err, "decoding number of chunks")
}
// allocate space for the required number of chunks
rec.Chks.Chks = make(index.ChunkMetas, 0, ln)
for len(dec.B) > 0 && dec.Err() == nil {
rec.Chks.Chks = append(rec.Chks.Chks, index.ChunkMeta{
MinTime: dec.Be64int64(),
MaxTime: dec.Be64int64(),
Checksum: dec.Be32(),
KB: dec.Be32(),
Entries: dec.Be32(),
})
}
if err := dec.Err(); err != nil {
return errors.Wrap(err, "decoding chunk metas")
}
return nil
}
func decodeWALRecord(b []byte, walRec *WALRecord) error {
var (
userID string
dec record.Decoder
decbuf = encoding.DecWith(b)
t = RecordType(decbuf.Byte())
)
switch t {
case WalRecordSeries:
userID = decbuf.UvarintStr()
rSeries, err := dec.Series(decbuf.B, nil)
if err != nil {
return errors.Wrap(err, "decoding head series")
}
// unlike tsdb, we only add one series per record.
if len(rSeries) > 1 {
return errors.New("more than one series detected in tsdb head wal record")
}
if len(rSeries) == 1 {
walRec.Series = rSeries[0]
}
case WalRecordSeriesWithFingerprint:
userID = decbuf.UvarintStr()
walRec.Fingerprint = decbuf.Be64()
rSeries, err := dec.Series(decbuf.B, nil)
if err != nil {
return errors.Wrap(err, "decoding head series")
}
// unlike tsdb, we only add one series per record.
if len(rSeries) > 1 {
return errors.New("more than one series detected in tsdb head wal record")
}
if len(rSeries) == 1 {
walRec.Series = rSeries[0]
}
case WalRecordChunks:
userID = decbuf.UvarintStr()
if err := decodeChunks(decbuf.B, walRec); err != nil {
return err
}
default:
return errors.New("unknown record type")
}
if decbuf.Err() != nil {
return decbuf.Err()
}
walRec.UserID = userID
return nil
}
// the headWAL, unlike Head, is multi-tenant. This is just to avoid the need to maintain
// an open segment per tenant (potentially thousands of them)
type headWAL struct {
initialized time.Time
log log.Logger
wal *wlog.WL
}
func newHeadWAL(log log.Logger, dir string, t time.Time) (*headWAL, error) {
// NB: if we use a non-nil Prometheus Registerer, ensure
// that the underlying metrics won't conflict with existing WAL metrics in the ingester.
// Likely, this can be done by adding extra label(s)
wal, err := wlog.NewSize(log, nil, dir, walSegmentSize, false)
if err != nil {
return nil, err
}
return &headWAL{
initialized: t,
log: log,
wal: wal,
}, nil
}
func (w *headWAL) Stop() error {
return w.wal.Close()
}
func (w *headWAL) Log(record *WALRecord) error {
if record == nil {
return nil
}
var buf []byte
// Always write series before chunks
if len(record.Series.Labels) > 0 {
buf = record.encodeSeriesWithFingerprint(buf[:0])
if err := w.wal.Log(buf); err != nil {
return err
}
}
if len(record.Chks.Chks) > 0 {
buf = record.encodeChunks(buf[:0])
if err := w.wal.Log(buf); err != nil {
return err
}
}
return nil
}