backend.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. if _, ok := err.(errClosed); ok {
  138. return true
  139. }
  140. if _, ok := err.(*errClosed); ok {
  141. return true
  142. }
  143. return false
  144. }
  145. func IsNotFound(err error) bool {
  146. if _, ok := err.(errNotFound); ok {
  147. return true
  148. }
  149. if _, ok := err.(*errNotFound); ok {
  150. return true
  151. }
  152. return false
  153. }
  154. // releaser manages counting on top of a waitgroup
  155. type releaser struct {
  156. wg *closeWaitGroup
  157. once *sync.Once
  158. }
  159. func newReleaser(wg *closeWaitGroup) (*releaser, error) {
  160. if err := wg.Add(1); err != nil {
  161. return nil, err
  162. }
  163. return &releaser{
  164. wg: wg,
  165. once: new(sync.Once),
  166. }, nil
  167. }
  168. func (r releaser) Release() {
  169. // We use the Once because we may get called multiple times from
  170. // Commit() and deferred Release().
  171. r.once.Do(func() {
  172. r.wg.Done()
  173. })
  174. }
  175. // closeWaitGroup behaves just like a sync.WaitGroup, but does not require
  176. // a single routine to do the Add and Wait calls. If Add is called after
  177. // CloseWait, it will return an error, and both are safe to be used concurrently.
  178. type closeWaitGroup struct {
  179. sync.WaitGroup
  180. closed bool
  181. closeMut sync.RWMutex
  182. }
  183. func (cg *closeWaitGroup) Add(i int) error {
  184. cg.closeMut.RLock()
  185. defer cg.closeMut.RUnlock()
  186. if cg.closed {
  187. return errClosed{}
  188. }
  189. cg.WaitGroup.Add(i)
  190. return nil
  191. }
  192. func (cg *closeWaitGroup) CloseWait() {
  193. cg.closeMut.Lock()
  194. cg.closed = true
  195. cg.closeMut.Unlock()
  196. cg.WaitGroup.Wait()
  197. }
  198. type opener func(path string) (Backend, error)
  199. // maybeCopyDatabase copies the database if the destination doesn't exist
  200. // but the source does.
  201. func maybeCopyDatabase(toPath, fromPath string, toOpen, fromOpen opener) error {
  202. if _, err := os.Lstat(toPath); !os.IsNotExist(err) {
  203. // Destination database exists (or is otherwise unavailable), do not
  204. // attempt to overwrite it.
  205. return nil
  206. }
  207. if _, err := os.Lstat(fromPath); err != nil {
  208. // Source database is not available, so nothing to copy
  209. return nil
  210. }
  211. fromDB, err := fromOpen(fromPath)
  212. if err != nil {
  213. return err
  214. }
  215. defer fromDB.Close()
  216. toDB, err := toOpen(toPath)
  217. if err != nil {
  218. // That's odd, but it will be handled & reported in the usual path
  219. // so we can ignore it here.
  220. return err
  221. }
  222. defer toDB.Close()
  223. l.Infoln("Copying database for format conversion...")
  224. if err := copyBackend(toDB, fromDB); err != nil {
  225. return err
  226. }
  227. // Move the old database out of the way to mark it as migrated.
  228. fromDB.Close()
  229. _ = os.Rename(fromPath, fromPath+".migrated."+time.Now().Format("20060102150405"))
  230. return nil
  231. }
  232. func copyBackend(to, from Backend) error {
  233. srcIt, err := from.NewPrefixIterator(nil)
  234. if err != nil {
  235. return err
  236. }
  237. defer srcIt.Release()
  238. dstTx, err := to.NewWriteTransaction()
  239. if err != nil {
  240. return err
  241. }
  242. defer dstTx.Release()
  243. for srcIt.Next() {
  244. if err := dstTx.Put(srcIt.Key(), srcIt.Value()); err != nil {
  245. return err
  246. }
  247. }
  248. if srcIt.Error() != nil {
  249. return err
  250. }
  251. srcIt.Release()
  252. return dstTx.Commit()
  253. }