backend.go 7.8 KB

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