transactions.go 8.1 KB

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