aggregator.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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 map[fs.EventType]int
  97. root *eventDir
  98. ctx context.Context
  99. }
  100. func newAggregator(folderCfg config.FolderConfiguration, ctx context.Context) *aggregator {
  101. a := &aggregator{
  102. folderID: folderCfg.ID,
  103. folderCfgUpdate: make(chan config.FolderConfiguration),
  104. notifyTimerNeedsReset: false,
  105. notifyTimerResetChan: make(chan time.Duration),
  106. counts: make(map[fs.EventType]int),
  107. root: newEventDir(),
  108. ctx: ctx,
  109. }
  110. a.updateConfig(folderCfg)
  111. return a
  112. }
  113. func Aggregate(in <-chan fs.Event, out chan<- []string, folderCfg config.FolderConfiguration, cfg *config.Wrapper, ctx context.Context) {
  114. a := newAggregator(folderCfg, ctx)
  115. // Necessary for unit tests where the backend is mocked
  116. go a.mainLoop(in, out, cfg)
  117. }
  118. func (a *aggregator) mainLoop(in <-chan fs.Event, out chan<- []string, cfg *config.Wrapper) {
  119. a.notifyTimer = time.NewTimer(a.notifyDelay)
  120. defer a.notifyTimer.Stop()
  121. inProgress := make(map[string]struct{})
  122. inProgressItemSubscription := events.Default.Subscribe(events.ItemStarted | events.ItemFinished)
  123. cfg.Subscribe(a)
  124. for {
  125. select {
  126. case event := <-in:
  127. a.newEvent(event, inProgress)
  128. case event := <-inProgressItemSubscription.C():
  129. updateInProgressSet(event, inProgress)
  130. case <-a.notifyTimer.C:
  131. a.actOnTimer(out)
  132. case interval := <-a.notifyTimerResetChan:
  133. a.resetNotifyTimer(interval)
  134. case folderCfg := <-a.folderCfgUpdate:
  135. a.updateConfig(folderCfg)
  136. case <-a.ctx.Done():
  137. cfg.Unsubscribe(a)
  138. l.Debugln(a, "Stopped")
  139. return
  140. }
  141. }
  142. }
  143. func (a *aggregator) newEvent(event fs.Event, inProgress map[string]struct{}) {
  144. if _, ok := a.root.events["."]; ok {
  145. l.Debugln(a, "Will scan entire folder anyway; dropping:", event.Name)
  146. return
  147. }
  148. if _, ok := inProgress[event.Name]; ok {
  149. l.Debugln(a, "Skipping path we modified:", event.Name)
  150. return
  151. }
  152. a.aggregateEvent(event, time.Now())
  153. }
  154. func (a *aggregator) aggregateEvent(event fs.Event, evTime time.Time) {
  155. if event.Name == "." || a.eventCount() == maxFiles {
  156. l.Debugln(a, "Scan entire folder")
  157. firstModTime := evTime
  158. if a.root.childCount() != 0 {
  159. event.Type = event.Type.Merge(a.root.eventType())
  160. firstModTime = a.root.firstModTime()
  161. }
  162. a.root.dirs = make(map[string]*eventDir)
  163. a.root.events = make(map[string]*aggregatedEvent)
  164. a.root.events["."] = &aggregatedEvent{
  165. firstModTime: firstModTime,
  166. lastModTime: evTime,
  167. evType: event.Type,
  168. }
  169. a.counts = make(map[fs.EventType]int)
  170. a.counts[event.Type]++
  171. a.resetNotifyTimerIfNeeded()
  172. return
  173. }
  174. parentDir := a.root
  175. // Check if any parent directory is already tracked or will exceed
  176. // events per directory limit bottom up
  177. pathSegments := strings.Split(filepath.ToSlash(event.Name), "/")
  178. // As root dir cannot be further aggregated, allow up to maxFiles
  179. // children.
  180. localMaxFilesPerDir := maxFiles
  181. var currPath string
  182. for i, name := range pathSegments[:len(pathSegments)-1] {
  183. currPath = filepath.Join(currPath, name)
  184. if ev, ok := parentDir.events[name]; ok {
  185. ev.lastModTime = evTime
  186. if merged := event.Type.Merge(ev.evType); ev.evType != merged {
  187. a.counts[ev.evType]--
  188. ev.evType = merged
  189. a.counts[ev.evType]++
  190. }
  191. l.Debugf("%v Parent %s (type %s) already tracked: %s", a, currPath, ev.evType, event.Name)
  192. return
  193. }
  194. if parentDir.childCount() == localMaxFilesPerDir {
  195. l.Debugf("%v Parent dir %s already has %d children, tracking it instead: %s", a, currPath, localMaxFilesPerDir, event.Name)
  196. event.Name = filepath.Dir(currPath)
  197. a.aggregateEvent(event, evTime)
  198. return
  199. }
  200. // If there are no events below path, but we need to recurse
  201. // into that path, create eventDir at path.
  202. if newParent, ok := parentDir.dirs[name]; ok {
  203. parentDir = newParent
  204. } else {
  205. l.Debugln(a, "Creating eventDir at:", currPath)
  206. newParent = newEventDir()
  207. parentDir.dirs[name] = newParent
  208. parentDir = newParent
  209. }
  210. // Reset allowed children count to maxFilesPerDir for non-root
  211. if i == 0 {
  212. localMaxFilesPerDir = maxFilesPerDir
  213. }
  214. }
  215. name := pathSegments[len(pathSegments)-1]
  216. if ev, ok := parentDir.events[name]; ok {
  217. ev.lastModTime = evTime
  218. if merged := event.Type.Merge(ev.evType); ev.evType != merged {
  219. a.counts[ev.evType]--
  220. ev.evType = merged
  221. a.counts[ev.evType]++
  222. }
  223. l.Debugf("%v Already tracked (type %v): %s", a, ev.evType, event.Name)
  224. return
  225. }
  226. childDir, ok := parentDir.dirs[name]
  227. // If a dir existed at path, it would be removed from dirs, thus
  228. // childCount would not increase.
  229. if !ok && parentDir.childCount() == localMaxFilesPerDir {
  230. l.Debugf("%v Parent dir already has %d children, tracking it instead: %s", a, localMaxFilesPerDir, event.Name)
  231. event.Name = filepath.Dir(event.Name)
  232. a.aggregateEvent(event, evTime)
  233. return
  234. }
  235. firstModTime := evTime
  236. if ok {
  237. firstModTime = childDir.firstModTime()
  238. if merged := event.Type.Merge(childDir.eventType()); event.Type != merged {
  239. a.counts[event.Type]--
  240. event.Type = merged
  241. }
  242. delete(parentDir.dirs, name)
  243. }
  244. l.Debugf("%v Tracking (type %v): %s", a, event.Type, event.Name)
  245. parentDir.events[name] = &aggregatedEvent{
  246. firstModTime: firstModTime,
  247. lastModTime: evTime,
  248. evType: event.Type,
  249. }
  250. a.counts[event.Type]++
  251. a.resetNotifyTimerIfNeeded()
  252. }
  253. func (a *aggregator) resetNotifyTimerIfNeeded() {
  254. if a.notifyTimerNeedsReset {
  255. a.resetNotifyTimer(a.notifyDelay)
  256. }
  257. }
  258. // resetNotifyTimer should only ever be called when notifyTimer has stopped
  259. // and notifyTimer.C been read from. Otherwise, call resetNotifyTimerIfNeeded.
  260. func (a *aggregator) resetNotifyTimer(duration time.Duration) {
  261. l.Debugln(a, "Resetting notifyTimer to", duration.String())
  262. a.notifyTimerNeedsReset = false
  263. a.notifyTimer.Reset(duration)
  264. }
  265. func (a *aggregator) actOnTimer(out chan<- []string) {
  266. c := a.eventCount()
  267. if c == 0 {
  268. l.Debugln(a, "No tracked events, waiting for new event.")
  269. a.notifyTimerNeedsReset = true
  270. return
  271. }
  272. oldEvents := make(map[string]*aggregatedEvent, c)
  273. a.popOldEventsTo(oldEvents, a.root, ".", time.Now(), true)
  274. if a.notifyDelay != a.notifyTimeout && a.counts[fs.NonRemove] == 0 && a.counts[fs.Remove]+a.counts[fs.Mixed] != 0 {
  275. // Only delayed events remaining, no need to delay them additionally
  276. a.popOldEventsTo(oldEvents, a.root, ".", time.Now(), false)
  277. }
  278. if len(oldEvents) == 0 {
  279. l.Debugln(a, "No old fs events")
  280. a.resetNotifyTimer(a.notifyDelay)
  281. return
  282. }
  283. // Sending to channel might block for a long time, but we need to keep
  284. // reading from notify backend channel to avoid overflow
  285. go a.notify(oldEvents, out)
  286. }
  287. // Schedule scan for given events dispatching deletes last and reset notification
  288. // afterwards to set up for the next scan scheduling.
  289. func (a *aggregator) notify(oldEvents map[string]*aggregatedEvent, out chan<- []string) {
  290. timeBeforeSending := time.Now()
  291. l.Debugf("%v Notifying about %d fs events", a, len(oldEvents))
  292. separatedBatches := make(map[fs.EventType][]string)
  293. for path, event := range oldEvents {
  294. separatedBatches[event.evType] = append(separatedBatches[event.evType], path)
  295. }
  296. for _, evType := range [3]fs.EventType{fs.NonRemove, fs.Mixed, fs.Remove} {
  297. currBatch := separatedBatches[evType]
  298. if len(currBatch) != 0 {
  299. select {
  300. case out <- currBatch:
  301. case <-a.ctx.Done():
  302. return
  303. }
  304. }
  305. }
  306. // If sending to channel blocked for a long time,
  307. // shorten next notifyDelay accordingly.
  308. duration := time.Since(timeBeforeSending)
  309. buffer := time.Millisecond
  310. var nextDelay time.Duration
  311. switch {
  312. case duration < a.notifyDelay/10:
  313. nextDelay = a.notifyDelay
  314. case duration+buffer > a.notifyDelay:
  315. nextDelay = buffer
  316. default:
  317. nextDelay = a.notifyDelay - duration
  318. }
  319. select {
  320. case a.notifyTimerResetChan <- nextDelay:
  321. case <-a.ctx.Done():
  322. }
  323. }
  324. // popOldEvents finds events that should be scheduled for scanning recursively in dirs,
  325. // removes those events and empty eventDirs and returns a map with all the removed
  326. // events referenced by their filesystem path
  327. func (a *aggregator) popOldEventsTo(to map[string]*aggregatedEvent, dir *eventDir, dirPath string, currTime time.Time, delayRem bool) {
  328. for childName, childDir := range dir.dirs {
  329. a.popOldEventsTo(to, childDir, filepath.Join(dirPath, childName), currTime, delayRem)
  330. if childDir.childCount() == 0 {
  331. delete(dir.dirs, childName)
  332. }
  333. }
  334. for name, event := range dir.events {
  335. if a.isOld(event, currTime, delayRem) {
  336. to[filepath.Join(dirPath, name)] = event
  337. delete(dir.events, name)
  338. a.counts[event.evType]--
  339. }
  340. }
  341. }
  342. func (a *aggregator) isOld(ev *aggregatedEvent, currTime time.Time, delayRem bool) bool {
  343. // Deletes should in general be scanned last, therefore they are delayed by
  344. // letting them time out. This behaviour is overriden by delayRem == false.
  345. // Refer to following comments as to why.
  346. // An event that has not registered any new modifications recently is scanned.
  347. // a.notifyDelay is the user facing value signifying the normal delay between
  348. // picking up a modification and scanning it. As scheduling scans happens at
  349. // regular intervals of a.notifyDelay the delay of a single event is not exactly
  350. // a.notifyDelay, but lies in the range of 0.5 to 1.5 times a.notifyDelay.
  351. if (!delayRem || ev.evType == fs.NonRemove) && 2*currTime.Sub(ev.lastModTime) > a.notifyDelay {
  352. return true
  353. }
  354. // When an event registers repeat modifications or involves removals it
  355. // is delayed to reduce resource usage, but after a certain time (notifyTimeout)
  356. // passed it is scanned anyway.
  357. // If only removals are remaining to be scanned, there is no point to delay
  358. // removals further, so this behaviour is overriden by delayRem == false.
  359. return currTime.Sub(ev.firstModTime) > a.notifyTimeout
  360. }
  361. func (a *aggregator) eventCount() int {
  362. c := 0
  363. for _, v := range a.counts {
  364. c += v
  365. }
  366. return c
  367. }
  368. func (a *aggregator) String() string {
  369. return fmt.Sprintf("aggregator/%s:", a.folderCfg.Description())
  370. }
  371. func (a *aggregator) VerifyConfiguration(from, to config.Configuration) error {
  372. return nil
  373. }
  374. func (a *aggregator) CommitConfiguration(from, to config.Configuration) bool {
  375. for _, folderCfg := range to.Folders {
  376. if folderCfg.ID == a.folderID {
  377. select {
  378. case a.folderCfgUpdate <- folderCfg:
  379. case <-a.ctx.Done():
  380. }
  381. return true
  382. }
  383. }
  384. // Nothing to do, model will soon stop this
  385. return true
  386. }
  387. func (a *aggregator) updateConfig(folderCfg config.FolderConfiguration) {
  388. a.notifyDelay = time.Duration(folderCfg.FSWatcherDelayS) * time.Second
  389. a.notifyTimeout = notifyTimeout(folderCfg.FSWatcherDelayS)
  390. a.folderCfg = folderCfg
  391. }
  392. func updateInProgressSet(event events.Event, inProgress map[string]struct{}) {
  393. if event.Type == events.ItemStarted {
  394. path := event.Data.(map[string]string)["item"]
  395. inProgress[path] = struct{}{}
  396. } else if event.Type == events.ItemFinished {
  397. path := event.Data.(map[string]interface{})["item"].(string)
  398. delete(inProgress, path)
  399. }
  400. }
  401. // Events that involve removals or continuously receive new modifications are
  402. // delayed but must time out at some point. The following numbers come out of thin
  403. // air, they were just considered as a sensible compromise between fast updates and
  404. // saving resources. For short delays the timeout is 6 times the delay, capped at 1
  405. // minute. For delays longer than 1 minute, the delay and timeout are equal.
  406. func notifyTimeout(eventDelayS int) time.Duration {
  407. shortDelayS := 10
  408. shortDelayMultiplicator := 6
  409. longDelayS := 60
  410. longDelayTimeout := time.Duration(1) * time.Minute
  411. if eventDelayS < shortDelayS {
  412. return time.Duration(eventDelayS*shortDelayMultiplicator) * time.Second
  413. }
  414. if eventDelayS < longDelayS {
  415. return longDelayTimeout
  416. }
  417. return time.Duration(eventDelayS) * time.Second
  418. }