set.go 10 KB

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