manifest.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. /*
  2. * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. package badger
  6. import (
  7. "bufio"
  8. "bytes"
  9. "encoding/binary"
  10. stderrors "errors"
  11. "fmt"
  12. "hash/crc32"
  13. "io"
  14. "math"
  15. "os"
  16. "path/filepath"
  17. "sync"
  18. "github.com/pkg/errors"
  19. "google.golang.org/protobuf/proto"
  20. "github.com/dgraph-io/badger/v4/options"
  21. "github.com/dgraph-io/badger/v4/pb"
  22. "github.com/dgraph-io/badger/v4/y"
  23. )
  24. // Manifest represents the contents of the MANIFEST file in a Badger store.
  25. //
  26. // The MANIFEST file describes the startup state of the db -- all LSM files and what level they're
  27. // at.
  28. //
  29. // It consists of a sequence of ManifestChangeSet objects. Each of these is treated atomically,
  30. // and contains a sequence of ManifestChange's (file creations/deletions) which we use to
  31. // reconstruct the manifest at startup.
  32. type Manifest struct {
  33. Levels []levelManifest
  34. Tables map[uint64]TableManifest
  35. // Contains total number of creation and deletion changes in the manifest -- used to compute
  36. // whether it'd be useful to rewrite the manifest.
  37. Creations int
  38. Deletions int
  39. }
  40. func createManifest() Manifest {
  41. levels := make([]levelManifest, 0)
  42. return Manifest{
  43. Levels: levels,
  44. Tables: make(map[uint64]TableManifest),
  45. }
  46. }
  47. // levelManifest contains information about LSM tree levels
  48. // in the MANIFEST file.
  49. type levelManifest struct {
  50. Tables map[uint64]struct{} // Set of table id's
  51. }
  52. // TableManifest contains information about a specific table
  53. // in the LSM tree.
  54. type TableManifest struct {
  55. Level uint8
  56. KeyID uint64
  57. Compression options.CompressionType
  58. }
  59. // manifestFile holds the file pointer (and other info) about the manifest file, which is a log
  60. // file we append to.
  61. type manifestFile struct {
  62. fp *os.File
  63. directory string
  64. // The external magic number used by the application running badger.
  65. externalMagic uint16
  66. // We make this configurable so that unit tests can hit rewrite() code quickly
  67. deletionsRewriteThreshold int
  68. // Guards appends, which includes access to the manifest field.
  69. appendLock sync.Mutex
  70. // Used to track the current state of the manifest, used when rewriting.
  71. manifest Manifest
  72. // Used to indicate if badger was opened in InMemory mode.
  73. inMemory bool
  74. }
  75. const (
  76. // ManifestFilename is the filename for the manifest file.
  77. ManifestFilename = "MANIFEST"
  78. manifestRewriteFilename = "MANIFEST-REWRITE"
  79. manifestDeletionsRewriteThreshold = 10000
  80. manifestDeletionsRatio = 10
  81. )
  82. // asChanges returns a sequence of changes that could be used to recreate the Manifest in its
  83. // present state.
  84. func (m *Manifest) asChanges() []*pb.ManifestChange {
  85. changes := make([]*pb.ManifestChange, 0, len(m.Tables))
  86. for id, tm := range m.Tables {
  87. changes = append(changes, newCreateChange(id, int(tm.Level), tm.KeyID, tm.Compression))
  88. }
  89. return changes
  90. }
  91. func (m *Manifest) clone() Manifest {
  92. changeSet := pb.ManifestChangeSet{Changes: m.asChanges()}
  93. ret := createManifest()
  94. y.Check(applyChangeSet(&ret, &changeSet))
  95. return ret
  96. }
  97. // openOrCreateManifestFile opens a Badger manifest file if it exists, or creates one if
  98. // doesn’t exists.
  99. func openOrCreateManifestFile(opt Options) (
  100. ret *manifestFile, result Manifest, err error) {
  101. if opt.InMemory {
  102. return &manifestFile{inMemory: true}, Manifest{}, nil
  103. }
  104. return helpOpenOrCreateManifestFile(opt.Dir, opt.ReadOnly, opt.ExternalMagicVersion,
  105. manifestDeletionsRewriteThreshold)
  106. }
  107. func helpOpenOrCreateManifestFile(dir string, readOnly bool, extMagic uint16,
  108. deletionsThreshold int) (*manifestFile, Manifest, error) {
  109. path := filepath.Join(dir, ManifestFilename)
  110. var flags y.Flags
  111. if readOnly {
  112. flags |= y.ReadOnly
  113. }
  114. fp, err := y.OpenExistingFile(path, flags) // We explicitly sync in addChanges, outside the lock.
  115. if err != nil {
  116. if !os.IsNotExist(err) {
  117. return nil, Manifest{}, err
  118. }
  119. if readOnly {
  120. return nil, Manifest{}, fmt.Errorf("no manifest found, required for read-only db")
  121. }
  122. m := createManifest()
  123. fp, netCreations, err := helpRewrite(dir, &m, extMagic)
  124. if err != nil {
  125. return nil, Manifest{}, err
  126. }
  127. y.AssertTrue(netCreations == 0)
  128. mf := &manifestFile{
  129. fp: fp,
  130. directory: dir,
  131. externalMagic: extMagic,
  132. manifest: m.clone(),
  133. deletionsRewriteThreshold: deletionsThreshold,
  134. }
  135. return mf, m, nil
  136. }
  137. manifest, truncOffset, err := ReplayManifestFile(fp, extMagic)
  138. if err != nil {
  139. _ = fp.Close()
  140. return nil, Manifest{}, err
  141. }
  142. if !readOnly {
  143. // Truncate file so we don't have a half-written entry at the end.
  144. if err := fp.Truncate(truncOffset); err != nil {
  145. _ = fp.Close()
  146. return nil, Manifest{}, err
  147. }
  148. }
  149. if _, err = fp.Seek(0, io.SeekEnd); err != nil {
  150. _ = fp.Close()
  151. return nil, Manifest{}, err
  152. }
  153. mf := &manifestFile{
  154. fp: fp,
  155. directory: dir,
  156. externalMagic: extMagic,
  157. manifest: manifest.clone(),
  158. deletionsRewriteThreshold: deletionsThreshold,
  159. }
  160. return mf, manifest, nil
  161. }
  162. func (mf *manifestFile) close() error {
  163. if mf.inMemory {
  164. return nil
  165. }
  166. return mf.fp.Close()
  167. }
  168. // addChanges writes a batch of changes, atomically, to the file. By "atomically" that means when
  169. // we replay the MANIFEST file, we'll either replay all the changes or none of them. (The truth of
  170. // this depends on the filesystem -- some might append garbage data if a system crash happens at
  171. // the wrong time.)
  172. func (mf *manifestFile) addChanges(changesParam []*pb.ManifestChange) error {
  173. if mf.inMemory {
  174. return nil
  175. }
  176. changes := pb.ManifestChangeSet{Changes: changesParam}
  177. buf, err := proto.Marshal(&changes)
  178. if err != nil {
  179. return err
  180. }
  181. // Maybe we could use O_APPEND instead (on certain file systems)
  182. mf.appendLock.Lock()
  183. defer mf.appendLock.Unlock()
  184. if err := applyChangeSet(&mf.manifest, &changes); err != nil {
  185. return err
  186. }
  187. // Rewrite manifest if it'd shrink by 1/10 and it's big enough to care
  188. if mf.manifest.Deletions > mf.deletionsRewriteThreshold &&
  189. mf.manifest.Deletions > manifestDeletionsRatio*(mf.manifest.Creations-mf.manifest.Deletions) {
  190. if err := mf.rewrite(); err != nil {
  191. return err
  192. }
  193. } else {
  194. var lenCrcBuf [8]byte
  195. binary.BigEndian.PutUint32(lenCrcBuf[0:4], uint32(len(buf)))
  196. binary.BigEndian.PutUint32(lenCrcBuf[4:8], crc32.Checksum(buf, y.CastagnoliCrcTable))
  197. buf = append(lenCrcBuf[:], buf...)
  198. if _, err := mf.fp.Write(buf); err != nil {
  199. return err
  200. }
  201. }
  202. return syncFunc(mf.fp)
  203. }
  204. // this function is saved here to allow injection of fake filesystem latency at test time.
  205. var syncFunc = func(f *os.File) error { return f.Sync() }
  206. // Has to be 4 bytes. The value can never change, ever, anyway.
  207. var magicText = [4]byte{'B', 'd', 'g', 'r'}
  208. // The magic version number. It is allocated 2 bytes, so it's value must be <= math.MaxUint16
  209. const badgerMagicVersion = 8
  210. func helpRewrite(dir string, m *Manifest, extMagic uint16) (*os.File, int, error) {
  211. rewritePath := filepath.Join(dir, manifestRewriteFilename)
  212. // We explicitly sync.
  213. fp, err := y.OpenTruncFile(rewritePath, false)
  214. if err != nil {
  215. return nil, 0, err
  216. }
  217. // magic bytes are structured as
  218. // +---------------------+-------------------------+-----------------------+
  219. // | magicText (4 bytes) | externalMagic (2 bytes) | badgerMagic (2 bytes) |
  220. // +---------------------+-------------------------+-----------------------+
  221. y.AssertTrue(badgerMagicVersion <= math.MaxUint16)
  222. buf := make([]byte, 8)
  223. copy(buf[0:4], magicText[:])
  224. binary.BigEndian.PutUint16(buf[4:6], extMagic)
  225. binary.BigEndian.PutUint16(buf[6:8], badgerMagicVersion)
  226. netCreations := len(m.Tables)
  227. changes := m.asChanges()
  228. set := pb.ManifestChangeSet{Changes: changes}
  229. changeBuf, err := proto.Marshal(&set)
  230. if err != nil {
  231. fp.Close()
  232. return nil, 0, err
  233. }
  234. var lenCrcBuf [8]byte
  235. binary.BigEndian.PutUint32(lenCrcBuf[0:4], uint32(len(changeBuf)))
  236. binary.BigEndian.PutUint32(lenCrcBuf[4:8], crc32.Checksum(changeBuf, y.CastagnoliCrcTable))
  237. buf = append(buf, lenCrcBuf[:]...)
  238. buf = append(buf, changeBuf...)
  239. if _, err := fp.Write(buf); err != nil {
  240. fp.Close()
  241. return nil, 0, err
  242. }
  243. if err := fp.Sync(); err != nil {
  244. fp.Close()
  245. return nil, 0, err
  246. }
  247. // In Windows the files should be closed before doing a Rename.
  248. if err = fp.Close(); err != nil {
  249. return nil, 0, err
  250. }
  251. manifestPath := filepath.Join(dir, ManifestFilename)
  252. if err := os.Rename(rewritePath, manifestPath); err != nil {
  253. return nil, 0, err
  254. }
  255. fp, err = y.OpenExistingFile(manifestPath, 0)
  256. if err != nil {
  257. return nil, 0, err
  258. }
  259. if _, err := fp.Seek(0, io.SeekEnd); err != nil {
  260. fp.Close()
  261. return nil, 0, err
  262. }
  263. if err := syncDir(dir); err != nil {
  264. fp.Close()
  265. return nil, 0, err
  266. }
  267. return fp, netCreations, nil
  268. }
  269. // Must be called while appendLock is held.
  270. func (mf *manifestFile) rewrite() error {
  271. // In Windows the files should be closed before doing a Rename.
  272. if err := mf.fp.Close(); err != nil {
  273. return err
  274. }
  275. fp, netCreations, err := helpRewrite(mf.directory, &mf.manifest, mf.externalMagic)
  276. if err != nil {
  277. return err
  278. }
  279. mf.fp = fp
  280. mf.manifest.Creations = netCreations
  281. mf.manifest.Deletions = 0
  282. return nil
  283. }
  284. type countingReader struct {
  285. wrapped *bufio.Reader
  286. count int64
  287. }
  288. func (r *countingReader) Read(p []byte) (n int, err error) {
  289. n, err = r.wrapped.Read(p)
  290. r.count += int64(n)
  291. return
  292. }
  293. func (r *countingReader) ReadByte() (b byte, err error) {
  294. b, err = r.wrapped.ReadByte()
  295. if err == nil {
  296. r.count++
  297. }
  298. return
  299. }
  300. var (
  301. errBadMagic = stderrors.New("manifest has bad magic")
  302. errBadChecksum = stderrors.New("manifest has checksum mismatch")
  303. )
  304. // ReplayManifestFile reads the manifest file and constructs two manifest objects. (We need one
  305. // immutable copy and one mutable copy of the manifest. Easiest way is to construct two of them.)
  306. // Also, returns the last offset after a completely read manifest entry -- the file must be
  307. // truncated at that point before further appends are made (if there is a partial entry after
  308. // that). In normal conditions, truncOffset is the file size.
  309. func ReplayManifestFile(fp *os.File, extMagic uint16) (Manifest, int64, error) {
  310. r := countingReader{wrapped: bufio.NewReader(fp)}
  311. var magicBuf [8]byte
  312. if _, err := io.ReadFull(&r, magicBuf[:]); err != nil {
  313. return Manifest{}, 0, errBadMagic
  314. }
  315. if !bytes.Equal(magicBuf[0:4], magicText[:]) {
  316. return Manifest{}, 0, errBadMagic
  317. }
  318. extVersion := y.BytesToU16(magicBuf[4:6])
  319. version := y.BytesToU16(magicBuf[6:8])
  320. if version != badgerMagicVersion {
  321. return Manifest{}, 0,
  322. //nolint:lll
  323. fmt.Errorf("manifest has unsupported version: %d (we support %d).\n"+
  324. "Please see https://docs.hypermode.com/badger/troubleshooting#i-see-manifest-has-unsupported-version-x-we-support-y-error"+
  325. " on how to fix this.",
  326. version, badgerMagicVersion)
  327. }
  328. if extVersion != extMagic {
  329. return Manifest{}, 0,
  330. fmt.Errorf("Cannot open DB because the external magic number doesn't match. "+
  331. "Expected: %d, version present in manifest: %d\n", extMagic, extVersion)
  332. }
  333. stat, err := fp.Stat()
  334. if err != nil {
  335. return Manifest{}, 0, err
  336. }
  337. build := createManifest()
  338. var offset int64
  339. for {
  340. offset = r.count
  341. var lenCrcBuf [8]byte
  342. _, err := io.ReadFull(&r, lenCrcBuf[:])
  343. if err != nil {
  344. if err == io.EOF || err == io.ErrUnexpectedEOF {
  345. break
  346. }
  347. return Manifest{}, 0, err
  348. }
  349. length := y.BytesToU32(lenCrcBuf[0:4])
  350. // Sanity check to ensure we don't over-allocate memory.
  351. if length > uint32(stat.Size()) {
  352. return Manifest{}, 0, errors.Errorf(
  353. "Buffer length: %d greater than file size: %d. Manifest file might be corrupted",
  354. length, stat.Size())
  355. }
  356. var buf = make([]byte, length)
  357. if _, err := io.ReadFull(&r, buf); err != nil {
  358. if err == io.EOF || err == io.ErrUnexpectedEOF {
  359. break
  360. }
  361. return Manifest{}, 0, err
  362. }
  363. if crc32.Checksum(buf, y.CastagnoliCrcTable) != y.BytesToU32(lenCrcBuf[4:8]) {
  364. return Manifest{}, 0, errBadChecksum
  365. }
  366. var changeSet pb.ManifestChangeSet
  367. if err := proto.Unmarshal(buf, &changeSet); err != nil {
  368. return Manifest{}, 0, err
  369. }
  370. if err := applyChangeSet(&build, &changeSet); err != nil {
  371. return Manifest{}, 0, err
  372. }
  373. }
  374. return build, offset, nil
  375. }
  376. func applyManifestChange(build *Manifest, tc *pb.ManifestChange) error {
  377. switch tc.Op {
  378. case pb.ManifestChange_CREATE:
  379. if _, ok := build.Tables[tc.Id]; ok {
  380. return fmt.Errorf("MANIFEST invalid, table %d exists", tc.Id)
  381. }
  382. build.Tables[tc.Id] = TableManifest{
  383. Level: uint8(tc.Level),
  384. KeyID: tc.KeyId,
  385. Compression: options.CompressionType(tc.Compression),
  386. }
  387. for len(build.Levels) <= int(tc.Level) {
  388. build.Levels = append(build.Levels, levelManifest{make(map[uint64]struct{})})
  389. }
  390. build.Levels[tc.Level].Tables[tc.Id] = struct{}{}
  391. build.Creations++
  392. case pb.ManifestChange_DELETE:
  393. tm, ok := build.Tables[tc.Id]
  394. if !ok {
  395. return fmt.Errorf("MANIFEST removes non-existing table %d", tc.Id)
  396. }
  397. delete(build.Levels[tm.Level].Tables, tc.Id)
  398. delete(build.Tables, tc.Id)
  399. build.Deletions++
  400. default:
  401. return fmt.Errorf("MANIFEST file has invalid manifestChange op")
  402. }
  403. return nil
  404. }
  405. // This is not a "recoverable" error -- opening the KV store fails because the MANIFEST file is
  406. // just plain broken.
  407. func applyChangeSet(build *Manifest, changeSet *pb.ManifestChangeSet) error {
  408. for _, change := range changeSet.Changes {
  409. if err := applyManifestChange(build, change); err != nil {
  410. return err
  411. }
  412. }
  413. return nil
  414. }
  415. func newCreateChange(
  416. id uint64, level int, keyID uint64, c options.CompressionType) *pb.ManifestChange {
  417. return &pb.ManifestChange{
  418. Id: id,
  419. Op: pb.ManifestChange_CREATE,
  420. Level: uint32(level),
  421. KeyId: keyID,
  422. // Hard coding it, since we're supporting only AES for now.
  423. EncryptionAlgo: pb.EncryptionAlgo_aes,
  424. Compression: uint32(c),
  425. }
  426. }
  427. func newDeleteChange(id uint64) *pb.ManifestChange {
  428. return &pb.ManifestChange{
  429. Id: id,
  430. Op: pb.ManifestChange_DELETE,
  431. }
  432. }