transactions.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. "github.com/syncthing/syncthing/lib/protocol"
  9. "github.com/syndtr/goleveldb/leveldb"
  10. "github.com/syndtr/goleveldb/leveldb/util"
  11. )
  12. // A readOnlyTransaction represents a database snapshot.
  13. type readOnlyTransaction struct {
  14. *leveldb.Snapshot
  15. keyer keyer
  16. }
  17. func (db *instance) newReadOnlyTransaction() readOnlyTransaction {
  18. snap, err := db.GetSnapshot()
  19. if err != nil {
  20. panic(err)
  21. }
  22. return readOnlyTransaction{
  23. Snapshot: snap,
  24. keyer: db.keyer,
  25. }
  26. }
  27. func (t readOnlyTransaction) close() {
  28. t.Release()
  29. }
  30. func (t readOnlyTransaction) getFile(folder, device, file []byte) (protocol.FileInfo, bool) {
  31. return t.getFileByKey(t.keyer.GenerateDeviceFileKey(nil, folder, device, file))
  32. }
  33. func (t readOnlyTransaction) getFileByKey(key []byte) (protocol.FileInfo, bool) {
  34. if f, ok := t.getFileTrunc(key, false); ok {
  35. return f.(protocol.FileInfo), true
  36. }
  37. return protocol.FileInfo{}, false
  38. }
  39. func (t readOnlyTransaction) getFileTrunc(key []byte, trunc bool) (FileIntf, bool) {
  40. bs, err := t.Get(key, nil)
  41. if err == leveldb.ErrNotFound {
  42. return nil, false
  43. }
  44. if err != nil {
  45. l.Debugln("surprise error:", err)
  46. return nil, false
  47. }
  48. f, err := unmarshalTrunc(bs, trunc)
  49. if err != nil {
  50. l.Debugln("unmarshal error:", err)
  51. return nil, false
  52. }
  53. return f, true
  54. }
  55. func (t readOnlyTransaction) getGlobal(keyBuf, folder, file []byte, truncate bool) ([]byte, FileIntf, bool) {
  56. keyBuf = t.keyer.GenerateGlobalVersionKey(keyBuf, folder, file)
  57. bs, err := t.Get(keyBuf, nil)
  58. if err != nil {
  59. return keyBuf, nil, false
  60. }
  61. vl, ok := unmarshalVersionList(bs)
  62. if !ok {
  63. return keyBuf, nil, false
  64. }
  65. keyBuf = t.keyer.GenerateDeviceFileKey(keyBuf, folder, vl.Versions[0].Device, file)
  66. if fi, ok := t.getFileTrunc(keyBuf, truncate); ok {
  67. return keyBuf, fi, true
  68. }
  69. return keyBuf, nil, false
  70. }
  71. // A readWriteTransaction is a readOnlyTransaction plus a batch for writes.
  72. // The batch will be committed on close() or by checkFlush() if it exceeds the
  73. // batch size.
  74. type readWriteTransaction struct {
  75. readOnlyTransaction
  76. *batch
  77. }
  78. func (db *instance) newReadWriteTransaction() readWriteTransaction {
  79. return readWriteTransaction{
  80. readOnlyTransaction: db.newReadOnlyTransaction(),
  81. batch: db.newBatch(),
  82. }
  83. }
  84. func (t readWriteTransaction) close() {
  85. t.flush()
  86. t.readOnlyTransaction.close()
  87. }
  88. // updateGlobal adds this device+version to the version list for the given
  89. // file. If the device is already present in the list, the version is updated.
  90. // If the file does not have an entry in the global list, it is created.
  91. func (t readWriteTransaction) updateGlobal(gk, keyBuf, folder, device []byte, file protocol.FileInfo, meta *metadataTracker) ([]byte, bool) {
  92. l.Debugf("update global; folder=%q device=%v file=%q version=%v invalid=%v", folder, protocol.DeviceIDFromBytes(device), file.Name, file.Version, file.IsInvalid())
  93. var fl VersionList
  94. if svl, err := t.Get(gk, nil); err == nil {
  95. fl.Unmarshal(svl) // Ignore error, continue with empty fl
  96. }
  97. fl, removedFV, removedAt, insertedAt := fl.update(folder, device, file, t.readOnlyTransaction)
  98. if insertedAt == -1 {
  99. l.Debugln("update global; same version, global unchanged")
  100. return keyBuf, false
  101. }
  102. name := []byte(file.Name)
  103. var global protocol.FileInfo
  104. if insertedAt == 0 {
  105. // Inserted a new newest version
  106. global = file
  107. } else {
  108. keyBuf = t.keyer.GenerateDeviceFileKey(keyBuf, folder, fl.Versions[0].Device, name)
  109. if new, ok := t.getFileByKey(keyBuf); ok {
  110. global = new
  111. } else {
  112. panic("This file must exist in the db")
  113. }
  114. }
  115. // Fixup the list of files we need.
  116. keyBuf = t.updateLocalNeed(keyBuf, folder, name, fl, global)
  117. if removedAt != 0 && insertedAt != 0 {
  118. l.Debugf(`new global for "%v" after update: %v`, file.Name, fl)
  119. t.Put(gk, mustMarshal(&fl))
  120. return keyBuf, true
  121. }
  122. // Remove the old global from the global size counter
  123. var oldGlobalFV FileVersion
  124. if removedAt == 0 {
  125. oldGlobalFV = removedFV
  126. } else if len(fl.Versions) > 1 {
  127. // The previous newest version is now at index 1
  128. oldGlobalFV = fl.Versions[1]
  129. }
  130. keyBuf = t.keyer.GenerateDeviceFileKey(keyBuf, folder, oldGlobalFV.Device, name)
  131. if oldFile, ok := t.getFileByKey(keyBuf); ok {
  132. // A failure to get the file here is surprising and our
  133. // global size data will be incorrect until a restart...
  134. meta.removeFile(protocol.GlobalDeviceID, oldFile)
  135. }
  136. // Add the new global to the global size counter
  137. meta.addFile(protocol.GlobalDeviceID, global)
  138. l.Debugf(`new global for "%v" after update: %v`, file.Name, fl)
  139. t.Put(gk, mustMarshal(&fl))
  140. return keyBuf, true
  141. }
  142. // updateLocalNeed checks whether the given file is still needed on the local
  143. // device according to the version list and global FileInfo given and updates
  144. // the db accordingly.
  145. func (t readWriteTransaction) updateLocalNeed(keyBuf, folder, name []byte, fl VersionList, global protocol.FileInfo) []byte {
  146. keyBuf = t.keyer.GenerateNeedFileKey(keyBuf, folder, name)
  147. hasNeeded, _ := t.Has(keyBuf, nil)
  148. if localFV, haveLocalFV := fl.Get(protocol.LocalDeviceID[:]); need(global, haveLocalFV, localFV.Version) {
  149. if !hasNeeded {
  150. l.Debugf("local need insert; folder=%q, name=%q", folder, name)
  151. t.Put(keyBuf, nil)
  152. }
  153. } else if hasNeeded {
  154. l.Debugf("local need delete; folder=%q, name=%q", folder, name)
  155. t.Delete(keyBuf)
  156. }
  157. return keyBuf
  158. }
  159. func need(global FileIntf, haveLocal bool, localVersion protocol.Vector) bool {
  160. // We never need an invalid file.
  161. if global.IsInvalid() {
  162. return false
  163. }
  164. // We don't need a deleted file if we don't have it.
  165. if global.IsDeleted() && !haveLocal {
  166. return false
  167. }
  168. // We don't need the global file if we already have the same version.
  169. if haveLocal && localVersion.GreaterEqual(global.FileVersion()) {
  170. return false
  171. }
  172. return true
  173. }
  174. // removeFromGlobal removes the device from the global version list for the
  175. // given file. If the version list is empty after this, the file entry is
  176. // removed entirely.
  177. func (t readWriteTransaction) removeFromGlobal(gk, keyBuf, folder, device []byte, file []byte, meta *metadataTracker) []byte {
  178. l.Debugf("remove from global; folder=%q device=%v file=%q", folder, protocol.DeviceIDFromBytes(device), file)
  179. svl, err := t.Get(gk, nil)
  180. if err != nil {
  181. // We might be called to "remove" a global version that doesn't exist
  182. // if the first update for the file is already marked invalid.
  183. return keyBuf
  184. }
  185. var fl VersionList
  186. err = fl.Unmarshal(svl)
  187. if err != nil {
  188. l.Debugln("unmarshal error:", err)
  189. return keyBuf
  190. }
  191. fl, _, removedAt := fl.pop(device)
  192. if removedAt == -1 {
  193. // There is no version for the given device
  194. return keyBuf
  195. }
  196. if removedAt == 0 {
  197. // A failure to get the file here is surprising and our
  198. // global size data will be incorrect until a restart...
  199. keyBuf = t.keyer.GenerateDeviceFileKey(keyBuf, folder, device, file)
  200. if f, ok := t.getFileByKey(keyBuf); ok {
  201. meta.removeFile(protocol.GlobalDeviceID, f)
  202. }
  203. }
  204. if len(fl.Versions) == 0 {
  205. keyBuf = t.keyer.GenerateNeedFileKey(keyBuf, folder, file)
  206. t.Delete(keyBuf)
  207. t.Delete(gk)
  208. return keyBuf
  209. }
  210. if removedAt == 0 {
  211. keyBuf = t.keyer.GenerateDeviceFileKey(keyBuf, folder, fl.Versions[0].Device, file)
  212. global, ok := t.getFileByKey(keyBuf)
  213. if !ok {
  214. panic("This file must exist in the db")
  215. }
  216. keyBuf = t.updateLocalNeed(keyBuf, folder, file, fl, global)
  217. meta.addFile(protocol.GlobalDeviceID, global)
  218. }
  219. l.Debugf("new global after remove: %v", fl)
  220. t.Put(gk, mustMarshal(&fl))
  221. return keyBuf
  222. }
  223. func (t readWriteTransaction) deleteKeyPrefix(prefix []byte) {
  224. dbi := t.NewIterator(util.BytesPrefix(prefix), nil)
  225. for dbi.Next() {
  226. t.Delete(dbi.Key())
  227. t.checkFlush()
  228. }
  229. dbi.Release()
  230. }
  231. type marshaller interface {
  232. Marshal() ([]byte, error)
  233. }
  234. func mustMarshal(f marshaller) []byte {
  235. bs, err := f.Marshal()
  236. if err != nil {
  237. panic(err)
  238. }
  239. return bs
  240. }