walk.go 20 KB

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