leveldb_transactions.go 7.0 KB

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