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