meta.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. // Copyright (C) 2017 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. "math/bits"
  10. "time"
  11. "github.com/syncthing/syncthing/lib/protocol"
  12. "github.com/syncthing/syncthing/lib/sync"
  13. )
  14. type countsMap struct {
  15. counts CountsSet
  16. indexes map[metaKey]int // device ID + local flags -> index in counts
  17. }
  18. // metadataTracker keeps metadata on a per device, per local flag basis.
  19. type metadataTracker struct {
  20. countsMap
  21. mut sync.RWMutex
  22. dirty bool
  23. }
  24. type metaKey struct {
  25. dev protocol.DeviceID
  26. flag uint32
  27. }
  28. const needFlag uint32 = 1 << 31 // Last bit, as early ones are local flags
  29. func newMetadataTracker() *metadataTracker {
  30. return &metadataTracker{
  31. mut: sync.NewRWMutex(),
  32. countsMap: countsMap{
  33. indexes: make(map[metaKey]int),
  34. },
  35. }
  36. }
  37. // Unmarshal loads a metadataTracker from the corresponding protobuf
  38. // representation
  39. func (m *metadataTracker) Unmarshal(bs []byte) error {
  40. if err := m.counts.Unmarshal(bs); err != nil {
  41. return err
  42. }
  43. // Initialize the index map
  44. for i, c := range m.counts.Counts {
  45. m.indexes[metaKey{protocol.DeviceIDFromBytes(c.DeviceID), c.LocalFlags}] = i
  46. }
  47. return nil
  48. }
  49. // Marshal returns the protobuf representation of the metadataTracker
  50. func (m *metadataTracker) Marshal() ([]byte, error) {
  51. return m.counts.Marshal()
  52. }
  53. // toDB saves the marshalled metadataTracker to the given db, under the key
  54. // corresponding to the given folder
  55. func (m *metadataTracker) toDB(t readWriteTransaction, folder []byte) error {
  56. key, err := t.keyer.GenerateFolderMetaKey(nil, folder)
  57. if err != nil {
  58. return err
  59. }
  60. m.mut.RLock()
  61. defer m.mut.RUnlock()
  62. if !m.dirty {
  63. return nil
  64. }
  65. bs, err := m.Marshal()
  66. if err != nil {
  67. return err
  68. }
  69. err = t.Put(key, bs)
  70. if err == nil {
  71. m.dirty = false
  72. }
  73. return err
  74. }
  75. // fromDB initializes the metadataTracker from the marshalled data found in
  76. // the database under the key corresponding to the given folder
  77. func (m *metadataTracker) fromDB(db *Lowlevel, folder []byte) error {
  78. key, err := db.keyer.GenerateFolderMetaKey(nil, folder)
  79. if err != nil {
  80. return err
  81. }
  82. bs, err := db.Get(key)
  83. if err != nil {
  84. return err
  85. }
  86. return m.Unmarshal(bs)
  87. }
  88. // countsPtr returns a pointer to the corresponding Counts struct, if
  89. // necessary allocating one in the process
  90. func (m *metadataTracker) countsPtr(dev protocol.DeviceID, flag uint32) *Counts {
  91. // must be called with the mutex held
  92. if bits.OnesCount32(flag) > 1 {
  93. panic("incorrect usage: set at most one bit in flag")
  94. }
  95. key := metaKey{dev, flag}
  96. idx, ok := m.indexes[key]
  97. if !ok {
  98. idx = len(m.counts.Counts)
  99. m.counts.Counts = append(m.counts.Counts, Counts{DeviceID: dev[:], LocalFlags: flag})
  100. m.indexes[key] = idx
  101. if flag == needFlag {
  102. // Initially a new device needs everything, except deletes
  103. m.counts.Counts[idx] = m.allNeededCounts(dev)
  104. }
  105. }
  106. return &m.counts.Counts[idx]
  107. }
  108. // allNeeded makes sure there is a counts in case the device needs everything.
  109. func (m *countsMap) allNeededCounts(dev protocol.DeviceID) Counts {
  110. counts := Counts{}
  111. if idx, ok := m.indexes[metaKey{protocol.GlobalDeviceID, 0}]; ok {
  112. counts = m.counts.Counts[idx]
  113. counts.Deleted = 0 // Don't need deletes if having nothing
  114. }
  115. counts.DeviceID = dev[:]
  116. counts.LocalFlags = needFlag
  117. return counts
  118. }
  119. // addFile adds a file to the counts, adjusting the sequence number as
  120. // appropriate
  121. func (m *metadataTracker) addFile(dev protocol.DeviceID, f FileIntf) {
  122. m.mut.Lock()
  123. defer m.mut.Unlock()
  124. m.dirty = true
  125. m.updateSeqLocked(dev, f)
  126. if f.IsInvalid() && f.FileLocalFlags() == 0 {
  127. // This is a remote invalid file; it does not count.
  128. return
  129. }
  130. if flags := f.FileLocalFlags(); flags == 0 {
  131. // Account regular files in the zero-flags bucket.
  132. m.addFileLocked(dev, 0, f)
  133. } else {
  134. // Account in flag specific buckets.
  135. eachFlagBit(flags, func(flag uint32) {
  136. m.addFileLocked(dev, flag, f)
  137. })
  138. }
  139. }
  140. // emptyNeeded makes sure there is a zero counts in case the device needs nothing.
  141. func (m *metadataTracker) emptyNeeded(dev protocol.DeviceID) {
  142. m.mut.Lock()
  143. defer m.mut.Unlock()
  144. m.dirty = true
  145. m.indexes[metaKey{dev, needFlag}] = len(m.counts.Counts)
  146. m.counts.Counts = append(m.counts.Counts, Counts{
  147. DeviceID: dev[:],
  148. LocalFlags: needFlag,
  149. })
  150. }
  151. // addNeeded adds a file to the needed counts
  152. func (m *metadataTracker) addNeeded(dev protocol.DeviceID, f FileIntf) {
  153. m.mut.Lock()
  154. defer m.mut.Unlock()
  155. m.dirty = true
  156. m.addFileLocked(dev, needFlag, f)
  157. }
  158. func (m *metadataTracker) Sequence(dev protocol.DeviceID) int64 {
  159. m.mut.Lock()
  160. defer m.mut.Unlock()
  161. return m.countsPtr(dev, 0).Sequence
  162. }
  163. func (m *metadataTracker) updateSeqLocked(dev protocol.DeviceID, f FileIntf) {
  164. if dev == protocol.GlobalDeviceID {
  165. return
  166. }
  167. if cp := m.countsPtr(dev, 0); f.SequenceNo() > cp.Sequence {
  168. cp.Sequence = f.SequenceNo()
  169. }
  170. }
  171. func (m *metadataTracker) addFileLocked(dev protocol.DeviceID, flag uint32, f FileIntf) {
  172. cp := m.countsPtr(dev, flag)
  173. switch {
  174. case f.IsDeleted():
  175. cp.Deleted++
  176. case f.IsDirectory() && !f.IsSymlink():
  177. cp.Directories++
  178. case f.IsSymlink():
  179. cp.Symlinks++
  180. default:
  181. cp.Files++
  182. }
  183. cp.Bytes += f.FileSize()
  184. }
  185. // removeFile removes a file from the counts
  186. func (m *metadataTracker) removeFile(dev protocol.DeviceID, f FileIntf) {
  187. if f.IsInvalid() && f.FileLocalFlags() == 0 {
  188. // This is a remote invalid file; it does not count.
  189. return
  190. }
  191. m.mut.Lock()
  192. defer m.mut.Unlock()
  193. m.dirty = true
  194. if flags := f.FileLocalFlags(); flags == 0 {
  195. // Remove regular files from the zero-flags bucket
  196. m.removeFileLocked(dev, 0, f)
  197. } else {
  198. // Remove from flag specific buckets.
  199. eachFlagBit(flags, func(flag uint32) {
  200. m.removeFileLocked(dev, flag, f)
  201. })
  202. }
  203. }
  204. // removeNeeded removes a file from the needed counts
  205. func (m *metadataTracker) removeNeeded(dev protocol.DeviceID, f FileIntf) {
  206. m.mut.Lock()
  207. defer m.mut.Unlock()
  208. m.dirty = true
  209. m.removeFileLocked(dev, needFlag, f)
  210. }
  211. func (m *metadataTracker) removeFileLocked(dev protocol.DeviceID, flag uint32, f FileIntf) {
  212. cp := m.countsPtr(dev, flag)
  213. switch {
  214. case f.IsDeleted():
  215. cp.Deleted--
  216. case f.IsDirectory() && !f.IsSymlink():
  217. cp.Directories--
  218. case f.IsSymlink():
  219. cp.Symlinks--
  220. default:
  221. cp.Files--
  222. }
  223. cp.Bytes -= f.FileSize()
  224. // If we've run into an impossible situation, correct it for now and set
  225. // the created timestamp to zero. Next time we start up the metadata
  226. // will be seen as infinitely old and recalculated from scratch.
  227. if cp.Deleted < 0 {
  228. cp.Deleted = 0
  229. m.counts.Created = 0
  230. }
  231. if cp.Files < 0 {
  232. cp.Files = 0
  233. m.counts.Created = 0
  234. }
  235. if cp.Directories < 0 {
  236. cp.Directories = 0
  237. m.counts.Created = 0
  238. }
  239. if cp.Symlinks < 0 {
  240. cp.Symlinks = 0
  241. m.counts.Created = 0
  242. }
  243. }
  244. // resetAll resets all metadata for the given device
  245. func (m *metadataTracker) resetAll(dev protocol.DeviceID) {
  246. m.mut.Lock()
  247. m.dirty = true
  248. for i, c := range m.counts.Counts {
  249. if bytes.Equal(c.DeviceID, dev[:]) {
  250. m.counts.Counts[i] = Counts{
  251. DeviceID: c.DeviceID,
  252. LocalFlags: c.LocalFlags,
  253. }
  254. }
  255. }
  256. m.mut.Unlock()
  257. }
  258. // resetCounts resets the file, dir, etc. counters, while retaining the
  259. // sequence number
  260. func (m *metadataTracker) resetCounts(dev protocol.DeviceID) {
  261. m.mut.Lock()
  262. m.dirty = true
  263. for i, c := range m.counts.Counts {
  264. if bytes.Equal(c.DeviceID, dev[:]) {
  265. m.counts.Counts[i] = Counts{
  266. DeviceID: c.DeviceID,
  267. Sequence: c.Sequence,
  268. LocalFlags: c.LocalFlags,
  269. }
  270. }
  271. }
  272. m.mut.Unlock()
  273. }
  274. func (m *countsMap) Counts(dev protocol.DeviceID, flag uint32) Counts {
  275. if bits.OnesCount32(flag) > 1 {
  276. panic("incorrect usage: set at most one bit in flag")
  277. }
  278. idx, ok := m.indexes[metaKey{dev, flag}]
  279. if !ok {
  280. if flag == needFlag {
  281. // If there's nothing about a device in the index yet,
  282. // it needs everything.
  283. return m.allNeededCounts(dev)
  284. }
  285. return Counts{}
  286. }
  287. return m.counts.Counts[idx]
  288. }
  289. // Snapshot returns a copy of the metadata for reading.
  290. func (m *metadataTracker) Snapshot() *countsMap {
  291. m.mut.RLock()
  292. defer m.mut.RUnlock()
  293. c := &countsMap{
  294. counts: CountsSet{
  295. Counts: make([]Counts, len(m.counts.Counts)),
  296. Created: m.counts.Created,
  297. },
  298. indexes: make(map[metaKey]int, len(m.indexes)),
  299. }
  300. for k, v := range m.indexes {
  301. c.indexes[k] = v
  302. }
  303. for i := range m.counts.Counts {
  304. c.counts.Counts[i] = m.counts.Counts[i]
  305. }
  306. return c
  307. }
  308. // nextLocalSeq allocates a new local sequence number
  309. func (m *metadataTracker) nextLocalSeq() int64 {
  310. m.mut.Lock()
  311. defer m.mut.Unlock()
  312. c := m.countsPtr(protocol.LocalDeviceID, 0)
  313. c.Sequence++
  314. return c.Sequence
  315. }
  316. // devices returns the list of devices tracked, excluding the local device
  317. // (which we don't know the ID of)
  318. func (m *metadataTracker) devices() []protocol.DeviceID {
  319. m.mut.RLock()
  320. defer m.mut.RUnlock()
  321. return m.countsMap.devices()
  322. }
  323. func (m *countsMap) devices() []protocol.DeviceID {
  324. devs := make([]protocol.DeviceID, 0, len(m.counts.Counts))
  325. for _, dev := range m.counts.Counts {
  326. if dev.Sequence > 0 {
  327. id := protocol.DeviceIDFromBytes(dev.DeviceID)
  328. if id == protocol.GlobalDeviceID || id == protocol.LocalDeviceID {
  329. continue
  330. }
  331. devs = append(devs, id)
  332. }
  333. }
  334. return devs
  335. }
  336. func (m *metadataTracker) Created() time.Time {
  337. m.mut.RLock()
  338. defer m.mut.RUnlock()
  339. return time.Unix(0, m.counts.Created)
  340. }
  341. func (m *metadataTracker) SetCreated() {
  342. m.mut.Lock()
  343. m.counts.Created = time.Now().UnixNano()
  344. m.dirty = true
  345. m.mut.Unlock()
  346. }
  347. // eachFlagBit calls the function once for every bit that is set in flags
  348. func eachFlagBit(flags uint32, fn func(flag uint32)) {
  349. // Test each bit from the right, as long as there are bits left in the
  350. // flag set. Clear any bits found and stop testing as soon as there are
  351. // no more bits set.
  352. currentBit := uint32(1 << 0)
  353. for flags != 0 {
  354. if flags&currentBit != 0 {
  355. fn(currentBit)
  356. flags &^= currentBit
  357. }
  358. currentBit <<= 1
  359. }
  360. }