walk.go 21 KB

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