walk.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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 scanner
  7. import (
  8. "context"
  9. "errors"
  10. "fmt"
  11. "path/filepath"
  12. "strings"
  13. "sync/atomic"
  14. "time"
  15. "unicode/utf8"
  16. metrics "github.com/rcrowley/go-metrics"
  17. "github.com/syncthing/syncthing/lib/build"
  18. "github.com/syncthing/syncthing/lib/events"
  19. "github.com/syncthing/syncthing/lib/fs"
  20. "github.com/syncthing/syncthing/lib/ignore"
  21. "github.com/syncthing/syncthing/lib/osutil"
  22. "github.com/syncthing/syncthing/lib/protocol"
  23. "golang.org/x/text/unicode/norm"
  24. )
  25. type Config struct {
  26. // Folder for which the walker has been created
  27. Folder string
  28. // Limit walking to these paths within Dir, or no limit if Sub is empty
  29. Subs []string
  30. // If Matcher is not nil, it is used to identify files to ignore which were specified by the user.
  31. Matcher *ignore.Matcher
  32. // Number of hours to keep temporary files for
  33. TempLifetime time.Duration
  34. // If CurrentFiler is not nil, it is queried for the current file before rescanning.
  35. CurrentFiler CurrentFiler
  36. // The Filesystem provides an abstraction on top of the actual filesystem.
  37. Filesystem fs.Filesystem
  38. // If IgnorePerms is true, changes to permission bits will not be
  39. // detected.
  40. IgnorePerms bool
  41. // When AutoNormalize is set, file names that are in UTF8 but incorrect
  42. // normalization form will be corrected.
  43. AutoNormalize bool
  44. // Number of routines to use for hashing
  45. Hashers int
  46. // Our vector clock id
  47. ShortID protocol.ShortID
  48. // Optional progress tick interval which defines how often FolderScanProgress
  49. // events are emitted. Negative number means disabled.
  50. ProgressTickIntervalS int
  51. // Local flags to set on scanned files
  52. LocalFlags uint32
  53. // Modification time is to be considered unchanged if the difference is lower.
  54. ModTimeWindow time.Duration
  55. // Event logger to which the scan progress events are sent
  56. EventLogger events.Logger
  57. // If ScanOwnership is true, we pick up ownership information on files while scanning.
  58. ScanOwnership bool
  59. // If ScanXattrs is true, we pick up extended attributes on files while scanning.
  60. ScanXattrs bool
  61. // Filter for extended attributes
  62. XattrFilter XattrFilter
  63. }
  64. type CurrentFiler interface {
  65. // CurrentFile returns the file as seen at last scan.
  66. CurrentFile(name string) (protocol.FileInfo, bool)
  67. }
  68. type XattrFilter interface {
  69. Permit(string) bool
  70. GetMaxSingleEntrySize() int
  71. GetMaxTotalSize() int
  72. }
  73. type ScanResult struct {
  74. File protocol.FileInfo
  75. Err error
  76. Path string // to be set in case Err != nil and File == nil
  77. }
  78. func Walk(ctx context.Context, cfg Config) chan ScanResult {
  79. return newWalker(cfg).walk(ctx)
  80. }
  81. func WalkWithoutHashing(ctx context.Context, cfg Config) chan ScanResult {
  82. return newWalker(cfg).walkWithoutHashing(ctx)
  83. }
  84. func newWalker(cfg Config) *walker {
  85. w := &walker{cfg}
  86. if w.CurrentFiler == nil {
  87. w.CurrentFiler = noCurrentFiler{}
  88. }
  89. if w.Filesystem == nil {
  90. panic("no filesystem specified")
  91. }
  92. if w.Matcher == nil {
  93. w.Matcher = ignore.New(w.Filesystem)
  94. }
  95. registerFolderMetrics(w.Folder)
  96. return w
  97. }
  98. var (
  99. errUTF8Invalid = errors.New("item is not in UTF8 encoding")
  100. errUTF8Normalization = errors.New("item is not in the correct UTF8 normalization form")
  101. errUTF8Conflict = errors.New("item has UTF8 encoding conflict with another item")
  102. )
  103. type walker struct {
  104. Config
  105. }
  106. // Walk returns the list of files found in the local folder by scanning the
  107. // file system. Files are blockwise hashed.
  108. func (w *walker) walk(ctx context.Context) chan ScanResult {
  109. l.Debugln(w, "Walk", w.Subs, w.Matcher)
  110. toHashChan := make(chan protocol.FileInfo)
  111. finishedChan := make(chan ScanResult)
  112. // A routine which walks the filesystem tree, and sends files which have
  113. // been modified to the counter routine.
  114. go w.scan(ctx, toHashChan, finishedChan)
  115. // We're not required to emit scan progress events, just kick off hashers,
  116. // and feed inputs directly from the walker.
  117. if w.ProgressTickIntervalS < 0 {
  118. newParallelHasher(ctx, w.Folder, w.Filesystem, w.Hashers, finishedChan, toHashChan, nil, nil)
  119. return finishedChan
  120. }
  121. // Defaults to every 2 seconds.
  122. if w.ProgressTickIntervalS == 0 {
  123. w.ProgressTickIntervalS = 2
  124. }
  125. ticker := time.NewTicker(time.Duration(w.ProgressTickIntervalS) * time.Second)
  126. // We need to emit progress events, hence we create a routine which buffers
  127. // the list of files to be hashed, counts the total number of
  128. // bytes to hash, and once no more files need to be hashed (chan gets closed),
  129. // start a routine which periodically emits FolderScanProgress events,
  130. // until a stop signal is sent by the parallel hasher.
  131. // Parallel hasher is stopped by this routine when we close the channel over
  132. // which it receives the files we ask it to hash.
  133. go func() {
  134. var filesToHash []protocol.FileInfo
  135. var total int64 = 1
  136. for file := range toHashChan {
  137. filesToHash = append(filesToHash, file)
  138. total += file.Size
  139. }
  140. if len(filesToHash) == 0 {
  141. close(finishedChan)
  142. return
  143. }
  144. realToHashChan := make(chan protocol.FileInfo)
  145. done := make(chan struct{})
  146. progress := newByteCounter()
  147. newParallelHasher(ctx, w.Folder, w.Filesystem, w.Hashers, finishedChan, realToHashChan, progress, done)
  148. // A routine which actually emits the FolderScanProgress events
  149. // every w.ProgressTicker ticks, until the hasher routines terminate.
  150. go func() {
  151. defer progress.Close()
  152. emitProgressEvent := func() {
  153. current := progress.Total()
  154. rate := progress.Rate()
  155. l.Debugf("%v: Walk %s %s current progress %d/%d at %.01f MiB/s (%d%%)", w, w.Folder, w.Subs, current, total, rate/1024/1024, current*100/total)
  156. w.EventLogger.Log(events.FolderScanProgress, map[string]interface{}{
  157. "folder": w.Folder,
  158. "current": current,
  159. "total": total,
  160. "rate": rate, // bytes per second
  161. })
  162. }
  163. for {
  164. select {
  165. case <-done:
  166. emitProgressEvent()
  167. l.Debugln(w, "Walk progress done", w.Folder, w.Subs, w.Matcher)
  168. ticker.Stop()
  169. return
  170. case <-ticker.C:
  171. emitProgressEvent()
  172. case <-ctx.Done():
  173. ticker.Stop()
  174. return
  175. }
  176. }
  177. }()
  178. loop:
  179. for _, file := range filesToHash {
  180. l.Debugln(w, "real to hash:", file.Name)
  181. select {
  182. case realToHashChan <- file:
  183. case <-ctx.Done():
  184. break loop
  185. }
  186. }
  187. close(realToHashChan)
  188. }()
  189. return finishedChan
  190. }
  191. func (w *walker) walkWithoutHashing(ctx context.Context) chan ScanResult {
  192. l.Debugln(w, "Walk without hashing", w.Subs, w.Matcher)
  193. toHashChan := make(chan protocol.FileInfo)
  194. finishedChan := make(chan ScanResult)
  195. // A routine which walks the filesystem tree, and sends files which have
  196. // been modified to the counter routine.
  197. go w.scan(ctx, toHashChan, finishedChan)
  198. go func() {
  199. for file := range toHashChan {
  200. finishedChan <- ScanResult{File: file}
  201. }
  202. close(finishedChan)
  203. }()
  204. return finishedChan
  205. }
  206. func (w *walker) scan(ctx context.Context, toHashChan chan<- protocol.FileInfo, finishedChan chan<- ScanResult) {
  207. hashFiles := w.walkAndHashFiles(ctx, toHashChan, finishedChan)
  208. if len(w.Subs) == 0 {
  209. w.Filesystem.Walk(".", hashFiles)
  210. } else {
  211. for _, sub := range w.Subs {
  212. if err := osutil.TraversesSymlink(w.Filesystem, filepath.Dir(sub)); err != nil {
  213. l.Debugf("%v: Skip walking %v as it is below a symlink", w, sub)
  214. continue
  215. }
  216. w.Filesystem.Walk(sub, hashFiles)
  217. }
  218. }
  219. close(toHashChan)
  220. }
  221. func (w *walker) walkAndHashFiles(ctx context.Context, toHashChan chan<- protocol.FileInfo, finishedChan chan<- ScanResult) fs.WalkFunc {
  222. now := time.Now()
  223. ignoredParent := ""
  224. return func(path string, info fs.FileInfo, err error) error {
  225. select {
  226. case <-ctx.Done():
  227. return ctx.Err()
  228. default:
  229. }
  230. metricScannedItems.WithLabelValues(w.Folder).Inc()
  231. // Return value used when we are returning early and don't want to
  232. // process the item. For directories, this means do-not-descend.
  233. var skip error // nil
  234. // info nil when error is not nil
  235. if info != nil && info.IsDir() {
  236. skip = fs.SkipDir
  237. }
  238. if !utf8.ValidString(path) {
  239. handleError(ctx, "scan", path, errUTF8Invalid, finishedChan)
  240. return skip
  241. }
  242. if fs.IsTemporary(path) {
  243. l.Debugln(w, "temporary:", path, "err:", err)
  244. if err == nil && info.IsRegular() && info.ModTime().Add(w.TempLifetime).Before(now) {
  245. w.Filesystem.Remove(path)
  246. l.Debugln(w, "removing temporary:", path, info.ModTime())
  247. }
  248. return nil
  249. }
  250. if fs.IsInternal(path) {
  251. l.Debugln(w, "ignored (internal):", path)
  252. return skip
  253. }
  254. if w.Matcher.Match(path).IsIgnored() {
  255. l.Debugln(w, "ignored (patterns):", path)
  256. // Only descend if matcher says so and the current file is not a symlink.
  257. if err != nil || w.Matcher.SkipIgnoredDirs() || info.IsSymlink() {
  258. return skip
  259. }
  260. // If the parent wasn't ignored already, set this path as the "highest" ignored parent
  261. if info.IsDir() && (ignoredParent == "" || !fs.IsParent(path, ignoredParent)) {
  262. ignoredParent = path
  263. }
  264. return nil
  265. }
  266. if err != nil {
  267. // No need reporting errors for files that don't exist (e.g. scan
  268. // due to filesystem watcher)
  269. if !fs.IsNotExist(err) {
  270. handleError(ctx, "scan", path, err, finishedChan)
  271. }
  272. return skip
  273. }
  274. if path == "." {
  275. return nil
  276. }
  277. if ignoredParent == "" {
  278. // parent isn't ignored, nothing special
  279. return w.handleItem(ctx, path, info, toHashChan, finishedChan, skip)
  280. }
  281. // Part of current path below the ignored (potential) parent
  282. rel := strings.TrimPrefix(path, ignoredParent+string(fs.PathSeparator))
  283. // ignored path isn't actually a parent of the current path
  284. if rel == path {
  285. ignoredParent = ""
  286. return w.handleItem(ctx, path, info, toHashChan, finishedChan, skip)
  287. }
  288. // The previously ignored parent directories of the current, not
  289. // ignored path need to be handled as well.
  290. // Prepend an empty string to handle ignoredParent without anything
  291. // appended in the first iteration.
  292. for _, name := range append([]string{""}, fs.PathComponents(rel)...) {
  293. ignoredParent = filepath.Join(ignoredParent, name)
  294. info, err = w.Filesystem.Lstat(ignoredParent)
  295. // An error here would be weird as we've already gotten to this point, but act on it nonetheless
  296. if err != nil {
  297. handleError(ctx, "scan", ignoredParent, err, finishedChan)
  298. return skip
  299. }
  300. if err = w.handleItem(ctx, ignoredParent, info, toHashChan, finishedChan, skip); err != nil {
  301. return err
  302. }
  303. }
  304. ignoredParent = ""
  305. return nil
  306. }
  307. }
  308. func (w *walker) handleItem(ctx context.Context, path string, info fs.FileInfo, toHashChan chan<- protocol.FileInfo, finishedChan chan<- ScanResult, skip error) error {
  309. oldPath := path
  310. path, err := w.normalizePath(path, info)
  311. if err != nil {
  312. handleError(ctx, "normalizing path", oldPath, err, finishedChan)
  313. return skip
  314. }
  315. switch {
  316. case info.IsSymlink():
  317. if err := w.walkSymlink(ctx, path, info, finishedChan); err != nil {
  318. return err
  319. }
  320. if info.IsDir() {
  321. // under no circumstances shall we descend into a symlink
  322. return fs.SkipDir
  323. }
  324. return nil
  325. case info.IsDir():
  326. err = w.walkDir(ctx, path, info, finishedChan)
  327. case info.IsRegular():
  328. err = w.walkRegular(ctx, path, info, toHashChan)
  329. }
  330. return err
  331. }
  332. func (w *walker) walkRegular(ctx context.Context, relPath string, info fs.FileInfo, toHashChan chan<- protocol.FileInfo) error {
  333. curFile, hasCurFile := w.CurrentFiler.CurrentFile(relPath)
  334. blockSize := protocol.BlockSize(info.Size())
  335. if hasCurFile {
  336. // Check if we should retain current block size.
  337. curBlockSize := curFile.BlockSize()
  338. if blockSize > curBlockSize && blockSize/curBlockSize <= 2 {
  339. // New block size is larger, but not more than twice larger.
  340. // Retain.
  341. blockSize = curBlockSize
  342. } else if curBlockSize > blockSize && curBlockSize/blockSize <= 2 {
  343. // Old block size is larger, but not more than twice larger.
  344. // Retain.
  345. blockSize = curBlockSize
  346. }
  347. }
  348. f, err := CreateFileInfo(info, relPath, w.Filesystem, w.ScanOwnership, w.ScanXattrs, w.XattrFilter)
  349. if err != nil {
  350. return err
  351. }
  352. f = w.updateFileInfo(f, curFile)
  353. f.NoPermissions = w.IgnorePerms
  354. f.RawBlockSize = blockSize
  355. l.Debugln(w, "checking:", f)
  356. if hasCurFile {
  357. if curFile.IsEquivalentOptional(f, protocol.FileInfoComparison{
  358. ModTimeWindow: w.ModTimeWindow,
  359. IgnorePerms: w.IgnorePerms,
  360. IgnoreBlocks: true,
  361. IgnoreFlags: w.LocalFlags,
  362. IgnoreOwnership: !w.ScanOwnership,
  363. IgnoreXattrs: !w.ScanXattrs,
  364. }) {
  365. l.Debugln(w, "unchanged:", curFile)
  366. return nil
  367. }
  368. if curFile.ShouldConflict() && !f.ShouldConflict() {
  369. // The old file was invalid for whatever reason and probably not
  370. // up to date with what was out there in the cluster. Drop all
  371. // others from the version vector to indicate that we haven't
  372. // taken their version into account, and possibly cause a
  373. // conflict. However, only do this if the new file is not also
  374. // invalid. This would indicate that the new file is not part
  375. // of the cluster, but e.g. a local change.
  376. f.Version = f.Version.DropOthers(w.ShortID)
  377. }
  378. l.Debugln(w, "rescan:", curFile)
  379. }
  380. l.Debugln(w, "to hash:", relPath, f)
  381. select {
  382. case toHashChan <- f:
  383. case <-ctx.Done():
  384. return ctx.Err()
  385. }
  386. return nil
  387. }
  388. func (w *walker) walkDir(ctx context.Context, relPath string, info fs.FileInfo, finishedChan chan<- ScanResult) error {
  389. curFile, hasCurFile := w.CurrentFiler.CurrentFile(relPath)
  390. f, err := CreateFileInfo(info, relPath, w.Filesystem, w.ScanOwnership, w.ScanXattrs, w.XattrFilter)
  391. if err != nil {
  392. return err
  393. }
  394. f = w.updateFileInfo(f, curFile)
  395. f.NoPermissions = w.IgnorePerms
  396. l.Debugln(w, "checking:", f)
  397. if hasCurFile {
  398. if curFile.IsEquivalentOptional(f, protocol.FileInfoComparison{
  399. ModTimeWindow: w.ModTimeWindow,
  400. IgnorePerms: w.IgnorePerms,
  401. IgnoreBlocks: true,
  402. IgnoreFlags: w.LocalFlags,
  403. IgnoreOwnership: !w.ScanOwnership,
  404. IgnoreXattrs: !w.ScanXattrs,
  405. }) {
  406. l.Debugln(w, "unchanged:", curFile)
  407. return nil
  408. }
  409. if curFile.ShouldConflict() && !f.ShouldConflict() {
  410. // The old file was invalid for whatever reason and probably not
  411. // up to date with what was out there in the cluster. Drop all
  412. // others from the version vector to indicate that we haven't
  413. // taken their version into account, and possibly cause a
  414. // conflict. However, only do this if the new file is not also
  415. // invalid. This would indicate that the new file is not part
  416. // of the cluster, but e.g. a local change.
  417. f.Version = f.Version.DropOthers(w.ShortID)
  418. }
  419. l.Debugln(w, "rescan:", curFile)
  420. }
  421. l.Debugln(w, "dir:", relPath, f)
  422. select {
  423. case finishedChan <- ScanResult{File: f}:
  424. case <-ctx.Done():
  425. return ctx.Err()
  426. }
  427. return nil
  428. }
  429. // walkSymlink returns nil or an error, if the error is of the nature that
  430. // it should stop the entire walk.
  431. func (w *walker) walkSymlink(ctx context.Context, relPath string, info fs.FileInfo, finishedChan chan<- ScanResult) error {
  432. // Symlinks are not supported on Windows. We ignore instead of returning
  433. // an error.
  434. if build.IsWindows {
  435. return nil
  436. }
  437. f, err := CreateFileInfo(info, relPath, w.Filesystem, w.ScanOwnership, w.ScanXattrs, w.XattrFilter)
  438. if err != nil {
  439. handleError(ctx, "reading link", relPath, err, finishedChan)
  440. return nil
  441. }
  442. curFile, hasCurFile := w.CurrentFiler.CurrentFile(relPath)
  443. f = w.updateFileInfo(f, curFile)
  444. l.Debugln(w, "checking:", f)
  445. if hasCurFile {
  446. if curFile.IsEquivalentOptional(f, protocol.FileInfoComparison{
  447. ModTimeWindow: w.ModTimeWindow,
  448. IgnorePerms: w.IgnorePerms,
  449. IgnoreBlocks: true,
  450. IgnoreFlags: w.LocalFlags,
  451. IgnoreOwnership: !w.ScanOwnership,
  452. IgnoreXattrs: !w.ScanXattrs,
  453. }) {
  454. l.Debugln(w, "unchanged:", curFile, info.ModTime().Unix(), info.Mode()&fs.ModePerm)
  455. return nil
  456. }
  457. if curFile.ShouldConflict() && !f.ShouldConflict() {
  458. // The old file was invalid for whatever reason and probably not
  459. // up to date with what was out there in the cluster. Drop all
  460. // others from the version vector to indicate that we haven't
  461. // taken their version into account, and possibly cause a
  462. // conflict. However, only do this if the new file is not also
  463. // invalid. This would indicate that the new file is not part
  464. // of the cluster, but e.g. a local change.
  465. f.Version = f.Version.DropOthers(w.ShortID)
  466. }
  467. l.Debugln(w, "rescan:", curFile)
  468. }
  469. l.Debugln(w, "symlink:", relPath, f)
  470. select {
  471. case finishedChan <- ScanResult{File: f}:
  472. case <-ctx.Done():
  473. return ctx.Err()
  474. }
  475. return nil
  476. }
  477. // normalizePath returns the normalized relative path (possibly after fixing
  478. // it on disk), or skip is true.
  479. func (w *walker) normalizePath(path string, info fs.FileInfo) (normPath string, err error) {
  480. if build.IsDarwin {
  481. // Mac OS X file names should always be NFD normalized.
  482. normPath = norm.NFD.String(path)
  483. } else {
  484. // Every other OS in the known universe uses NFC or just plain
  485. // doesn't bother to define an encoding. In our case *we* do care,
  486. // so we enforce NFC regardless.
  487. normPath = norm.NFC.String(path)
  488. }
  489. if path == normPath {
  490. // The file name is already normalized: nothing to do
  491. return path, nil
  492. }
  493. if !w.AutoNormalize {
  494. // We're not authorized to do anything about it, so complain and skip.
  495. return "", errUTF8Normalization
  496. }
  497. // We will attempt to normalize it.
  498. normInfo, err := w.Filesystem.Lstat(normPath)
  499. if fs.IsNotExist(err) {
  500. // Nothing exists with the normalized filename. Good.
  501. if err = w.Filesystem.Rename(path, normPath); err != nil {
  502. return "", err
  503. }
  504. l.Infof(`Normalized UTF8 encoding of file name "%s".`, path)
  505. return normPath, nil
  506. }
  507. if w.Filesystem.SameFile(info, normInfo) {
  508. // With some filesystems (ZFS), if there is an un-normalized path and you ask whether the normalized
  509. // version exists, it responds with true. Therefore we need to check fs.SameFile as well.
  510. // In this case, a call to Rename won't do anything, so we have to rename via a temp file.
  511. // We don't want to use the standard syncthing prefix here, as that will result in the file being ignored
  512. // and eventually deleted by Syncthing if the rename back fails.
  513. tempPath := fs.TempNameWithPrefix(normPath, "")
  514. if err = w.Filesystem.Rename(path, tempPath); err != nil {
  515. return "", err
  516. }
  517. if err = w.Filesystem.Rename(tempPath, normPath); err != nil {
  518. // I don't ever expect this to happen, but if it does, we should probably tell our caller that the normalized
  519. // path is the temp path: that way at least the user's data still gets synced.
  520. l.Warnf(`Error renaming "%s" to "%s" while normalizating UTF8 encoding: %v. You will want to rename this file back manually`, tempPath, normPath, err)
  521. return tempPath, nil
  522. }
  523. return normPath, nil
  524. }
  525. // There is something already in the way at the normalized
  526. // file name.
  527. return "", errUTF8Conflict
  528. }
  529. // updateFileInfo updates walker specific members of protocol.FileInfo that
  530. // do not depend on type, and things that should be preserved from the
  531. // previous version of the FileInfo.
  532. func (w *walker) updateFileInfo(dst, src protocol.FileInfo) protocol.FileInfo {
  533. if dst.Type == protocol.FileInfoTypeFile && build.IsWindows {
  534. // If we have an existing index entry, copy the executable bits
  535. // from there.
  536. dst.Permissions |= (src.Permissions & 0o111)
  537. }
  538. dst.Version = src.Version.Update(w.ShortID)
  539. dst.ModifiedBy = w.ShortID
  540. dst.LocalFlags = w.LocalFlags
  541. // Copy OS data from src to dst, unless it was already set on dst.
  542. dst.Platform.MergeWith(&src.Platform)
  543. return dst
  544. }
  545. func handleError(ctx context.Context, context, path string, err error, finishedChan chan<- ScanResult) {
  546. select {
  547. case finishedChan <- ScanResult{
  548. Err: fmt.Errorf("%s: %w", context, err),
  549. Path: path,
  550. }:
  551. case <-ctx.Done():
  552. }
  553. }
  554. func (w *walker) String() string {
  555. return fmt.Sprintf("walker/%s@%p", w.Folder, w)
  556. }
  557. // A byteCounter gets bytes added to it via Update() and then provides the
  558. // Total() and one minute moving average Rate() in bytes per second.
  559. type byteCounter struct {
  560. total atomic.Int64
  561. metrics.EWMA
  562. stop chan struct{}
  563. }
  564. func newByteCounter() *byteCounter {
  565. c := &byteCounter{
  566. EWMA: metrics.NewEWMA1(), // a one minute exponentially weighted moving average
  567. stop: make(chan struct{}),
  568. }
  569. go c.ticker()
  570. return c
  571. }
  572. func (c *byteCounter) ticker() {
  573. // The metrics.EWMA expects clock ticks every five seconds in order to
  574. // decay the average properly.
  575. t := time.NewTicker(5 * time.Second)
  576. for {
  577. select {
  578. case <-t.C:
  579. c.Tick()
  580. case <-c.stop:
  581. t.Stop()
  582. return
  583. }
  584. }
  585. }
  586. func (c *byteCounter) Update(bytes int64) {
  587. c.total.Add(bytes)
  588. c.EWMA.Update(bytes)
  589. }
  590. func (c *byteCounter) Total() int64 { return c.total.Load() }
  591. func (c *byteCounter) Close() {
  592. close(c.stop)
  593. }
  594. // A no-op CurrentFiler
  595. type noCurrentFiler struct{}
  596. func (noCurrentFiler) CurrentFile(_ string) (protocol.FileInfo, bool) {
  597. return protocol.FileInfo{}, false
  598. }
  599. func CreateFileInfo(fi fs.FileInfo, name string, filesystem fs.Filesystem, scanOwnership bool, scanXattrs bool, xattrFilter XattrFilter) (protocol.FileInfo, error) {
  600. f := protocol.FileInfo{Name: name}
  601. if scanOwnership || scanXattrs {
  602. if plat, err := filesystem.PlatformData(name, scanOwnership, scanXattrs, xattrFilter); err == nil {
  603. f.Platform = plat
  604. } else {
  605. return protocol.FileInfo{}, fmt.Errorf("reading platform data: %w", err)
  606. }
  607. }
  608. if ct := fi.InodeChangeTime(); !ct.IsZero() {
  609. f.InodeChangeNs = ct.UnixNano()
  610. } else {
  611. f.InodeChangeNs = 0
  612. }
  613. if fi.IsSymlink() {
  614. f.Type = protocol.FileInfoTypeSymlink
  615. target, err := filesystem.ReadSymlink(name)
  616. if err != nil {
  617. return protocol.FileInfo{}, err
  618. }
  619. f.SymlinkTarget = target
  620. f.NoPermissions = true // Symlinks don't have permissions of their own
  621. return f, nil
  622. }
  623. f.Permissions = uint32(fi.Mode() & fs.ModePerm)
  624. f.ModifiedS = fi.ModTime().Unix()
  625. f.ModifiedNs = fi.ModTime().Nanosecond()
  626. if fi.IsDir() {
  627. f.Type = protocol.FileInfoTypeDirectory
  628. return f, nil
  629. }
  630. f.Size = fi.Size()
  631. f.Type = protocol.FileInfoTypeFile
  632. return f, nil
  633. }