set.go 9.6 KB

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