leveldb_transactions.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // Copyright (C) 2014 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 db
  7. import (
  8. "bytes"
  9. "sync/atomic"
  10. "github.com/syncthing/syncthing/lib/protocol"
  11. "github.com/syndtr/goleveldb/leveldb"
  12. )
  13. // A readOnlyTransaction represents a database snapshot.
  14. type readOnlyTransaction struct {
  15. *leveldb.Snapshot
  16. db *Instance
  17. }
  18. func (db *Instance) newReadOnlyTransaction() readOnlyTransaction {
  19. snap, err := db.GetSnapshot()
  20. if err != nil {
  21. panic(err)
  22. }
  23. return readOnlyTransaction{
  24. Snapshot: snap,
  25. db: db,
  26. }
  27. }
  28. func (t readOnlyTransaction) close() {
  29. t.Release()
  30. }
  31. func (t readOnlyTransaction) getFile(folder, device, file []byte) (protocol.FileInfo, bool) {
  32. return t.db.getFile(t.db.deviceKey(folder, device, file))
  33. }
  34. // A readWriteTransaction is a readOnlyTransaction plus a batch for writes.
  35. // The batch will be committed on close() or by checkFlush() if it exceeds the
  36. // batch size.
  37. type readWriteTransaction struct {
  38. readOnlyTransaction
  39. *leveldb.Batch
  40. }
  41. func (db *Instance) newReadWriteTransaction() readWriteTransaction {
  42. t := db.newReadOnlyTransaction()
  43. return readWriteTransaction{
  44. readOnlyTransaction: t,
  45. Batch: new(leveldb.Batch),
  46. }
  47. }
  48. func (t readWriteTransaction) close() {
  49. t.flush()
  50. t.readOnlyTransaction.close()
  51. }
  52. func (t readWriteTransaction) checkFlush() {
  53. if t.Batch.Len() > batchFlushSize {
  54. t.flush()
  55. t.Batch.Reset()
  56. }
  57. }
  58. func (t readWriteTransaction) flush() {
  59. if err := t.db.Write(t.Batch, nil); err != nil {
  60. panic(err)
  61. }
  62. atomic.AddInt64(&t.db.committed, int64(t.Batch.Len()))
  63. }
  64. func (t readWriteTransaction) insertFile(fk, folder, device []byte, file protocol.FileInfo) {
  65. l.Debugf("insert; folder=%q device=%v %v", folder, protocol.DeviceIDFromBytes(device), file)
  66. t.Put(fk, mustMarshal(&file))
  67. }
  68. // updateGlobal adds this device+version to the version list for the given
  69. // file. If the device is already present in the list, the version is updated.
  70. // If the file does not have an entry in the global list, it is created.
  71. func (t readWriteTransaction) updateGlobal(gk, folder, device []byte, file protocol.FileInfo, meta *metadataTracker) bool {
  72. l.Debugf("update global; folder=%q device=%v file=%q version=%v invalid=%v", folder, protocol.DeviceIDFromBytes(device), file.Name, file.Version, file.Invalid)
  73. name := []byte(file.Name)
  74. svl, _ := t.Get(gk, nil) // skip error, we check len(svl) != 0 later
  75. var fl VersionList
  76. var oldFile protocol.FileInfo
  77. var hasOldFile bool
  78. // Remove the device from the current version list
  79. if len(svl) != 0 {
  80. fl.Unmarshal(svl) // skip error, range handles success case
  81. for i := range fl.Versions {
  82. if bytes.Equal(fl.Versions[i].Device, device) {
  83. if fl.Versions[i].Version.Equal(file.Version) && fl.Versions[i].Invalid == file.Invalid {
  84. // No need to do anything
  85. return false
  86. }
  87. if i == 0 {
  88. // Keep the current newest file around so we can subtract it from
  89. // the metadata if we replace it.
  90. oldFile, hasOldFile = t.getFile(folder, fl.Versions[0].Device, name)
  91. }
  92. fl.Versions = append(fl.Versions[:i], fl.Versions[i+1:]...)
  93. break
  94. }
  95. }
  96. }
  97. nv := FileVersion{
  98. Device: device,
  99. Version: file.Version,
  100. Invalid: file.Invalid,
  101. }
  102. insertedAt := -1
  103. // Find a position in the list to insert this file. The file at the front
  104. // of the list is the newer, the "global".
  105. insert:
  106. for i := range fl.Versions {
  107. switch fl.Versions[i].Version.Compare(file.Version) {
  108. case protocol.Equal:
  109. if nv.Invalid {
  110. continue insert
  111. }
  112. fallthrough
  113. case protocol.Lesser:
  114. // The version at this point in the list is equal to or lesser
  115. // ("older") than us. We insert ourselves in front of it.
  116. fl.Versions = insertVersion(fl.Versions, i, nv)
  117. insertedAt = i
  118. break insert
  119. case protocol.ConcurrentLesser, protocol.ConcurrentGreater:
  120. // The version at this point is in conflict with us. We must pull
  121. // the actual file metadata to determine who wins. If we win, we
  122. // insert ourselves in front of the loser here. (The "Lesser" and
  123. // "Greater" in the condition above is just based on the device
  124. // IDs in the version vector, which is not the only thing we use
  125. // to determine the winner.)
  126. //
  127. // A surprise missing file entry here is counted as a win for us.
  128. if of, ok := t.getFile(folder, fl.Versions[i].Device, name); !ok || file.WinsConflict(of) {
  129. fl.Versions = insertVersion(fl.Versions, i, nv)
  130. insertedAt = i
  131. break insert
  132. }
  133. }
  134. }
  135. if insertedAt == -1 {
  136. // We didn't find a position for an insert above, so append to the end.
  137. fl.Versions = append(fl.Versions, nv)
  138. insertedAt = len(fl.Versions) - 1
  139. }
  140. // Fixup the global size calculation.
  141. if hasOldFile {
  142. // We removed the previous newest version
  143. meta.removeFile(globalDeviceID, oldFile)
  144. if insertedAt == 0 {
  145. // inserted a new newest version
  146. meta.addFile(globalDeviceID, file)
  147. } else {
  148. // The previous second version is now the first
  149. if newGlobal, ok := t.getFile(folder, fl.Versions[0].Device, name); ok {
  150. // A failure to get the file here is surprising and our
  151. // global size data will be incorrect until a restart...
  152. meta.addFile(globalDeviceID, newGlobal)
  153. }
  154. }
  155. } else if insertedAt == 0 {
  156. // We just inserted a new newest version.
  157. meta.addFile(globalDeviceID, file)
  158. if len(fl.Versions) > 1 {
  159. // The previous newest version is now at index 1, grab it from there.
  160. if oldFile, ok := t.getFile(folder, fl.Versions[1].Device, name); ok {
  161. // A failure to get the file here is surprising and our
  162. // global size data will be incorrect until a restart...
  163. meta.removeFile(globalDeviceID, oldFile)
  164. }
  165. }
  166. }
  167. l.Debugf("new global after update: %v", fl)
  168. t.Put(gk, mustMarshal(&fl))
  169. return true
  170. }
  171. // removeFromGlobal removes the device from the global version list for the
  172. // given file. If the version list is empty after this, the file entry is
  173. // removed entirely.
  174. func (t readWriteTransaction) removeFromGlobal(gk, folder, device, file []byte, meta *metadataTracker) {
  175. l.Debugf("remove from global; folder=%q device=%v file=%q", folder, protocol.DeviceIDFromBytes(device), file)
  176. svl, err := t.Get(gk, nil)
  177. if err != nil {
  178. // We might be called to "remove" a global version that doesn't exist
  179. // if the first update for the file is already marked invalid.
  180. return
  181. }
  182. var fl VersionList
  183. err = fl.Unmarshal(svl)
  184. if err != nil {
  185. l.Debugln("unmarshal error:", err)
  186. return
  187. }
  188. removed := false
  189. for i := range fl.Versions {
  190. if bytes.Equal(fl.Versions[i].Device, device) {
  191. if i == 0 && meta != nil {
  192. f, ok := t.getFile(folder, device, file)
  193. if !ok {
  194. // didn't exist anyway, apparently
  195. continue
  196. }
  197. meta.removeFile(globalDeviceID, f)
  198. removed = true
  199. }
  200. fl.Versions = append(fl.Versions[:i], fl.Versions[i+1:]...)
  201. break
  202. }
  203. }
  204. if len(fl.Versions) == 0 {
  205. t.Delete(gk)
  206. return
  207. }
  208. l.Debugf("new global after remove: %v", fl)
  209. t.Put(gk, mustMarshal(&fl))
  210. if removed {
  211. if f, ok := t.getFile(folder, fl.Versions[0].Device, file); ok {
  212. // A failure to get the file here is surprising and our
  213. // global size data will be incorrect until a restart...
  214. meta.addFile(globalDeviceID, f)
  215. }
  216. }
  217. }
  218. func insertVersion(vl []FileVersion, i int, v FileVersion) []FileVersion {
  219. t := append(vl, FileVersion{})
  220. copy(t[i+1:], t[i:])
  221. t[i] = v
  222. return t
  223. }
  224. type marshaller interface {
  225. Marshal() ([]byte, error)
  226. }
  227. func mustMarshal(f marshaller) []byte {
  228. bs, err := f.Marshal()
  229. if err != nil {
  230. panic(err)
  231. }
  232. return bs
  233. }