backend.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. // Copyright (C) 2019 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package backend
  7. import (
  8. "errors"
  9. "os"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/syncthing/syncthing/lib/locations"
  14. )
  15. // CommitHook is a function that is executed before a WriteTransaction is
  16. // committed or before it is flushed to disk, e.g. on calling CheckPoint. The
  17. // transaction can be accessed via a closure.
  18. type CommitHook func(WriteTransaction) error
  19. // The Reader interface specifies the read-only operations available on the
  20. // main database and on read-only transactions (snapshots). Note that when
  21. // called directly on the database handle these operations may take implicit
  22. // transactions and performance may suffer.
  23. type Reader interface {
  24. Get(key []byte) ([]byte, error)
  25. NewPrefixIterator(prefix []byte) (Iterator, error)
  26. NewRangeIterator(first, last []byte) (Iterator, error)
  27. }
  28. // The Writer interface specifies the mutating operations available on the
  29. // main database and on writable transactions. Note that when called
  30. // directly on the database handle these operations may take implicit
  31. // transactions and performance may suffer.
  32. type Writer interface {
  33. Put(key, val []byte) error
  34. Delete(key []byte) error
  35. }
  36. // The ReadTransaction interface specifies the operations on read-only
  37. // transactions. Every ReadTransaction must be released when no longer
  38. // required.
  39. type ReadTransaction interface {
  40. Reader
  41. Release()
  42. }
  43. // The WriteTransaction interface specifies the operations on writable
  44. // transactions. Every WriteTransaction must be either committed or released
  45. // (i.e., discarded) when no longer required. No further operations must be
  46. // performed after release or commit (regardless of whether commit succeeded),
  47. // with one exception -- it's fine to release an already committed or released
  48. // transaction.
  49. //
  50. // A Checkpoint is a potential partial commit of the transaction so far, for
  51. // purposes of saving memory when transactions are in-RAM. Note that
  52. // transactions may be checkpointed *anyway* even if this is not called, due to
  53. // resource constraints, but this gives you a chance to decide when. If, and
  54. // only if, calling Checkpoint will result in a partial commit/flush, the
  55. // CommitHooks passed to Backend.NewWriteTransaction are called before
  56. // committing. If any of those returns an error, committing is aborted and the
  57. // error bubbled.
  58. type WriteTransaction interface {
  59. ReadTransaction
  60. Writer
  61. Checkpoint() error
  62. Commit() error
  63. }
  64. // The Iterator interface specifies the operations available on iterators
  65. // returned by NewPrefixIterator and NewRangeIterator. The iterator pattern
  66. // is to loop while Next returns true, then check Error after the loop. Next
  67. // will return false when iteration is complete (Error() == nil) or when
  68. // there is an error preventing iteration, which is then returned by
  69. // Error(). For example:
  70. //
  71. // it, err := db.NewPrefixIterator(nil)
  72. // if err != nil {
  73. // // problem preventing iteration
  74. // }
  75. // defer it.Release()
  76. // for it.Next() {
  77. // // ...
  78. // }
  79. // if err := it.Error(); err != nil {
  80. // // there was a database problem while iterating
  81. // }
  82. //
  83. // An iterator must be Released when no longer required. The Error method
  84. // can be called either before or after Release with the same results. If an
  85. // iterator was created in a transaction (whether read-only or write) it
  86. // must be released before the transaction is released (or committed).
  87. type Iterator interface {
  88. Next() bool
  89. Key() []byte
  90. Value() []byte
  91. Error() error
  92. Release()
  93. }
  94. // The Backend interface represents the main database handle. It supports
  95. // both read/write operations and opening read-only or writable
  96. // transactions. Depending on the actual implementation, individual
  97. // read/write operations may be implicitly wrapped in transactions, making
  98. // them perform quite badly when used repeatedly. For bulk operations,
  99. // consider always using a transaction of the appropriate type. The
  100. // transaction isolation level is "read committed" - there are no dirty
  101. // reads.
  102. type Backend interface {
  103. Reader
  104. Writer
  105. NewReadTransaction() (ReadTransaction, error)
  106. NewWriteTransaction(hooks ...CommitHook) (WriteTransaction, error)
  107. Close() error
  108. Compact() error
  109. }
  110. type Tuning int
  111. const (
  112. // N.b. these constants must match those in lib/config.Tuning!
  113. TuningAuto Tuning = iota
  114. TuningSmall
  115. TuningLarge
  116. )
  117. func Open(path string, tuning Tuning) (Backend, error) {
  118. if os.Getenv("USE_BADGER") != "" {
  119. l.Warnln("Using experimental badger db")
  120. if err := maybeCopyDatabase(path, strings.Replace(path, locations.BadgerDir, locations.LevelDBDir, 1), OpenBadger, OpenLevelDBRO); err != nil {
  121. return nil, err
  122. }
  123. return OpenBadger(path)
  124. }
  125. if err := maybeCopyDatabase(path, strings.Replace(path, locations.LevelDBDir, locations.BadgerDir, 1), OpenLevelDBAuto, OpenBadger); err != nil {
  126. return nil, err
  127. }
  128. return OpenLevelDB(path, tuning)
  129. }
  130. func OpenMemory() Backend {
  131. if os.Getenv("USE_BADGER") != "" {
  132. return OpenBadgerMemory()
  133. }
  134. return OpenLevelDBMemory()
  135. }
  136. type errClosed struct{}
  137. func (*errClosed) Error() string { return "database is closed" }
  138. type errNotFound struct{}
  139. func (*errNotFound) Error() string { return "key not found" }
  140. func IsClosed(err error) bool {
  141. var e *errClosed
  142. return errors.As(err, &e)
  143. }
  144. func IsNotFound(err error) bool {
  145. var e *errNotFound
  146. return errors.As(err, &e)
  147. }
  148. // releaser manages counting on top of a waitgroup
  149. type releaser struct {
  150. wg *closeWaitGroup
  151. once *sync.Once
  152. }
  153. func newReleaser(wg *closeWaitGroup) (*releaser, error) {
  154. if err := wg.Add(1); err != nil {
  155. return nil, err
  156. }
  157. return &releaser{
  158. wg: wg,
  159. once: new(sync.Once),
  160. }, nil
  161. }
  162. func (r releaser) Release() {
  163. // We use the Once because we may get called multiple times from
  164. // Commit() and deferred Release().
  165. r.once.Do(func() {
  166. r.wg.Done()
  167. })
  168. }
  169. // closeWaitGroup behaves just like a sync.WaitGroup, but does not require
  170. // a single routine to do the Add and Wait calls. If Add is called after
  171. // CloseWait, it will return an error, and both are safe to be used concurrently.
  172. type closeWaitGroup struct {
  173. sync.WaitGroup
  174. closed bool
  175. closeMut sync.RWMutex
  176. }
  177. func (cg *closeWaitGroup) Add(i int) error {
  178. cg.closeMut.RLock()
  179. defer cg.closeMut.RUnlock()
  180. if cg.closed {
  181. return &errClosed{}
  182. }
  183. cg.WaitGroup.Add(i)
  184. return nil
  185. }
  186. func (cg *closeWaitGroup) CloseWait() {
  187. cg.closeMut.Lock()
  188. cg.closed = true
  189. cg.closeMut.Unlock()
  190. cg.WaitGroup.Wait()
  191. }
  192. type opener func(path string) (Backend, error)
  193. // maybeCopyDatabase copies the database if the destination doesn't exist
  194. // but the source does.
  195. func maybeCopyDatabase(toPath, fromPath string, toOpen, fromOpen opener) error {
  196. if _, err := os.Lstat(toPath); !os.IsNotExist(err) {
  197. // Destination database exists (or is otherwise unavailable), do not
  198. // attempt to overwrite it.
  199. return nil
  200. }
  201. if _, err := os.Lstat(fromPath); err != nil {
  202. // Source database is not available, so nothing to copy
  203. return nil
  204. }
  205. fromDB, err := fromOpen(fromPath)
  206. if err != nil {
  207. return err
  208. }
  209. defer fromDB.Close()
  210. toDB, err := toOpen(toPath)
  211. if err != nil {
  212. // That's odd, but it will be handled & reported in the usual path
  213. // so we can ignore it here.
  214. return err
  215. }
  216. defer toDB.Close()
  217. l.Infoln("Copying database for format conversion...")
  218. if err := copyBackend(toDB, fromDB); err != nil {
  219. return err
  220. }
  221. // Move the old database out of the way to mark it as migrated.
  222. fromDB.Close()
  223. _ = os.Rename(fromPath, fromPath+".migrated."+time.Now().Format("20060102150405"))
  224. return nil
  225. }
  226. func copyBackend(to, from Backend) error {
  227. srcIt, err := from.NewPrefixIterator(nil)
  228. if err != nil {
  229. return err
  230. }
  231. defer srcIt.Release()
  232. dstTx, err := to.NewWriteTransaction()
  233. if err != nil {
  234. return err
  235. }
  236. defer dstTx.Release()
  237. for srcIt.Next() {
  238. if err := dstTx.Put(srcIt.Key(), srcIt.Value()); err != nil {
  239. return err
  240. }
  241. }
  242. if srcIt.Error() != nil {
  243. return err
  244. }
  245. srcIt.Release()
  246. return dstTx.Commit()
  247. }