transactions.go 8.3 KB

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