folder.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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 model
  7. import (
  8. "context"
  9. "fmt"
  10. "math/rand"
  11. "path/filepath"
  12. "sort"
  13. "sync/atomic"
  14. "time"
  15. "github.com/pkg/errors"
  16. "github.com/syncthing/syncthing/lib/config"
  17. "github.com/syncthing/syncthing/lib/db"
  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/locations"
  22. "github.com/syncthing/syncthing/lib/osutil"
  23. "github.com/syncthing/syncthing/lib/protocol"
  24. "github.com/syncthing/syncthing/lib/scanner"
  25. "github.com/syncthing/syncthing/lib/stats"
  26. "github.com/syncthing/syncthing/lib/svcutil"
  27. "github.com/syncthing/syncthing/lib/sync"
  28. "github.com/syncthing/syncthing/lib/util"
  29. "github.com/syncthing/syncthing/lib/versioner"
  30. "github.com/syncthing/syncthing/lib/watchaggregator"
  31. )
  32. // Arbitrary limit that triggers a warning on kqueue systems
  33. const kqueueItemCountThreshold = 10000
  34. type folder struct {
  35. stateTracker
  36. config.FolderConfiguration
  37. *stats.FolderStatisticsReference
  38. ioLimiter *util.Semaphore
  39. localFlags uint32
  40. model *model
  41. shortID protocol.ShortID
  42. fset *db.FileSet
  43. ignores *ignore.Matcher
  44. mtimefs fs.Filesystem
  45. modTimeWindow time.Duration
  46. ctx context.Context // used internally, only accessible on serve lifetime
  47. done chan struct{} // used externally, accessible regardless of serve
  48. scanInterval time.Duration
  49. scanTimer *time.Timer
  50. scanDelay chan time.Duration
  51. initialScanFinished chan struct{}
  52. scanScheduled chan struct{}
  53. versionCleanupInterval time.Duration
  54. versionCleanupTimer *time.Timer
  55. pullScheduled chan struct{}
  56. pullPause time.Duration
  57. pullFailTimer *time.Timer
  58. scanErrors []FileError
  59. pullErrors []FileError
  60. errorsMut sync.Mutex
  61. doInSyncChan chan syncRequest
  62. forcedRescanRequested chan struct{}
  63. forcedRescanPaths map[string]struct{}
  64. forcedRescanPathsMut sync.Mutex
  65. watchCancel context.CancelFunc
  66. watchChan chan []string
  67. restartWatchChan chan struct{}
  68. watchErr error
  69. watchMut sync.Mutex
  70. puller puller
  71. versioner versioner.Versioner
  72. warnedKqueue bool
  73. }
  74. type syncRequest struct {
  75. fn func() error
  76. err chan error
  77. }
  78. type puller interface {
  79. pull() (bool, error) // true when successful and should not be retried
  80. }
  81. func newFolder(model *model, fset *db.FileSet, ignores *ignore.Matcher, cfg config.FolderConfiguration, evLogger events.Logger, ioLimiter *util.Semaphore, ver versioner.Versioner) folder {
  82. f := folder{
  83. stateTracker: newStateTracker(cfg.ID, evLogger),
  84. FolderConfiguration: cfg,
  85. FolderStatisticsReference: stats.NewFolderStatisticsReference(model.db, cfg.ID),
  86. ioLimiter: ioLimiter,
  87. model: model,
  88. shortID: model.shortID,
  89. fset: fset,
  90. ignores: ignores,
  91. mtimefs: cfg.Filesystem(fset),
  92. modTimeWindow: cfg.ModTimeWindow(),
  93. done: make(chan struct{}),
  94. scanInterval: time.Duration(cfg.RescanIntervalS) * time.Second,
  95. scanTimer: time.NewTimer(0), // The first scan should be done immediately.
  96. scanDelay: make(chan time.Duration),
  97. initialScanFinished: make(chan struct{}),
  98. scanScheduled: make(chan struct{}, 1),
  99. versionCleanupInterval: time.Duration(cfg.Versioning.CleanupIntervalS) * time.Second,
  100. versionCleanupTimer: time.NewTimer(time.Duration(cfg.Versioning.CleanupIntervalS) * time.Second),
  101. pullScheduled: make(chan struct{}, 1), // This needs to be 1-buffered so that we queue a pull if we're busy when it comes.
  102. errorsMut: sync.NewMutex(),
  103. doInSyncChan: make(chan syncRequest),
  104. forcedRescanRequested: make(chan struct{}, 1),
  105. forcedRescanPaths: make(map[string]struct{}),
  106. forcedRescanPathsMut: sync.NewMutex(),
  107. watchCancel: func() {},
  108. restartWatchChan: make(chan struct{}, 1),
  109. watchMut: sync.NewMutex(),
  110. versioner: ver,
  111. }
  112. f.pullPause = f.pullBasePause()
  113. f.pullFailTimer = time.NewTimer(0)
  114. <-f.pullFailTimer.C
  115. return f
  116. }
  117. func (f *folder) Serve(ctx context.Context) error {
  118. atomic.AddInt32(&f.model.foldersRunning, 1)
  119. defer atomic.AddInt32(&f.model.foldersRunning, -1)
  120. f.ctx = ctx
  121. l.Debugln(f, "starting")
  122. defer l.Debugln(f, "exiting")
  123. defer func() {
  124. f.scanTimer.Stop()
  125. f.versionCleanupTimer.Stop()
  126. f.setState(FolderIdle)
  127. }()
  128. if f.FSWatcherEnabled && f.getHealthErrorAndLoadIgnores() == nil {
  129. f.startWatch()
  130. }
  131. // If we're configured to not do version cleanup, or we don't have a
  132. // versioner, cancel and drain that timer now.
  133. if f.versionCleanupInterval == 0 || f.versioner == nil {
  134. if !f.versionCleanupTimer.Stop() {
  135. <-f.versionCleanupTimer.C
  136. }
  137. }
  138. initialCompleted := f.initialScanFinished
  139. for {
  140. var err error
  141. select {
  142. case <-f.ctx.Done():
  143. close(f.done)
  144. return nil
  145. case <-f.pullScheduled:
  146. _, err = f.pull()
  147. case <-f.pullFailTimer.C:
  148. var success bool
  149. success, err = f.pull()
  150. if (err != nil || !success) && f.pullPause < 60*f.pullBasePause() {
  151. // Back off from retrying to pull
  152. f.pullPause *= 2
  153. }
  154. case <-initialCompleted:
  155. // Initial scan has completed, we should do a pull
  156. initialCompleted = nil // never hit this case again
  157. _, err = f.pull()
  158. case <-f.forcedRescanRequested:
  159. err = f.handleForcedRescans()
  160. case <-f.scanTimer.C:
  161. l.Debugln(f, "Scanning due to timer")
  162. err = f.scanTimerFired()
  163. case req := <-f.doInSyncChan:
  164. l.Debugln(f, "Running something due to request")
  165. err = req.fn()
  166. req.err <- err
  167. case next := <-f.scanDelay:
  168. l.Debugln(f, "Delaying scan")
  169. f.scanTimer.Reset(next)
  170. case <-f.scanScheduled:
  171. l.Debugln(f, "Scan was scheduled")
  172. f.scanTimer.Reset(0)
  173. case fsEvents := <-f.watchChan:
  174. l.Debugln(f, "Scan due to watcher")
  175. err = f.scanSubdirs(fsEvents)
  176. case <-f.restartWatchChan:
  177. l.Debugln(f, "Restart watcher")
  178. err = f.restartWatch()
  179. case <-f.versionCleanupTimer.C:
  180. l.Debugln(f, "Doing version cleanup")
  181. f.versionCleanupTimerFired()
  182. }
  183. if err != nil {
  184. if svcutil.IsFatal(err) {
  185. return err
  186. }
  187. f.setError(err)
  188. }
  189. }
  190. }
  191. func (f *folder) BringToFront(string) {}
  192. func (f *folder) Override() {}
  193. func (f *folder) Revert() {}
  194. func (f *folder) DelayScan(next time.Duration) {
  195. select {
  196. case f.scanDelay <- next:
  197. case <-f.done:
  198. }
  199. }
  200. func (f *folder) ScheduleScan() {
  201. // 1-buffered chan
  202. select {
  203. case f.scanScheduled <- struct{}{}:
  204. default:
  205. }
  206. }
  207. func (f *folder) ignoresUpdated() {
  208. if f.FSWatcherEnabled {
  209. f.scheduleWatchRestart()
  210. }
  211. }
  212. func (f *folder) SchedulePull() {
  213. select {
  214. case f.pullScheduled <- struct{}{}:
  215. default:
  216. // We might be busy doing a pull and thus not reading from this
  217. // channel. The channel is 1-buffered, so one notification will be
  218. // queued to ensure we recheck after the pull, but beyond that we must
  219. // make sure to not block index receiving.
  220. }
  221. }
  222. func (f *folder) Jobs(_, _ int) ([]string, []string, int) {
  223. return nil, nil, 0
  224. }
  225. func (f *folder) Scan(subdirs []string) error {
  226. <-f.initialScanFinished
  227. return f.doInSync(func() error { return f.scanSubdirs(subdirs) })
  228. }
  229. // doInSync allows to run functions synchronously in folder.serve from exported,
  230. // asynchronously called methods.
  231. func (f *folder) doInSync(fn func() error) error {
  232. req := syncRequest{
  233. fn: fn,
  234. err: make(chan error, 1),
  235. }
  236. select {
  237. case f.doInSyncChan <- req:
  238. return <-req.err
  239. case <-f.done:
  240. return context.Canceled
  241. }
  242. }
  243. func (f *folder) Reschedule() {
  244. if f.scanInterval == 0 {
  245. return
  246. }
  247. // Sleep a random time between 3/4 and 5/4 of the configured interval.
  248. sleepNanos := (f.scanInterval.Nanoseconds()*3 + rand.Int63n(2*f.scanInterval.Nanoseconds())) / 4
  249. interval := time.Duration(sleepNanos) * time.Nanosecond
  250. l.Debugln(f, "next rescan in", interval)
  251. f.scanTimer.Reset(interval)
  252. }
  253. func (f *folder) getHealthErrorAndLoadIgnores() error {
  254. if err := f.getHealthErrorWithoutIgnores(); err != nil {
  255. return err
  256. }
  257. if f.Type != config.FolderTypeReceiveEncrypted {
  258. if err := f.ignores.Load(".stignore"); err != nil && !fs.IsNotExist(err) {
  259. return errors.Wrap(err, "loading ignores")
  260. }
  261. }
  262. return nil
  263. }
  264. func (f *folder) getHealthErrorWithoutIgnores() error {
  265. // Check for folder errors, with the most serious and specific first and
  266. // generic ones like out of space on the home disk later.
  267. if err := f.CheckPath(); err != nil {
  268. return err
  269. }
  270. dbPath := locations.Get(locations.Database)
  271. if usage, err := fs.NewFilesystem(fs.FilesystemTypeBasic, dbPath).Usage("."); err == nil {
  272. if err = config.CheckFreeSpace(f.model.cfg.Options().MinHomeDiskFree, usage); err != nil {
  273. return fmt.Errorf("insufficient space on disk for database (%v): %w", dbPath, err)
  274. }
  275. }
  276. return nil
  277. }
  278. func (f *folder) pull() (success bool, err error) {
  279. f.pullFailTimer.Stop()
  280. select {
  281. case <-f.pullFailTimer.C:
  282. default:
  283. }
  284. select {
  285. case <-f.initialScanFinished:
  286. default:
  287. // Once the initial scan finished, a pull will be scheduled
  288. return true, nil
  289. }
  290. defer func() {
  291. if success {
  292. // We're good, reset the pause interval.
  293. f.pullPause = f.pullBasePause()
  294. }
  295. }()
  296. // If there is nothing to do, don't even enter sync-waiting state.
  297. abort := true
  298. snap, err := f.dbSnapshot()
  299. if err != nil {
  300. return false, err
  301. }
  302. snap.WithNeed(protocol.LocalDeviceID, func(intf protocol.FileIntf) bool {
  303. abort = false
  304. return false
  305. })
  306. snap.Release()
  307. if abort {
  308. // Clears pull failures on items that were needed before, but aren't anymore.
  309. f.errorsMut.Lock()
  310. f.pullErrors = nil
  311. f.errorsMut.Unlock()
  312. return true, nil
  313. }
  314. // Abort early (before acquiring a token) if there's a folder error
  315. err = f.getHealthErrorWithoutIgnores()
  316. if err != nil {
  317. l.Debugln("Skipping pull of", f.Description(), "due to folder error:", err)
  318. return false, err
  319. }
  320. // Send only folder doesn't do any io, it only checks for out-of-sync
  321. // items that differ in metadata and updates those.
  322. if f.Type != config.FolderTypeSendOnly {
  323. f.setState(FolderSyncWaiting)
  324. if err := f.ioLimiter.TakeWithContext(f.ctx, 1); err != nil {
  325. return true, err
  326. }
  327. defer f.ioLimiter.Give(1)
  328. }
  329. startTime := time.Now()
  330. // Check if the ignore patterns changed.
  331. oldHash := f.ignores.Hash()
  332. defer func() {
  333. if f.ignores.Hash() != oldHash {
  334. f.ignoresUpdated()
  335. }
  336. }()
  337. err = f.getHealthErrorAndLoadIgnores()
  338. if err != nil {
  339. l.Debugln("Skipping pull of", f.Description(), "due to folder error:", err)
  340. return false, err
  341. }
  342. f.setError(nil)
  343. success, err = f.puller.pull()
  344. if success && err == nil {
  345. return true, nil
  346. }
  347. // Pulling failed, try again later.
  348. delay := f.pullPause + time.Since(startTime)
  349. l.Infof("Folder %v isn't making sync progress - retrying in %v.", f.Description(), util.NiceDurationString(delay))
  350. f.pullFailTimer.Reset(delay)
  351. return false, err
  352. }
  353. func (f *folder) scanSubdirs(subDirs []string) error {
  354. l.Debugf("%v scanning", f)
  355. oldHash := f.ignores.Hash()
  356. err := f.getHealthErrorAndLoadIgnores()
  357. if err != nil {
  358. return err
  359. }
  360. f.setError(nil)
  361. // Check on the way out if the ignore patterns changed as part of scanning
  362. // this folder. If they did we should schedule a pull of the folder so that
  363. // we request things we might have suddenly become unignored and so on.
  364. defer func() {
  365. if f.ignores.Hash() != oldHash {
  366. l.Debugln("Folder", f.Description(), "ignore patterns change detected while scanning; triggering puller")
  367. f.ignoresUpdated()
  368. f.SchedulePull()
  369. }
  370. }()
  371. f.setState(FolderScanWaiting)
  372. defer f.setState(FolderIdle)
  373. if err := f.ioLimiter.TakeWithContext(f.ctx, 1); err != nil {
  374. return err
  375. }
  376. defer f.ioLimiter.Give(1)
  377. for i := range subDirs {
  378. sub := osutil.NativeFilename(subDirs[i])
  379. if sub == "" {
  380. // A blank subdirs means to scan the entire folder. We can trim
  381. // the subDirs list and go on our way.
  382. subDirs = nil
  383. break
  384. }
  385. subDirs[i] = sub
  386. }
  387. // Clean the list of subitems to ensure that we start at a known
  388. // directory, and don't scan subdirectories of things we've already
  389. // scanned.
  390. snap, err := f.dbSnapshot()
  391. if err != nil {
  392. return err
  393. }
  394. subDirs = unifySubs(subDirs, func(file string) bool {
  395. _, ok := snap.Get(protocol.LocalDeviceID, file)
  396. return ok
  397. })
  398. snap.Release()
  399. f.setState(FolderScanning)
  400. f.clearScanErrors(subDirs)
  401. batch := f.newScanBatch()
  402. // Schedule a pull after scanning, but only if we actually detected any
  403. // changes.
  404. changes := 0
  405. defer func() {
  406. l.Debugf("%v finished scanning, detected %v changes", f, changes)
  407. if changes > 0 {
  408. f.SchedulePull()
  409. }
  410. }()
  411. changesHere, err := f.scanSubdirsChangedAndNew(subDirs, batch)
  412. changes += changesHere
  413. if err != nil {
  414. return err
  415. }
  416. if err := batch.Flush(); err != nil {
  417. return err
  418. }
  419. if len(subDirs) == 0 {
  420. // If we have no specific subdirectories to traverse, set it to one
  421. // empty prefix so we traverse the entire folder contents once.
  422. subDirs = []string{""}
  423. }
  424. // Do a scan of the database for each prefix, to check for deleted and
  425. // ignored files.
  426. changesHere, err = f.scanSubdirsDeletedAndIgnored(subDirs, batch)
  427. changes += changesHere
  428. if err != nil {
  429. return err
  430. }
  431. if err := batch.Flush(); err != nil {
  432. return err
  433. }
  434. f.ScanCompleted()
  435. return nil
  436. }
  437. const maxToRemove = 1000
  438. type scanBatch struct {
  439. f *folder
  440. updateBatch *db.FileInfoBatch
  441. toRemove []string
  442. }
  443. func (f *folder) newScanBatch() *scanBatch {
  444. b := &scanBatch{
  445. f: f,
  446. toRemove: make([]string, 0, maxToRemove),
  447. }
  448. b.updateBatch = db.NewFileInfoBatch(func(fs []protocol.FileInfo) error {
  449. if err := b.f.getHealthErrorWithoutIgnores(); err != nil {
  450. l.Debugf("Stopping scan of folder %s due to: %s", b.f.Description(), err)
  451. return err
  452. }
  453. b.f.updateLocalsFromScanning(fs)
  454. return nil
  455. })
  456. return b
  457. }
  458. func (b *scanBatch) Remove(item string) {
  459. b.toRemove = append(b.toRemove, item)
  460. }
  461. func (b *scanBatch) flushToRemove() {
  462. if len(b.toRemove) > 0 {
  463. b.f.fset.RemoveLocalItems(b.toRemove)
  464. b.toRemove = b.toRemove[:0]
  465. }
  466. }
  467. func (b *scanBatch) Flush() error {
  468. b.flushToRemove()
  469. return b.updateBatch.Flush()
  470. }
  471. func (b *scanBatch) FlushIfFull() error {
  472. if len(b.toRemove) >= maxToRemove {
  473. b.flushToRemove()
  474. }
  475. return b.updateBatch.FlushIfFull()
  476. }
  477. // Update adds the fileinfo to the batch for updating, and does a few checks.
  478. // It returns false if the checks result in the file not going to be updated or removed.
  479. func (b *scanBatch) Update(fi protocol.FileInfo, snap *db.Snapshot) bool {
  480. // Check for a "virtual" parent directory of encrypted files. We don't track
  481. // it, but check if anything still exists within and delete it otherwise.
  482. if b.f.Type == config.FolderTypeReceiveEncrypted && fi.IsDirectory() && protocol.IsEncryptedParent(fs.PathComponents(fi.Name)) {
  483. if names, err := b.f.mtimefs.DirNames(fi.Name); err == nil && len(names) == 0 {
  484. b.f.mtimefs.Remove(fi.Name)
  485. }
  486. return false
  487. }
  488. // Resolve receive-only items which are identical with the global state or
  489. // the global item is our own receive-only item.
  490. switch gf, ok := snap.GetGlobal(fi.Name); {
  491. case !ok:
  492. case gf.IsReceiveOnlyChanged():
  493. if fi.IsDeleted() {
  494. // Our item is deleted and the global item is our own receive only
  495. // file. No point in keeping track of that.
  496. b.Remove(fi.Name)
  497. return true
  498. }
  499. case gf.IsEquivalentOptional(fi, b.f.modTimeWindow, false, false, protocol.FlagLocalReceiveOnly):
  500. // What we have locally is equivalent to the global file.
  501. l.Debugf("%v scanning: Merging identical locally changed item with global", b.f, fi)
  502. fi = gf
  503. }
  504. b.updateBatch.Append(fi)
  505. return true
  506. }
  507. func (f *folder) scanSubdirsChangedAndNew(subDirs []string, batch *scanBatch) (int, error) {
  508. changes := 0
  509. snap, err := f.dbSnapshot()
  510. if err != nil {
  511. return changes, err
  512. }
  513. defer snap.Release()
  514. // If we return early e.g. due to a folder health error, the scan needs
  515. // to be cancelled.
  516. scanCtx, scanCancel := context.WithCancel(f.ctx)
  517. defer scanCancel()
  518. scanConfig := scanner.Config{
  519. Folder: f.ID,
  520. Subs: subDirs,
  521. Matcher: f.ignores,
  522. TempLifetime: time.Duration(f.model.cfg.Options().KeepTemporariesH) * time.Hour,
  523. CurrentFiler: cFiler{snap},
  524. Filesystem: f.mtimefs,
  525. IgnorePerms: f.IgnorePerms,
  526. AutoNormalize: f.AutoNormalize,
  527. Hashers: f.model.numHashers(f.ID),
  528. ShortID: f.shortID,
  529. ProgressTickIntervalS: f.ScanProgressIntervalS,
  530. LocalFlags: f.localFlags,
  531. ModTimeWindow: f.modTimeWindow,
  532. EventLogger: f.evLogger,
  533. }
  534. var fchan chan scanner.ScanResult
  535. if f.Type == config.FolderTypeReceiveEncrypted {
  536. fchan = scanner.WalkWithoutHashing(scanCtx, scanConfig)
  537. } else {
  538. fchan = scanner.Walk(scanCtx, scanConfig)
  539. }
  540. alreadyUsedOrExisting := make(map[string]struct{})
  541. for res := range fchan {
  542. if res.Err != nil {
  543. f.newScanError(res.Path, res.Err)
  544. continue
  545. }
  546. if err := batch.FlushIfFull(); err != nil {
  547. // Prevent a race between the scan aborting due to context
  548. // cancellation and releasing the snapshot in defer here.
  549. scanCancel()
  550. for range fchan {
  551. }
  552. return changes, err
  553. }
  554. if batch.Update(res.File, snap) {
  555. changes++
  556. }
  557. switch f.Type {
  558. case config.FolderTypeReceiveOnly, config.FolderTypeReceiveEncrypted:
  559. default:
  560. if nf, ok := f.findRename(snap, res.File, alreadyUsedOrExisting); ok {
  561. if batch.Update(nf, snap) {
  562. changes++
  563. }
  564. }
  565. }
  566. }
  567. return changes, nil
  568. }
  569. func (f *folder) scanSubdirsDeletedAndIgnored(subDirs []string, batch *scanBatch) (int, error) {
  570. var toIgnore []db.FileInfoTruncated
  571. ignoredParent := ""
  572. changes := 0
  573. snap, err := f.dbSnapshot()
  574. if err != nil {
  575. return 0, err
  576. }
  577. defer snap.Release()
  578. for _, sub := range subDirs {
  579. var iterError error
  580. snap.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi protocol.FileIntf) bool {
  581. select {
  582. case <-f.ctx.Done():
  583. return false
  584. default:
  585. }
  586. file := fi.(db.FileInfoTruncated)
  587. if err := batch.FlushIfFull(); err != nil {
  588. iterError = err
  589. return false
  590. }
  591. if ignoredParent != "" && !fs.IsParent(file.Name, ignoredParent) {
  592. for _, file := range toIgnore {
  593. l.Debugln("marking file as ignored", file)
  594. nf := file.ConvertToIgnoredFileInfo()
  595. if batch.Update(nf, snap) {
  596. changes++
  597. }
  598. if err := batch.FlushIfFull(); err != nil {
  599. iterError = err
  600. return false
  601. }
  602. }
  603. toIgnore = toIgnore[:0]
  604. ignoredParent = ""
  605. }
  606. switch ignored := f.ignores.Match(file.Name).IsIgnored(); {
  607. case file.IsIgnored() && ignored:
  608. return true
  609. case !file.IsIgnored() && ignored:
  610. // File was not ignored at last pass but has been ignored.
  611. if file.IsDirectory() {
  612. // Delay ignoring as a child might be unignored.
  613. toIgnore = append(toIgnore, file)
  614. if ignoredParent == "" {
  615. // If the parent wasn't ignored already, set
  616. // this path as the "highest" ignored parent
  617. ignoredParent = file.Name
  618. }
  619. return true
  620. }
  621. l.Debugln("marking file as ignored", file)
  622. nf := file.ConvertToIgnoredFileInfo()
  623. if batch.Update(nf, snap) {
  624. changes++
  625. }
  626. case file.IsIgnored() && !ignored:
  627. // Successfully scanned items are already un-ignored during
  628. // the scan, so check whether it is deleted.
  629. fallthrough
  630. case !file.IsIgnored() && !file.IsDeleted() && !file.IsUnsupported():
  631. // The file is not ignored, deleted or unsupported. Lets check if
  632. // it's still here. Simply stat:ing it wont do as there are
  633. // tons of corner cases (e.g. parent dir->symlink, missing
  634. // permissions)
  635. if !osutil.IsDeleted(f.mtimefs, file.Name) {
  636. if ignoredParent != "" {
  637. // Don't ignore parents of this not ignored item
  638. toIgnore = toIgnore[:0]
  639. ignoredParent = ""
  640. }
  641. return true
  642. }
  643. nf := file.ConvertToDeletedFileInfo(f.shortID)
  644. nf.LocalFlags = f.localFlags
  645. if file.ShouldConflict() {
  646. // We do not want to override the global version with
  647. // the deleted file. Setting to an empty version makes
  648. // sure the file gets in sync on the following pull.
  649. nf.Version = protocol.Vector{}
  650. }
  651. l.Debugln("marking file as deleted", nf)
  652. if batch.Update(nf, snap) {
  653. changes++
  654. }
  655. case file.IsDeleted() && file.IsReceiveOnlyChanged():
  656. switch f.Type {
  657. case config.FolderTypeReceiveOnly, config.FolderTypeReceiveEncrypted:
  658. switch gf, ok := snap.GetGlobal(file.Name); {
  659. case !ok:
  660. case gf.IsReceiveOnlyChanged():
  661. l.Debugln("removing deleted, receive-only item that is globally receive-only from db", file)
  662. batch.Remove(file.Name)
  663. changes++
  664. case gf.IsDeleted():
  665. // Our item is deleted and the global item is deleted too. We just
  666. // pretend it is a normal deleted file (nobody cares about that).
  667. l.Debugf("%v scanning: Marking globally deleted item as not locally changed: %v", f, file.Name)
  668. file.LocalFlags &^= protocol.FlagLocalReceiveOnly
  669. if batch.Update(file.ConvertDeletedToFileInfo(), snap) {
  670. changes++
  671. }
  672. }
  673. default:
  674. // No need to bump the version for a file that was and is
  675. // deleted and just the folder type/local flags changed.
  676. file.LocalFlags &^= protocol.FlagLocalReceiveOnly
  677. l.Debugln("removing receive-only flag on deleted item", file)
  678. if batch.Update(file.ConvertDeletedToFileInfo(), snap) {
  679. changes++
  680. }
  681. }
  682. }
  683. return true
  684. })
  685. select {
  686. case <-f.ctx.Done():
  687. return changes, f.ctx.Err()
  688. default:
  689. }
  690. if iterError == nil && len(toIgnore) > 0 {
  691. for _, file := range toIgnore {
  692. l.Debugln("marking file as ignored", f)
  693. nf := file.ConvertToIgnoredFileInfo()
  694. if batch.Update(nf, snap) {
  695. changes++
  696. }
  697. if iterError = batch.FlushIfFull(); iterError != nil {
  698. break
  699. }
  700. }
  701. toIgnore = toIgnore[:0]
  702. }
  703. if iterError != nil {
  704. return changes, iterError
  705. }
  706. }
  707. return changes, nil
  708. }
  709. func (f *folder) findRename(snap *db.Snapshot, file protocol.FileInfo, alreadyUsedOrExisting map[string]struct{}) (protocol.FileInfo, bool) {
  710. if len(file.Blocks) == 0 || file.Size == 0 {
  711. return protocol.FileInfo{}, false
  712. }
  713. found := false
  714. nf := protocol.FileInfo{}
  715. snap.WithBlocksHash(file.BlocksHash, func(ifi protocol.FileIntf) bool {
  716. fi := ifi.(protocol.FileInfo)
  717. select {
  718. case <-f.ctx.Done():
  719. return false
  720. default:
  721. }
  722. if fi.Name == file.Name {
  723. alreadyUsedOrExisting[fi.Name] = struct{}{}
  724. return true
  725. }
  726. if _, ok := alreadyUsedOrExisting[fi.Name]; ok {
  727. return true
  728. }
  729. if fi.ShouldConflict() {
  730. return true
  731. }
  732. if f.ignores.Match(fi.Name).IsIgnored() {
  733. return true
  734. }
  735. // Only check the size.
  736. // No point checking block equality, as that uses BlocksHash comparison if that is set (which it will be).
  737. // No point checking BlocksHash comparison as WithBlocksHash already does that.
  738. if file.Size != fi.Size {
  739. return true
  740. }
  741. alreadyUsedOrExisting[fi.Name] = struct{}{}
  742. if !osutil.IsDeleted(f.mtimefs, fi.Name) {
  743. return true
  744. }
  745. nf = fi
  746. nf.SetDeleted(f.shortID)
  747. nf.LocalFlags = f.localFlags
  748. found = true
  749. return false
  750. })
  751. return nf, found
  752. }
  753. func (f *folder) scanTimerFired() error {
  754. err := f.scanSubdirs(nil)
  755. select {
  756. case <-f.initialScanFinished:
  757. default:
  758. status := "Completed"
  759. if err != nil {
  760. status = "Failed"
  761. }
  762. l.Infoln(status, "initial scan of", f.Type.String(), "folder", f.Description())
  763. close(f.initialScanFinished)
  764. }
  765. f.Reschedule()
  766. return err
  767. }
  768. func (f *folder) versionCleanupTimerFired() {
  769. f.setState(FolderCleanWaiting)
  770. defer f.setState(FolderIdle)
  771. if err := f.ioLimiter.TakeWithContext(f.ctx, 1); err != nil {
  772. return
  773. }
  774. defer f.ioLimiter.Give(1)
  775. f.setState(FolderCleaning)
  776. if err := f.versioner.Clean(f.ctx); err != nil {
  777. l.Infoln("Failed to clean versions in %s: %v", f.Description(), err)
  778. }
  779. f.versionCleanupTimer.Reset(f.versionCleanupInterval)
  780. }
  781. func (f *folder) WatchError() error {
  782. f.watchMut.Lock()
  783. defer f.watchMut.Unlock()
  784. return f.watchErr
  785. }
  786. // stopWatch immediately aborts watching and may be called asynchronously
  787. func (f *folder) stopWatch() {
  788. f.watchMut.Lock()
  789. f.watchCancel()
  790. f.watchMut.Unlock()
  791. f.setWatchError(nil, 0)
  792. }
  793. // scheduleWatchRestart makes sure watching is restarted from the main for loop
  794. // in a folder's Serve and thus may be called asynchronously (e.g. when ignores change).
  795. func (f *folder) scheduleWatchRestart() {
  796. select {
  797. case f.restartWatchChan <- struct{}{}:
  798. default:
  799. // We might be busy doing a pull and thus not reading from this
  800. // channel. The channel is 1-buffered, so one notification will be
  801. // queued to ensure we recheck after the pull.
  802. }
  803. }
  804. // restartWatch should only ever be called synchronously. If you want to use
  805. // this asynchronously, you should probably use scheduleWatchRestart instead.
  806. func (f *folder) restartWatch() error {
  807. f.stopWatch()
  808. f.startWatch()
  809. return f.scanSubdirs(nil)
  810. }
  811. // startWatch should only ever be called synchronously. If you want to use
  812. // this asynchronously, you should probably use scheduleWatchRestart instead.
  813. func (f *folder) startWatch() {
  814. ctx, cancel := context.WithCancel(f.ctx)
  815. f.watchMut.Lock()
  816. f.watchChan = make(chan []string)
  817. f.watchCancel = cancel
  818. f.watchMut.Unlock()
  819. go f.monitorWatch(ctx)
  820. }
  821. // monitorWatch starts the filesystem watching and retries every minute on failure.
  822. // It should not be used except in startWatch.
  823. func (f *folder) monitorWatch(ctx context.Context) {
  824. failTimer := time.NewTimer(0)
  825. aggrCtx, aggrCancel := context.WithCancel(ctx)
  826. var err error
  827. var eventChan <-chan fs.Event
  828. var errChan <-chan error
  829. warnedOutside := false
  830. var lastWatch time.Time
  831. pause := time.Minute
  832. // Subscribe to folder summaries only on kqueue systems, to warn about potential high resource usage
  833. var summarySub events.Subscription
  834. var summaryChan <-chan events.Event
  835. if fs.WatchKqueue && !f.warnedKqueue {
  836. summarySub = f.evLogger.Subscribe(events.FolderCompletion)
  837. summaryChan = summarySub.C()
  838. }
  839. defer func() {
  840. aggrCancel() // aggrCancel might e re-assigned -> call within closure
  841. if summaryChan != nil {
  842. summarySub.Unsubscribe()
  843. }
  844. }()
  845. for {
  846. select {
  847. case <-failTimer.C:
  848. eventChan, errChan, err = f.mtimefs.Watch(".", f.ignores, ctx, f.IgnorePerms)
  849. // We do this once per minute initially increased to
  850. // max one hour in case of repeat failures.
  851. f.scanOnWatchErr()
  852. f.setWatchError(err, pause)
  853. if err != nil {
  854. failTimer.Reset(pause)
  855. if pause < 60*time.Minute {
  856. pause *= 2
  857. }
  858. continue
  859. }
  860. lastWatch = time.Now()
  861. watchaggregator.Aggregate(aggrCtx, eventChan, f.watchChan, f.FolderConfiguration, f.model.cfg, f.evLogger)
  862. l.Debugln("Started filesystem watcher for folder", f.Description())
  863. case err = <-errChan:
  864. var next time.Duration
  865. if dur := time.Since(lastWatch); dur > pause {
  866. pause = time.Minute
  867. next = 0
  868. } else {
  869. next = pause - dur
  870. if pause < 60*time.Minute {
  871. pause *= 2
  872. }
  873. }
  874. failTimer.Reset(next)
  875. f.setWatchError(err, next)
  876. // This error was previously a panic and should never occur, so generate
  877. // a warning, but don't do it repetitively.
  878. var errOutside *fs.ErrWatchEventOutsideRoot
  879. if errors.As(err, &errOutside) {
  880. if !warnedOutside {
  881. l.Warnln(err)
  882. warnedOutside = true
  883. }
  884. f.evLogger.Log(events.Failure, "watching for changes encountered an event outside of the filesystem root")
  885. }
  886. aggrCancel()
  887. errChan = nil
  888. aggrCtx, aggrCancel = context.WithCancel(ctx)
  889. case ev := <-summaryChan:
  890. if data, ok := ev.Data.(FolderSummaryEventData); !ok {
  891. f.evLogger.Log(events.Failure, "Unexpected type of folder-summary event in folder.monitorWatch")
  892. } else if data.Summary.LocalTotalItems > kqueueItemCountThreshold {
  893. f.warnedKqueue = true
  894. summarySub.Unsubscribe()
  895. summaryChan = nil
  896. l.Warnf("Filesystem watching (kqueue) is enabled on %v with a lot of files/directories, and that requires a lot of resources and might slow down your system significantly", f.Description())
  897. }
  898. case <-ctx.Done():
  899. return
  900. }
  901. }
  902. }
  903. // setWatchError sets the current error state of the watch and should be called
  904. // regardless of whether err is nil or not.
  905. func (f *folder) setWatchError(err error, nextTryIn time.Duration) {
  906. f.watchMut.Lock()
  907. prevErr := f.watchErr
  908. f.watchErr = err
  909. f.watchMut.Unlock()
  910. if err != prevErr {
  911. data := map[string]string{
  912. "folder": f.ID,
  913. }
  914. if prevErr != nil {
  915. data["from"] = prevErr.Error()
  916. }
  917. if err != nil {
  918. data["to"] = err.Error()
  919. }
  920. f.evLogger.Log(events.FolderWatchStateChanged, data)
  921. }
  922. if err == nil {
  923. return
  924. }
  925. msg := fmt.Sprintf("Error while trying to start filesystem watcher for folder %s, trying again in %v: %v", f.Description(), nextTryIn, err)
  926. if prevErr != err {
  927. l.Infof(msg)
  928. return
  929. }
  930. l.Debugf(msg)
  931. }
  932. // scanOnWatchErr schedules a full scan immediately if an error occurred while watching.
  933. func (f *folder) scanOnWatchErr() {
  934. f.watchMut.Lock()
  935. err := f.watchErr
  936. f.watchMut.Unlock()
  937. if err != nil {
  938. f.DelayScan(0)
  939. }
  940. }
  941. func (f *folder) setError(err error) {
  942. select {
  943. case <-f.ctx.Done():
  944. return
  945. default:
  946. }
  947. _, _, oldErr := f.getState()
  948. if (err != nil && oldErr != nil && oldErr.Error() == err.Error()) || (err == nil && oldErr == nil) {
  949. return
  950. }
  951. if err != nil {
  952. if oldErr == nil {
  953. l.Warnf("Error on folder %s: %v", f.Description(), err)
  954. } else {
  955. l.Infof("Error on folder %s changed: %q -> %q", f.Description(), oldErr, err)
  956. }
  957. } else {
  958. l.Infoln("Cleared error on folder", f.Description())
  959. f.SchedulePull()
  960. }
  961. if f.FSWatcherEnabled {
  962. if err != nil {
  963. f.stopWatch()
  964. } else {
  965. f.scheduleWatchRestart()
  966. }
  967. }
  968. f.stateTracker.setError(err)
  969. }
  970. func (f *folder) pullBasePause() time.Duration {
  971. if f.PullerPauseS == 0 {
  972. return defaultPullerPause
  973. }
  974. return time.Duration(f.PullerPauseS) * time.Second
  975. }
  976. func (f *folder) String() string {
  977. return fmt.Sprintf("%s/%s@%p", f.Type, f.folderID, f)
  978. }
  979. func (f *folder) newScanError(path string, err error) {
  980. f.errorsMut.Lock()
  981. l.Infof("Scanner (folder %s, item %q): %v", f.Description(), path, err)
  982. f.scanErrors = append(f.scanErrors, FileError{
  983. Err: err.Error(),
  984. Path: path,
  985. })
  986. f.errorsMut.Unlock()
  987. }
  988. func (f *folder) clearScanErrors(subDirs []string) {
  989. f.errorsMut.Lock()
  990. defer f.errorsMut.Unlock()
  991. if len(subDirs) == 0 {
  992. f.scanErrors = nil
  993. return
  994. }
  995. filtered := f.scanErrors[:0]
  996. outer:
  997. for _, fe := range f.scanErrors {
  998. for _, sub := range subDirs {
  999. if fe.Path == sub || fs.IsParent(fe.Path, sub) {
  1000. continue outer
  1001. }
  1002. }
  1003. filtered = append(filtered, fe)
  1004. }
  1005. f.scanErrors = filtered
  1006. }
  1007. func (f *folder) Errors() []FileError {
  1008. f.errorsMut.Lock()
  1009. defer f.errorsMut.Unlock()
  1010. scanLen := len(f.scanErrors)
  1011. errors := make([]FileError, scanLen+len(f.pullErrors))
  1012. copy(errors[:scanLen], f.scanErrors)
  1013. copy(errors[scanLen:], f.pullErrors)
  1014. sort.Sort(fileErrorList(errors))
  1015. return errors
  1016. }
  1017. // ScheduleForceRescan marks the file such that it gets rehashed on next scan, and schedules a scan.
  1018. func (f *folder) ScheduleForceRescan(path string) {
  1019. f.forcedRescanPathsMut.Lock()
  1020. f.forcedRescanPaths[path] = struct{}{}
  1021. f.forcedRescanPathsMut.Unlock()
  1022. select {
  1023. case f.forcedRescanRequested <- struct{}{}:
  1024. default:
  1025. }
  1026. }
  1027. func (f *folder) updateLocalsFromScanning(fs []protocol.FileInfo) {
  1028. f.updateLocals(fs)
  1029. f.emitDiskChangeEvents(fs, events.LocalChangeDetected)
  1030. }
  1031. func (f *folder) updateLocalsFromPulling(fs []protocol.FileInfo) {
  1032. f.updateLocals(fs)
  1033. f.emitDiskChangeEvents(fs, events.RemoteChangeDetected)
  1034. }
  1035. func (f *folder) updateLocals(fs []protocol.FileInfo) {
  1036. f.fset.Update(protocol.LocalDeviceID, fs)
  1037. filenames := make([]string, len(fs))
  1038. f.forcedRescanPathsMut.Lock()
  1039. for i, file := range fs {
  1040. filenames[i] = file.Name
  1041. // No need to rescan a file that was changed since anyway.
  1042. delete(f.forcedRescanPaths, file.Name)
  1043. }
  1044. f.forcedRescanPathsMut.Unlock()
  1045. seq := f.fset.Sequence(protocol.LocalDeviceID)
  1046. f.evLogger.Log(events.LocalIndexUpdated, map[string]interface{}{
  1047. "folder": f.ID,
  1048. "items": len(fs),
  1049. "filenames": filenames,
  1050. "sequence": seq,
  1051. "version": seq, // legacy for sequence
  1052. })
  1053. }
  1054. func (f *folder) emitDiskChangeEvents(fs []protocol.FileInfo, typeOfEvent events.EventType) {
  1055. for _, file := range fs {
  1056. if file.IsInvalid() {
  1057. continue
  1058. }
  1059. objType := "file"
  1060. action := "modified"
  1061. if file.IsDeleted() {
  1062. action = "deleted"
  1063. }
  1064. if file.IsSymlink() {
  1065. objType = "symlink"
  1066. } else if file.IsDirectory() {
  1067. objType = "dir"
  1068. }
  1069. // Two different events can be fired here based on what EventType is passed into function
  1070. f.evLogger.Log(typeOfEvent, map[string]string{
  1071. "folder": f.ID,
  1072. "folderID": f.ID, // incorrect, deprecated, kept for historical compliance
  1073. "label": f.Label,
  1074. "action": action,
  1075. "type": objType,
  1076. "path": filepath.FromSlash(file.Name),
  1077. "modifiedBy": file.ModifiedBy.String(),
  1078. })
  1079. }
  1080. }
  1081. func (f *folder) handleForcedRescans() error {
  1082. f.forcedRescanPathsMut.Lock()
  1083. paths := make([]string, 0, len(f.forcedRescanPaths))
  1084. for path := range f.forcedRescanPaths {
  1085. paths = append(paths, path)
  1086. }
  1087. f.forcedRescanPaths = make(map[string]struct{})
  1088. f.forcedRescanPathsMut.Unlock()
  1089. if len(paths) == 0 {
  1090. return nil
  1091. }
  1092. batch := db.NewFileInfoBatch(func(fs []protocol.FileInfo) error {
  1093. f.fset.Update(protocol.LocalDeviceID, fs)
  1094. return nil
  1095. })
  1096. snap, err := f.dbSnapshot()
  1097. if err != nil {
  1098. return err
  1099. }
  1100. defer snap.Release()
  1101. for _, path := range paths {
  1102. if err := batch.FlushIfFull(); err != nil {
  1103. return err
  1104. }
  1105. fi, ok := snap.Get(protocol.LocalDeviceID, path)
  1106. if !ok {
  1107. continue
  1108. }
  1109. fi.SetMustRescan()
  1110. batch.Append(fi)
  1111. }
  1112. if err = batch.Flush(); err != nil {
  1113. return err
  1114. }
  1115. return f.scanSubdirs(paths)
  1116. }
  1117. // dbSnapshots gets a snapshot from the fileset, and wraps any error
  1118. // in a svcutil.FatalErr.
  1119. func (f *folder) dbSnapshot() (*db.Snapshot, error) {
  1120. snap, err := f.fset.Snapshot()
  1121. if err != nil {
  1122. return nil, svcutil.AsFatalErr(err, svcutil.ExitError)
  1123. }
  1124. return snap, nil
  1125. }
  1126. // The exists function is expected to return true for all known paths
  1127. // (excluding "" and ".")
  1128. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  1129. if len(dirs) == 0 {
  1130. return nil
  1131. }
  1132. sort.Strings(dirs)
  1133. if dirs[0] == "" || dirs[0] == "." || dirs[0] == string(fs.PathSeparator) {
  1134. return nil
  1135. }
  1136. prev := "./" // Anything that can't be parent of a clean path
  1137. for i := 0; i < len(dirs); {
  1138. dir, err := fs.Canonicalize(dirs[i])
  1139. if err != nil {
  1140. l.Debugf("Skipping %v for scan: %s", dirs[i], err)
  1141. dirs = append(dirs[:i], dirs[i+1:]...)
  1142. continue
  1143. }
  1144. if dir == prev || fs.IsParent(dir, prev) {
  1145. dirs = append(dirs[:i], dirs[i+1:]...)
  1146. continue
  1147. }
  1148. parent := filepath.Dir(dir)
  1149. for parent != "." && parent != string(fs.PathSeparator) && !exists(parent) {
  1150. dir = parent
  1151. parent = filepath.Dir(dir)
  1152. }
  1153. dirs[i] = dir
  1154. prev = dir
  1155. i++
  1156. }
  1157. return dirs
  1158. }
  1159. type cFiler struct {
  1160. *db.Snapshot
  1161. }
  1162. // Implements scanner.CurrentFiler
  1163. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  1164. return cf.Get(protocol.LocalDeviceID, file)
  1165. }