delta.go 10.6 KB
Newer Older
B
Bjoern Rabenstein 已提交
1
// Copyright 2014 The Prometheus Authors
B
Bjoern Rabenstein 已提交
2 3 4 5 6 7 8 9 10 11 12 13
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

B
Bjoern Rabenstein 已提交
14
package local
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

import (
	"encoding/binary"
	"fmt"
	"io"
	"math"
	"sort"

	clientmodel "github.com/prometheus/client_golang/model"

	"github.com/prometheus/prometheus/storage/metric"
)

// The 21-byte header of a delta-encoded chunk looks like:
//
// - time delta bytes:  1 bytes
// - value delta bytes: 1 bytes
// - is integer:        1 byte
// - base time:         8 bytes
// - base value:        8 bytes
// - used buf bytes:    2 bytes
const (
	deltaHeaderBytes = 21

	deltaHeaderTimeBytesOffset  = 0
	deltaHeaderValueBytesOffset = 1
	deltaHeaderIsIntOffset      = 2
	deltaHeaderBaseTimeOffset   = 3
	deltaHeaderBaseValueOffset  = 11
	deltaHeaderBufLenOffset     = 19
)

B
Bjoern Rabenstein 已提交
47
// A deltaEncodedChunk adaptively stores sample timestamps and values with a
B
beorn7 已提交
48
// delta encoding of various types (int, float) and bit widths. However, once 8
B
Bjoern Rabenstein 已提交
49 50
// bytes would be needed to encode a delta value, a fall-back to the absolute
// numbers happens (so that timestamps are saved directly as int64 and values as
B
Bjoern Rabenstein 已提交
51
// float64). It implements the chunk interface.
B
beorn7 已提交
52
type deltaEncodedChunk []byte
53

B
Bjoern Rabenstein 已提交
54
// newDeltaEncodedChunk returns a newly allocated deltaEncodedChunk.
B
beorn7 已提交
55 56 57 58 59 60 61 62 63 64 65
func newDeltaEncodedChunk(tb, vb deltaBytes, isInt bool, length int) *deltaEncodedChunk {
	if tb < 1 {
		panic("need at least 1 time delta byte")
	}
	if length < deltaHeaderBytes+16 {
		panic(fmt.Errorf(
			"chunk length %d bytes is insufficient, need at least %d",
			length, deltaHeaderBytes+16,
		))
	}
	c := make(deltaEncodedChunk, deltaHeaderIsIntOffset+1, length)
66

B
beorn7 已提交
67 68
	c[deltaHeaderTimeBytesOffset] = byte(tb)
	c[deltaHeaderValueBytesOffset] = byte(vb)
B
Bjoern Rabenstein 已提交
69
	if vb < d8 && isInt { // Only use int for fewer than 8 value delta bytes.
B
beorn7 已提交
70
		c[deltaHeaderIsIntOffset] = 1
71
	} else {
B
beorn7 已提交
72
		c[deltaHeaderIsIntOffset] = 0
73 74
	}

B
beorn7 已提交
75
	return &c
76 77
}

B
beorn7 已提交
78 79
func (c deltaEncodedChunk) newFollowupChunk() chunk {
	return newDeltaEncodedChunk(d1, d0, true, cap(c))
80 81
}

B
Bjoern Rabenstein 已提交
82
// clone implements chunk.
B
beorn7 已提交
83 84 85 86
func (c deltaEncodedChunk) clone() chunk {
	clone := make(deltaEncodedChunk, len(c), cap(c))
	copy(clone, c)
	return &clone
87 88
}

B
beorn7 已提交
89 90
func (c deltaEncodedChunk) timeBytes() deltaBytes {
	return deltaBytes(c[deltaHeaderTimeBytesOffset])
91 92
}

B
beorn7 已提交
93 94
func (c deltaEncodedChunk) valueBytes() deltaBytes {
	return deltaBytes(c[deltaHeaderValueBytesOffset])
95 96
}

B
beorn7 已提交
97 98
func (c deltaEncodedChunk) isInt() bool {
	return c[deltaHeaderIsIntOffset] == 1
99 100
}

B
beorn7 已提交
101 102
func (c deltaEncodedChunk) baseTime() clientmodel.Timestamp {
	return clientmodel.Timestamp(binary.LittleEndian.Uint64(c[deltaHeaderBaseTimeOffset:]))
103 104
}

B
beorn7 已提交
105 106
func (c deltaEncodedChunk) baseValue() clientmodel.SampleValue {
	return clientmodel.SampleValue(math.Float64frombits(binary.LittleEndian.Uint64(c[deltaHeaderBaseValueOffset:])))
107 108
}

B
Bjoern Rabenstein 已提交
109
// add implements chunk.
B
beorn7 已提交
110 111 112 113 114
func (c deltaEncodedChunk) add(s *metric.SamplePair) []chunk {
	if len(c) < deltaHeaderBytes {
		c = c[:deltaHeaderBytes]
		binary.LittleEndian.PutUint64(c[deltaHeaderBaseTimeOffset:], uint64(s.Timestamp))
		binary.LittleEndian.PutUint64(c[deltaHeaderBaseValueOffset:], math.Float64bits(float64(s.Value)))
115 116
	}

B
beorn7 已提交
117
	remainingBytes := cap(c) - len(c)
118 119 120
	sampleSize := c.sampleSize()

	// Do we generally have space for another sample in this chunk? If not,
B
Bjoern Rabenstein 已提交
121
	// overflow into a new one.
122 123
	if remainingBytes < sampleSize {
		overflowChunks := c.newFollowupChunk().add(s)
B
beorn7 已提交
124
		return []chunk{&c, overflowChunks[0]}
125 126
	}

B
beorn7 已提交
127 128
	// TODO(beorn7): Once https://github.com/prometheus/prometheus/issues/481 is
	// fixed, we should panic here if dt is negative.
129 130
	dt := s.Timestamp - c.baseTime()
	dv := s.Value - c.baseValue()
B
Bjoern Rabenstein 已提交
131 132
	tb := c.timeBytes()
	vb := c.valueBytes()
133 134 135 136 137

	// If the new sample is incompatible with the current encoding, reencode the
	// existing chunk data into new chunk(s).
	//
	// int->float.
B
beorn7 已提交
138 139
	if c.isInt() && !isInt64(dv) {
		return transcodeAndAdd(newDeltaEncodedChunk(tb, d4, false, cap(c)), &c, s)
140 141
	}
	// float32->float64.
B
beorn7 已提交
142 143
	if !c.isInt() && vb == d4 && !isFloat32(dv) {
		return transcodeAndAdd(newDeltaEncodedChunk(tb, d8, false, cap(c)), &c, s)
144
	}
B
Bjoern Rabenstein 已提交
145 146
	if tb < d8 || vb < d8 {
		// Maybe more bytes per sample.
B
beorn7 已提交
147 148 149
		ntb := bytesNeededForUnsignedTimestampDelta(dt)
		nvb := bytesNeededForSampleValueDelta(dv, c.isInt())
		if ntb > tb || nvb > vb {
B
Bjoern Rabenstein 已提交
150 151
			ntb = max(ntb, tb)
			nvb = max(nvb, vb)
B
beorn7 已提交
152
			return transcodeAndAdd(newDeltaEncodedChunk(ntb, nvb, c.isInt(), cap(c)), &c, s)
B
Bjoern Rabenstein 已提交
153
		}
154
	}
B
beorn7 已提交
155 156
	offset := len(c)
	c = c[:offset+sampleSize]
157

B
Bjoern Rabenstein 已提交
158 159
	switch tb {
	case d1:
B
beorn7 已提交
160
		c[offset] = byte(dt)
B
Bjoern Rabenstein 已提交
161
	case d2:
B
beorn7 已提交
162
		binary.LittleEndian.PutUint16(c[offset:], uint16(dt))
B
Bjoern Rabenstein 已提交
163
	case d4:
B
beorn7 已提交
164
		binary.LittleEndian.PutUint32(c[offset:], uint32(dt))
B
Bjoern Rabenstein 已提交
165 166
	case d8:
		// Store the absolute value (no delta) in case of d8.
B
beorn7 已提交
167
		binary.LittleEndian.PutUint64(c[offset:], uint64(s.Timestamp))
B
Bjoern Rabenstein 已提交
168 169
	default:
		panic("invalid number of bytes for time delta")
170 171
	}

B
Bjoern Rabenstein 已提交
172
	offset += int(tb)
173 174

	if c.isInt() {
B
Bjoern Rabenstein 已提交
175 176
		switch vb {
		case d0:
177
			// No-op. Constant value is stored as base value.
B
Bjoern Rabenstein 已提交
178
		case d1:
B
beorn7 已提交
179
			c[offset] = byte(dv)
B
Bjoern Rabenstein 已提交
180
		case d2:
B
beorn7 已提交
181
			binary.LittleEndian.PutUint16(c[offset:], uint16(dv))
B
Bjoern Rabenstein 已提交
182
		case d4:
B
beorn7 已提交
183
			binary.LittleEndian.PutUint32(c[offset:], uint32(dv))
B
Bjoern Rabenstein 已提交
184
		// d8 must not happen. Those samples are encoded as float64.
185
		default:
B
Bjoern Rabenstein 已提交
186
			panic("invalid number of bytes for integer delta")
187 188
		}
	} else {
B
Bjoern Rabenstein 已提交
189 190
		switch vb {
		case d4:
B
beorn7 已提交
191
			binary.LittleEndian.PutUint32(c[offset:], math.Float32bits(float32(dv)))
B
Bjoern Rabenstein 已提交
192 193
		case d8:
			// Store the absolute value (no delta) in case of d8.
B
beorn7 已提交
194
			binary.LittleEndian.PutUint64(c[offset:], math.Float64bits(float64(s.Value)))
195
		default:
B
Bjoern Rabenstein 已提交
196
			panic("invalid number of bytes for floating point delta")
197 198
		}
	}
B
beorn7 已提交
199
	return []chunk{&c}
200 201
}

B
beorn7 已提交
202
func (c deltaEncodedChunk) sampleSize() int {
203 204 205
	return int(c.timeBytes() + c.valueBytes())
}

B
beorn7 已提交
206 207
func (c deltaEncodedChunk) len() int {
	if len(c) < deltaHeaderBytes {
208 209
		return 0
	}
B
beorn7 已提交
210
	return (len(c) - deltaHeaderBytes) / c.sampleSize()
211 212
}

B
Bjoern Rabenstein 已提交
213
// values implements chunk.
B
beorn7 已提交
214
func (c deltaEncodedChunk) values() <-chan *metric.SamplePair {
215 216 217 218 219 220 221 222 223 224 225
	n := c.len()
	valuesChan := make(chan *metric.SamplePair)
	go func() {
		for i := 0; i < n; i++ {
			valuesChan <- c.valueAtIndex(i)
		}
		close(valuesChan)
	}()
	return valuesChan
}

B
beorn7 已提交
226
func (c deltaEncodedChunk) valueAtIndex(idx int) *metric.SamplePair {
227 228
	offset := deltaHeaderBytes + idx*c.sampleSize()

B
Bjoern Rabenstein 已提交
229
	var ts clientmodel.Timestamp
230
	switch c.timeBytes() {
B
Bjoern Rabenstein 已提交
231
	case d1:
B
beorn7 已提交
232
		ts = c.baseTime() + clientmodel.Timestamp(uint8(c[offset]))
B
Bjoern Rabenstein 已提交
233
	case d2:
B
beorn7 已提交
234
		ts = c.baseTime() + clientmodel.Timestamp(binary.LittleEndian.Uint16(c[offset:]))
B
Bjoern Rabenstein 已提交
235
	case d4:
B
beorn7 已提交
236
		ts = c.baseTime() + clientmodel.Timestamp(binary.LittleEndian.Uint32(c[offset:]))
B
Bjoern Rabenstein 已提交
237 238
	case d8:
		// Take absolute value for d8.
B
beorn7 已提交
239
		ts = clientmodel.Timestamp(binary.LittleEndian.Uint64(c[offset:]))
B
Bjoern Rabenstein 已提交
240 241
	default:
		panic("Invalid number of bytes for time delta")
242 243 244 245
	}

	offset += int(c.timeBytes())

B
Bjoern Rabenstein 已提交
246
	var v clientmodel.SampleValue
247 248
	if c.isInt() {
		switch c.valueBytes() {
B
Bjoern Rabenstein 已提交
249 250 251
		case d0:
			v = c.baseValue()
		case d1:
B
beorn7 已提交
252
			v = c.baseValue() + clientmodel.SampleValue(int8(c[offset]))
B
Bjoern Rabenstein 已提交
253
		case d2:
B
beorn7 已提交
254
			v = c.baseValue() + clientmodel.SampleValue(int16(binary.LittleEndian.Uint16(c[offset:])))
B
Bjoern Rabenstein 已提交
255
		case d4:
B
beorn7 已提交
256
			v = c.baseValue() + clientmodel.SampleValue(int32(binary.LittleEndian.Uint32(c[offset:])))
B
Bjoern Rabenstein 已提交
257
		// No d8 for ints.
258 259 260 261 262
		default:
			panic("Invalid number of bytes for integer delta")
		}
	} else {
		switch c.valueBytes() {
B
Bjoern Rabenstein 已提交
263
		case d4:
B
beorn7 已提交
264
			v = c.baseValue() + clientmodel.SampleValue(math.Float32frombits(binary.LittleEndian.Uint32(c[offset:])))
B
Bjoern Rabenstein 已提交
265 266
		case d8:
			// Take absolute value for d8.
B
beorn7 已提交
267
			v = clientmodel.SampleValue(math.Float64frombits(binary.LittleEndian.Uint64(c[offset:])))
268 269 270 271 272
		default:
			panic("Invalid number of bytes for floating point delta")
		}
	}
	return &metric.SamplePair{
B
Bjoern Rabenstein 已提交
273 274
		Timestamp: ts,
		Value:     v,
275 276 277
	}
}

B
Bjoern Rabenstein 已提交
278
// firstTime implements chunk.
B
beorn7 已提交
279
func (c deltaEncodedChunk) firstTime() clientmodel.Timestamp {
280 281 282
	return c.valueAtIndex(0).Timestamp
}

B
Bjoern Rabenstein 已提交
283
// lastTime implements chunk.
B
beorn7 已提交
284
func (c deltaEncodedChunk) lastTime() clientmodel.Timestamp {
285 286 287
	return c.valueAtIndex(c.len() - 1).Timestamp
}

B
Bjoern Rabenstein 已提交
288
// marshal implements chunk.
B
beorn7 已提交
289 290
func (c deltaEncodedChunk) marshal(w io.Writer) error {
	if len(c) > math.MaxUint16 {
291 292
		panic("chunk buffer length would overflow a 16 bit uint.")
	}
B
beorn7 已提交
293
	binary.LittleEndian.PutUint16(c[deltaHeaderBufLenOffset:], uint16(len(c)))
294

B
beorn7 已提交
295
	n, err := w.Write(c[:cap(c)])
296 297 298
	if err != nil {
		return err
	}
B
beorn7 已提交
299 300
	if n != cap(c) {
		return fmt.Errorf("wanted to write %d bytes, wrote %d", len(c), n)
301 302 303 304
	}
	return nil
}

B
Bjoern Rabenstein 已提交
305
// unmarshal implements chunk.
306
func (c *deltaEncodedChunk) unmarshal(r io.Reader) error {
B
beorn7 已提交
307
	*c = (*c)[:cap(*c)]
308
	readBytes := 0
B
beorn7 已提交
309 310
	for readBytes < len(*c) {
		n, err := r.Read((*c)[readBytes:])
311 312 313 314 315
		if err != nil {
			return err
		}
		readBytes += n
	}
B
beorn7 已提交
316
	*c = (*c)[:binary.LittleEndian.Uint16((*c)[deltaHeaderBufLenOffset:])]
317 318 319
	return nil
}

B
Bjoern Rabenstein 已提交
320
// deltaEncodedChunkIterator implements chunkIterator.
321 322 323 324 325
type deltaEncodedChunkIterator struct {
	chunk *deltaEncodedChunk
	// TODO: add more fields here to keep track of last position.
}

B
Bjoern Rabenstein 已提交
326
// newIterator implements chunk.
327 328 329 330 331 332
func (c *deltaEncodedChunk) newIterator() chunkIterator {
	return &deltaEncodedChunkIterator{
		chunk: c,
	}
}

B
Bjoern Rabenstein 已提交
333
// getValueAtTime implements chunkIterator.
334 335 336 337 338 339 340 341 342 343 344
func (it *deltaEncodedChunkIterator) getValueAtTime(t clientmodel.Timestamp) metric.Values {
	i := sort.Search(it.chunk.len(), func(i int) bool {
		return !it.chunk.valueAtIndex(i).Timestamp.Before(t)
	})

	switch i {
	case 0:
		return metric.Values{*it.chunk.valueAtIndex(0)}
	case it.chunk.len():
		return metric.Values{*it.chunk.valueAtIndex(it.chunk.len() - 1)}
	default:
345 346
		v := it.chunk.valueAtIndex(i)
		if v.Timestamp.Equal(t) {
347 348
			return metric.Values{*v}
		}
349
		return metric.Values{*it.chunk.valueAtIndex(i - 1), *v}
350 351 352
	}
}

B
Bjoern Rabenstein 已提交
353
// getRangeValues implements chunkIterator.
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
func (it *deltaEncodedChunkIterator) getRangeValues(in metric.Interval) metric.Values {
	oldest := sort.Search(it.chunk.len(), func(i int) bool {
		return !it.chunk.valueAtIndex(i).Timestamp.Before(in.OldestInclusive)
	})

	newest := sort.Search(it.chunk.len(), func(i int) bool {
		return it.chunk.valueAtIndex(i).Timestamp.After(in.NewestInclusive)
	})

	if oldest == it.chunk.len() {
		return nil
	}

	result := make(metric.Values, 0, newest-oldest)
	for i := oldest; i < newest; i++ {
		result = append(result, *it.chunk.valueAtIndex(i))
	}
	return result
}

B
Bjoern Rabenstein 已提交
374
// contains implements chunkIterator.
375 376 377
func (it *deltaEncodedChunkIterator) contains(t clientmodel.Timestamp) bool {
	return !t.Before(it.chunk.firstTime()) && !t.After(it.chunk.lastTime())
}