backend.go 7.8 KB

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