-
Notifications
You must be signed in to change notification settings - Fork 17
/
block.go
431 lines (391 loc) · 11.9 KB
/
block.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
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/*************************************************************************
* Copyright 2017 Gravwell, Inc. All rights reserved.
* Contact: <legal@gravwell.io>
*
* This software may be modified and distributed under the terms of the
* BSD 2-clause license. See the LICENSE file for details.
**************************************************************************/
package entry
import (
"encoding/binary"
"errors"
"net"
)
const (
EntryBlockHeaderSize = 4 + 4 + 8
maxEntryBlockSize = (1024 * 1024 * 1024 * 2) //2GB which is insane
)
var (
ErrNilEntry error = errors.New("Cannot add nil entry")
ErrInvalidKey error = errors.New("Entry key does not match block")
ErrBadKey error = errors.New("EntryBlock key is invalid")
ErrKeyAlreadySet error = errors.New("Entry key for block already set")
ErrInvalidEntryBlock error = errors.New("EntryBlock is invalid")
ErrBlockTooLarge error = errors.New("EntryBlock is too large to encode")
ErrInvalidDestBuff error = errors.New("EntryBlock buffer is too small")
ErrInvalidSrcBuff error = errors.New("Buffer is invalid for an EntryBlock")
ErrPartialDecode error = errors.New("Buffer is short/invalid for EntryBlock decode")
)
// standard entry block, primarily used in ingesters
type EntryBlock struct {
size uint64
key int64
entries []*Entry
}
// NewEntryBlock creates a new entry block from the set and size parameters
// the size is taken at face value and should represent the storage size needed to
// encode the given set
func NewEntryBlock(set []*Entry, size uint64) EntryBlock {
var key int64
if len(set) > 0 {
if set[0] != nil {
key = set[0].TS.Sec
}
if size == 0 {
//go figure out what the size should be if they don't know
for i := range set {
if set[i] != nil {
size += set[i].Size()
}
}
}
}
return EntryBlock{
size: size,
key: key,
entries: set,
}
}
// NewEntryBlock creates a new entry block from the set and size parameters
// the size is taken at face value and should represent the storage size needed to
// encode the given set. The slice of Entry handed in is NOT copied, caller should not modify the slice until the block is done
func NewEntryBlockNP(set []Entry, size uint64) (eb EntryBlock) {
if len(set) > 0 {
eb.key = set[0].TS.Sec
if size == 0 {
//go figure out what the size should be if they don't know
for i := range set {
size += set[i].Size()
}
}
}
eb.size = size
eb.entries = make([]*Entry, len(set))
for i := range set {
eb.entries[i] = &set[i]
}
return
}
// Add adds an entry to the entry block, if no key is currently set, the entries TS is used
func (eb *EntryBlock) Add(e *Entry) {
eb.size += e.Size()
eb.entries = append(eb.entries, e)
if eb.key == 0 {
eb.key = e.TS.Sec
}
}
// Merge merges a provided entry block into the given entry block, the keys for the two blocks must match
func (eb *EntryBlock) Merge(neb *EntryBlock) error {
if eb.key != neb.key {
return ErrBadKey
}
eb.size += neb.size
eb.entries = append(eb.entries, neb.entries...)
return nil
}
// Count returns the number of entries held in the block
func (eb *EntryBlock) Count() int {
return len(eb.entries)
}
// Entry returns the ith entry from the block. If i is an invalid index nil is returned
func (eb *EntryBlock) Entry(i int) *Entry {
if i >= len(eb.entries) {
return nil
}
return eb.entries[i]
}
// Entries returns the underlying entry slice
func (eb *EntryBlock) Entries() []*Entry {
return eb.entries
}
// Peel splits off a set of entries from the EntryBlock, returning a new EntryBlock
// and updating the state of the current EntryBlock, the count and size are used as barrier
// we peel until we hit either the count or the size
func (eb *EntryBlock) Peel(cnt int, sz uint64) (neb EntryBlock) {
if len(eb.entries) == 0 || sz <= 0 {
return
}
var removedSize uint64
var torem int
neb.key = eb.key
for i := range eb.entries {
if i >= cnt || removedSize > sz {
break
}
torem++
removedSize += eb.entries[i].Size()
}
neb.entries = eb.entries[0:torem]
neb.size = removedSize
eb.entries = eb.entries[torem:]
eb.size -= removedSize
return
}
type entryBlockHeader struct {
blockSize uint32
entryCount uint32
key int64
}
func (ebh entryBlockHeader) encode(b []byte) error {
if len(b) < int(EntryBlockHeaderSize) {
return ErrInvalidDestBuff
}
binary.LittleEndian.PutUint32(b[0:], ebh.blockSize)
binary.LittleEndian.PutUint32(b[4:], ebh.entryCount)
binary.LittleEndian.PutUint64(b[8:], uint64(ebh.key))
return nil
}
func (ebh *entryBlockHeader) decode(b []byte) error {
if len(b) < int(EntryBlockHeaderSize) {
return ErrInvalidSrcBuff
}
ebh.blockSize = binary.LittleEndian.Uint32(b[0:])
ebh.entryCount = binary.LittleEndian.Uint32(b[4:])
ebh.key = int64(binary.LittleEndian.Uint64(b[8:]))
return nil
}
// Encode encodes the EntryBlock to a buffer suitable for transmitting across a network or storing to a file
func (eb *EntryBlock) Encode() ([]byte, error) {
if eb == nil || len(eb.entries) == 0 || eb.key <= 0 || eb.size <= 0 {
return nil, ErrInvalidEntryBlock
}
if (eb.size + EntryBlockHeaderSize) > maxEntryBlockSize {
return nil, ErrBlockTooLarge
}
//generate a buffer for encoding
buff := make([]byte, eb.size+EntryBlockHeaderSize)
if _, err := eb.encodeInto(buff); err != nil {
return nil, err
}
return buff, nil
}
func (eb *EntryBlock) encodeInto(buff []byte) (int, error) {
hdr := entryBlockHeader{
blockSize: uint32(eb.size),
key: eb.key,
entryCount: uint32(len(eb.entries)),
}
//encode the header
if err := hdr.encode(buff[:EntryBlockHeaderSize]); err != nil {
return 0, err
}
return eb.encode(buff[EntryBlockHeaderSize:])
}
// EncodeInto encodes the entry block into the given buffer. The buffer MUST be large enough
// to hold the entire block, an encoded size and nil is returned on success
// 0 and an error is returned if the buffer is too small
// the size checks are performed on the actual entries as well as the block size
func (eb *EntryBlock) EncodeInto(buff []byte) (int, error) {
if eb == nil || len(eb.entries) == 0 || eb.key <= 0 || eb.size <= 0 {
return 0, ErrInvalidEntryBlock
}
if (eb.size + EntryBlockHeaderSize) > maxEntryBlockSize {
return 0, ErrBlockTooLarge
}
if (eb.size + EntryBlockHeaderSize) > uint64(len(buff)) {
return 0, ErrInvalidDestBuff
}
return eb.encodeInto(buff)
}
// EncodeEntries encodes just the set of entries into the provided buffer
func (eb *EntryBlock) EncodeEntries(buff []byte) (int, error) {
return eb.encode(buff)
}
func (eb *EntryBlock) encode(buff []byte) (int, error) {
if uint64(len(buff)) < eb.size {
return 0, ErrInvalidDestBuff
}
//encode each of the entries
offset := int(0)
for i := range eb.entries {
sz := int(eb.entries[i].Size())
if (offset + sz) > len(buff) {
return 0, ErrInvalidDestBuff
}
if n, err := eb.entries[i].Encode(buff[offset:(offset + sz)]); err != nil {
return 0, err
} else {
offset += n
}
}
return offset, nil
}
// EncodeAppend takes the current buffer, and appends addional entries to the buffer
// we also update the header
func (eb *EntryBlock) EncodeAppend(buff []byte) ([]byte, error) {
//decode the original header
var ebh entryBlockHeader
if len(buff) > EntryBlockHeaderSize {
if err := ebh.decode(buff); err != nil {
return nil, err
}
} else {
//if the input is too small, make a buffer that at least represents a header
buff = make([]byte, EntryBlockHeaderSize)
}
//update the header values
ebh.blockSize += uint32(eb.size)
ebh.entryCount += uint32(len(eb.entries))
//encode the additional items
b := append(buff, make([]byte, eb.size)...)
if _, err := eb.encode(b[len(buff):]); err != nil {
return nil, err
}
//update the header
if err := ebh.encode(b); err != nil {
return nil, err
}
return b, nil
}
// Decode will decode an EntryBlock from a buffer, with error checking
func (eb *EntryBlock) Decode(b []byte) error {
if len(b) < EntryBlockHeaderSize {
return ErrInvalidSrcBuff
}
var ebh entryBlockHeader
if err := ebh.decode(b); err != nil {
return err
}
if ebh.blockSize > maxEntryBlockSize {
return ErrBlockTooLarge
}
if ebh.blockSize+EntryBlockHeaderSize != uint32(len(b)) {
return ErrInvalidSrcBuff
}
offset := uint64(EntryBlockHeaderSize)
blen := uint64(len(b))
var sz uint32
for i := uint32(0); i < ebh.entryCount; i++ {
var ent Entry
n, hasEvs, err := ent.DecodeHeader(b[offset:])
if err != nil {
return err
}
dlen := uint64(n)
if (dlen + uint64(ENTRY_HEADER_SIZE) + offset) > blen {
return ErrInvalidSrcBuff
}
offset += uint64(ENTRY_HEADER_SIZE)
ent.Data = b[offset : offset+dlen]
if hasEvs {
if evlen, err := ent.EVB.Decode(b[offset+dlen:]); err != nil {
return ErrInvalidSrcBuff
} else {
dlen += uint64(evlen)
}
}
offset += dlen
eb.entries = append(eb.entries, &ent)
sz += uint32(ent.Size())
}
if offset != uint64(len(b)) {
return ErrPartialDecode
}
if sz != ebh.blockSize {
return ErrPartialDecode
}
eb.size = uint64(sz)
eb.key = ebh.key
return nil
}
// SetKey manually sets the key of a block, this is not an override, if the key is already set
// an error is returned
func (eb *EntryBlock) SetKey(k EntryKey) error {
if eb.key > 0 {
return ErrKeyAlreadySet
}
if k <= 0 {
return ErrBadKey
}
eb.key = int64(k)
return nil
}
// Size returns the size of the entry block (without encoding header)
func (eb EntryBlock) Size() uint64 {
return eb.size
}
// EncodedSize returns the size of an entry block as would be encoded to disk without compression
func (eb EntryBlock) EncodedSize() uint64 {
return eb.size + EntryBlockHeaderSize
}
// Len returns the number of entries allocated, there is no garuntee the entries are all non-nil
func (eb EntryBlock) Len() int {
return len(eb.entries)
}
// Key returns the timestamp associated with the block,
// There is no garuntee that all entries are part of this key,
// if the construction of the block didn't adhere to grouping the key means little
// The key is basically a hint
func (eb EntryBlock) Key() int64 {
return eb.key
}
// EntryKey returns the key associated with an entry in the block and an error if the entry doesn't exist
func (eb EntryBlock) EntryKey(i int) (int64, error) {
if i >= len(eb.entries) {
return -1, errors.New("invalid index")
}
if eb.entries[i] != nil {
return eb.entries[i].TS.Sec, nil
}
return 0, errors.New("Invalid entry")
}
// Deep copy performs an agressive deep copy of the entire block, all entries, and any underlying buffers
// this is useful when you are pulling entries out of a RO memory reagion and want to ensure your block
// is entirely orthogonal to the backing memory region.
// WARNING: this will hammer the memory allocator, only use when you know what you are doing
func (eb EntryBlock) DeepCopy() EntryBlock {
return NewDeepCopyEntryBlock(eb.entries, eb.size)
}
// NewDeepCopyEntryBlock creates a new EntryBlock with a deep copy on all data in the provided set
// the sz size parameter is used as a hint for allocation, provide zero if unknown
func NewDeepCopyEntryBlock(set []*Entry, sz uint64) (neb EntryBlock) {
//short circuit out on empty sets
if len(set) == 0 {
return
}
var buff []byte
if sz > 0 {
//allocate a block large enough to hold all entry SRC and DATA fields
trimSize := uint64(len(set) * (ENTRY_HEADER_SIZE - SRC_SIZE))
if trimSize > sz {
sz = 4096
} else {
sz = sz - trimSize
}
buff = make([]byte, 0, sz)
}
//we sweep through copying SRC and Data into our new buffer, everything else is allocated via the
//a new Entry
var off int
var ne *Entry
for _, e := range set {
if e == nil {
continue
}
buff = append(buff, e.SRC...)
buff = append(buff, e.Data...)
ne = &Entry{
TS: e.TS,
Tag: e.Tag,
SRC: net.IP(buff[off : off+len(e.SRC)]),
Data: net.IP(buff[off+len(e.SRC) : off+len(e.SRC)+len(e.Data)]),
}
neb.size += ne.Size()
off += len(e.SRC) + len(e.Data)
neb.entries = append(neb.entries, ne)
}
if len(neb.entries) > 0 && neb.key != neb.entries[0].TS.Sec {
neb.key = neb.entries[0].TS.Sec
}
return
}