set.go 10 KB

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