set.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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 provides a set type to track local/remote files with newness
  7. // checks. We must do a certain amount of normalization in here. We will get
  8. // fed paths with either native or wire-format separators and encodings
  9. // depending on who calls us. We transform paths to wire-format (NFC and
  10. // slashes) on the way to the database, and transform to native format
  11. // (varying separator and encoding) on the way back out.
  12. package db
  13. import (
  14. stdsync "sync"
  15. "sync/atomic"
  16. "github.com/syncthing/syncthing/lib/fs"
  17. "github.com/syncthing/syncthing/lib/osutil"
  18. "github.com/syncthing/syncthing/lib/protocol"
  19. "github.com/syncthing/syncthing/lib/sync"
  20. )
  21. type FileSet struct {
  22. sequence int64 // Our local sequence number
  23. folder string
  24. fs fs.Filesystem
  25. db *Instance
  26. blockmap *BlockMap
  27. localSize sizeTracker
  28. globalSize sizeTracker
  29. remoteSequence map[protocol.DeviceID]int64 // Highest seen sequence numbers for other devices
  30. updateMutex sync.Mutex // protects remoteSequence and database updates
  31. }
  32. // FileIntf is the set of methods implemented by both protocol.FileInfo and
  33. // FileInfoTruncated.
  34. type FileIntf interface {
  35. FileSize() int64
  36. FileName() string
  37. IsDeleted() bool
  38. IsInvalid() bool
  39. IsDirectory() bool
  40. IsSymlink() bool
  41. HasPermissionBits() bool
  42. }
  43. // The Iterator is called with either a protocol.FileInfo or a
  44. // FileInfoTruncated (depending on the method) and returns true to
  45. // continue iteration, false to stop.
  46. type Iterator func(f FileIntf) bool
  47. type Counts struct {
  48. Files int
  49. Directories int
  50. Symlinks int
  51. Deleted int
  52. Bytes int64
  53. }
  54. type sizeTracker struct {
  55. Counts
  56. mut stdsync.Mutex
  57. }
  58. func (s *sizeTracker) addFile(f FileIntf) {
  59. if f.IsInvalid() {
  60. return
  61. }
  62. s.mut.Lock()
  63. switch {
  64. case f.IsDeleted():
  65. s.Deleted++
  66. case f.IsDirectory() && !f.IsSymlink():
  67. s.Directories++
  68. case f.IsSymlink():
  69. s.Symlinks++
  70. default:
  71. s.Files++
  72. }
  73. s.Bytes += f.FileSize()
  74. s.mut.Unlock()
  75. }
  76. func (s *sizeTracker) removeFile(f FileIntf) {
  77. if f.IsInvalid() {
  78. return
  79. }
  80. s.mut.Lock()
  81. switch {
  82. case f.IsDeleted():
  83. s.Deleted--
  84. case f.IsDirectory() && !f.IsSymlink():
  85. s.Directories--
  86. case f.IsSymlink():
  87. s.Symlinks--
  88. default:
  89. s.Files--
  90. }
  91. s.Bytes -= f.FileSize()
  92. if s.Deleted < 0 || s.Files < 0 || s.Directories < 0 || s.Symlinks < 0 {
  93. panic("bug: removed more than added")
  94. }
  95. s.mut.Unlock()
  96. }
  97. func (s *sizeTracker) reset() {
  98. s.mut.Lock()
  99. defer s.mut.Unlock()
  100. s.Counts = Counts{}
  101. }
  102. func (s *sizeTracker) Size() Counts {
  103. s.mut.Lock()
  104. defer s.mut.Unlock()
  105. return s.Counts
  106. }
  107. func NewFileSet(folder string, fs fs.Filesystem, db *Instance) *FileSet {
  108. var s = FileSet{
  109. remoteSequence: make(map[protocol.DeviceID]int64),
  110. folder: folder,
  111. fs: fs,
  112. db: db,
  113. blockmap: NewBlockMap(db, db.folderIdx.ID([]byte(folder))),
  114. updateMutex: sync.NewMutex(),
  115. }
  116. s.db.checkGlobals([]byte(folder), &s.globalSize)
  117. var deviceID protocol.DeviceID
  118. s.db.withAllFolderTruncated([]byte(folder), func(device []byte, f FileInfoTruncated) bool {
  119. copy(deviceID[:], device)
  120. if deviceID == protocol.LocalDeviceID {
  121. if f.Sequence > s.sequence {
  122. s.sequence = f.Sequence
  123. }
  124. s.localSize.addFile(f)
  125. } else if f.Sequence > s.remoteSequence[deviceID] {
  126. s.remoteSequence[deviceID] = f.Sequence
  127. }
  128. return true
  129. })
  130. l.Debugf("loaded sequence for %q: %#v", folder, s.sequence)
  131. return &s
  132. }
  133. func (s *FileSet) Drop(device protocol.DeviceID) {
  134. l.Debugf("%s Drop(%v)", s.folder, device)
  135. s.updateMutex.Lock()
  136. defer s.updateMutex.Unlock()
  137. s.db.dropDeviceFolder(device[:], []byte(s.folder), &s.globalSize)
  138. if device == protocol.LocalDeviceID {
  139. s.blockmap.Drop()
  140. s.localSize.reset()
  141. // We deliberately do not reset s.sequence here. Dropping all files
  142. // for the local device ID only happens in testing - which expects
  143. // the sequence to be retained, like an old Replace() of all files
  144. // would do. However, if we ever did it "in production" we would
  145. // anyway want to retain the sequence for delta indexes to be happy.
  146. } else {
  147. // Here, on the other hand, we want to make sure that any file
  148. // announced from the remote is newer than our current sequence
  149. // number.
  150. s.remoteSequence[device] = 0
  151. }
  152. }
  153. func (s *FileSet) Update(device protocol.DeviceID, fs []protocol.FileInfo) {
  154. l.Debugf("%s Update(%v, [%d])", s.folder, device, len(fs))
  155. normalizeFilenames(fs)
  156. s.updateMutex.Lock()
  157. defer s.updateMutex.Unlock()
  158. s.updateLocked(device, fs)
  159. }
  160. func (s *FileSet) updateLocked(device protocol.DeviceID, fs []protocol.FileInfo) {
  161. // names must be normalized and the lock held
  162. if device == protocol.LocalDeviceID {
  163. discards := make([]protocol.FileInfo, 0, len(fs))
  164. updates := make([]protocol.FileInfo, 0, len(fs))
  165. // db.UpdateFiles will sort unchanged files out -> save one db lookup
  166. // filter slice according to https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating
  167. oldFs := fs
  168. fs = fs[:0]
  169. for _, nf := range oldFs {
  170. ef, ok := s.db.getFile([]byte(s.folder), device[:], []byte(nf.Name))
  171. if ok && ef.Version.Equal(nf.Version) && ef.Invalid == nf.Invalid {
  172. continue
  173. }
  174. nf.Sequence = atomic.AddInt64(&s.sequence, 1)
  175. fs = append(fs, nf)
  176. if ok {
  177. discards = append(discards, ef)
  178. }
  179. updates = append(updates, nf)
  180. }
  181. s.blockmap.Discard(discards)
  182. s.blockmap.Update(updates)
  183. } else {
  184. s.remoteSequence[device] = maxSequence(fs)
  185. }
  186. s.db.updateFiles([]byte(s.folder), device[:], fs, &s.localSize, &s.globalSize)
  187. }
  188. func (s *FileSet) WithNeed(device protocol.DeviceID, fn Iterator) {
  189. l.Debugf("%s WithNeed(%v)", s.folder, device)
  190. s.db.withNeed([]byte(s.folder), device[:], false, false, nativeFileIterator(fn))
  191. }
  192. func (s *FileSet) WithNeedTruncated(device protocol.DeviceID, fn Iterator) {
  193. l.Debugf("%s WithNeedTruncated(%v)", s.folder, device)
  194. s.db.withNeed([]byte(s.folder), device[:], true, false, nativeFileIterator(fn))
  195. }
  196. // WithNeedOrInvalid considers all invalid files as needed, regardless of their version
  197. // (e.g. for pulling when ignore patterns changed)
  198. func (s *FileSet) WithNeedOrInvalid(device protocol.DeviceID, fn Iterator) {
  199. l.Debugf("%s WithNeedExcludingInvalid(%v)", s.folder, device)
  200. s.db.withNeed([]byte(s.folder), device[:], false, true, nativeFileIterator(fn))
  201. }
  202. func (s *FileSet) WithNeedOrInvalidTruncated(device protocol.DeviceID, fn Iterator) {
  203. l.Debugf("%s WithNeedExcludingInvalidTruncated(%v)", s.folder, device)
  204. s.db.withNeed([]byte(s.folder), device[:], true, true, nativeFileIterator(fn))
  205. }
  206. func (s *FileSet) WithHave(device protocol.DeviceID, fn Iterator) {
  207. l.Debugf("%s WithHave(%v)", s.folder, device)
  208. s.db.withHave([]byte(s.folder), device[:], nil, false, nativeFileIterator(fn))
  209. }
  210. func (s *FileSet) WithHaveTruncated(device protocol.DeviceID, fn Iterator) {
  211. l.Debugf("%s WithHaveTruncated(%v)", s.folder, device)
  212. s.db.withHave([]byte(s.folder), device[:], nil, true, nativeFileIterator(fn))
  213. }
  214. func (s *FileSet) WithPrefixedHaveTruncated(device protocol.DeviceID, prefix string, fn Iterator) {
  215. l.Debugf("%s WithPrefixedHaveTruncated(%v)", s.folder, device)
  216. s.db.withHave([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  217. }
  218. func (s *FileSet) WithGlobal(fn Iterator) {
  219. l.Debugf("%s WithGlobal()", s.folder)
  220. s.db.withGlobal([]byte(s.folder), nil, false, nativeFileIterator(fn))
  221. }
  222. func (s *FileSet) WithGlobalTruncated(fn Iterator) {
  223. l.Debugf("%s WithGlobalTruncated()", s.folder)
  224. s.db.withGlobal([]byte(s.folder), nil, true, nativeFileIterator(fn))
  225. }
  226. func (s *FileSet) WithPrefixedGlobalTruncated(prefix string, fn Iterator) {
  227. l.Debugf("%s WithPrefixedGlobalTruncated()", s.folder, prefix)
  228. s.db.withGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  229. }
  230. func (s *FileSet) Get(device protocol.DeviceID, file string) (protocol.FileInfo, bool) {
  231. f, ok := s.db.getFile([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(file)))
  232. f.Name = osutil.NativeFilename(f.Name)
  233. return f, ok
  234. }
  235. func (s *FileSet) GetGlobal(file string) (protocol.FileInfo, bool) {
  236. fi, ok := s.db.getGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), false)
  237. if !ok {
  238. return protocol.FileInfo{}, false
  239. }
  240. f := fi.(protocol.FileInfo)
  241. f.Name = osutil.NativeFilename(f.Name)
  242. return f, true
  243. }
  244. func (s *FileSet) GetGlobalTruncated(file string) (FileInfoTruncated, bool) {
  245. fi, ok := s.db.getGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), true)
  246. if !ok {
  247. return FileInfoTruncated{}, false
  248. }
  249. f := fi.(FileInfoTruncated)
  250. f.Name = osutil.NativeFilename(f.Name)
  251. return f, true
  252. }
  253. func (s *FileSet) Availability(file string) []protocol.DeviceID {
  254. return s.db.availability([]byte(s.folder), []byte(osutil.NormalizedFilename(file)))
  255. }
  256. func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
  257. if device == protocol.LocalDeviceID {
  258. return atomic.LoadInt64(&s.sequence)
  259. }
  260. s.updateMutex.Lock()
  261. defer s.updateMutex.Unlock()
  262. return s.remoteSequence[device]
  263. }
  264. func (s *FileSet) LocalSize() Counts {
  265. return s.localSize.Size()
  266. }
  267. func (s *FileSet) GlobalSize() Counts {
  268. return s.globalSize.Size()
  269. }
  270. func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
  271. id := s.db.getIndexID(device[:], []byte(s.folder))
  272. if id == 0 && device == protocol.LocalDeviceID {
  273. // No index ID set yet. We create one now.
  274. id = protocol.NewIndexID()
  275. s.db.setIndexID(device[:], []byte(s.folder), id)
  276. }
  277. return id
  278. }
  279. func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
  280. if device == protocol.LocalDeviceID {
  281. panic("do not explicitly set index ID for local device")
  282. }
  283. s.db.setIndexID(device[:], []byte(s.folder), id)
  284. }
  285. func (s *FileSet) MtimeFS() *fs.MtimeFS {
  286. prefix := s.db.mtimesKey([]byte(s.folder))
  287. kv := NewNamespacedKV(s.db, string(prefix))
  288. return fs.NewMtimeFS(s.fs, kv)
  289. }
  290. func (s *FileSet) ListDevices() []protocol.DeviceID {
  291. s.updateMutex.Lock()
  292. devices := make([]protocol.DeviceID, 0, len(s.remoteSequence))
  293. for id, seq := range s.remoteSequence {
  294. if seq > 0 {
  295. devices = append(devices, id)
  296. }
  297. }
  298. s.updateMutex.Unlock()
  299. return devices
  300. }
  301. // maxSequence returns the highest of the Sequence numbers found in
  302. // the given slice of FileInfos. This should really be the Sequence of
  303. // the last item, but Syncthing v0.14.0 and other implementations may not
  304. // implement update sorting....
  305. func maxSequence(fs []protocol.FileInfo) int64 {
  306. var max int64
  307. for _, f := range fs {
  308. if f.Sequence > max {
  309. max = f.Sequence
  310. }
  311. }
  312. return max
  313. }
  314. // DropFolder clears out all information related to the given folder from the
  315. // database.
  316. func DropFolder(db *Instance, folder string) {
  317. db.dropFolder([]byte(folder))
  318. db.dropMtimes([]byte(folder))
  319. bm := &BlockMap{
  320. db: db,
  321. folder: db.folderIdx.ID([]byte(folder)),
  322. }
  323. bm.Drop()
  324. }
  325. func normalizeFilenames(fs []protocol.FileInfo) {
  326. for i := range fs {
  327. fs[i].Name = osutil.NormalizedFilename(fs[i].Name)
  328. }
  329. }
  330. func nativeFileIterator(fn Iterator) Iterator {
  331. return func(fi FileIntf) bool {
  332. switch f := fi.(type) {
  333. case protocol.FileInfo:
  334. f.Name = osutil.NativeFilename(f.Name)
  335. return fn(f)
  336. case FileInfoTruncated:
  337. f.Name = osutil.NativeFilename(f.Name)
  338. return fn(f)
  339. default:
  340. panic("unknown interface type")
  341. }
  342. }
  343. }