value.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. /*
  2. * Copyright 2017 Dgraph Labs, Inc. and Contributors
  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. package badger
  17. import (
  18. "bufio"
  19. "bytes"
  20. "encoding/binary"
  21. "fmt"
  22. "hash/crc32"
  23. "io"
  24. "io/ioutil"
  25. "log"
  26. "math"
  27. "math/rand"
  28. "os"
  29. "sort"
  30. "strconv"
  31. "strings"
  32. "sync"
  33. "sync/atomic"
  34. "time"
  35. "github.com/dgraph-io/badger/options"
  36. "github.com/dgraph-io/badger/y"
  37. "github.com/pkg/errors"
  38. "golang.org/x/net/trace"
  39. )
  40. // Values have their first byte being byteData or byteDelete. This helps us distinguish between
  41. // a key that has never been seen and a key that has been explicitly deleted.
  42. const (
  43. bitDelete byte = 1 << 0 // Set if the key has been deleted.
  44. bitValuePointer byte = 1 << 1 // Set if the value is NOT stored directly next to key.
  45. bitDiscardEarlierVersions byte = 1 << 2 // Set if earlier versions can be discarded.
  46. // The MSB 2 bits are for transactions.
  47. bitTxn byte = 1 << 6 // Set if the entry is part of a txn.
  48. bitFinTxn byte = 1 << 7 // Set if the entry is to indicate end of txn in value log.
  49. mi int64 = 1 << 20
  50. )
  51. type logFile struct {
  52. path string
  53. // This is a lock on the log file. It guards the fd’s value, the file’s
  54. // existence and the file’s memory map.
  55. //
  56. // Use shared ownership when reading/writing the file or memory map, use
  57. // exclusive ownership to open/close the descriptor, unmap or remove the file.
  58. lock sync.RWMutex
  59. fd *os.File
  60. fid uint32
  61. fmap []byte
  62. size uint32
  63. loadingMode options.FileLoadingMode
  64. }
  65. // openReadOnly assumes that we have a write lock on logFile.
  66. func (lf *logFile) openReadOnly() error {
  67. var err error
  68. lf.fd, err = os.OpenFile(lf.path, os.O_RDONLY, 0666)
  69. if err != nil {
  70. return errors.Wrapf(err, "Unable to open %q as RDONLY.", lf.path)
  71. }
  72. fi, err := lf.fd.Stat()
  73. if err != nil {
  74. return errors.Wrapf(err, "Unable to check stat for %q", lf.path)
  75. }
  76. lf.size = uint32(fi.Size())
  77. if err = lf.mmap(fi.Size()); err != nil {
  78. _ = lf.fd.Close()
  79. return y.Wrapf(err, "Unable to map file")
  80. }
  81. return nil
  82. }
  83. func (lf *logFile) mmap(size int64) (err error) {
  84. if lf.loadingMode != options.MemoryMap {
  85. // Nothing to do
  86. return nil
  87. }
  88. lf.fmap, err = y.Mmap(lf.fd, false, size)
  89. if err == nil {
  90. err = y.Madvise(lf.fmap, false) // Disable readahead
  91. }
  92. return err
  93. }
  94. func (lf *logFile) munmap() (err error) {
  95. if lf.loadingMode != options.MemoryMap {
  96. // Nothing to do
  97. return nil
  98. }
  99. if err := y.Munmap(lf.fmap); err != nil {
  100. return errors.Wrapf(err, "Unable to munmap value log: %q", lf.path)
  101. }
  102. return nil
  103. }
  104. // Acquire lock on mmap/file if you are calling this
  105. func (lf *logFile) read(p valuePointer, s *y.Slice) (buf []byte, err error) {
  106. var nbr int64
  107. offset := p.Offset
  108. if lf.loadingMode == options.FileIO {
  109. buf = s.Resize(int(p.Len))
  110. var n int
  111. n, err = lf.fd.ReadAt(buf, int64(offset))
  112. nbr = int64(n)
  113. } else {
  114. size := uint32(len(lf.fmap))
  115. valsz := p.Len
  116. if offset >= size || offset+valsz > size {
  117. err = y.ErrEOF
  118. } else {
  119. buf = lf.fmap[offset : offset+valsz]
  120. nbr = int64(valsz)
  121. }
  122. }
  123. y.NumReads.Add(1)
  124. y.NumBytesRead.Add(nbr)
  125. return buf, err
  126. }
  127. func (lf *logFile) doneWriting(offset uint32) error {
  128. // Sync before acquiring lock. (We call this from write() and thus know we have shared access
  129. // to the fd.)
  130. if err := lf.fd.Sync(); err != nil {
  131. return errors.Wrapf(err, "Unable to sync value log: %q", lf.path)
  132. }
  133. // Close and reopen the file read-only. Acquire lock because fd will become invalid for a bit.
  134. // Acquiring the lock is bad because, while we don't hold the lock for a long time, it forces
  135. // one batch of readers wait for the preceding batch of readers to finish.
  136. //
  137. // If there's a benefit to reopening the file read-only, it might be on Windows. I don't know
  138. // what the benefit is. Consider keeping the file read-write, or use fcntl to change
  139. // permissions.
  140. lf.lock.Lock()
  141. defer lf.lock.Unlock()
  142. if err := lf.munmap(); err != nil {
  143. return err
  144. }
  145. // TODO: Confirm if we need to run a file sync after truncation.
  146. // Truncation must run after unmapping, otherwise Windows would crap itself.
  147. if err := lf.fd.Truncate(int64(offset)); err != nil {
  148. return errors.Wrapf(err, "Unable to truncate file: %q", lf.path)
  149. }
  150. if err := lf.fd.Close(); err != nil {
  151. return errors.Wrapf(err, "Unable to close value log: %q", lf.path)
  152. }
  153. return lf.openReadOnly()
  154. }
  155. // You must hold lf.lock to sync()
  156. func (lf *logFile) sync() error {
  157. return lf.fd.Sync()
  158. }
  159. var errStop = errors.New("Stop iteration")
  160. var errTruncate = errors.New("Do truncate")
  161. type logEntry func(e Entry, vp valuePointer) error
  162. type safeRead struct {
  163. k []byte
  164. v []byte
  165. recordOffset uint32
  166. }
  167. func (r *safeRead) Entry(reader *bufio.Reader) (*Entry, error) {
  168. var hbuf [headerBufSize]byte
  169. var err error
  170. hash := crc32.New(y.CastagnoliCrcTable)
  171. tee := io.TeeReader(reader, hash)
  172. if _, err = io.ReadFull(tee, hbuf[:]); err != nil {
  173. return nil, err
  174. }
  175. var h header
  176. h.Decode(hbuf[:])
  177. if h.klen > maxKeySize {
  178. return nil, errTruncate
  179. }
  180. kl := int(h.klen)
  181. if cap(r.k) < kl {
  182. r.k = make([]byte, 2*kl)
  183. }
  184. vl := int(h.vlen)
  185. if cap(r.v) < vl {
  186. r.v = make([]byte, 2*vl)
  187. }
  188. e := &Entry{}
  189. e.offset = r.recordOffset
  190. e.Key = r.k[:kl]
  191. e.Value = r.v[:vl]
  192. if _, err = io.ReadFull(tee, e.Key); err != nil {
  193. if err == io.EOF {
  194. err = errTruncate
  195. }
  196. return nil, err
  197. }
  198. if _, err = io.ReadFull(tee, e.Value); err != nil {
  199. if err == io.EOF {
  200. err = errTruncate
  201. }
  202. return nil, err
  203. }
  204. var crcBuf [4]byte
  205. if _, err = io.ReadFull(reader, crcBuf[:]); err != nil {
  206. if err == io.EOF {
  207. err = errTruncate
  208. }
  209. return nil, err
  210. }
  211. crc := binary.BigEndian.Uint32(crcBuf[:])
  212. if crc != hash.Sum32() {
  213. return nil, errTruncate
  214. }
  215. e.meta = h.meta
  216. e.UserMeta = h.userMeta
  217. e.ExpiresAt = h.expiresAt
  218. return e, nil
  219. }
  220. // iterate iterates over log file. It doesn't not allocate new memory for every kv pair.
  221. // Therefore, the kv pair is only valid for the duration of fn call.
  222. func (vlog *valueLog) iterate(lf *logFile, offset uint32, fn logEntry) error {
  223. _, err := lf.fd.Seek(int64(offset), io.SeekStart)
  224. if err != nil {
  225. return y.Wrap(err)
  226. }
  227. reader := bufio.NewReader(lf.fd)
  228. read := &safeRead{
  229. k: make([]byte, 10),
  230. v: make([]byte, 10),
  231. recordOffset: offset,
  232. }
  233. truncate := false
  234. var lastCommit uint64
  235. var validEndOffset uint32
  236. for {
  237. e, err := read.Entry(reader)
  238. if err == io.EOF {
  239. break
  240. } else if err == io.ErrUnexpectedEOF || err == errTruncate {
  241. truncate = true
  242. break
  243. } else if err != nil {
  244. return err
  245. } else if e == nil {
  246. continue
  247. }
  248. var vp valuePointer
  249. vp.Len = uint32(headerBufSize + len(e.Key) + len(e.Value) + 4) // len(crcBuf)
  250. read.recordOffset += vp.Len
  251. vp.Offset = e.offset
  252. vp.Fid = lf.fid
  253. if e.meta&bitTxn > 0 {
  254. txnTs := y.ParseTs(e.Key)
  255. if lastCommit == 0 {
  256. lastCommit = txnTs
  257. }
  258. if lastCommit != txnTs {
  259. truncate = true
  260. break
  261. }
  262. } else if e.meta&bitFinTxn > 0 {
  263. txnTs, err := strconv.ParseUint(string(e.Value), 10, 64)
  264. if err != nil || lastCommit != txnTs {
  265. truncate = true
  266. break
  267. }
  268. // Got the end of txn. Now we can store them.
  269. lastCommit = 0
  270. validEndOffset = read.recordOffset
  271. } else {
  272. if lastCommit != 0 {
  273. // This is most likely an entry which was moved as part of GC.
  274. // We shouldn't get this entry in the middle of a transaction.
  275. truncate = true
  276. break
  277. }
  278. validEndOffset = read.recordOffset
  279. }
  280. if vlog.opt.ReadOnly {
  281. return ErrReplayNeeded
  282. }
  283. if err := fn(*e, vp); err != nil {
  284. if err == errStop {
  285. break
  286. }
  287. return y.Wrap(err)
  288. }
  289. }
  290. if vlog.opt.Truncate && truncate && len(lf.fmap) == 0 {
  291. // Only truncate if the file isn't mmaped. Otherwise, Windows would puke.
  292. if err := lf.fd.Truncate(int64(validEndOffset)); err != nil {
  293. return err
  294. }
  295. } else if truncate {
  296. return ErrTruncateNeeded
  297. }
  298. return nil
  299. }
  300. func (vlog *valueLog) rewrite(f *logFile, tr trace.Trace) error {
  301. maxFid := atomic.LoadUint32(&vlog.maxFid)
  302. y.AssertTruef(uint32(f.fid) < maxFid, "fid to move: %d. Current max fid: %d", f.fid, maxFid)
  303. tr.LazyPrintf("Rewriting fid: %d", f.fid)
  304. wb := make([]*Entry, 0, 1000)
  305. var size int64
  306. y.AssertTrue(vlog.kv != nil)
  307. var count, moved int
  308. fe := func(e Entry) error {
  309. count++
  310. if count%100000 == 0 {
  311. tr.LazyPrintf("Processing entry %d", count)
  312. }
  313. vs, err := vlog.kv.get(e.Key)
  314. if err != nil {
  315. return err
  316. }
  317. if discardEntry(e, vs) {
  318. return nil
  319. }
  320. // Value is still present in value log.
  321. if len(vs.Value) == 0 {
  322. return errors.Errorf("Empty value: %+v", vs)
  323. }
  324. var vp valuePointer
  325. vp.Decode(vs.Value)
  326. if vp.Fid > f.fid {
  327. return nil
  328. }
  329. if vp.Offset > e.offset {
  330. return nil
  331. }
  332. if vp.Fid == f.fid && vp.Offset == e.offset {
  333. moved++
  334. // This new entry only contains the key, and a pointer to the value.
  335. ne := new(Entry)
  336. ne.meta = 0 // Remove all bits. Different keyspace doesn't need these bits.
  337. ne.UserMeta = e.UserMeta
  338. // Create a new key in a separate keyspace, prefixed by moveKey. We are not
  339. // allowed to rewrite an older version of key in the LSM tree, because then this older
  340. // version would be at the top of the LSM tree. To work correctly, reads expect the
  341. // latest versions to be at the top, and the older versions at the bottom.
  342. if bytes.HasPrefix(e.Key, badgerMove) {
  343. ne.Key = append([]byte{}, e.Key...)
  344. } else {
  345. ne.Key = append([]byte{}, badgerMove...)
  346. ne.Key = append(ne.Key, e.Key...)
  347. }
  348. ne.Value = append([]byte{}, e.Value...)
  349. wb = append(wb, ne)
  350. size += int64(e.estimateSize(vlog.opt.ValueThreshold))
  351. if size >= 64*mi {
  352. tr.LazyPrintf("request has %d entries, size %d", len(wb), size)
  353. if err := vlog.kv.batchSet(wb); err != nil {
  354. return err
  355. }
  356. size = 0
  357. wb = wb[:0]
  358. }
  359. } else {
  360. log.Printf("WARNING: This entry should have been caught. %+v\n", e)
  361. }
  362. return nil
  363. }
  364. err := vlog.iterate(f, 0, func(e Entry, vp valuePointer) error {
  365. return fe(e)
  366. })
  367. if err != nil {
  368. return err
  369. }
  370. tr.LazyPrintf("request has %d entries, size %d", len(wb), size)
  371. batchSize := 1024
  372. var loops int
  373. for i := 0; i < len(wb); {
  374. loops++
  375. if batchSize == 0 {
  376. log.Printf("WARNING: We shouldn't reach batch size of zero.")
  377. return ErrNoRewrite
  378. }
  379. end := i + batchSize
  380. if end > len(wb) {
  381. end = len(wb)
  382. }
  383. if err := vlog.kv.batchSet(wb[i:end]); err != nil {
  384. if err == ErrTxnTooBig {
  385. // Decrease the batch size to half.
  386. batchSize = batchSize / 2
  387. tr.LazyPrintf("Dropped batch size to %d", batchSize)
  388. continue
  389. }
  390. return err
  391. }
  392. i += batchSize
  393. }
  394. tr.LazyPrintf("Processed %d entries in %d loops", len(wb), loops)
  395. tr.LazyPrintf("Total entries: %d. Moved: %d", count, moved)
  396. tr.LazyPrintf("Removing fid: %d", f.fid)
  397. var deleteFileNow bool
  398. // Entries written to LSM. Remove the older file now.
  399. {
  400. vlog.filesLock.Lock()
  401. // Just a sanity-check.
  402. if _, ok := vlog.filesMap[f.fid]; !ok {
  403. vlog.filesLock.Unlock()
  404. return errors.Errorf("Unable to find fid: %d", f.fid)
  405. }
  406. if vlog.numActiveIterators == 0 {
  407. delete(vlog.filesMap, f.fid)
  408. deleteFileNow = true
  409. } else {
  410. vlog.filesToBeDeleted = append(vlog.filesToBeDeleted, f.fid)
  411. }
  412. vlog.filesLock.Unlock()
  413. }
  414. if deleteFileNow {
  415. vlog.deleteLogFile(f)
  416. }
  417. return nil
  418. }
  419. func (vlog *valueLog) deleteMoveKeysFor(fid uint32, tr trace.Trace) {
  420. db := vlog.kv
  421. var result []*Entry
  422. var count, pointers uint64
  423. tr.LazyPrintf("Iterating over move keys to find invalids for fid: %d", fid)
  424. err := db.View(func(txn *Txn) error {
  425. opt := DefaultIteratorOptions
  426. opt.internalAccess = true
  427. opt.PrefetchValues = false
  428. itr := txn.NewIterator(opt)
  429. defer itr.Close()
  430. for itr.Seek(badgerMove); itr.ValidForPrefix(badgerMove); itr.Next() {
  431. count++
  432. item := itr.Item()
  433. if item.meta&bitValuePointer == 0 {
  434. continue
  435. }
  436. pointers++
  437. var vp valuePointer
  438. vp.Decode(item.vptr)
  439. if vp.Fid == fid {
  440. e := &Entry{Key: item.KeyCopy(nil), meta: bitDelete}
  441. result = append(result, e)
  442. }
  443. }
  444. return nil
  445. })
  446. if err != nil {
  447. tr.LazyPrintf("Got error while iterating move keys: %v", err)
  448. tr.SetError()
  449. return
  450. }
  451. tr.LazyPrintf("Num total move keys: %d. Num pointers: %d", count, pointers)
  452. tr.LazyPrintf("Number of invalid move keys found: %d", len(result))
  453. batchSize := 10240
  454. for i := 0; i < len(result); {
  455. end := i + batchSize
  456. if end > len(result) {
  457. end = len(result)
  458. }
  459. if err := db.batchSet(result[i:end]); err != nil {
  460. if err == ErrTxnTooBig {
  461. batchSize /= 2
  462. tr.LazyPrintf("Dropped batch size to %d", batchSize)
  463. continue
  464. }
  465. tr.LazyPrintf("Error while doing batchSet: %v", err)
  466. tr.SetError()
  467. return
  468. }
  469. i += batchSize
  470. }
  471. tr.LazyPrintf("Move keys deletion done.")
  472. return
  473. }
  474. func (vlog *valueLog) incrIteratorCount() {
  475. atomic.AddInt32(&vlog.numActiveIterators, 1)
  476. }
  477. func (vlog *valueLog) decrIteratorCount() error {
  478. num := atomic.AddInt32(&vlog.numActiveIterators, -1)
  479. if num != 0 {
  480. return nil
  481. }
  482. vlog.filesLock.Lock()
  483. lfs := make([]*logFile, 0, len(vlog.filesToBeDeleted))
  484. for _, id := range vlog.filesToBeDeleted {
  485. lfs = append(lfs, vlog.filesMap[id])
  486. delete(vlog.filesMap, id)
  487. }
  488. vlog.filesToBeDeleted = nil
  489. vlog.filesLock.Unlock()
  490. for _, lf := range lfs {
  491. if err := vlog.deleteLogFile(lf); err != nil {
  492. return err
  493. }
  494. }
  495. return nil
  496. }
  497. func (vlog *valueLog) deleteLogFile(lf *logFile) error {
  498. path := vlog.fpath(lf.fid)
  499. if err := lf.munmap(); err != nil {
  500. _ = lf.fd.Close()
  501. return err
  502. }
  503. if err := lf.fd.Close(); err != nil {
  504. return err
  505. }
  506. return os.Remove(path)
  507. }
  508. // lfDiscardStats keeps track of the amount of data that could be discarded for
  509. // a given logfile.
  510. type lfDiscardStats struct {
  511. sync.Mutex
  512. m map[uint32]int64
  513. }
  514. type valueLog struct {
  515. buf bytes.Buffer
  516. dirPath string
  517. elog trace.EventLog
  518. // guards our view of which files exist, which to be deleted, how many active iterators
  519. filesLock sync.RWMutex
  520. filesMap map[uint32]*logFile
  521. filesToBeDeleted []uint32
  522. // A refcount of iterators -- when this hits zero, we can delete the filesToBeDeleted.
  523. numActiveIterators int32
  524. kv *DB
  525. maxFid uint32
  526. writableLogOffset uint32
  527. numEntriesWritten uint32
  528. opt Options
  529. garbageCh chan struct{}
  530. lfDiscardStats *lfDiscardStats
  531. }
  532. func vlogFilePath(dirPath string, fid uint32) string {
  533. return fmt.Sprintf("%s%s%06d.vlog", dirPath, string(os.PathSeparator), fid)
  534. }
  535. func (vlog *valueLog) fpath(fid uint32) string {
  536. return vlogFilePath(vlog.dirPath, fid)
  537. }
  538. func (vlog *valueLog) openOrCreateFiles(readOnly bool) error {
  539. files, err := ioutil.ReadDir(vlog.dirPath)
  540. if err != nil {
  541. return errors.Wrapf(err, "Error while opening value log")
  542. }
  543. found := make(map[uint64]struct{})
  544. var maxFid uint32 // Beware len(files) == 0 case, this starts at 0.
  545. for _, file := range files {
  546. if !strings.HasSuffix(file.Name(), ".vlog") {
  547. continue
  548. }
  549. fsz := len(file.Name())
  550. fid, err := strconv.ParseUint(file.Name()[:fsz-5], 10, 32)
  551. if err != nil {
  552. return errors.Wrapf(err, "Error while parsing value log id for file: %q", file.Name())
  553. }
  554. if _, ok := found[fid]; ok {
  555. return errors.Errorf("Found the same value log file twice: %d", fid)
  556. }
  557. found[fid] = struct{}{}
  558. lf := &logFile{
  559. fid: uint32(fid),
  560. path: vlog.fpath(uint32(fid)),
  561. loadingMode: vlog.opt.ValueLogLoadingMode,
  562. }
  563. vlog.filesMap[uint32(fid)] = lf
  564. if uint32(fid) > maxFid {
  565. maxFid = uint32(fid)
  566. }
  567. }
  568. vlog.maxFid = uint32(maxFid)
  569. // Open all previous log files as read only. Open the last log file
  570. // as read write (unless the DB is read only).
  571. for fid, lf := range vlog.filesMap {
  572. if fid == maxFid {
  573. var flags uint32
  574. if vlog.opt.SyncWrites {
  575. flags |= y.Sync
  576. }
  577. if readOnly {
  578. flags |= y.ReadOnly
  579. }
  580. if lf.fd, err = y.OpenExistingFile(vlog.fpath(fid), flags); err != nil {
  581. return errors.Wrapf(err, "Unable to open value log file")
  582. }
  583. } else {
  584. if err := lf.openReadOnly(); err != nil {
  585. return err
  586. }
  587. }
  588. }
  589. // If no files are found, then create a new file.
  590. if len(vlog.filesMap) == 0 {
  591. // We already set vlog.maxFid above
  592. _, err := vlog.createVlogFile(0)
  593. if err != nil {
  594. return err
  595. }
  596. }
  597. return nil
  598. }
  599. func (vlog *valueLog) createVlogFile(fid uint32) (*logFile, error) {
  600. path := vlog.fpath(fid)
  601. lf := &logFile{fid: fid, path: path, loadingMode: vlog.opt.ValueLogLoadingMode}
  602. vlog.writableLogOffset = 0
  603. vlog.numEntriesWritten = 0
  604. var err error
  605. if lf.fd, err = y.CreateSyncedFile(path, vlog.opt.SyncWrites); err != nil {
  606. return nil, errors.Wrapf(err, "Unable to create value log file")
  607. }
  608. if err = syncDir(vlog.dirPath); err != nil {
  609. return nil, errors.Wrapf(err, "Unable to sync value log file dir")
  610. }
  611. vlog.filesLock.Lock()
  612. vlog.filesMap[fid] = lf
  613. vlog.filesLock.Unlock()
  614. return lf, nil
  615. }
  616. func (vlog *valueLog) Open(kv *DB, opt Options) error {
  617. vlog.dirPath = opt.ValueDir
  618. vlog.opt = opt
  619. vlog.kv = kv
  620. vlog.filesMap = make(map[uint32]*logFile)
  621. if err := vlog.openOrCreateFiles(kv.opt.ReadOnly); err != nil {
  622. return errors.Wrapf(err, "Unable to open value log")
  623. }
  624. vlog.elog = trace.NewEventLog("Badger", "Valuelog")
  625. vlog.garbageCh = make(chan struct{}, 1) // Only allow one GC at a time.
  626. vlog.lfDiscardStats = &lfDiscardStats{m: make(map[uint32]int64)}
  627. return nil
  628. }
  629. func (vlog *valueLog) Close() error {
  630. vlog.elog.Printf("Stopping garbage collection of values.")
  631. defer vlog.elog.Finish()
  632. var err error
  633. for id, f := range vlog.filesMap {
  634. f.lock.Lock() // We won’t release the lock.
  635. if munmapErr := f.munmap(); munmapErr != nil && err == nil {
  636. err = munmapErr
  637. }
  638. if !vlog.opt.ReadOnly && id == vlog.maxFid {
  639. // truncate writable log file to correct offset.
  640. if truncErr := f.fd.Truncate(
  641. int64(vlog.writableLogOffset)); truncErr != nil && err == nil {
  642. err = truncErr
  643. }
  644. }
  645. if closeErr := f.fd.Close(); closeErr != nil && err == nil {
  646. err = closeErr
  647. }
  648. }
  649. return err
  650. }
  651. // sortedFids returns the file id's not pending deletion, sorted. Assumes we have shared access to
  652. // filesMap.
  653. func (vlog *valueLog) sortedFids() []uint32 {
  654. toBeDeleted := make(map[uint32]struct{})
  655. for _, fid := range vlog.filesToBeDeleted {
  656. toBeDeleted[fid] = struct{}{}
  657. }
  658. ret := make([]uint32, 0, len(vlog.filesMap))
  659. for fid := range vlog.filesMap {
  660. if _, ok := toBeDeleted[fid]; !ok {
  661. ret = append(ret, fid)
  662. }
  663. }
  664. sort.Slice(ret, func(i, j int) bool {
  665. return ret[i] < ret[j]
  666. })
  667. return ret
  668. }
  669. // Replay replays the value log. The kv provided is only valid for the lifetime of function call.
  670. func (vlog *valueLog) Replay(ptr valuePointer, fn logEntry) error {
  671. fid := ptr.Fid
  672. offset := ptr.Offset + ptr.Len
  673. vlog.elog.Printf("Seeking at value pointer: %+v\n", ptr)
  674. fids := vlog.sortedFids()
  675. for _, id := range fids {
  676. if id < fid {
  677. continue
  678. }
  679. of := offset
  680. if id > fid {
  681. of = 0
  682. }
  683. f := vlog.filesMap[id]
  684. err := vlog.iterate(f, of, fn)
  685. if err != nil {
  686. return errors.Wrapf(err, "Unable to replay value log: %q", f.path)
  687. }
  688. }
  689. // Seek to the end to start writing.
  690. var err error
  691. last := vlog.filesMap[vlog.maxFid]
  692. lastOffset, err := last.fd.Seek(0, io.SeekEnd)
  693. atomic.AddUint32(&vlog.writableLogOffset, uint32(lastOffset))
  694. return errors.Wrapf(err, "Unable to seek to end of value log: %q", last.path)
  695. }
  696. type request struct {
  697. // Input values
  698. Entries []*Entry
  699. // Output values and wait group stuff below
  700. Ptrs []valuePointer
  701. Wg sync.WaitGroup
  702. Err error
  703. }
  704. func (req *request) Wait() error {
  705. req.Wg.Wait()
  706. req.Entries = nil
  707. err := req.Err
  708. requestPool.Put(req)
  709. return err
  710. }
  711. // sync is thread-unsafe and should not be called concurrently with write.
  712. func (vlog *valueLog) sync() error {
  713. if vlog.opt.SyncWrites {
  714. return nil
  715. }
  716. vlog.filesLock.RLock()
  717. if len(vlog.filesMap) == 0 {
  718. vlog.filesLock.RUnlock()
  719. return nil
  720. }
  721. curlf := vlog.filesMap[vlog.maxFid]
  722. curlf.lock.RLock()
  723. vlog.filesLock.RUnlock()
  724. dirSyncCh := make(chan error)
  725. go func() { dirSyncCh <- syncDir(vlog.opt.ValueDir) }()
  726. err := curlf.sync()
  727. curlf.lock.RUnlock()
  728. dirSyncErr := <-dirSyncCh
  729. if err != nil {
  730. err = dirSyncErr
  731. }
  732. return err
  733. }
  734. func (vlog *valueLog) writableOffset() uint32 {
  735. return atomic.LoadUint32(&vlog.writableLogOffset)
  736. }
  737. // write is thread-unsafe by design and should not be called concurrently.
  738. func (vlog *valueLog) write(reqs []*request) error {
  739. vlog.filesLock.RLock()
  740. curlf := vlog.filesMap[vlog.maxFid]
  741. vlog.filesLock.RUnlock()
  742. toDisk := func() error {
  743. if vlog.buf.Len() == 0 {
  744. return nil
  745. }
  746. vlog.elog.Printf("Flushing %d blocks of total size: %d", len(reqs), vlog.buf.Len())
  747. n, err := curlf.fd.Write(vlog.buf.Bytes())
  748. if err != nil {
  749. return errors.Wrapf(err, "Unable to write to value log file: %q", curlf.path)
  750. }
  751. y.NumWrites.Add(1)
  752. y.NumBytesWritten.Add(int64(n))
  753. vlog.elog.Printf("Done")
  754. atomic.AddUint32(&vlog.writableLogOffset, uint32(n))
  755. vlog.buf.Reset()
  756. if vlog.writableOffset() > uint32(vlog.opt.ValueLogFileSize) ||
  757. vlog.numEntriesWritten > vlog.opt.ValueLogMaxEntries {
  758. var err error
  759. if err = curlf.doneWriting(vlog.writableLogOffset); err != nil {
  760. return err
  761. }
  762. newid := atomic.AddUint32(&vlog.maxFid, 1)
  763. y.AssertTruef(newid <= math.MaxUint32, "newid will overflow uint32: %v", newid)
  764. newlf, err := vlog.createVlogFile(newid)
  765. if err != nil {
  766. return err
  767. }
  768. if err = newlf.mmap(2 * vlog.opt.ValueLogFileSize); err != nil {
  769. return err
  770. }
  771. curlf = newlf
  772. }
  773. return nil
  774. }
  775. for i := range reqs {
  776. b := reqs[i]
  777. b.Ptrs = b.Ptrs[:0]
  778. for j := range b.Entries {
  779. e := b.Entries[j]
  780. var p valuePointer
  781. p.Fid = curlf.fid
  782. // Use the offset including buffer length so far.
  783. p.Offset = vlog.writableOffset() + uint32(vlog.buf.Len())
  784. plen, err := encodeEntry(e, &vlog.buf) // Now encode the entry into buffer.
  785. if err != nil {
  786. return err
  787. }
  788. p.Len = uint32(plen)
  789. b.Ptrs = append(b.Ptrs, p)
  790. }
  791. vlog.numEntriesWritten += uint32(len(b.Entries))
  792. // We write to disk here so that all entries that are part of the same transaction are
  793. // written to the same vlog file.
  794. writeNow :=
  795. vlog.writableOffset()+uint32(vlog.buf.Len()) > uint32(vlog.opt.ValueLogFileSize) ||
  796. vlog.numEntriesWritten > uint32(vlog.opt.ValueLogMaxEntries)
  797. if writeNow {
  798. if err := toDisk(); err != nil {
  799. return err
  800. }
  801. }
  802. }
  803. return toDisk()
  804. // Acquire mutex locks around this manipulation, so that the reads don't try to use
  805. // an invalid file descriptor.
  806. }
  807. // Gets the logFile and acquires and RLock() for the mmap. You must call RUnlock on the file
  808. // (if non-nil)
  809. func (vlog *valueLog) getFileRLocked(fid uint32) (*logFile, error) {
  810. vlog.filesLock.RLock()
  811. defer vlog.filesLock.RUnlock()
  812. ret, ok := vlog.filesMap[fid]
  813. if !ok {
  814. // log file has gone away, will need to retry the operation.
  815. return nil, ErrRetry
  816. }
  817. ret.lock.RLock()
  818. return ret, nil
  819. }
  820. // Read reads the value log at a given location.
  821. // TODO: Make this read private.
  822. func (vlog *valueLog) Read(vp valuePointer, s *y.Slice) ([]byte, func(), error) {
  823. // Check for valid offset if we are reading to writable log.
  824. if vp.Fid == vlog.maxFid && vp.Offset >= vlog.writableOffset() {
  825. return nil, nil, errors.Errorf(
  826. "Invalid value pointer offset: %d greater than current offset: %d",
  827. vp.Offset, vlog.writableOffset())
  828. }
  829. buf, cb, err := vlog.readValueBytes(vp, s)
  830. if err != nil {
  831. return nil, cb, err
  832. }
  833. var h header
  834. h.Decode(buf)
  835. n := uint32(headerBufSize) + h.klen
  836. return buf[n : n+h.vlen], cb, nil
  837. }
  838. func (vlog *valueLog) readValueBytes(vp valuePointer, s *y.Slice) ([]byte, func(), error) {
  839. lf, err := vlog.getFileRLocked(vp.Fid)
  840. if err != nil {
  841. return nil, nil, err
  842. }
  843. buf, err := lf.read(vp, s)
  844. if vlog.opt.ValueLogLoadingMode == options.MemoryMap {
  845. return buf, lf.lock.RUnlock, err
  846. }
  847. // If we are using File I/O we unlock the file immediately
  848. // and return an empty function as callback.
  849. lf.lock.RUnlock()
  850. return buf, nil, err
  851. }
  852. // Test helper
  853. func valueBytesToEntry(buf []byte) (e Entry) {
  854. var h header
  855. h.Decode(buf)
  856. n := uint32(headerBufSize)
  857. e.Key = buf[n : n+h.klen]
  858. n += h.klen
  859. e.meta = h.meta
  860. e.UserMeta = h.userMeta
  861. e.Value = buf[n : n+h.vlen]
  862. return
  863. }
  864. func (vlog *valueLog) pickLog(head valuePointer, tr trace.Trace) (files []*logFile) {
  865. vlog.filesLock.RLock()
  866. defer vlog.filesLock.RUnlock()
  867. fids := vlog.sortedFids()
  868. if len(fids) <= 1 {
  869. tr.LazyPrintf("Only one or less value log file.")
  870. return nil
  871. } else if head.Fid == 0 {
  872. tr.LazyPrintf("Head pointer is at zero.")
  873. return nil
  874. }
  875. // Pick a candidate that contains the largest amount of discardable data
  876. candidate := struct {
  877. fid uint32
  878. discard int64
  879. }{math.MaxUint32, 0}
  880. vlog.lfDiscardStats.Lock()
  881. for _, fid := range fids {
  882. if fid >= head.Fid {
  883. break
  884. }
  885. if vlog.lfDiscardStats.m[fid] > candidate.discard {
  886. candidate.fid = fid
  887. candidate.discard = vlog.lfDiscardStats.m[fid]
  888. }
  889. }
  890. vlog.lfDiscardStats.Unlock()
  891. if candidate.fid != math.MaxUint32 { // Found a candidate
  892. tr.LazyPrintf("Found candidate via discard stats: %v", candidate)
  893. files = append(files, vlog.filesMap[candidate.fid])
  894. } else {
  895. tr.LazyPrintf("Could not find candidate via discard stats. Randomly picking one.")
  896. }
  897. // Fallback to randomly picking a log file
  898. var idxHead int
  899. for i, fid := range fids {
  900. if fid == head.Fid {
  901. idxHead = i
  902. break
  903. }
  904. }
  905. if idxHead == 0 { // Not found or first file
  906. tr.LazyPrintf("Could not find any file.")
  907. return nil
  908. }
  909. idx := rand.Intn(idxHead) // Don’t include head.Fid. We pick a random file before it.
  910. if idx > 0 {
  911. idx = rand.Intn(idx + 1) // Another level of rand to favor smaller fids.
  912. }
  913. tr.LazyPrintf("Randomly chose fid: %d", fids[idx])
  914. files = append(files, vlog.filesMap[fids[idx]])
  915. return files
  916. }
  917. func discardEntry(e Entry, vs y.ValueStruct) bool {
  918. if vs.Version != y.ParseTs(e.Key) {
  919. // Version not found. Discard.
  920. return true
  921. }
  922. if isDeletedOrExpired(vs.Meta, vs.ExpiresAt) {
  923. return true
  924. }
  925. if (vs.Meta & bitValuePointer) == 0 {
  926. // Key also stores the value in LSM. Discard.
  927. return true
  928. }
  929. if (vs.Meta & bitFinTxn) > 0 {
  930. // Just a txn finish entry. Discard.
  931. return true
  932. }
  933. return false
  934. }
  935. func (vlog *valueLog) doRunGC(lf *logFile, discardRatio float64, tr trace.Trace) (err error) {
  936. // Update stats before exiting
  937. defer func() {
  938. if err == nil {
  939. vlog.lfDiscardStats.Lock()
  940. delete(vlog.lfDiscardStats.m, lf.fid)
  941. vlog.lfDiscardStats.Unlock()
  942. }
  943. }()
  944. type reason struct {
  945. total float64
  946. discard float64
  947. count int
  948. }
  949. fi, err := lf.fd.Stat()
  950. if err != nil {
  951. tr.LazyPrintf("Error while finding file size: %v", err)
  952. tr.SetError()
  953. return err
  954. }
  955. // Set up the sampling window sizes.
  956. sizeWindow := float64(fi.Size()) * 0.1 // 10% of the file as window.
  957. countWindow := int(float64(vlog.opt.ValueLogMaxEntries) * 0.01) // 1% of num entries.
  958. tr.LazyPrintf("Size window: %5.2f. Count window: %d.", sizeWindow, countWindow)
  959. // Pick a random start point for the log.
  960. skipFirstM := float64(rand.Int63n(fi.Size())) // Pick a random starting location.
  961. skipFirstM -= sizeWindow // Avoid hitting EOF by moving back by window.
  962. skipFirstM /= float64(mi) // Convert to MBs.
  963. tr.LazyPrintf("Skip first %5.2f MB of file of size: %d MB", skipFirstM, fi.Size()/mi)
  964. var skipped float64
  965. var r reason
  966. start := time.Now()
  967. y.AssertTrue(vlog.kv != nil)
  968. s := new(y.Slice)
  969. var numIterations int
  970. err = vlog.iterate(lf, 0, func(e Entry, vp valuePointer) error {
  971. numIterations++
  972. esz := float64(vp.Len) / (1 << 20) // in MBs.
  973. if skipped < skipFirstM {
  974. skipped += esz
  975. return nil
  976. }
  977. // Sample until we reach the window sizes or exceed 10 seconds.
  978. if r.count > countWindow {
  979. tr.LazyPrintf("Stopping sampling after %d entries.", countWindow)
  980. return errStop
  981. }
  982. if r.total > sizeWindow {
  983. tr.LazyPrintf("Stopping sampling after reaching window size.")
  984. return errStop
  985. }
  986. if time.Since(start) > 10*time.Second {
  987. tr.LazyPrintf("Stopping sampling after 10 seconds.")
  988. return errStop
  989. }
  990. r.total += esz
  991. r.count++
  992. vs, err := vlog.kv.get(e.Key)
  993. if err != nil {
  994. return err
  995. }
  996. if discardEntry(e, vs) {
  997. r.discard += esz
  998. return nil
  999. }
  1000. // Value is still present in value log.
  1001. y.AssertTrue(len(vs.Value) > 0)
  1002. vp.Decode(vs.Value)
  1003. if vp.Fid > lf.fid {
  1004. // Value is present in a later log. Discard.
  1005. r.discard += esz
  1006. return nil
  1007. }
  1008. if vp.Offset > e.offset {
  1009. // Value is present in a later offset, but in the same log.
  1010. r.discard += esz
  1011. return nil
  1012. }
  1013. if vp.Fid == lf.fid && vp.Offset == e.offset {
  1014. // This is still the active entry. This would need to be rewritten.
  1015. } else {
  1016. vlog.elog.Printf("Reason=%+v\n", r)
  1017. buf, cb, err := vlog.readValueBytes(vp, s)
  1018. if err != nil {
  1019. return errStop
  1020. }
  1021. ne := valueBytesToEntry(buf)
  1022. ne.offset = vp.Offset
  1023. ne.print("Latest Entry Header in LSM")
  1024. e.print("Latest Entry in Log")
  1025. runCallback(cb)
  1026. return errors.Errorf("This shouldn't happen. Latest Pointer:%+v. Meta:%v.",
  1027. vp, vs.Meta)
  1028. }
  1029. return nil
  1030. })
  1031. if err != nil {
  1032. tr.LazyPrintf("Error while iterating for RunGC: %v", err)
  1033. tr.SetError()
  1034. return err
  1035. }
  1036. tr.LazyPrintf("Fid: %d. Skipped: %5.2fMB Num iterations: %d. Data status=%+v\n",
  1037. lf.fid, skipped, numIterations, r)
  1038. // If we couldn't sample at least a 1000 KV pairs or at least 75% of the window size,
  1039. // and what we can discard is below the threshold, we should skip the rewrite.
  1040. if (r.count < countWindow && r.total < sizeWindow*0.75) || r.discard < discardRatio*r.total {
  1041. tr.LazyPrintf("Skipping GC on fid: %d", lf.fid)
  1042. return ErrNoRewrite
  1043. }
  1044. if err = vlog.rewrite(lf, tr); err != nil {
  1045. return err
  1046. }
  1047. tr.LazyPrintf("Done rewriting.")
  1048. return nil
  1049. }
  1050. func (vlog *valueLog) waitOnGC(lc *y.Closer) {
  1051. defer lc.Done()
  1052. <-lc.HasBeenClosed() // Wait for lc to be closed.
  1053. // Block any GC in progress to finish, and don't allow any more writes to runGC by filling up
  1054. // the channel of size 1.
  1055. vlog.garbageCh <- struct{}{}
  1056. }
  1057. func (vlog *valueLog) runGC(discardRatio float64, head valuePointer) error {
  1058. select {
  1059. case vlog.garbageCh <- struct{}{}:
  1060. // Pick a log file for GC.
  1061. tr := trace.New("Badger.ValueLog", "GC")
  1062. tr.SetMaxEvents(100)
  1063. defer func() {
  1064. tr.Finish()
  1065. <-vlog.garbageCh
  1066. }()
  1067. var err error
  1068. files := vlog.pickLog(head, tr)
  1069. if len(files) == 0 {
  1070. tr.LazyPrintf("PickLog returned zero results.")
  1071. return ErrNoRewrite
  1072. }
  1073. tried := make(map[uint32]bool)
  1074. for _, lf := range files {
  1075. if _, done := tried[lf.fid]; done {
  1076. continue
  1077. }
  1078. tried[lf.fid] = true
  1079. err = vlog.doRunGC(lf, discardRatio, tr)
  1080. if err == nil {
  1081. vlog.deleteMoveKeysFor(lf.fid, tr)
  1082. return nil
  1083. }
  1084. }
  1085. return err
  1086. default:
  1087. return ErrRejected
  1088. }
  1089. }
  1090. func (vlog *valueLog) updateGCStats(stats map[uint32]int64) {
  1091. vlog.lfDiscardStats.Lock()
  1092. for fid, sz := range stats {
  1093. vlog.lfDiscardStats.m[fid] += sz
  1094. }
  1095. vlog.lfDiscardStats.Unlock()
  1096. }