backend.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. // Location returns the path to the database, as given to Open. The returned string
  103. // is empty for a db in memory.
  104. type Backend interface {
  105. Reader
  106. Writer
  107. NewReadTransaction() (ReadTransaction, error)
  108. NewWriteTransaction(hooks ...CommitHook) (WriteTransaction, error)
  109. Close() error
  110. Compact() error
  111. Location() string
  112. }
  113. type Tuning int
  114. const (
  115. // N.b. these constants must match those in lib/config.Tuning!
  116. TuningAuto Tuning = iota
  117. TuningSmall
  118. TuningLarge
  119. )
  120. func Open(path string, tuning Tuning) (Backend, error) {
  121. if os.Getenv("USE_BADGER") != "" {
  122. l.Warnln("Using experimental badger db")
  123. if err := maybeCopyDatabase(path, strings.Replace(path, locations.BadgerDir, locations.LevelDBDir, 1), OpenBadger, OpenLevelDBRO); err != nil {
  124. return nil, err
  125. }
  126. return OpenBadger(path)
  127. }
  128. if err := maybeCopyDatabase(path, strings.Replace(path, locations.LevelDBDir, locations.BadgerDir, 1), OpenLevelDBAuto, OpenBadger); err != nil {
  129. return nil, err
  130. }
  131. return OpenLevelDB(path, tuning)
  132. }
  133. func OpenMemory() Backend {
  134. if os.Getenv("USE_BADGER") != "" {
  135. return OpenBadgerMemory()
  136. }
  137. return OpenLevelDBMemory()
  138. }
  139. type errClosed struct{}
  140. func (*errClosed) Error() string { return "database is closed" }
  141. type errNotFound struct{}
  142. func (*errNotFound) Error() string { return "key not found" }
  143. func IsClosed(err error) bool {
  144. var e *errClosed
  145. return errors.As(err, &e)
  146. }
  147. func IsNotFound(err error) bool {
  148. var e *errNotFound
  149. return errors.As(err, &e)
  150. }
  151. // releaser manages counting on top of a waitgroup
  152. type releaser struct {
  153. wg *closeWaitGroup
  154. once *sync.Once
  155. }
  156. func newReleaser(wg *closeWaitGroup) (*releaser, error) {
  157. if err := wg.Add(1); err != nil {
  158. return nil, err
  159. }
  160. return &releaser{
  161. wg: wg,
  162. once: new(sync.Once),
  163. }, nil
  164. }
  165. func (r releaser) Release() {
  166. // We use the Once because we may get called multiple times from
  167. // Commit() and deferred Release().
  168. r.once.Do(func() {
  169. r.wg.Done()
  170. })
  171. }
  172. // closeWaitGroup behaves just like a sync.WaitGroup, but does not require
  173. // a single routine to do the Add and Wait calls. If Add is called after
  174. // CloseWait, it will return an error, and both are safe to be used concurrently.
  175. type closeWaitGroup struct {
  176. sync.WaitGroup
  177. closed bool
  178. closeMut sync.RWMutex
  179. }
  180. func (cg *closeWaitGroup) Add(i int) error {
  181. cg.closeMut.RLock()
  182. defer cg.closeMut.RUnlock()
  183. if cg.closed {
  184. return &errClosed{}
  185. }
  186. cg.WaitGroup.Add(i)
  187. return nil
  188. }
  189. func (cg *closeWaitGroup) CloseWait() {
  190. cg.closeMut.Lock()
  191. cg.closed = true
  192. cg.closeMut.Unlock()
  193. cg.WaitGroup.Wait()
  194. }
  195. type opener func(path string) (Backend, error)
  196. // maybeCopyDatabase copies the database if the destination doesn't exist
  197. // but the source does.
  198. func maybeCopyDatabase(toPath, fromPath string, toOpen, fromOpen opener) error {
  199. if _, err := os.Lstat(toPath); !os.IsNotExist(err) {
  200. // Destination database exists (or is otherwise unavailable), do not
  201. // attempt to overwrite it.
  202. return nil
  203. }
  204. if _, err := os.Lstat(fromPath); err != nil {
  205. // Source database is not available, so nothing to copy
  206. return nil
  207. }
  208. fromDB, err := fromOpen(fromPath)
  209. if err != nil {
  210. return err
  211. }
  212. defer fromDB.Close()
  213. toDB, err := toOpen(toPath)
  214. if err != nil {
  215. // That's odd, but it will be handled & reported in the usual path
  216. // so we can ignore it here.
  217. return err
  218. }
  219. defer toDB.Close()
  220. l.Infoln("Copying database for format conversion...")
  221. if err := copyBackend(toDB, fromDB); err != nil {
  222. return err
  223. }
  224. // Move the old database out of the way to mark it as migrated.
  225. fromDB.Close()
  226. _ = os.Rename(fromPath, fromPath+".migrated."+time.Now().Format("20060102150405"))
  227. return nil
  228. }
  229. func copyBackend(to, from Backend) error {
  230. srcIt, err := from.NewPrefixIterator(nil)
  231. if err != nil {
  232. return err
  233. }
  234. defer srcIt.Release()
  235. dstTx, err := to.NewWriteTransaction()
  236. if err != nil {
  237. return err
  238. }
  239. defer dstTx.Release()
  240. for srcIt.Next() {
  241. if err := dstTx.Put(srcIt.Key(), srcIt.Value()); err != nil {
  242. return err
  243. }
  244. }
  245. if srcIt.Error() != nil {
  246. return err
  247. }
  248. srcIt.Release()
  249. return dstTx.Commit()
  250. }