leveldb_transactions.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 getFile(t, 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(folder, device []byte, file protocol.FileInfo) {
  65. l.Debugf("insert; folder=%q device=%v %v", folder, protocol.DeviceIDFromBytes(device), file)
  66. name := []byte(file.Name)
  67. nk := t.db.deviceKey(folder, device, name)
  68. t.Put(nk, mustMarshal(&file))
  69. }
  70. // updateGlobal adds this device+version to the version list for the given
  71. // file. If the device is already present in the list, the version is updated.
  72. // If the file does not have an entry in the global list, it is created.
  73. func (t readWriteTransaction) updateGlobal(folder, device []byte, file protocol.FileInfo, meta *metadataTracker) bool {
  74. l.Debugf("update global; folder=%q device=%v file=%q version=%v invalid=%v", folder, protocol.DeviceIDFromBytes(device), file.Name, file.Version, file.Invalid)
  75. name := []byte(file.Name)
  76. gk := t.db.globalKey(folder, name)
  77. svl, _ := t.Get(gk, nil) // skip error, we check len(svl) != 0 later
  78. var fl VersionList
  79. var oldFile protocol.FileInfo
  80. var hasOldFile bool
  81. // Remove the device from the current version list
  82. if len(svl) != 0 {
  83. fl.Unmarshal(svl) // skip error, range handles success case
  84. for i := range fl.Versions {
  85. if bytes.Equal(fl.Versions[i].Device, device) {
  86. if fl.Versions[i].Version.Equal(file.Version) && fl.Versions[i].Invalid == file.Invalid {
  87. // No need to do anything
  88. return false
  89. }
  90. if i == 0 {
  91. // Keep the current newest file around so we can subtract it from
  92. // the metadata if we replace it.
  93. oldFile, hasOldFile = t.getFile(folder, fl.Versions[0].Device, name)
  94. }
  95. fl.Versions = append(fl.Versions[:i], fl.Versions[i+1:]...)
  96. break
  97. }
  98. }
  99. }
  100. nv := FileVersion{
  101. Device: device,
  102. Version: file.Version,
  103. Invalid: file.Invalid,
  104. }
  105. insertedAt := -1
  106. // Find a position in the list to insert this file. The file at the front
  107. // of the list is the newer, the "global".
  108. insert:
  109. for i := range fl.Versions {
  110. switch fl.Versions[i].Version.Compare(file.Version) {
  111. case protocol.Equal:
  112. if nv.Invalid {
  113. continue insert
  114. }
  115. fallthrough
  116. case protocol.Lesser:
  117. // The version at this point in the list is equal to or lesser
  118. // ("older") than us. We insert ourselves in front of it.
  119. fl.Versions = insertVersion(fl.Versions, i, nv)
  120. insertedAt = i
  121. break insert
  122. case protocol.ConcurrentLesser, protocol.ConcurrentGreater:
  123. // The version at this point is in conflict with us. We must pull
  124. // the actual file metadata to determine who wins. If we win, we
  125. // insert ourselves in front of the loser here. (The "Lesser" and
  126. // "Greater" in the condition above is just based on the device
  127. // IDs in the version vector, which is not the only thing we use
  128. // to determine the winner.)
  129. //
  130. // A surprise missing file entry here is counted as a win for us.
  131. of, ok := t.getFile(folder, fl.Versions[i].Device, name)
  132. if !ok || file.WinsConflict(of) {
  133. fl.Versions = insertVersion(fl.Versions, i, nv)
  134. insertedAt = i
  135. break insert
  136. }
  137. }
  138. }
  139. if insertedAt == -1 {
  140. // We didn't find a position for an insert above, so append to the end.
  141. fl.Versions = append(fl.Versions, nv)
  142. insertedAt = len(fl.Versions) - 1
  143. }
  144. if insertedAt == 0 {
  145. // We just inserted a new newest version. Fixup the global size
  146. // calculation.
  147. if !file.Version.Equal(oldFile.Version) || file.Invalid != oldFile.Invalid {
  148. meta.addFile(globalDeviceID, file)
  149. if hasOldFile {
  150. // We have the old file that was removed at the head of the list.
  151. meta.removeFile(globalDeviceID, oldFile)
  152. } else if len(fl.Versions) > 1 {
  153. // The previous newest version is now at index 1, grab it from there.
  154. if oldFile, ok := t.getFile(folder, fl.Versions[1].Device, name); ok {
  155. // A failure to get the file here is surprising and our
  156. // global size data will be incorrect until a restart...
  157. meta.removeFile(globalDeviceID, oldFile)
  158. }
  159. }
  160. }
  161. }
  162. l.Debugf("new global after update: %v", fl)
  163. t.Put(gk, mustMarshal(&fl))
  164. return true
  165. }
  166. // removeFromGlobal removes the device from the global version list for the
  167. // given file. If the version list is empty after this, the file entry is
  168. // removed entirely.
  169. func (t readWriteTransaction) removeFromGlobal(folder, device, file []byte, meta *metadataTracker) {
  170. l.Debugf("remove from global; folder=%q device=%v file=%q", folder, protocol.DeviceIDFromBytes(device), file)
  171. gk := t.db.globalKey(folder, file)
  172. svl, err := t.Get(gk, nil)
  173. if err != nil {
  174. // We might be called to "remove" a global version that doesn't exist
  175. // if the first update for the file is already marked invalid.
  176. return
  177. }
  178. var fl VersionList
  179. err = fl.Unmarshal(svl)
  180. if err != nil {
  181. l.Debugln("unmarshal error:", err)
  182. return
  183. }
  184. removed := false
  185. for i := range fl.Versions {
  186. if bytes.Equal(fl.Versions[i].Device, device) {
  187. if i == 0 && meta != nil {
  188. f, ok := t.getFile(folder, device, file)
  189. if !ok {
  190. // didn't exist anyway, apparently
  191. continue
  192. }
  193. meta.removeFile(globalDeviceID, f)
  194. removed = true
  195. }
  196. fl.Versions = append(fl.Versions[:i], fl.Versions[i+1:]...)
  197. break
  198. }
  199. }
  200. if len(fl.Versions) == 0 {
  201. t.Delete(gk)
  202. return
  203. }
  204. l.Debugf("new global after remove: %v", fl)
  205. t.Put(gk, mustMarshal(&fl))
  206. if removed {
  207. if f, ok := t.getFile(folder, fl.Versions[0].Device, file); ok {
  208. // A failure to get the file here is surprising and our
  209. // global size data will be incorrect until a restart...
  210. meta.addFile(globalDeviceID, f)
  211. }
  212. }
  213. }
  214. func insertVersion(vl []FileVersion, i int, v FileVersion) []FileVersion {
  215. t := append(vl, FileVersion{})
  216. copy(t[i+1:], t[i:])
  217. t[i] = v
  218. return t
  219. }
  220. type marshaller interface {
  221. Marshal() ([]byte, error)
  222. }
  223. func mustMarshal(f marshaller) []byte {
  224. bs, err := f.Marshal()
  225. if err != nil {
  226. panic(err)
  227. }
  228. return bs
  229. }