meta.go 11 KB

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