leveldb_transactions.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. "bytes"
  9. "sync/atomic"
  10. "github.com/syncthing/syncthing/lib/protocol"
  11. "github.com/syndtr/goleveldb/leveldb"
  12. "github.com/syndtr/goleveldb/leveldb/util"
  13. )
  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.db.getFile(t.db.deviceKey(folder, device, file))
  34. }
  35. // A readWriteTransaction is a readOnlyTransaction plus a batch for writes.
  36. // The batch will be committed on close() or by checkFlush() if it exceeds the
  37. // batch size.
  38. type readWriteTransaction struct {
  39. readOnlyTransaction
  40. *leveldb.Batch
  41. }
  42. func (db *Instance) newReadWriteTransaction() readWriteTransaction {
  43. t := db.newReadOnlyTransaction()
  44. return readWriteTransaction{
  45. readOnlyTransaction: t,
  46. Batch: new(leveldb.Batch),
  47. }
  48. }
  49. func (t readWriteTransaction) close() {
  50. t.flush()
  51. t.readOnlyTransaction.close()
  52. }
  53. func (t readWriteTransaction) checkFlush() {
  54. if t.Batch.Len() > batchFlushSize {
  55. t.flush()
  56. t.Batch.Reset()
  57. }
  58. }
  59. func (t readWriteTransaction) flush() {
  60. if err := t.db.Write(t.Batch, nil); err != nil {
  61. panic(err)
  62. }
  63. atomic.AddInt64(&t.db.committed, int64(t.Batch.Len()))
  64. }
  65. func (t readWriteTransaction) insertFile(fk, folder, device []byte, file protocol.FileInfo) {
  66. l.Debugf("insert; folder=%q device=%v %v", folder, protocol.DeviceIDFromBytes(device), file)
  67. t.Put(fk, mustMarshal(&file))
  68. }
  69. // updateGlobal adds this device+version to the version list for the given
  70. // file. If the device is already present in the list, the version is updated.
  71. // If the file does not have an entry in the global list, it is created.
  72. func (t readWriteTransaction) updateGlobal(gk, folder, device []byte, file protocol.FileInfo, meta *metadataTracker) bool {
  73. l.Debugf("update global; folder=%q device=%v file=%q version=%v invalid=%v", folder, protocol.DeviceIDFromBytes(device), file.Name, file.Version, file.Invalid)
  74. var fl VersionList
  75. if svl, err := t.Get(gk, nil); err == nil {
  76. fl.Unmarshal(svl) // Ignore error, continue with empty fl
  77. }
  78. fl, removedFV, removedAt, insertedAt := fl.update(folder, device, file, t.db)
  79. if insertedAt == -1 {
  80. l.Debugln("update global; same version, global unchanged")
  81. return false
  82. }
  83. name := []byte(file.Name)
  84. if removedAt != 0 && insertedAt != 0 {
  85. if bytes.Equal(device, protocol.LocalDeviceID[:]) && file.Version.Equal(fl.Versions[0].Version) {
  86. l.Debugf("local need delete; folder=%q, name=%q", folder, name)
  87. t.Delete(t.db.needKey(folder, name))
  88. }
  89. l.Debugf(`new global for "%v" after update: %v`, file.Name, fl)
  90. t.Put(gk, mustMarshal(&fl))
  91. return true
  92. }
  93. // Remove the old global from the global size counter
  94. var oldGlobalFV FileVersion
  95. if removedAt == 0 {
  96. oldGlobalFV = removedFV
  97. } else if len(fl.Versions) > 1 {
  98. // The previous newest version is now at index 1
  99. oldGlobalFV = fl.Versions[1]
  100. }
  101. if oldFile, ok := t.getFile(folder, oldGlobalFV.Device, name); ok {
  102. // A failure to get the file here is surprising and our
  103. // global size data will be incorrect until a restart...
  104. meta.removeFile(globalDeviceID, oldFile)
  105. }
  106. // Add the new global to the global size counter
  107. var newGlobal protocol.FileInfo
  108. if insertedAt == 0 {
  109. // Inserted a new newest version
  110. newGlobal = file
  111. } else if new, ok := t.getFile(folder, fl.Versions[0].Device, name); ok {
  112. // The previous second version is now the first
  113. newGlobal = new
  114. } else {
  115. panic("This file must exist in the db")
  116. }
  117. meta.addFile(globalDeviceID, newGlobal)
  118. // Fixup the list of files we need.
  119. nk := t.db.needKey(folder, name)
  120. hasNeeded, _ := t.db.Has(nk, nil)
  121. if localFV, haveLocalFV := fl.Get(protocol.LocalDeviceID[:]); need(newGlobal, haveLocalFV, localFV.Version) {
  122. if !hasNeeded {
  123. l.Debugf("local need insert; folder=%q, name=%q", folder, name)
  124. t.Put(nk, nil)
  125. }
  126. } else if hasNeeded {
  127. l.Debugf("local need delete; folder=%q, name=%q", folder, name)
  128. t.Delete(nk)
  129. }
  130. l.Debugf(`new global for "%v" after update: %v`, file.Name, fl)
  131. t.Put(gk, mustMarshal(&fl))
  132. return true
  133. }
  134. func need(global FileIntf, haveLocal bool, localVersion protocol.Vector) bool {
  135. // We never need an invalid file.
  136. if global.IsInvalid() {
  137. return false
  138. }
  139. // We don't need a deleted file if we don't have it.
  140. if global.IsDeleted() && !haveLocal {
  141. return false
  142. }
  143. // We don't need the global file if we already have the same version.
  144. if haveLocal && localVersion.Equal(global.FileVersion()) {
  145. return false
  146. }
  147. return true
  148. }
  149. // removeFromGlobal removes the device from the global version list for the
  150. // given file. If the version list is empty after this, the file entry is
  151. // removed entirely.
  152. func (t readWriteTransaction) removeFromGlobal(gk, folder, device, file []byte, meta *metadataTracker) {
  153. l.Debugf("remove from global; folder=%q device=%v file=%q", folder, protocol.DeviceIDFromBytes(device), file)
  154. svl, err := t.Get(gk, nil)
  155. if err != nil {
  156. // We might be called to "remove" a global version that doesn't exist
  157. // if the first update for the file is already marked invalid.
  158. return
  159. }
  160. var fl VersionList
  161. err = fl.Unmarshal(svl)
  162. if err != nil {
  163. l.Debugln("unmarshal error:", err)
  164. return
  165. }
  166. removed := false
  167. for i := range fl.Versions {
  168. if bytes.Equal(fl.Versions[i].Device, device) {
  169. if i == 0 && meta != nil {
  170. f, ok := t.getFile(folder, device, file)
  171. if !ok {
  172. // didn't exist anyway, apparently
  173. continue
  174. }
  175. meta.removeFile(globalDeviceID, f)
  176. removed = true
  177. }
  178. fl.Versions = append(fl.Versions[:i], fl.Versions[i+1:]...)
  179. break
  180. }
  181. }
  182. if len(fl.Versions) == 0 {
  183. t.Delete(gk)
  184. return
  185. }
  186. l.Debugf("new global after remove: %v", fl)
  187. t.Put(gk, mustMarshal(&fl))
  188. if removed {
  189. if f, ok := t.getFile(folder, fl.Versions[0].Device, file); ok {
  190. // A failure to get the file here is surprising and our
  191. // global size data will be incorrect until a restart...
  192. meta.addFile(globalDeviceID, f)
  193. }
  194. }
  195. }
  196. func (t readWriteTransaction) deleteKeyPrefix(prefix []byte) {
  197. dbi := t.NewIterator(util.BytesPrefix(prefix), nil)
  198. for dbi.Next() {
  199. t.Delete(dbi.Key())
  200. t.checkFlush()
  201. }
  202. dbi.Release()
  203. }
  204. type marshaller interface {
  205. Marshal() ([]byte, error)
  206. }
  207. func mustMarshal(f marshaller) []byte {
  208. bs, err := f.Marshal()
  209. if err != nil {
  210. panic(err)
  211. }
  212. return bs
  213. }