Line data Source code
1 : // Copyright 2018 The LevelDB-Go and Pebble Authors. All rights reserved. Use
2 : // of this source code is governed by a BSD-style license that can be found in
3 : // the LICENSE file.
4 :
5 : package sstable
6 :
7 : import (
8 : "bytes"
9 : "encoding/binary"
10 : "fmt"
11 : "math"
12 : "reflect"
13 : "sort"
14 : "unsafe"
15 :
16 : "github.com/cockroachdb/pebble/internal/intern"
17 : )
18 :
19 : const propertiesBlockRestartInterval = math.MaxInt32
20 :
21 : var propTagMap = make(map[string]reflect.StructField)
22 : var propBoolTrue = []byte{'1'}
23 : var propBoolFalse = []byte{'0'}
24 :
25 : var propOffsetTagMap = make(map[uintptr]string)
26 :
27 1 : func generateTagMaps(t reflect.Type, indexPrefix []int) {
28 1 : for i := 0; i < t.NumField(); i++ {
29 1 : f := t.Field(i)
30 1 : if f.Type.Kind() == reflect.Struct {
31 1 : if tag := f.Tag.Get("prop"); i == 0 && tag == "pebble.embbeded_common_properties" {
32 1 : // CommonProperties struct embedded in Properties. Note that since
33 1 : // CommonProperties is placed at the top of properties we can use
34 1 : // the offsets of the fields within CommonProperties to determine
35 1 : // the offsets of those fields within Properties.
36 1 : generateTagMaps(f.Type, []int{i})
37 1 : continue
38 : }
39 0 : panic("pebble: unknown struct type in Properties")
40 : }
41 1 : if tag := f.Tag.Get("prop"); tag != "" {
42 1 : switch f.Type.Kind() {
43 1 : case reflect.Bool:
44 1 : case reflect.Uint32:
45 1 : case reflect.Uint64:
46 1 : case reflect.String:
47 0 : default:
48 0 : panic(fmt.Sprintf("unsupported property field type: %s %s", f.Name, f.Type))
49 : }
50 1 : if len(indexPrefix) > 0 {
51 1 : // Prepend the index prefix so that we can use FieldByIndex on the top-level struct.
52 1 : f.Index = append(indexPrefix[:len(indexPrefix):len(indexPrefix)], f.Index...)
53 1 : }
54 1 : propTagMap[tag] = f
55 1 : propOffsetTagMap[f.Offset] = tag
56 : }
57 : }
58 : }
59 :
60 1 : func init() {
61 1 : generateTagMaps(reflect.TypeOf(Properties{}), nil)
62 1 : }
63 :
64 : // CommonProperties holds properties for either a virtual or a physical sstable. This
65 : // can be used by code which doesn't care to make the distinction between physical
66 : // and virtual sstables properties.
67 : //
68 : // For virtual sstables, fields are constructed through extrapolation upon virtual
69 : // reader construction. See MakeVirtualReader for implementation details.
70 : //
71 : // NB: The values of these properties can affect correctness. For example,
72 : // if NumRangeKeySets == 0, but the sstable actually contains range keys, then
73 : // the iterators will behave incorrectly.
74 : type CommonProperties struct {
75 : // The number of entries in this table.
76 : NumEntries uint64 `prop:"rocksdb.num.entries"`
77 : // Total raw key size.
78 : RawKeySize uint64 `prop:"rocksdb.raw.key.size"`
79 : // Total raw value size.
80 : RawValueSize uint64 `prop:"rocksdb.raw.value.size"`
81 : // Total raw key size of point deletion tombstones. This value is comparable
82 : // to RawKeySize.
83 : RawPointTombstoneKeySize uint64 `prop:"pebble.raw.point-tombstone.key.size"`
84 : // Sum of the raw value sizes carried by point deletion tombstones
85 : // containing size estimates. See the DeleteSized key kind. This value is
86 : // comparable to Raw{Key,Value}Size.
87 : RawPointTombstoneValueSize uint64 `prop:"pebble.raw.point-tombstone.value.size"`
88 : // The number of point deletion entries ("tombstones") in this table that
89 : // carry a size hint indicating the size of the value the tombstone deletes.
90 : NumSizedDeletions uint64 `prop:"pebble.num.deletions.sized"`
91 : // The number of deletion entries in this table, including both point and
92 : // range deletions.
93 : NumDeletions uint64 `prop:"rocksdb.deleted.keys"`
94 : // The number of range deletions in this table.
95 : NumRangeDeletions uint64 `prop:"rocksdb.num.range-deletions"`
96 : // The number of RANGEKEYDELs in this table.
97 : NumRangeKeyDels uint64 `prop:"pebble.num.range-key-dels"`
98 : // The number of RANGEKEYSETs in this table.
99 : NumRangeKeySets uint64 `prop:"pebble.num.range-key-sets"`
100 : // Total size of value blocks and value index block. Only serialized if > 0.
101 : ValueBlocksSize uint64 `prop:"pebble.value-blocks.size"`
102 : }
103 :
104 : // String is only used for testing purposes.
105 1 : func (c *CommonProperties) String() string {
106 1 : var buf bytes.Buffer
107 1 : v := reflect.ValueOf(*c)
108 1 : loaded := make(map[uintptr]struct{})
109 1 : writeProperties(loaded, v, &buf)
110 1 : return buf.String()
111 1 : }
112 :
113 : // NumPointDeletions is the number of point deletions in the sstable. For virtual
114 : // sstables, this is an estimate.
115 1 : func (c *CommonProperties) NumPointDeletions() uint64 {
116 1 : return c.NumDeletions - c.NumRangeDeletions
117 1 : }
118 :
119 : // Properties holds the sstable property values. The properties are
120 : // automatically populated during sstable creation and load from the properties
121 : // meta block when an sstable is opened.
122 : type Properties struct {
123 : // CommonProperties needs to be at the top of the Properties struct so that the
124 : // offsets of the fields in CommonProperties match the offsets of the embedded
125 : // fields of CommonProperties in Properties.
126 : CommonProperties `prop:"pebble.embbeded_common_properties"`
127 :
128 : // The name of the comparer used in this table.
129 : ComparerName string `prop:"rocksdb.comparator"`
130 : // The compression algorithm used to compress blocks.
131 : CompressionName string `prop:"rocksdb.compression"`
132 : // The compression options used to compress blocks.
133 : CompressionOptions string `prop:"rocksdb.compression_options"`
134 : // The total size of all data blocks.
135 : DataSize uint64 `prop:"rocksdb.data.size"`
136 : // The name of the filter policy used in this table. Empty if no filter
137 : // policy is used.
138 : FilterPolicyName string `prop:"rocksdb.filter.policy"`
139 : // The size of filter block.
140 : FilterSize uint64 `prop:"rocksdb.filter.size"`
141 : // Total number of index partitions if kTwoLevelIndexSearch is used.
142 : IndexPartitions uint64 `prop:"rocksdb.index.partitions"`
143 : // The size of index block.
144 : IndexSize uint64 `prop:"rocksdb.index.size"`
145 : // The index type. TODO(peter): add a more detailed description.
146 : IndexType uint32 `prop:"rocksdb.block.based.table.index.type"`
147 : // For formats >= TableFormatPebblev4, this is set to true if the obsolete
148 : // bit is strict for all the point keys.
149 : IsStrictObsolete bool `prop:"pebble.obsolete.is_strict"`
150 : // The name of the merger used in this table. Empty if no merger is used.
151 : MergerName string `prop:"rocksdb.merge.operator"`
152 : // The number of blocks in this table.
153 : NumDataBlocks uint64 `prop:"rocksdb.num.data.blocks"`
154 : // The number of merge operands in the table.
155 : NumMergeOperands uint64 `prop:"rocksdb.merge.operands"`
156 : // The number of RANGEKEYUNSETs in this table.
157 : NumRangeKeyUnsets uint64 `prop:"pebble.num.range-key-unsets"`
158 : // The number of value blocks in this table. Only serialized if > 0.
159 : NumValueBlocks uint64 `prop:"pebble.num.value-blocks"`
160 : // The number of values stored in value blocks. Only serialized if > 0.
161 : NumValuesInValueBlocks uint64 `prop:"pebble.num.values.in.value-blocks"`
162 : // A comma separated list of names of the property collectors used in this
163 : // table.
164 : PropertyCollectorNames string `prop:"rocksdb.property.collectors"`
165 : // Total raw rangekey key size.
166 : RawRangeKeyKeySize uint64 `prop:"pebble.raw.range-key.key.size"`
167 : // Total raw rangekey value size.
168 : RawRangeKeyValueSize uint64 `prop:"pebble.raw.range-key.value.size"`
169 : // The total number of keys in this table that were pinned by open snapshots.
170 : SnapshotPinnedKeys uint64 `prop:"pebble.num.snapshot-pinned-keys"`
171 : // The cumulative bytes of keys in this table that were pinned by
172 : // open snapshots. This value is comparable to RawKeySize.
173 : SnapshotPinnedKeySize uint64 `prop:"pebble.raw.snapshot-pinned-keys.size"`
174 : // The cumulative bytes of values in this table that were pinned by
175 : // open snapshots. This value is comparable to RawValueSize.
176 : SnapshotPinnedValueSize uint64 `prop:"pebble.raw.snapshot-pinned-values.size"`
177 : // Size of the top-level index if kTwoLevelIndexSearch is used.
178 : TopLevelIndexSize uint64 `prop:"rocksdb.top-level.index.size"`
179 : // User collected properties. Currently, we only use them to store block
180 : // properties aggregated at the table level.
181 : UserProperties map[string]string
182 :
183 : // Loaded set indicating which fields have been loaded from disk. Indexed by
184 : // the field's byte offset within the struct
185 : // (reflect.StructField.Offset). Only set if the properties have been loaded
186 : // from a file. Only exported for testing purposes.
187 : Loaded map[uintptr]struct{}
188 : }
189 :
190 : // NumPointDeletions returns the number of point deletions in this table.
191 1 : func (p *Properties) NumPointDeletions() uint64 {
192 1 : return p.NumDeletions - p.NumRangeDeletions
193 1 : }
194 :
195 : // NumRangeKeys returns a count of the number of range keys in this table.
196 1 : func (p *Properties) NumRangeKeys() uint64 {
197 1 : return p.NumRangeKeyDels + p.NumRangeKeySets + p.NumRangeKeyUnsets
198 1 : }
199 :
200 1 : func writeProperties(loaded map[uintptr]struct{}, v reflect.Value, buf *bytes.Buffer) {
201 1 : vt := v.Type()
202 1 : for i := 0; i < v.NumField(); i++ {
203 1 : ft := vt.Field(i)
204 1 : if ft.Type.Kind() == reflect.Struct {
205 1 : // Embedded struct within the properties.
206 1 : writeProperties(loaded, v.Field(i), buf)
207 1 : continue
208 : }
209 1 : tag := ft.Tag.Get("prop")
210 1 : if tag == "" {
211 1 : continue
212 : }
213 :
214 1 : f := v.Field(i)
215 1 : // TODO(peter): Use f.IsZero() when we can rely on go1.13.
216 1 : if zero := reflect.Zero(f.Type()); zero.Interface() == f.Interface() {
217 1 : // Skip printing of zero values which were not loaded from disk.
218 1 : if _, ok := loaded[ft.Offset]; !ok {
219 1 : continue
220 : }
221 : }
222 :
223 1 : fmt.Fprintf(buf, "%s: ", tag)
224 1 : switch ft.Type.Kind() {
225 0 : case reflect.Bool:
226 0 : fmt.Fprintf(buf, "%t\n", f.Bool())
227 1 : case reflect.Uint32:
228 1 : fmt.Fprintf(buf, "%d\n", f.Uint())
229 1 : case reflect.Uint64:
230 1 : fmt.Fprintf(buf, "%d\n", f.Uint())
231 1 : case reflect.String:
232 1 : fmt.Fprintf(buf, "%s\n", f.String())
233 0 : default:
234 0 : panic("not reached")
235 : }
236 : }
237 : }
238 :
239 1 : func (p *Properties) String() string {
240 1 : var buf bytes.Buffer
241 1 : v := reflect.ValueOf(*p)
242 1 : writeProperties(p.Loaded, v, &buf)
243 1 :
244 1 : // Write the UserProperties.
245 1 : keys := make([]string, 0, len(p.UserProperties))
246 1 : for key := range p.UserProperties {
247 1 : keys = append(keys, key)
248 1 : }
249 1 : sort.Strings(keys)
250 1 : for _, key := range keys {
251 1 : fmt.Fprintf(&buf, "%s: %s\n", key, p.UserProperties[key])
252 1 : }
253 1 : return buf.String()
254 : }
255 :
256 : func (p *Properties) load(
257 : b block, blockOffset uint64, deniedUserProperties map[string]struct{},
258 1 : ) error {
259 1 : i, err := newRawBlockIter(bytes.Compare, b)
260 1 : if err != nil {
261 0 : return err
262 0 : }
263 1 : p.Loaded = make(map[uintptr]struct{})
264 1 : v := reflect.ValueOf(p).Elem()
265 1 :
266 1 : for valid := i.First(); valid; valid = i.Next() {
267 1 : if f, ok := propTagMap[string(i.Key().UserKey)]; ok {
268 1 : p.Loaded[f.Offset] = struct{}{}
269 1 : field := v.FieldByIndex(f.Index)
270 1 : switch f.Type.Kind() {
271 1 : case reflect.Bool:
272 1 : field.SetBool(bytes.Equal(i.Value(), propBoolTrue))
273 1 : case reflect.Uint32:
274 1 : field.SetUint(uint64(binary.LittleEndian.Uint32(i.Value())))
275 1 : case reflect.Uint64:
276 1 : n, _ := binary.Uvarint(i.Value())
277 1 : field.SetUint(n)
278 1 : case reflect.String:
279 1 : field.SetString(intern.Bytes(i.Value()))
280 0 : default:
281 0 : panic("not reached")
282 : }
283 1 : continue
284 : }
285 1 : if p.UserProperties == nil {
286 1 : p.UserProperties = make(map[string]string)
287 1 : }
288 :
289 1 : if _, denied := deniedUserProperties[string(i.Key().UserKey)]; !denied {
290 1 : p.UserProperties[intern.Bytes(i.Key().UserKey)] = string(i.Value())
291 1 : }
292 : }
293 1 : return nil
294 : }
295 :
296 1 : func (p *Properties) saveBool(m map[string][]byte, offset uintptr, value bool) {
297 1 : tag := propOffsetTagMap[offset]
298 1 : if value {
299 1 : m[tag] = propBoolTrue
300 1 : } else {
301 0 : m[tag] = propBoolFalse
302 0 : }
303 : }
304 :
305 1 : func (p *Properties) saveUint32(m map[string][]byte, offset uintptr, value uint32) {
306 1 : var buf [4]byte
307 1 : binary.LittleEndian.PutUint32(buf[:], value)
308 1 : m[propOffsetTagMap[offset]] = buf[:]
309 1 : }
310 :
311 0 : func (p *Properties) saveUint64(m map[string][]byte, offset uintptr, value uint64) {
312 0 : var buf [8]byte
313 0 : binary.LittleEndian.PutUint64(buf[:], value)
314 0 : m[propOffsetTagMap[offset]] = buf[:]
315 0 : }
316 :
317 : var _ = (*Properties).saveUint64
318 :
319 1 : func (p *Properties) saveUvarint(m map[string][]byte, offset uintptr, value uint64) {
320 1 : var buf [10]byte
321 1 : n := binary.PutUvarint(buf[:], value)
322 1 : m[propOffsetTagMap[offset]] = buf[:n]
323 1 : }
324 :
325 1 : func (p *Properties) saveString(m map[string][]byte, offset uintptr, value string) {
326 1 : m[propOffsetTagMap[offset]] = []byte(value)
327 1 : }
328 :
329 1 : func (p *Properties) save(tblFormat TableFormat, w *rawBlockWriter) {
330 1 : m := make(map[string][]byte)
331 1 : for k, v := range p.UserProperties {
332 1 : m[k] = []byte(v)
333 1 : }
334 :
335 1 : if p.ComparerName != "" {
336 1 : p.saveString(m, unsafe.Offsetof(p.ComparerName), p.ComparerName)
337 1 : }
338 1 : if p.CompressionName != "" {
339 1 : p.saveString(m, unsafe.Offsetof(p.CompressionName), p.CompressionName)
340 1 : }
341 1 : if p.CompressionOptions != "" {
342 1 : p.saveString(m, unsafe.Offsetof(p.CompressionOptions), p.CompressionOptions)
343 1 : }
344 1 : p.saveUvarint(m, unsafe.Offsetof(p.DataSize), p.DataSize)
345 1 : if p.FilterPolicyName != "" {
346 1 : p.saveString(m, unsafe.Offsetof(p.FilterPolicyName), p.FilterPolicyName)
347 1 : }
348 1 : p.saveUvarint(m, unsafe.Offsetof(p.FilterSize), p.FilterSize)
349 1 : if p.IndexPartitions != 0 {
350 1 : p.saveUvarint(m, unsafe.Offsetof(p.IndexPartitions), p.IndexPartitions)
351 1 : p.saveUvarint(m, unsafe.Offsetof(p.TopLevelIndexSize), p.TopLevelIndexSize)
352 1 : }
353 1 : p.saveUvarint(m, unsafe.Offsetof(p.IndexSize), p.IndexSize)
354 1 : p.saveUint32(m, unsafe.Offsetof(p.IndexType), p.IndexType)
355 1 : if p.IsStrictObsolete {
356 1 : p.saveBool(m, unsafe.Offsetof(p.IsStrictObsolete), p.IsStrictObsolete)
357 1 : }
358 1 : if p.MergerName != "" {
359 1 : p.saveString(m, unsafe.Offsetof(p.MergerName), p.MergerName)
360 1 : }
361 1 : p.saveUvarint(m, unsafe.Offsetof(p.NumDataBlocks), p.NumDataBlocks)
362 1 : p.saveUvarint(m, unsafe.Offsetof(p.NumEntries), p.NumEntries)
363 1 : p.saveUvarint(m, unsafe.Offsetof(p.NumDeletions), p.NumDeletions)
364 1 : if p.NumSizedDeletions > 0 {
365 1 : p.saveUvarint(m, unsafe.Offsetof(p.NumSizedDeletions), p.NumSizedDeletions)
366 1 : }
367 1 : p.saveUvarint(m, unsafe.Offsetof(p.NumMergeOperands), p.NumMergeOperands)
368 1 : p.saveUvarint(m, unsafe.Offsetof(p.NumRangeDeletions), p.NumRangeDeletions)
369 1 : // NB: We only write out some properties for Pebble formats. This isn't
370 1 : // strictly necessary because unrecognized properties are interpreted as
371 1 : // user-defined properties, however writing them prevents byte-for-byte
372 1 : // equivalence with RocksDB files that some of our testing requires.
373 1 : if p.RawPointTombstoneKeySize > 0 && tblFormat >= TableFormatPebblev1 {
374 1 : p.saveUvarint(m, unsafe.Offsetof(p.RawPointTombstoneKeySize), p.RawPointTombstoneKeySize)
375 1 : }
376 1 : if p.RawPointTombstoneValueSize > 0 {
377 1 : p.saveUvarint(m, unsafe.Offsetof(p.RawPointTombstoneValueSize), p.RawPointTombstoneValueSize)
378 1 : }
379 1 : if p.NumRangeKeys() > 0 {
380 1 : p.saveUvarint(m, unsafe.Offsetof(p.NumRangeKeyDels), p.NumRangeKeyDels)
381 1 : p.saveUvarint(m, unsafe.Offsetof(p.NumRangeKeySets), p.NumRangeKeySets)
382 1 : p.saveUvarint(m, unsafe.Offsetof(p.NumRangeKeyUnsets), p.NumRangeKeyUnsets)
383 1 : p.saveUvarint(m, unsafe.Offsetof(p.RawRangeKeyKeySize), p.RawRangeKeyKeySize)
384 1 : p.saveUvarint(m, unsafe.Offsetof(p.RawRangeKeyValueSize), p.RawRangeKeyValueSize)
385 1 : }
386 1 : if p.NumValueBlocks > 0 {
387 1 : p.saveUvarint(m, unsafe.Offsetof(p.NumValueBlocks), p.NumValueBlocks)
388 1 : }
389 1 : if p.NumValuesInValueBlocks > 0 {
390 1 : p.saveUvarint(m, unsafe.Offsetof(p.NumValuesInValueBlocks), p.NumValuesInValueBlocks)
391 1 : }
392 1 : if p.PropertyCollectorNames != "" {
393 1 : p.saveString(m, unsafe.Offsetof(p.PropertyCollectorNames), p.PropertyCollectorNames)
394 1 : }
395 1 : if p.SnapshotPinnedKeys > 0 {
396 1 : p.saveUvarint(m, unsafe.Offsetof(p.SnapshotPinnedKeys), p.SnapshotPinnedKeys)
397 1 : p.saveUvarint(m, unsafe.Offsetof(p.SnapshotPinnedKeySize), p.SnapshotPinnedKeySize)
398 1 : p.saveUvarint(m, unsafe.Offsetof(p.SnapshotPinnedValueSize), p.SnapshotPinnedValueSize)
399 1 : }
400 1 : p.saveUvarint(m, unsafe.Offsetof(p.RawKeySize), p.RawKeySize)
401 1 : p.saveUvarint(m, unsafe.Offsetof(p.RawValueSize), p.RawValueSize)
402 1 : if p.ValueBlocksSize > 0 {
403 1 : p.saveUvarint(m, unsafe.Offsetof(p.ValueBlocksSize), p.ValueBlocksSize)
404 1 : }
405 :
406 1 : if tblFormat < TableFormatPebblev1 {
407 1 : m["rocksdb.column.family.id"] = binary.AppendUvarint([]byte(nil), math.MaxInt32)
408 1 : m["rocksdb.fixed.key.length"] = []byte{0x00}
409 1 : m["rocksdb.index.key.is.user.key"] = []byte{0x00}
410 1 : m["rocksdb.index.value.is.delta.encoded"] = []byte{0x00}
411 1 : m["rocksdb.oldest.key.time"] = []byte{0x00}
412 1 : m["rocksdb.creation.time"] = []byte{0x00}
413 1 : m["rocksdb.format.version"] = []byte{0x00}
414 1 : }
415 :
416 1 : keys := make([]string, 0, len(m))
417 1 : for key := range m {
418 1 : keys = append(keys, key)
419 1 : }
420 1 : sort.Strings(keys)
421 1 : for _, key := range keys {
422 1 : w.add(InternalKey{UserKey: []byte(key)}, m[key])
423 1 : }
424 : }
|