meta.go 11 KB

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