leveldb_transactions.go 6.9 KB

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