set.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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, 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, nativeFileIterator(fn))
  189. }
  190. func (s *FileSet) WithHave(device protocol.DeviceID, fn Iterator) {
  191. l.Debugf("%s WithHave(%v)", s.folder, device)
  192. s.db.withHave([]byte(s.folder), device[:], nil, false, nativeFileIterator(fn))
  193. }
  194. func (s *FileSet) WithHaveTruncated(device protocol.DeviceID, fn Iterator) {
  195. l.Debugf("%s WithHaveTruncated(%v)", s.folder, device)
  196. s.db.withHave([]byte(s.folder), device[:], nil, true, nativeFileIterator(fn))
  197. }
  198. func (s *FileSet) WithPrefixedHaveTruncated(device protocol.DeviceID, prefix string, fn Iterator) {
  199. l.Debugf("%s WithPrefixedHaveTruncated(%v)", s.folder, device)
  200. s.db.withHave([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  201. }
  202. func (s *FileSet) WithGlobal(fn Iterator) {
  203. l.Debugf("%s WithGlobal()", s.folder)
  204. s.db.withGlobal([]byte(s.folder), nil, false, nativeFileIterator(fn))
  205. }
  206. func (s *FileSet) WithGlobalTruncated(fn Iterator) {
  207. l.Debugf("%s WithGlobalTruncated()", s.folder)
  208. s.db.withGlobal([]byte(s.folder), nil, true, nativeFileIterator(fn))
  209. }
  210. func (s *FileSet) WithPrefixedGlobalTruncated(prefix string, fn Iterator) {
  211. l.Debugf("%s WithPrefixedGlobalTruncated()", s.folder, prefix)
  212. s.db.withGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  213. }
  214. func (s *FileSet) Get(device protocol.DeviceID, file string) (protocol.FileInfo, bool) {
  215. f, ok := s.db.getFile([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(file)))
  216. f.Name = osutil.NativeFilename(f.Name)
  217. return f, ok
  218. }
  219. func (s *FileSet) GetGlobal(file string) (protocol.FileInfo, bool) {
  220. fi, ok := s.db.getGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), false)
  221. if !ok {
  222. return protocol.FileInfo{}, false
  223. }
  224. f := fi.(protocol.FileInfo)
  225. f.Name = osutil.NativeFilename(f.Name)
  226. return f, true
  227. }
  228. func (s *FileSet) GetGlobalTruncated(file string) (FileInfoTruncated, bool) {
  229. fi, ok := s.db.getGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), true)
  230. if !ok {
  231. return FileInfoTruncated{}, false
  232. }
  233. f := fi.(FileInfoTruncated)
  234. f.Name = osutil.NativeFilename(f.Name)
  235. return f, true
  236. }
  237. func (s *FileSet) Availability(file string) []protocol.DeviceID {
  238. return s.db.availability([]byte(s.folder), []byte(osutil.NormalizedFilename(file)))
  239. }
  240. func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
  241. if device == protocol.LocalDeviceID {
  242. return atomic.LoadInt64(&s.sequence)
  243. }
  244. s.updateMutex.Lock()
  245. defer s.updateMutex.Unlock()
  246. return s.remoteSequence[device]
  247. }
  248. func (s *FileSet) LocalSize() Counts {
  249. return s.localSize.Size()
  250. }
  251. func (s *FileSet) GlobalSize() Counts {
  252. return s.globalSize.Size()
  253. }
  254. func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
  255. id := s.db.getIndexID(device[:], []byte(s.folder))
  256. if id == 0 && device == protocol.LocalDeviceID {
  257. // No index ID set yet. We create one now.
  258. id = protocol.NewIndexID()
  259. s.db.setIndexID(device[:], []byte(s.folder), id)
  260. }
  261. return id
  262. }
  263. func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
  264. if device == protocol.LocalDeviceID {
  265. panic("do not explicitly set index ID for local device")
  266. }
  267. s.db.setIndexID(device[:], []byte(s.folder), id)
  268. }
  269. func (s *FileSet) MtimeFS() *fs.MtimeFS {
  270. prefix := s.db.mtimesKey([]byte(s.folder))
  271. kv := NewNamespacedKV(s.db, string(prefix))
  272. return fs.NewMtimeFS(s.fs, kv)
  273. }
  274. func (s *FileSet) ListDevices() []protocol.DeviceID {
  275. s.updateMutex.Lock()
  276. devices := make([]protocol.DeviceID, 0, len(s.remoteSequence))
  277. for id, seq := range s.remoteSequence {
  278. if seq > 0 {
  279. devices = append(devices, id)
  280. }
  281. }
  282. s.updateMutex.Unlock()
  283. return devices
  284. }
  285. // maxSequence returns the highest of the Sequence numbers found in
  286. // the given slice of FileInfos. This should really be the Sequence of
  287. // the last item, but Syncthing v0.14.0 and other implementations may not
  288. // implement update sorting....
  289. func maxSequence(fs []protocol.FileInfo) int64 {
  290. var max int64
  291. for _, f := range fs {
  292. if f.Sequence > max {
  293. max = f.Sequence
  294. }
  295. }
  296. return max
  297. }
  298. // DropFolder clears out all information related to the given folder from the
  299. // database.
  300. func DropFolder(db *Instance, folder string) {
  301. db.dropFolder([]byte(folder))
  302. db.dropMtimes([]byte(folder))
  303. bm := &BlockMap{
  304. db: db,
  305. folder: db.folderIdx.ID([]byte(folder)),
  306. }
  307. bm.Drop()
  308. }
  309. func normalizeFilenames(fs []protocol.FileInfo) {
  310. for i := range fs {
  311. fs[i].Name = osutil.NormalizedFilename(fs[i].Name)
  312. }
  313. }
  314. func nativeFileIterator(fn Iterator) Iterator {
  315. return func(fi FileIntf) bool {
  316. switch f := fi.(type) {
  317. case protocol.FileInfo:
  318. f.Name = osutil.NativeFilename(f.Name)
  319. return fn(f)
  320. case FileInfoTruncated:
  321. f.Name = osutil.NativeFilename(f.Name)
  322. return fn(f)
  323. default:
  324. panic("unknown interface type")
  325. }
  326. }
  327. }