aggregator.go 13 KB

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