aggregator.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. // Copyright (C) 2016 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package watchaggregator
  7. import (
  8. "context"
  9. "fmt"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. "github.com/syncthing/syncthing/lib/config"
  14. "github.com/syncthing/syncthing/lib/events"
  15. "github.com/syncthing/syncthing/lib/fs"
  16. )
  17. // Not meant to be changed, but must be changeable for tests
  18. var (
  19. maxFiles = 512
  20. maxFilesPerDir = 128
  21. )
  22. // aggregatedEvent represents potentially multiple events at and/or recursively
  23. // below one path until it times out and a scan is scheduled.
  24. // If it represents multiple events and there are events of both Remove and
  25. // NonRemove types, the evType attribute is Mixed (as returned by fs.Event.Merge).
  26. type aggregatedEvent struct {
  27. firstModTime time.Time
  28. lastModTime time.Time
  29. evType fs.EventType
  30. }
  31. // Stores pointers to both aggregated events directly within this directory and
  32. // child directories recursively containing aggregated events themselves.
  33. type eventDir struct {
  34. events map[string]*aggregatedEvent
  35. dirs map[string]*eventDir
  36. }
  37. func newEventDir() *eventDir {
  38. return &eventDir{
  39. events: make(map[string]*aggregatedEvent),
  40. dirs: make(map[string]*eventDir),
  41. }
  42. }
  43. func (dir *eventDir) childCount() int {
  44. return len(dir.events) + len(dir.dirs)
  45. }
  46. func (dir *eventDir) firstModTime() time.Time {
  47. if dir.childCount() == 0 {
  48. panic("bug: firstModTime must not be used on empty eventDir")
  49. }
  50. firstModTime := time.Now()
  51. for _, childDir := range dir.dirs {
  52. dirTime := childDir.firstModTime()
  53. if dirTime.Before(firstModTime) {
  54. firstModTime = dirTime
  55. }
  56. }
  57. for _, event := range dir.events {
  58. if event.firstModTime.Before(firstModTime) {
  59. firstModTime = event.firstModTime
  60. }
  61. }
  62. return firstModTime
  63. }
  64. func (dir *eventDir) eventType() fs.EventType {
  65. if dir.childCount() == 0 {
  66. panic("bug: eventType must not be used on empty eventDir")
  67. }
  68. var evType fs.EventType
  69. for _, childDir := range dir.dirs {
  70. evType |= childDir.eventType()
  71. if evType == fs.Mixed {
  72. return fs.Mixed
  73. }
  74. }
  75. for _, event := range dir.events {
  76. evType |= event.evType
  77. if evType == fs.Mixed {
  78. return fs.Mixed
  79. }
  80. }
  81. return evType
  82. }
  83. type aggregator struct {
  84. // folderID never changes and is accessed in CommitConfiguration, which
  85. // asynchronously updates folderCfg -> can't use folderCfg.ID (racy)
  86. folderID string
  87. folderCfg config.FolderConfiguration
  88. folderCfgUpdate chan config.FolderConfiguration
  89. // Time after which an event is scheduled for scanning when no modifications occur.
  90. notifyDelay time.Duration
  91. // Time after which an event is scheduled for scanning even though modifications occur.
  92. notifyTimeout time.Duration
  93. notifyTimer *time.Timer
  94. notifyTimerNeedsReset bool
  95. notifyTimerResetChan chan time.Duration
  96. counts eventCounter
  97. root *eventDir
  98. ctx context.Context
  99. }
  100. type eventCounter struct {
  101. removes int // Includes mixed events.
  102. nonRemoves int
  103. }
  104. func (c *eventCounter) add(typ fs.EventType, n int) {
  105. if typ&fs.Remove != 0 {
  106. c.removes += n
  107. } else {
  108. c.nonRemoves += n
  109. }
  110. }
  111. func (c *eventCounter) total() int { return c.removes + c.nonRemoves }
  112. func newAggregator(ctx context.Context, folderCfg config.FolderConfiguration) *aggregator {
  113. a := &aggregator{
  114. folderID: folderCfg.ID,
  115. folderCfgUpdate: make(chan config.FolderConfiguration),
  116. notifyTimerNeedsReset: false,
  117. notifyTimerResetChan: make(chan time.Duration),
  118. root: newEventDir(),
  119. ctx: ctx,
  120. }
  121. a.updateConfig(folderCfg)
  122. return a
  123. }
  124. func Aggregate(ctx context.Context, in <-chan fs.Event, out chan<- []string, folderCfg config.FolderConfiguration, cfg config.Wrapper, evLogger events.Logger) {
  125. a := newAggregator(ctx, folderCfg)
  126. // Necessary for unit tests where the backend is mocked
  127. go a.mainLoop(in, out, cfg, evLogger)
  128. }
  129. func (a *aggregator) mainLoop(in <-chan fs.Event, out chan<- []string, cfg config.Wrapper, evLogger events.Logger) {
  130. a.notifyTimer = time.NewTimer(a.notifyDelay)
  131. defer a.notifyTimer.Stop()
  132. inProgressItemSubscription := evLogger.Subscribe(events.ItemStarted | events.ItemFinished)
  133. defer inProgressItemSubscription.Unsubscribe()
  134. cfg.Subscribe(a)
  135. defer cfg.Unsubscribe(a)
  136. inProgress := make(map[string]struct{})
  137. for {
  138. select {
  139. case event := <-in:
  140. a.newEvent(event, inProgress)
  141. case event, ok := <-inProgressItemSubscription.C():
  142. if ok {
  143. updateInProgressSet(event, inProgress)
  144. }
  145. case <-a.notifyTimer.C:
  146. a.actOnTimer(out)
  147. case interval := <-a.notifyTimerResetChan:
  148. a.resetNotifyTimer(interval)
  149. case folderCfg := <-a.folderCfgUpdate:
  150. a.updateConfig(folderCfg)
  151. case <-a.ctx.Done():
  152. l.Debugln(a, "Stopped")
  153. return
  154. }
  155. }
  156. }
  157. func (a *aggregator) newEvent(event fs.Event, inProgress map[string]struct{}) {
  158. if _, ok := a.root.events["."]; ok {
  159. l.Debugln(a, "Will scan entire folder anyway; dropping:", event.Name)
  160. return
  161. }
  162. if _, ok := inProgress[event.Name]; ok {
  163. l.Debugln(a, "Skipping path we modified:", event.Name)
  164. return
  165. }
  166. a.aggregateEvent(event, time.Now())
  167. }
  168. func (a *aggregator) aggregateEvent(event fs.Event, evTime time.Time) {
  169. if event.Name == "." || a.counts.total() == maxFiles {
  170. l.Debugln(a, "Scan entire folder")
  171. firstModTime := evTime
  172. if a.root.childCount() != 0 {
  173. event.Type = event.Type.Merge(a.root.eventType())
  174. firstModTime = a.root.firstModTime()
  175. }
  176. a.root.dirs = make(map[string]*eventDir)
  177. a.root.events = make(map[string]*aggregatedEvent)
  178. a.root.events["."] = &aggregatedEvent{
  179. firstModTime: firstModTime,
  180. lastModTime: evTime,
  181. evType: event.Type,
  182. }
  183. a.counts = eventCounter{}
  184. a.counts.add(event.Type, 1)
  185. a.resetNotifyTimerIfNeeded()
  186. return
  187. }
  188. parentDir := a.root
  189. // Check if any parent directory is already tracked or will exceed
  190. // events per directory limit bottom up
  191. pathSegments := strings.Split(filepath.ToSlash(event.Name), "/")
  192. // As root dir cannot be further aggregated, allow up to maxFiles
  193. // children.
  194. localMaxFilesPerDir := maxFiles
  195. var currPath string
  196. for i, name := range pathSegments[:len(pathSegments)-1] {
  197. currPath = filepath.Join(currPath, name)
  198. if ev, ok := parentDir.events[name]; ok {
  199. ev.lastModTime = evTime
  200. if merged := event.Type.Merge(ev.evType); ev.evType != merged {
  201. a.counts.add(ev.evType, -1)
  202. a.counts.add(merged, 1)
  203. ev.evType = merged
  204. }
  205. l.Debugf("%v Parent %s (type %s) already tracked: %s", a, currPath, ev.evType, event.Name)
  206. return
  207. }
  208. if parentDir.childCount() == localMaxFilesPerDir {
  209. l.Debugf("%v Parent dir %s already has %d children, tracking it instead: %s", a, currPath, localMaxFilesPerDir, event.Name)
  210. event.Name = filepath.Dir(currPath)
  211. a.aggregateEvent(event, evTime)
  212. return
  213. }
  214. // If there are no events below path, but we need to recurse
  215. // into that path, create eventDir at path.
  216. if newParent, ok := parentDir.dirs[name]; ok {
  217. parentDir = newParent
  218. } else {
  219. l.Debugln(a, "Creating eventDir at:", currPath)
  220. newParent = newEventDir()
  221. parentDir.dirs[name] = newParent
  222. parentDir = newParent
  223. }
  224. // Reset allowed children count to maxFilesPerDir for non-root
  225. if i == 0 {
  226. localMaxFilesPerDir = maxFilesPerDir
  227. }
  228. }
  229. name := pathSegments[len(pathSegments)-1]
  230. if ev, ok := parentDir.events[name]; ok {
  231. ev.lastModTime = evTime
  232. if merged := event.Type.Merge(ev.evType); ev.evType != merged {
  233. a.counts.add(ev.evType, -1)
  234. a.counts.add(merged, 1)
  235. ev.evType = merged
  236. }
  237. l.Debugf("%v Already tracked (type %v): %s", a, ev.evType, event.Name)
  238. return
  239. }
  240. childDir, ok := parentDir.dirs[name]
  241. // If a dir existed at path, it would be removed from dirs, thus
  242. // childCount would not increase.
  243. if !ok && parentDir.childCount() == localMaxFilesPerDir {
  244. l.Debugf("%v Parent dir already has %d children, tracking it instead: %s", a, localMaxFilesPerDir, event.Name)
  245. event.Name = filepath.Dir(event.Name)
  246. a.aggregateEvent(event, evTime)
  247. return
  248. }
  249. firstModTime := evTime
  250. if ok {
  251. firstModTime = childDir.firstModTime()
  252. if merged := event.Type.Merge(childDir.eventType()); event.Type != merged {
  253. a.counts.add(event.Type, -1)
  254. event.Type = merged
  255. }
  256. delete(parentDir.dirs, name)
  257. }
  258. l.Debugf("%v Tracking (type %v): %s", a, event.Type, event.Name)
  259. parentDir.events[name] = &aggregatedEvent{
  260. firstModTime: firstModTime,
  261. lastModTime: evTime,
  262. evType: event.Type,
  263. }
  264. a.counts.add(event.Type, 1)
  265. a.resetNotifyTimerIfNeeded()
  266. }
  267. func (a *aggregator) resetNotifyTimerIfNeeded() {
  268. if a.notifyTimerNeedsReset {
  269. a.resetNotifyTimer(a.notifyDelay)
  270. }
  271. }
  272. // resetNotifyTimer should only ever be called when notifyTimer has stopped
  273. // and notifyTimer.C been read from. Otherwise, call resetNotifyTimerIfNeeded.
  274. func (a *aggregator) resetNotifyTimer(duration time.Duration) {
  275. l.Debugln(a, "Resetting notifyTimer to", duration.String())
  276. a.notifyTimerNeedsReset = false
  277. a.notifyTimer.Reset(duration)
  278. }
  279. func (a *aggregator) actOnTimer(out chan<- []string) {
  280. c := a.counts.total()
  281. if c == 0 {
  282. l.Debugln(a, "No tracked events, waiting for new event.")
  283. a.notifyTimerNeedsReset = true
  284. return
  285. }
  286. oldEvents := make(map[string]*aggregatedEvent, c)
  287. a.popOldEventsTo(oldEvents, a.root, ".", time.Now(), true)
  288. if a.notifyDelay != a.notifyTimeout && a.counts.nonRemoves == 0 && a.counts.removes != 0 {
  289. // Only delayed events remaining, no need to delay them additionally
  290. a.popOldEventsTo(oldEvents, a.root, ".", time.Now(), false)
  291. }
  292. if len(oldEvents) == 0 {
  293. l.Debugln(a, "No old fs events")
  294. a.resetNotifyTimer(a.notifyDelay)
  295. return
  296. }
  297. // Sending to channel might block for a long time, but we need to keep
  298. // reading from notify backend channel to avoid overflow
  299. go a.notify(oldEvents, out)
  300. }
  301. // Schedule scan for given events dispatching deletes last and reset notification
  302. // afterwards to set up for the next scan scheduling.
  303. func (a *aggregator) notify(oldEvents map[string]*aggregatedEvent, out chan<- []string) {
  304. timeBeforeSending := time.Now()
  305. l.Debugf("%v Notifying about %d fs events", a, len(oldEvents))
  306. separatedBatches := make(map[fs.EventType][]string)
  307. for path, event := range oldEvents {
  308. separatedBatches[event.evType] = append(separatedBatches[event.evType], path)
  309. }
  310. for _, evType := range [3]fs.EventType{fs.NonRemove, fs.Mixed, fs.Remove} {
  311. currBatch := separatedBatches[evType]
  312. if len(currBatch) != 0 {
  313. select {
  314. case out <- currBatch:
  315. case <-a.ctx.Done():
  316. return
  317. }
  318. }
  319. }
  320. // If sending to channel blocked for a long time,
  321. // shorten next notifyDelay accordingly.
  322. duration := time.Since(timeBeforeSending)
  323. buffer := time.Millisecond
  324. var nextDelay time.Duration
  325. switch {
  326. case duration < a.notifyDelay/10:
  327. nextDelay = a.notifyDelay
  328. case duration+buffer > a.notifyDelay:
  329. nextDelay = buffer
  330. default:
  331. nextDelay = a.notifyDelay - duration
  332. }
  333. select {
  334. case a.notifyTimerResetChan <- nextDelay:
  335. case <-a.ctx.Done():
  336. }
  337. }
  338. // popOldEvents finds events that should be scheduled for scanning recursively in dirs,
  339. // removes those events and empty eventDirs and returns a map with all the removed
  340. // events referenced by their filesystem path
  341. func (a *aggregator) popOldEventsTo(to map[string]*aggregatedEvent, dir *eventDir, dirPath string, currTime time.Time, delayRem bool) {
  342. for childName, childDir := range dir.dirs {
  343. a.popOldEventsTo(to, childDir, filepath.Join(dirPath, childName), currTime, delayRem)
  344. if childDir.childCount() == 0 {
  345. delete(dir.dirs, childName)
  346. }
  347. }
  348. for name, event := range dir.events {
  349. if a.isOld(event, currTime, delayRem) {
  350. to[filepath.Join(dirPath, name)] = event
  351. delete(dir.events, name)
  352. a.counts.add(event.evType, -1)
  353. }
  354. }
  355. }
  356. func (a *aggregator) isOld(ev *aggregatedEvent, currTime time.Time, delayRem bool) bool {
  357. // Deletes should in general be scanned last, therefore they are delayed by
  358. // letting them time out. This behaviour is overridden by delayRem == false.
  359. // Refer to following comments as to why.
  360. // An event that has not registered any new modifications recently is scanned.
  361. // a.notifyDelay is the user facing value signifying the normal delay between
  362. // picking up a modification and scanning it. As scheduling scans happens at
  363. // regular intervals of a.notifyDelay the delay of a single event is not exactly
  364. // a.notifyDelay, but lies in the range of 0.5 to 1.5 times a.notifyDelay.
  365. if (!delayRem || ev.evType == fs.NonRemove) && 2*currTime.Sub(ev.lastModTime) > a.notifyDelay {
  366. return true
  367. }
  368. // When an event registers repeat modifications or involves removals it
  369. // is delayed to reduce resource usage, but after a certain time (notifyTimeout)
  370. // passed it is scanned anyway.
  371. // If only removals are remaining to be scanned, there is no point to delay
  372. // removals further, so this behaviour is overridden by delayRem == false.
  373. return currTime.Sub(ev.firstModTime) > a.notifyTimeout
  374. }
  375. func (a *aggregator) String() string {
  376. return fmt.Sprintf("aggregator/%s:", a.folderCfg.Description())
  377. }
  378. func (a *aggregator) CommitConfiguration(_, to config.Configuration) bool {
  379. for _, folderCfg := range to.Folders {
  380. if folderCfg.ID == a.folderID {
  381. select {
  382. case a.folderCfgUpdate <- folderCfg:
  383. case <-a.ctx.Done():
  384. }
  385. return true
  386. }
  387. }
  388. // Nothing to do, model will soon stop this
  389. return true
  390. }
  391. func (a *aggregator) updateConfig(folderCfg config.FolderConfiguration) {
  392. a.notifyDelay = time.Duration(folderCfg.FSWatcherDelayS) * time.Second
  393. a.notifyTimeout = notifyTimeout(folderCfg.FSWatcherDelayS)
  394. a.folderCfg = folderCfg
  395. }
  396. func updateInProgressSet(event events.Event, inProgress map[string]struct{}) {
  397. if event.Type == events.ItemStarted {
  398. path := event.Data.(map[string]string)["item"]
  399. inProgress[path] = struct{}{}
  400. } else if event.Type == events.ItemFinished {
  401. path := event.Data.(map[string]interface{})["item"].(string)
  402. delete(inProgress, path)
  403. }
  404. }
  405. // Events that involve removals or continuously receive new modifications are
  406. // delayed but must time out at some point. The following numbers come out of thin
  407. // air, they were just considered as a sensible compromise between fast updates and
  408. // saving resources. For short delays the timeout is 6 times the delay, capped at 1
  409. // minute. For delays longer than 1 minute, the delay and timeout are equal.
  410. func notifyTimeout(eventDelayS float64) time.Duration {
  411. const (
  412. shortDelayS = 10
  413. shortDelayMultiplicator = 6
  414. longDelayS = 60
  415. )
  416. longDelayTimeout := time.Duration(1) * time.Minute
  417. if eventDelayS < shortDelayS {
  418. return time.Duration(eventDelayS*shortDelayMultiplicator) * time.Second
  419. }
  420. if eventDelayS < longDelayS {
  421. return longDelayTimeout
  422. }
  423. return time.Duration(eventDelayS) * time.Second
  424. }