meta.go 11 KB

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