set.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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) Size() Counts {
  98. s.mut.Lock()
  99. defer s.mut.Unlock()
  100. return s.Counts
  101. }
  102. func NewFileSet(folder string, fs fs.Filesystem, db *Instance) *FileSet {
  103. var s = FileSet{
  104. remoteSequence: make(map[protocol.DeviceID]int64),
  105. folder: folder,
  106. fs: fs,
  107. db: db,
  108. blockmap: NewBlockMap(db, db.folderIdx.ID([]byte(folder))),
  109. updateMutex: sync.NewMutex(),
  110. }
  111. s.db.checkGlobals([]byte(folder), &s.globalSize)
  112. var deviceID protocol.DeviceID
  113. s.db.withAllFolderTruncated([]byte(folder), func(device []byte, f FileInfoTruncated) bool {
  114. copy(deviceID[:], device)
  115. if deviceID == protocol.LocalDeviceID {
  116. if f.Sequence > s.sequence {
  117. s.sequence = f.Sequence
  118. }
  119. s.localSize.addFile(f)
  120. } else if f.Sequence > s.remoteSequence[deviceID] {
  121. s.remoteSequence[deviceID] = f.Sequence
  122. }
  123. return true
  124. })
  125. l.Debugf("loaded sequence for %q: %#v", folder, s.sequence)
  126. return &s
  127. }
  128. func (s *FileSet) Replace(device protocol.DeviceID, fs []protocol.FileInfo) {
  129. l.Debugf("%s Replace(%v, [%d])", s.folder, device, len(fs))
  130. normalizeFilenames(fs)
  131. s.updateMutex.Lock()
  132. defer s.updateMutex.Unlock()
  133. if device == protocol.LocalDeviceID {
  134. if len(fs) == 0 {
  135. s.sequence = 0
  136. } else {
  137. // Always overwrite Sequence on updated files to ensure
  138. // correct ordering. The caller is supposed to leave it set to
  139. // zero anyhow.
  140. for i := range fs {
  141. fs[i].Sequence = atomic.AddInt64(&s.sequence, 1)
  142. }
  143. }
  144. } else {
  145. s.remoteSequence[device] = maxSequence(fs)
  146. }
  147. s.db.replace([]byte(s.folder), device[:], fs, &s.localSize, &s.globalSize)
  148. if device == protocol.LocalDeviceID {
  149. s.blockmap.Drop()
  150. s.blockmap.Add(fs)
  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. if device == protocol.LocalDeviceID {
  159. discards := make([]protocol.FileInfo, 0, len(fs))
  160. updates := make([]protocol.FileInfo, 0, len(fs))
  161. // db.UpdateFiles will sort unchanged files out -> save one db lookup
  162. // filter slice according to https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating
  163. oldFs := fs
  164. fs = fs[:0]
  165. for _, nf := range oldFs {
  166. ef, ok := s.db.getFile([]byte(s.folder), device[:], []byte(nf.Name))
  167. if ok && ef.Version.Equal(nf.Version) && ef.Invalid == nf.Invalid {
  168. continue
  169. }
  170. nf.Sequence = atomic.AddInt64(&s.sequence, 1)
  171. fs = append(fs, nf)
  172. discards = append(discards, ef)
  173. updates = append(updates, nf)
  174. }
  175. s.blockmap.Discard(discards)
  176. s.blockmap.Update(updates)
  177. } else {
  178. s.remoteSequence[device] = maxSequence(fs)
  179. }
  180. s.db.updateFiles([]byte(s.folder), device[:], fs, &s.localSize, &s.globalSize)
  181. }
  182. func (s *FileSet) WithNeed(device protocol.DeviceID, fn Iterator) {
  183. l.Debugf("%s WithNeed(%v)", s.folder, device)
  184. s.db.withNeed([]byte(s.folder), device[:], false, false, nativeFileIterator(fn))
  185. }
  186. func (s *FileSet) WithNeedTruncated(device protocol.DeviceID, fn Iterator) {
  187. l.Debugf("%s WithNeedTruncated(%v)", s.folder, device)
  188. s.db.withNeed([]byte(s.folder), device[:], true, false, nativeFileIterator(fn))
  189. }
  190. // WithNeedOrInvalid considers all invalid files as needed, regardless of their version
  191. // (e.g. for pulling when ignore patterns changed)
  192. func (s *FileSet) WithNeedOrInvalid(device protocol.DeviceID, fn Iterator) {
  193. l.Debugf("%s WithNeedExcludingInvalid(%v)", s.folder, device)
  194. s.db.withNeed([]byte(s.folder), device[:], false, true, nativeFileIterator(fn))
  195. }
  196. func (s *FileSet) WithNeedOrInvalidTruncated(device protocol.DeviceID, fn Iterator) {
  197. l.Debugf("%s WithNeedExcludingInvalidTruncated(%v)", s.folder, device)
  198. s.db.withNeed([]byte(s.folder), device[:], true, true, nativeFileIterator(fn))
  199. }
  200. func (s *FileSet) WithHave(device protocol.DeviceID, fn Iterator) {
  201. l.Debugf("%s WithHave(%v)", s.folder, device)
  202. s.db.withHave([]byte(s.folder), device[:], nil, false, nativeFileIterator(fn))
  203. }
  204. func (s *FileSet) WithHaveTruncated(device protocol.DeviceID, fn Iterator) {
  205. l.Debugf("%s WithHaveTruncated(%v)", s.folder, device)
  206. s.db.withHave([]byte(s.folder), device[:], nil, true, nativeFileIterator(fn))
  207. }
  208. func (s *FileSet) WithPrefixedHaveTruncated(device protocol.DeviceID, prefix string, fn Iterator) {
  209. l.Debugf("%s WithPrefixedHaveTruncated(%v)", s.folder, device)
  210. s.db.withHave([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  211. }
  212. func (s *FileSet) WithGlobal(fn Iterator) {
  213. l.Debugf("%s WithGlobal()", s.folder)
  214. s.db.withGlobal([]byte(s.folder), nil, false, nativeFileIterator(fn))
  215. }
  216. func (s *FileSet) WithGlobalTruncated(fn Iterator) {
  217. l.Debugf("%s WithGlobalTruncated()", s.folder)
  218. s.db.withGlobal([]byte(s.folder), nil, true, nativeFileIterator(fn))
  219. }
  220. func (s *FileSet) WithPrefixedGlobalTruncated(prefix string, fn Iterator) {
  221. l.Debugf("%s WithPrefixedGlobalTruncated()", s.folder, prefix)
  222. s.db.withGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  223. }
  224. func (s *FileSet) Get(device protocol.DeviceID, file string) (protocol.FileInfo, bool) {
  225. f, ok := s.db.getFile([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(file)))
  226. f.Name = osutil.NativeFilename(f.Name)
  227. return f, ok
  228. }
  229. func (s *FileSet) GetGlobal(file string) (protocol.FileInfo, bool) {
  230. fi, ok := s.db.getGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), false)
  231. if !ok {
  232. return protocol.FileInfo{}, false
  233. }
  234. f := fi.(protocol.FileInfo)
  235. f.Name = osutil.NativeFilename(f.Name)
  236. return f, true
  237. }
  238. func (s *FileSet) GetGlobalTruncated(file string) (FileInfoTruncated, bool) {
  239. fi, ok := s.db.getGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), true)
  240. if !ok {
  241. return FileInfoTruncated{}, false
  242. }
  243. f := fi.(FileInfoTruncated)
  244. f.Name = osutil.NativeFilename(f.Name)
  245. return f, true
  246. }
  247. func (s *FileSet) Availability(file string) []protocol.DeviceID {
  248. return s.db.availability([]byte(s.folder), []byte(osutil.NormalizedFilename(file)))
  249. }
  250. func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
  251. if device == protocol.LocalDeviceID {
  252. return atomic.LoadInt64(&s.sequence)
  253. }
  254. s.updateMutex.Lock()
  255. defer s.updateMutex.Unlock()
  256. return s.remoteSequence[device]
  257. }
  258. func (s *FileSet) LocalSize() Counts {
  259. return s.localSize.Size()
  260. }
  261. func (s *FileSet) GlobalSize() Counts {
  262. return s.globalSize.Size()
  263. }
  264. func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
  265. id := s.db.getIndexID(device[:], []byte(s.folder))
  266. if id == 0 && device == protocol.LocalDeviceID {
  267. // No index ID set yet. We create one now.
  268. id = protocol.NewIndexID()
  269. s.db.setIndexID(device[:], []byte(s.folder), id)
  270. }
  271. return id
  272. }
  273. func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
  274. if device == protocol.LocalDeviceID {
  275. panic("do not explicitly set index ID for local device")
  276. }
  277. s.db.setIndexID(device[:], []byte(s.folder), id)
  278. }
  279. func (s *FileSet) MtimeFS() *fs.MtimeFS {
  280. prefix := s.db.mtimesKey([]byte(s.folder))
  281. kv := NewNamespacedKV(s.db, string(prefix))
  282. return fs.NewMtimeFS(s.fs, kv)
  283. }
  284. func (s *FileSet) ListDevices() []protocol.DeviceID {
  285. s.updateMutex.Lock()
  286. devices := make([]protocol.DeviceID, 0, len(s.remoteSequence))
  287. for id, seq := range s.remoteSequence {
  288. if seq > 0 {
  289. devices = append(devices, id)
  290. }
  291. }
  292. s.updateMutex.Unlock()
  293. return devices
  294. }
  295. // maxSequence returns the highest of the Sequence numbers found in
  296. // the given slice of FileInfos. This should really be the Sequence of
  297. // the last item, but Syncthing v0.14.0 and other implementations may not
  298. // implement update sorting....
  299. func maxSequence(fs []protocol.FileInfo) int64 {
  300. var max int64
  301. for _, f := range fs {
  302. if f.Sequence > max {
  303. max = f.Sequence
  304. }
  305. }
  306. return max
  307. }
  308. // DropFolder clears out all information related to the given folder from the
  309. // database.
  310. func DropFolder(db *Instance, folder string) {
  311. db.dropFolder([]byte(folder))
  312. db.dropMtimes([]byte(folder))
  313. bm := &BlockMap{
  314. db: db,
  315. folder: db.folderIdx.ID([]byte(folder)),
  316. }
  317. bm.Drop()
  318. }
  319. func normalizeFilenames(fs []protocol.FileInfo) {
  320. for i := range fs {
  321. fs[i].Name = osutil.NormalizedFilename(fs[i].Name)
  322. }
  323. }
  324. func nativeFileIterator(fn Iterator) Iterator {
  325. return func(fi FileIntf) bool {
  326. switch f := fi.(type) {
  327. case protocol.FileInfo:
  328. f.Name = osutil.NativeFilename(f.Name)
  329. return fn(f)
  330. case FileInfoTruncated:
  331. f.Name = osutil.NativeFilename(f.Name)
  332. return fn(f)
  333. default:
  334. panic("unknown interface type")
  335. }
  336. }
  337. }