Debian Codegraph @

cmd/containerd-stargz-grpc/db/db.go

raw
1 /*
2 Copyright The containerd Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package db
18
19 import (
20 "encoding/binary"
21 "fmt"
22 "os"
23 "sort"
24
25 "github.com/containerd/stargz-snapshotter/metadata"
26 bolt "go.etcd.io/bbolt"
27 )
28
29 // Metadata package stores filesystem metadata in the following schema.
30 //
31 // - filesystems
32 // - *filesystem id* : bucket for each filesystem keyed by a unique string.
33 // - nodes
34 // - *node id* : bucket for each node keyed by a uniqe uint64.
35 // - size : <varint> : size of the regular node.
36 // - modtime : <varint> : modification time of the node.
37 // - linkName : <string> : link target of symlink
38 // - mode : <uvarint> : permission and mode bits (os.FileMode).
39 // - uid : <varint> : uid of the owner.
40 // - gid : <varint> : gid of the owner.
41 // - devMajor : <varint> : the major device number for device
42 // - devMinor : <varint> : the minor device number for device
43 // - xattrKey : <string> : key of the first extended attribute.
44 // - xattrValue : <string> : value of the first extended attribute
45 // - xattrsExtra : 2nd and the following extended attribute.
46 // - *key* : <string> : map of key to value string
47 // - numLink : <varint> : the number of links pointing to this node.
48 // - metadata
49 // - *node id* : bucket for each node keyed by a uniqe uint64.
50 // - childName : <string> : base name of the first child
51 // - childID : <node id> : id of the first child
52 // - childrenExtra : 2nd and following child nodes of directory.
53 // - *basename* : <node id> : map of basename string to the child node id
54 // - chunk : <encoded> : information of the first chunkn
55 // - chunksExtra : 2nd and following chunks (this is rarely used so we can avoid the cost of creating the bucket)
56 // - *chunk offset* : <encoded> : keyed by chunk offset (varint) in the estargz file to the chunk.
57 // - nextOffset : <varint> : the offset of the next node with a non-zero offset.
58 // - stream
59 // - *offset* : bucket for each chunk stream that have multiple inner chunks.
60 // - *innerOffset* : node id : node id that has the contents at the keyed innerOffset.
61
62 var (
63 bucketKeyFilesystems = []byte("filesystems")
64
65 bucketKeyNodes = []byte("nodes")
66 bucketKeySize = []byte("size")
67 bucketKeyModTime = []byte("modtime")
68 bucketKeyLinkName = []byte("linkName")
69 bucketKeyMode = []byte("mode")
70 bucketKeyUID = []byte("uid")
71 bucketKeyGID = []byte("gid")
72 bucketKeyDevMajor = []byte("devMajor")
73 bucketKeyDevMinor = []byte("devMinor")
74 bucketKeyXattrKey = []byte("xattrKey")
75 bucketKeyXattrValue = []byte("xattrValue")
76 bucketKeyXattrsExtra = []byte("xattrsExtra")
77 bucketKeyNumLink = []byte("numLink")
78
79 bucketKeyMetadata = []byte("metadata")
80 bucketKeyChildName = []byte("childName")
81 bucketKeyChildID = []byte("childID")
82 bucketKeyChildrenExtra = []byte("childrenExtra")
83 bucketKeyChunk = []byte("chunk")
84 bucketKeyChunksExtra = []byte("chunksExtra")
85 bucketKeyNextOffset = []byte("nextOffset")
86
87 bucketKeyStream = []byte("stream")
88 )
89
90 type childEntry struct {
91 base string
92 id uint32
93 }
94
95 type chunkEntry struct {
96 offset int64
97 chunkOffset int64
98 chunkSize int64
99 chunkDigest string
100 innerOffset int64 // -1 indicates that no following chunks in the stream.
101 }
102
103 type metadataEntry struct {
104 children map[string]childEntry
105 chunks []chunkEntry
106 nextOffset int64
107 }
108
109 func getNodes(tx *bolt.Tx, fsID string) (*bolt.Bucket, error) {
110 filesystems := tx.Bucket(bucketKeyFilesystems)
111 if filesystems == nil {
112 return nil, fmt.Errorf("fs %q not found: no fs is registered", fsID)
113 }
114 lbkt := filesystems.Bucket([]byte(fsID))
115 if lbkt == nil {
116 return nil, fmt.Errorf("fs bucket for %q not found", fsID)
117 }
118 nodes := lbkt.Bucket(bucketKeyNodes)
119 if nodes == nil {
120 return nil, fmt.Errorf("nodes bucket for %q not found", fsID)
121 }
122 return nodes, nil
123 }
124
125 func getMetadata(tx *bolt.Tx, fsID string) (*bolt.Bucket, error) {
126 filesystems := tx.Bucket(bucketKeyFilesystems)
127 if filesystems == nil {
128 return nil, fmt.Errorf("fs %q not found: no fs is registered", fsID)
129 }
130 lbkt := filesystems.Bucket([]byte(fsID))
131 if lbkt == nil {
132 return nil, fmt.Errorf("fs bucket for %q not found", fsID)
133 }
134 md := lbkt.Bucket(bucketKeyMetadata)
135 if md == nil {
136 return nil, fmt.Errorf("metadata bucket for fs %q not found", fsID)
137 }
138 return md, nil
139 }
140
141 func getStream(tx *bolt.Tx, fsID string) (*bolt.Bucket, error) {
142 filesystems := tx.Bucket(bucketKeyFilesystems)
143 if filesystems == nil {
144 return nil, fmt.Errorf("fs %q not found: no fs is registered", fsID)
145 }
146 lbkt := filesystems.Bucket([]byte(fsID))
147 if lbkt == nil {
148 return nil, fmt.Errorf("fs bucket for %q not found", fsID)
149 }
150 st := lbkt.Bucket(bucketKeyStream)
151 if st == nil {
152 return nil, fmt.Errorf("stream bucket for fs %q not found", fsID)
153 }
154 return st, nil
155 }
156
157 func getNodeBucketByID(nodes *bolt.Bucket, id uint32) (*bolt.Bucket, error) {
158 b := nodes.Bucket(encodeID(id))
159 if b == nil {
160 return nil, fmt.Errorf("node bucket for %d not found", id)
161 }
162 return b, nil
163 }
164
165 func getMetadataBucketByID(md *bolt.Bucket, id uint32) (*bolt.Bucket, error) {
166 b := md.Bucket(encodeID(id))
167 if b == nil {
168 return nil, fmt.Errorf("metadata bucket for %d not found", id)
169 }
170 return b, nil
171 }
172
173 func writeAttr(b *bolt.Bucket, attr *metadata.Attr) error {
174 for _, v := range []struct {
175 key []byte
176 val int64
177 }{
178 {bucketKeySize, attr.Size},
179 {bucketKeyUID, int64(attr.UID)},
180 {bucketKeyGID, int64(attr.GID)},
181 {bucketKeyDevMajor, int64(attr.DevMajor)},
182 {bucketKeyDevMinor, int64(attr.DevMinor)},
183 {bucketKeyNumLink, int64(attr.NumLink - 1)}, // numLink = 0 means num link = 1 in DB
184 } {
185 if v.val != 0 {
186 val, err := encodeInt(v.val)
187 if err != nil {
188 return err
189 }
190 if err := b.Put(v.key, val); err != nil {
191 return err
192 }
193 }
194 }
195 if !attr.ModTime.IsZero() {
196 te, err := attr.ModTime.GobEncode()
197 if err != nil {
198 return err
199 }
200 if err := b.Put(bucketKeyModTime, te); err != nil {
201 return err
202 }
203 }
204 if len(attr.LinkName) > 0 {
205 if err := b.Put(bucketKeyLinkName, []byte(attr.LinkName)); err != nil {
206 return err
207 }
208 }
209 if attr.Mode != 0 {
210 val, err := encodeUint(uint64(attr.Mode))
211 if err != nil {
212 return err
213 }
214 if err := b.Put(bucketKeyMode, val); err != nil {
215 return err
216 }
217 }
218 if len(attr.Xattrs) > 0 {
219 var firstK string
220 var firstV []byte
221 for k, v := range attr.Xattrs {
222 firstK, firstV = k, v
223 break
224 }
225 if err := b.Put(bucketKeyXattrKey, []byte(firstK)); err != nil {
226 return err
227 }
228 if err := b.Put(bucketKeyXattrValue, firstV); err != nil {
229 return err
230 }
231 var xbkt *bolt.Bucket
232 for k, v := range attr.Xattrs {
233 if k == firstK || len(v) == 0 {
234 continue
235 }
236 if xbkt == nil {
237 if xbkt := b.Bucket(bucketKeyXattrsExtra); xbkt != nil {
238 // Reset
239 if err := b.DeleteBucket(bucketKeyXattrsExtra); err != nil {
240 return err
241 }
242 }
243 var err error
244 xbkt, err = b.CreateBucket(bucketKeyXattrsExtra)
245 if err != nil {
246 return err
247 }
248 }
249 if err := xbkt.Put([]byte(k), v); err != nil {
250 return fmt.Errorf("failed to set xattr %q=%q: %w", k, string(v), err)
251 }
252 }
253 }
254
255 return nil
256 }
257
258 func readAttr(b *bolt.Bucket, attr *metadata.Attr) error {
259 return b.ForEach(func(k, v []byte) error {
260 switch string(k) {
261 case string(bucketKeySize):
262 attr.Size, _ = binary.Varint(v)
263 case string(bucketKeyModTime):
264 if err := (&attr.ModTime).GobDecode(v); err != nil {
265 return err
266 }
267 case string(bucketKeyLinkName):
268 attr.LinkName = string(v)
269 case string(bucketKeyMode):
270 mode, _ := binary.Uvarint(v)
271 attr.Mode = os.FileMode(uint32(mode))
272 case string(bucketKeyUID):
273 i, _ := binary.Varint(v)
274 attr.UID = int(i)
275 case string(bucketKeyGID):
276 i, _ := binary.Varint(v)
277 attr.GID = int(i)
278 case string(bucketKeyDevMajor):
279 i, _ := binary.Varint(v)
280 attr.DevMajor = int(i)
281 case string(bucketKeyDevMinor):
282 i, _ := binary.Varint(v)
283 attr.DevMinor = int(i)
284 case string(bucketKeyNumLink):
285 i, _ := binary.Varint(v)
286 attr.NumLink = int(i) + 1 // numLink = 0 means num link = 1 in DB
287 case string(bucketKeyXattrKey):
288 if attr.Xattrs == nil {
289 attr.Xattrs = make(map[string][]byte)
290 }
291 attr.Xattrs[string(v)] = b.Get(bucketKeyXattrValue)
292 case string(bucketKeyXattrsExtra):
293 if err := b.Bucket(k).ForEach(func(k, v []byte) error {
294 if attr.Xattrs == nil {
295 attr.Xattrs = make(map[string][]byte)
296 }
297 attr.Xattrs[string(k)] = v
298 return nil
299 }); err != nil {
300 return err
301 }
302 }
303 return nil
304 })
305 }
306
307 func readNumLink(b *bolt.Bucket) int {
308 // numLink = 0 means num link = 1 in BD
309 numLink, _ := binary.Varint(b.Get(bucketKeyNumLink))
310 return int(numLink) + 1
311 }
312
313 func readChunks(b *bolt.Bucket, size int64) (chunks []chunkEntry, err error) {
314 if chunk := b.Get(bucketKeyChunk); len(chunk) > 0 {
315 e, err := decodeChunkEntry(chunk)
316 if err != nil {
317 return nil, err
318 }
319 chunks = append(chunks, e)
320 }
321 if chbkt := b.Bucket(bucketKeyChunksExtra); chbkt != nil {
322 if err := chbkt.ForEach(func(_, v []byte) error {
323 e, err := decodeChunkEntry(v)
324 if err != nil {
325 return err
326 }
327 chunks = append(chunks, e)
328 return nil
329 }); err != nil {
330 return nil, err
331 }
332 sort.Slice(chunks, func(i, j int) bool {
333 return chunks[i].chunkOffset < chunks[j].chunkOffset
334 })
335 }
336 nextOffset := size
337 for i := len(chunks) - 1; i >= 0; i-- {
338 chunks[i].chunkSize = nextOffset - chunks[i].chunkOffset
339 nextOffset = chunks[i].chunkOffset
340 }
341 return
342 }
343
344 type chunkEntryWithID struct {
345 chunkEntry
346 id uint32
347 }
348
349 func readInnerChunks(tx *bolt.Tx, fsID string, off int64) (chunks []chunkEntryWithID, err error) {
350 sb, err := getStream(tx, fsID)
351 if err != nil {
352 return nil, err
353 }
354 offEncoded, err := encodeInt(off)
355 if err != nil {
356 return nil, err
357 }
358 ob := sb.Bucket(offEncoded)
359 if ob == nil {
360 return nil, fmt.Errorf("inner chunk bucket for %d not found", off)
361 }
362 nodes, err := getNodes(tx, fsID)
363 if err != nil {
364 return nil, fmt.Errorf("nodes bucket of %q not found: %w", fsID, err)
365 }
366 metadataEntries, err := getMetadata(tx, fsID)
367 if err != nil {
368 return nil, fmt.Errorf("metadata bucket of %q not found: %w", fsID, err)
369 }
370 if err := ob.ForEach(func(_, v []byte) error {
371 nodeid := decodeID(v)
372 b, err := getNodeBucketByID(nodes, nodeid)
373 if err != nil {
374 return fmt.Errorf("failed to get file bucket %d: %w", nodeid, err)
375 }
376 size, _ := binary.Varint(b.Get(bucketKeySize))
377 if md, err := getMetadataBucketByID(metadataEntries, nodeid); err == nil {
378 nodeChunks, err := readChunks(md, size)
379 if err != nil {
380 return fmt.Errorf("failed to get chunks: %w", err)
381 }
382 for _, e := range nodeChunks {
383 if e.offset == off {
384 chunks = append(chunks, chunkEntryWithID{e, nodeid})
385 }
386 }
387 }
388 return nil
389 }); err != nil {
390 return nil, err
391 }
392 sort.Slice(chunks, func(i, j int) bool {
393 return chunks[i].innerOffset < chunks[j].innerOffset
394 })
395 return chunks, nil
396 }
397
398 func readChild(md *bolt.Bucket, base string) (uint32, error) {
399 if base == string(md.Get(bucketKeyChildName)) {
400 return decodeID(md.Get(bucketKeyChildID)), nil
401 }
402 cbkt := md.Bucket(bucketKeyChildrenExtra)
403 if cbkt == nil {
404 return 0, fmt.Errorf("extra children not found")
405 }
406 eid := cbkt.Get([]byte(base))
407 if len(eid) == 0 {
408 return 0, fmt.Errorf("children %q not found", base)
409 }
410 return decodeID(eid), nil
411 }
412
413 func writeMetadataEntry(md *bolt.Bucket, m *metadataEntry) error {
414 if len(m.children) > 0 {
415 var firstChildName string
416 var firstChild childEntry
417 for name, child := range m.children {
418 firstChildName, firstChild = name, child
419 break
420 }
421 if err := md.Put(bucketKeyChildID, encodeID(firstChild.id)); err != nil {
422 return fmt.Errorf("failed to put id of first child %q: %w", firstChildName, err)
423 }
424 if err := md.Put(bucketKeyChildName, []byte(firstChildName)); err != nil {
425 return fmt.Errorf("failed to put name first child %q: %w", firstChildName, err)
426 }
427 if len(m.children) > 1 {
428 var cbkt *bolt.Bucket
429 for k, c := range m.children {
430 if k == firstChildName {
431 continue
432 }
433 if cbkt == nil {
434 if cbkt := md.Bucket(bucketKeyChildrenExtra); cbkt != nil {
435 // Reset
436 if err := md.DeleteBucket(bucketKeyChildrenExtra); err != nil {
437 return err
438 }
439 }
440 var err error
441 cbkt, err = md.CreateBucket(bucketKeyChildrenExtra)
442 if err != nil {
443 return err
444 }
445 }
446 if err := cbkt.Put([]byte(c.base), encodeID(c.id)); err != nil {
447 return fmt.Errorf("failed to add child ID %q: %w", c.id, err)
448 }
449 }
450 }
451 }
452 if len(m.chunks) > 0 {
453 first := m.chunks[0]
454 if err := md.Put(bucketKeyChunk, encodeChunkEntry(first)); err != nil {
455 return fmt.Errorf("failed to set chunk %q: %w", first.offset, err)
456 }
457 var cbkt *bolt.Bucket
458 for _, e := range m.chunks[1:] {
459 if cbkt == nil {
460 if cbkt := md.Bucket(bucketKeyChunksExtra); cbkt != nil {
461 // Reset
462 if err := md.DeleteBucket(bucketKeyChunksExtra); err != nil {
463 return err
464 }
465 }
466 var err error
467 cbkt, err = md.CreateBucket(bucketKeyChunksExtra)
468 if err != nil {
469 return err
470 }
471 }
472 ecoff, err := encodeInt(e.chunkOffset)
473 if err != nil {
474 return err
475 }
476 if err := cbkt.Put(ecoff, encodeChunkEntry(e)); err != nil {
477 return err
478 }
479 }
480 }
481 if m.nextOffset > 0 {
482 if err := putInt(md, bucketKeyNextOffset, m.nextOffset); err != nil {
483 return fmt.Errorf("failed to set next offset value %d: %w", m.nextOffset, err)
484 }
485 }
486 return nil
487 }
488
489 func encodeChunkEntry(e chunkEntry) []byte {
490 eb := make([]byte, 24+len([]byte(e.chunkDigest)))
491 binary.BigEndian.PutUint64(eb[0:8], uint64(e.chunkOffset))
492 binary.BigEndian.PutUint64(eb[8:16], uint64(e.offset))
493 binary.BigEndian.PutUint64(eb[16:24], uint64(e.innerOffset))
494 copy(eb[24:], []byte(e.chunkDigest))
495 return eb
496 }
497
498 func decodeChunkEntry(d []byte) (e chunkEntry, _ error) {
499 if len(d) < 24 {
500 return e, fmt.Errorf("mulformed chunk entry (len:%d)", len(d))
501 }
502 e.chunkOffset = int64(binary.BigEndian.Uint64(d[0:8]))
503 e.offset = int64(binary.BigEndian.Uint64(d[8:16]))
504 e.innerOffset = int64(binary.BigEndian.Uint64(d[16:24]))
505 if len(d) > 24 {
506 e.chunkDigest = string(d[24:])
507 }
508 return e, nil
509 }
510
511 func putInt(b *bolt.Bucket, k []byte, v int64) error {
512 i, err := encodeInt(v)
513 if err != nil {
514 return err
515 }
516 return b.Put(k, i)
517 }
518
519 func encodeID(id uint32) []byte {
520 b := [4]byte{}
521 binary.BigEndian.PutUint32(b[:], id)
522 return b[:]
523 }
524
525 func decodeID(b []byte) uint32 {
526 return binary.BigEndian.Uint32(b)
527 }
528
529 func encodeInt(i int64) ([]byte, error) {
530 var (
531 buf [binary.MaxVarintLen64]byte
532 iEncoded = buf[:]
533 )
534 iEncoded = iEncoded[:binary.PutVarint(iEncoded, i)]
535
536 if len(iEncoded) == 0 {
537 return nil, fmt.Errorf("failed encoding integer = %v", i)
538 }
539 return iEncoded, nil
540 }
541
542 func encodeUint(i uint64) ([]byte, error) {
543 var (
544 buf [binary.MaxVarintLen64]byte
545 iEncoded = buf[:]
546 )
547 iEncoded = iEncoded[:binary.PutUvarint(iEncoded, i)]
548
549 if len(iEncoded) == 0 {
550 return nil, fmt.Errorf("failed encoding integer = %v", i)
551 }
552 return iEncoded, nil
553 }