set.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 http://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. db *Instance
  25. blockmap *BlockMap
  26. localSize sizeTracker
  27. globalSize sizeTracker
  28. remoteSequence map[protocol.DeviceID]int64 // Highest seen sequence numbers for other devices
  29. updateMutex sync.Mutex // protects remoteSequence and database updates
  30. }
  31. // FileIntf is the set of methods implemented by both protocol.FileInfo and
  32. // FileInfoTruncated.
  33. type FileIntf interface {
  34. FileSize() int64
  35. FileName() string
  36. IsDeleted() bool
  37. IsInvalid() bool
  38. IsDirectory() bool
  39. IsSymlink() bool
  40. HasPermissionBits() bool
  41. }
  42. // The Iterator is called with either a protocol.FileInfo or a
  43. // FileInfoTruncated (depending on the method) and returns true to
  44. // continue iteration, false to stop.
  45. type Iterator func(f FileIntf) bool
  46. type sizeTracker struct {
  47. files int
  48. deleted int
  49. bytes int64
  50. mut stdsync.Mutex
  51. }
  52. func (s *sizeTracker) addFile(f FileIntf) {
  53. if f.IsInvalid() {
  54. return
  55. }
  56. s.mut.Lock()
  57. if f.IsDeleted() {
  58. s.deleted++
  59. } else {
  60. s.files++
  61. }
  62. s.bytes += f.FileSize()
  63. s.mut.Unlock()
  64. }
  65. func (s *sizeTracker) removeFile(f FileIntf) {
  66. if f.IsInvalid() {
  67. return
  68. }
  69. s.mut.Lock()
  70. if f.IsDeleted() {
  71. s.deleted--
  72. } else {
  73. s.files--
  74. }
  75. s.bytes -= f.FileSize()
  76. if s.deleted < 0 || s.files < 0 {
  77. panic("bug: removed more than added")
  78. }
  79. s.mut.Unlock()
  80. }
  81. func (s *sizeTracker) Size() (files, deleted int, bytes int64) {
  82. s.mut.Lock()
  83. defer s.mut.Unlock()
  84. return s.files, s.deleted, s.bytes
  85. }
  86. func NewFileSet(folder string, db *Instance) *FileSet {
  87. var s = FileSet{
  88. remoteSequence: make(map[protocol.DeviceID]int64),
  89. folder: folder,
  90. db: db,
  91. blockmap: NewBlockMap(db, db.folderIdx.ID([]byte(folder))),
  92. updateMutex: sync.NewMutex(),
  93. }
  94. s.db.checkGlobals([]byte(folder), &s.globalSize)
  95. var deviceID protocol.DeviceID
  96. s.db.withAllFolderTruncated([]byte(folder), func(device []byte, f FileInfoTruncated) bool {
  97. copy(deviceID[:], device)
  98. if deviceID == protocol.LocalDeviceID {
  99. if f.Sequence > s.sequence {
  100. s.sequence = f.Sequence
  101. }
  102. s.localSize.addFile(f)
  103. } else if f.Sequence > s.remoteSequence[deviceID] {
  104. s.remoteSequence[deviceID] = f.Sequence
  105. }
  106. return true
  107. })
  108. l.Debugf("loaded sequence for %q: %#v", folder, s.sequence)
  109. return &s
  110. }
  111. func (s *FileSet) Replace(device protocol.DeviceID, fs []protocol.FileInfo) {
  112. l.Debugf("%s Replace(%v, [%d])", s.folder, device, len(fs))
  113. normalizeFilenames(fs)
  114. s.updateMutex.Lock()
  115. defer s.updateMutex.Unlock()
  116. if device == protocol.LocalDeviceID {
  117. if len(fs) == 0 {
  118. s.sequence = 0
  119. } else {
  120. // Always overwrite Sequence on updated files to ensure
  121. // correct ordering. The caller is supposed to leave it set to
  122. // zero anyhow.
  123. for i := range fs {
  124. fs[i].Sequence = atomic.AddInt64(&s.sequence, 1)
  125. }
  126. }
  127. } else {
  128. s.remoteSequence[device] = maxSequence(fs)
  129. }
  130. s.db.replace([]byte(s.folder), device[:], fs, &s.localSize, &s.globalSize)
  131. if device == protocol.LocalDeviceID {
  132. s.blockmap.Drop()
  133. s.blockmap.Add(fs)
  134. }
  135. }
  136. func (s *FileSet) Update(device protocol.DeviceID, fs []protocol.FileInfo) {
  137. l.Debugf("%s Update(%v, [%d])", s.folder, device, len(fs))
  138. normalizeFilenames(fs)
  139. s.updateMutex.Lock()
  140. defer s.updateMutex.Unlock()
  141. if device == protocol.LocalDeviceID {
  142. discards := make([]protocol.FileInfo, 0, len(fs))
  143. updates := make([]protocol.FileInfo, 0, len(fs))
  144. for i, newFile := range fs {
  145. fs[i].Sequence = atomic.AddInt64(&s.sequence, 1)
  146. existingFile, ok := s.db.getFile([]byte(s.folder), device[:], []byte(newFile.Name))
  147. if !ok || !existingFile.Version.Equal(newFile.Version) {
  148. discards = append(discards, existingFile)
  149. updates = append(updates, newFile)
  150. }
  151. }
  152. s.blockmap.Discard(discards)
  153. s.blockmap.Update(updates)
  154. } else {
  155. s.remoteSequence[device] = maxSequence(fs)
  156. }
  157. s.db.updateFiles([]byte(s.folder), device[:], fs, &s.localSize, &s.globalSize)
  158. }
  159. func (s *FileSet) WithNeed(device protocol.DeviceID, fn Iterator) {
  160. l.Debugf("%s WithNeed(%v)", s.folder, device)
  161. s.db.withNeed([]byte(s.folder), device[:], false, nativeFileIterator(fn))
  162. }
  163. func (s *FileSet) WithNeedTruncated(device protocol.DeviceID, fn Iterator) {
  164. l.Debugf("%s WithNeedTruncated(%v)", s.folder, device)
  165. s.db.withNeed([]byte(s.folder), device[:], true, nativeFileIterator(fn))
  166. }
  167. func (s *FileSet) WithHave(device protocol.DeviceID, fn Iterator) {
  168. l.Debugf("%s WithHave(%v)", s.folder, device)
  169. s.db.withHave([]byte(s.folder), device[:], nil, false, nativeFileIterator(fn))
  170. }
  171. func (s *FileSet) WithHaveTruncated(device protocol.DeviceID, fn Iterator) {
  172. l.Debugf("%s WithHaveTruncated(%v)", s.folder, device)
  173. s.db.withHave([]byte(s.folder), device[:], nil, true, nativeFileIterator(fn))
  174. }
  175. func (s *FileSet) WithPrefixedHaveTruncated(device protocol.DeviceID, prefix string, fn Iterator) {
  176. l.Debugf("%s WithPrefixedHaveTruncated(%v)", s.folder, device)
  177. s.db.withHave([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  178. }
  179. func (s *FileSet) WithGlobal(fn Iterator) {
  180. l.Debugf("%s WithGlobal()", s.folder)
  181. s.db.withGlobal([]byte(s.folder), nil, false, nativeFileIterator(fn))
  182. }
  183. func (s *FileSet) WithGlobalTruncated(fn Iterator) {
  184. l.Debugf("%s WithGlobalTruncated()", s.folder)
  185. s.db.withGlobal([]byte(s.folder), nil, true, nativeFileIterator(fn))
  186. }
  187. func (s *FileSet) WithPrefixedGlobalTruncated(prefix string, fn Iterator) {
  188. l.Debugf("%s WithPrefixedGlobalTruncated()", s.folder, prefix)
  189. s.db.withGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(prefix)), true, nativeFileIterator(fn))
  190. }
  191. func (s *FileSet) Get(device protocol.DeviceID, file string) (protocol.FileInfo, bool) {
  192. f, ok := s.db.getFile([]byte(s.folder), device[:], []byte(osutil.NormalizedFilename(file)))
  193. f.Name = osutil.NativeFilename(f.Name)
  194. return f, ok
  195. }
  196. func (s *FileSet) GetGlobal(file string) (protocol.FileInfo, bool) {
  197. fi, ok := s.db.getGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), false)
  198. if !ok {
  199. return protocol.FileInfo{}, false
  200. }
  201. f := fi.(protocol.FileInfo)
  202. f.Name = osutil.NativeFilename(f.Name)
  203. return f, true
  204. }
  205. func (s *FileSet) GetGlobalTruncated(file string) (FileInfoTruncated, bool) {
  206. fi, ok := s.db.getGlobal([]byte(s.folder), []byte(osutil.NormalizedFilename(file)), true)
  207. if !ok {
  208. return FileInfoTruncated{}, false
  209. }
  210. f := fi.(FileInfoTruncated)
  211. f.Name = osutil.NativeFilename(f.Name)
  212. return f, true
  213. }
  214. func (s *FileSet) Availability(file string) []protocol.DeviceID {
  215. return s.db.availability([]byte(s.folder), []byte(osutil.NormalizedFilename(file)))
  216. }
  217. func (s *FileSet) Sequence(device protocol.DeviceID) int64 {
  218. if device == protocol.LocalDeviceID {
  219. return atomic.LoadInt64(&s.sequence)
  220. }
  221. s.updateMutex.Lock()
  222. defer s.updateMutex.Unlock()
  223. return s.remoteSequence[device]
  224. }
  225. func (s *FileSet) LocalSize() (files, deleted int, bytes int64) {
  226. return s.localSize.Size()
  227. }
  228. func (s *FileSet) GlobalSize() (files, deleted int, bytes int64) {
  229. return s.globalSize.Size()
  230. }
  231. func (s *FileSet) IndexID(device protocol.DeviceID) protocol.IndexID {
  232. id := s.db.getIndexID(device[:], []byte(s.folder))
  233. if id == 0 && device == protocol.LocalDeviceID {
  234. // No index ID set yet. We create one now.
  235. id = protocol.NewIndexID()
  236. s.db.setIndexID(device[:], []byte(s.folder), id)
  237. }
  238. return id
  239. }
  240. func (s *FileSet) SetIndexID(device protocol.DeviceID, id protocol.IndexID) {
  241. if device == protocol.LocalDeviceID {
  242. panic("do not explicitly set index ID for local device")
  243. }
  244. s.db.setIndexID(device[:], []byte(s.folder), id)
  245. }
  246. func (s *FileSet) MtimeFS() *fs.MtimeFS {
  247. prefix := s.db.mtimesKey([]byte(s.folder))
  248. kv := NewNamespacedKV(s.db, string(prefix))
  249. return fs.NewMtimeFS(kv)
  250. }
  251. // maxSequence returns the highest of the Sequence numbers found in
  252. // the given slice of FileInfos. This should really be the Sequence of
  253. // the last item, but Syncthing v0.14.0 and other implementations may not
  254. // implement update sorting....
  255. func maxSequence(fs []protocol.FileInfo) int64 {
  256. var max int64
  257. for _, f := range fs {
  258. if f.Sequence > max {
  259. max = f.Sequence
  260. }
  261. }
  262. return max
  263. }
  264. // DropFolder clears out all information related to the given folder from the
  265. // database.
  266. func DropFolder(db *Instance, folder string) {
  267. db.dropFolder([]byte(folder))
  268. db.dropMtimes([]byte(folder))
  269. bm := &BlockMap{
  270. db: db,
  271. folder: db.folderIdx.ID([]byte(folder)),
  272. }
  273. bm.Drop()
  274. }
  275. func normalizeFilenames(fs []protocol.FileInfo) {
  276. for i := range fs {
  277. fs[i].Name = osutil.NormalizedFilename(fs[i].Name)
  278. }
  279. }
  280. func nativeFileIterator(fn Iterator) Iterator {
  281. return func(fi FileIntf) bool {
  282. switch f := fi.(type) {
  283. case protocol.FileInfo:
  284. f.Name = osutil.NativeFilename(f.Name)
  285. return fn(f)
  286. case FileInfoTruncated:
  287. f.Name = osutil.NativeFilename(f.Name)
  288. return fn(f)
  289. default:
  290. panic("unknown interface type")
  291. }
  292. }
  293. }