folder_summary.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // Copyright (C) 2015 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. "strings"
  11. "time"
  12. "github.com/thejerf/suture"
  13. "github.com/syncthing/syncthing/lib/config"
  14. "github.com/syncthing/syncthing/lib/events"
  15. "github.com/syncthing/syncthing/lib/protocol"
  16. "github.com/syncthing/syncthing/lib/sync"
  17. "github.com/syncthing/syncthing/lib/util"
  18. )
  19. const minSummaryInterval = time.Minute
  20. type FolderSummaryService interface {
  21. suture.Service
  22. Summary(folder string) (map[string]interface{}, error)
  23. OnEventRequest()
  24. }
  25. // The folderSummaryService adds summary information events (FolderSummary and
  26. // FolderCompletion) into the event stream at certain intervals.
  27. type folderSummaryService struct {
  28. *suture.Supervisor
  29. cfg config.Wrapper
  30. model Model
  31. id protocol.DeviceID
  32. evLogger events.Logger
  33. immediate chan string
  34. // For keeping track of folders to recalculate for
  35. foldersMut sync.Mutex
  36. folders map[string]struct{}
  37. // For keeping track of when the last event request on the API was
  38. lastEventReq time.Time
  39. lastEventReqMut sync.Mutex
  40. }
  41. func NewFolderSummaryService(cfg config.Wrapper, m Model, id protocol.DeviceID, evLogger events.Logger) FolderSummaryService {
  42. service := &folderSummaryService{
  43. Supervisor: suture.New("folderSummaryService", suture.Spec{
  44. PassThroughPanics: true,
  45. }),
  46. cfg: cfg,
  47. model: m,
  48. id: id,
  49. evLogger: evLogger,
  50. immediate: make(chan string),
  51. folders: make(map[string]struct{}),
  52. foldersMut: sync.NewMutex(),
  53. lastEventReqMut: sync.NewMutex(),
  54. }
  55. service.Add(util.AsService(service.listenForUpdates, fmt.Sprintf("%s/listenForUpdates", service)))
  56. service.Add(util.AsService(service.calculateSummaries, fmt.Sprintf("%s/calculateSummaries", service)))
  57. return service
  58. }
  59. func (c *folderSummaryService) String() string {
  60. return fmt.Sprintf("FolderSummaryService@%p", c)
  61. }
  62. func (c *folderSummaryService) Summary(folder string) (map[string]interface{}, error) {
  63. var res = make(map[string]interface{})
  64. snap, err := c.model.DBSnapshot(folder)
  65. if err != nil {
  66. return nil, err
  67. }
  68. errors, err := c.model.FolderErrors(folder)
  69. if err != nil && err != ErrFolderPaused && err != errFolderNotRunning {
  70. // Stats from the db can still be obtained if the folder is just paused/being started
  71. return nil, err
  72. }
  73. res["errors"] = len(errors)
  74. res["pullErrors"] = len(errors) // deprecated
  75. res["invalid"] = "" // Deprecated, retains external API for now
  76. global := snap.GlobalSize()
  77. res["globalFiles"], res["globalDirectories"], res["globalSymlinks"], res["globalDeleted"], res["globalBytes"], res["globalTotalItems"] = global.Files, global.Directories, global.Symlinks, global.Deleted, global.Bytes, global.TotalItems()
  78. local := snap.LocalSize()
  79. res["localFiles"], res["localDirectories"], res["localSymlinks"], res["localDeleted"], res["localBytes"], res["localTotalItems"] = local.Files, local.Directories, local.Symlinks, local.Deleted, local.Bytes, local.TotalItems()
  80. need := snap.NeedSize()
  81. need.Bytes -= c.model.FolderProgressBytesCompleted(folder)
  82. // This may happen if we are in progress of pulling files that were
  83. // deleted globally after the pull started.
  84. if need.Bytes < 0 {
  85. need.Bytes = 0
  86. }
  87. res["needFiles"], res["needDirectories"], res["needSymlinks"], res["needDeletes"], res["needBytes"], res["needTotalItems"] = need.Files, need.Directories, need.Symlinks, need.Deleted, need.Bytes, need.TotalItems()
  88. fcfg, ok := c.cfg.Folder(folder)
  89. if ok && fcfg.IgnoreDelete {
  90. res["needDeletes"] = 0
  91. }
  92. if ok && fcfg.Type == config.FolderTypeReceiveOnly {
  93. // Add statistics for things that have changed locally in a receive
  94. // only folder.
  95. ro := snap.ReceiveOnlyChangedSize()
  96. res["receiveOnlyChangedFiles"] = ro.Files
  97. res["receiveOnlyChangedDirectories"] = ro.Directories
  98. res["receiveOnlyChangedSymlinks"] = ro.Symlinks
  99. res["receiveOnlyChangedDeletes"] = ro.Deleted
  100. res["receiveOnlyChangedBytes"] = ro.Bytes
  101. res["receiveOnlyTotalItems"] = ro.TotalItems()
  102. }
  103. res["inSyncFiles"], res["inSyncBytes"] = global.Files-need.Files, global.Bytes-need.Bytes
  104. res["state"], res["stateChanged"], err = c.model.State(folder)
  105. if err != nil {
  106. res["error"] = err.Error()
  107. }
  108. ourSeq := snap.Sequence(protocol.LocalDeviceID)
  109. remoteSeq := snap.Sequence(protocol.GlobalDeviceID)
  110. res["version"] = ourSeq + remoteSeq // legacy
  111. res["sequence"] = ourSeq + remoteSeq // new name
  112. ignorePatterns, _, _ := c.model.GetIgnores(folder)
  113. res["ignorePatterns"] = false
  114. for _, line := range ignorePatterns {
  115. if len(line) > 0 && !strings.HasPrefix(line, "//") {
  116. res["ignorePatterns"] = true
  117. break
  118. }
  119. }
  120. err = c.model.WatchError(folder)
  121. if err != nil {
  122. res["watchError"] = err.Error()
  123. }
  124. return res, nil
  125. }
  126. func (c *folderSummaryService) OnEventRequest() {
  127. c.lastEventReqMut.Lock()
  128. c.lastEventReq = time.Now()
  129. c.lastEventReqMut.Unlock()
  130. }
  131. // listenForUpdates subscribes to the event bus and makes note of folders that
  132. // need their data recalculated.
  133. func (c *folderSummaryService) listenForUpdates(ctx context.Context) {
  134. sub := c.evLogger.Subscribe(events.LocalIndexUpdated | events.RemoteIndexUpdated | events.StateChanged | events.RemoteDownloadProgress | events.DeviceConnected | events.FolderWatchStateChanged | events.DownloadProgress)
  135. defer sub.Unsubscribe()
  136. for {
  137. // This loop needs to be fast so we don't miss too many events.
  138. select {
  139. case ev := <-sub.C():
  140. c.processUpdate(ev)
  141. case <-ctx.Done():
  142. return
  143. }
  144. }
  145. }
  146. func (c *folderSummaryService) processUpdate(ev events.Event) {
  147. var folder string
  148. switch ev.Type {
  149. case events.DeviceConnected:
  150. // When a device connects we schedule a refresh of all
  151. // folders shared with that device.
  152. data := ev.Data.(map[string]string)
  153. deviceID, _ := protocol.DeviceIDFromString(data["id"])
  154. c.foldersMut.Lock()
  155. nextFolder:
  156. for _, folder := range c.cfg.Folders() {
  157. for _, dev := range folder.Devices {
  158. if dev.DeviceID == deviceID {
  159. c.folders[folder.ID] = struct{}{}
  160. continue nextFolder
  161. }
  162. }
  163. }
  164. c.foldersMut.Unlock()
  165. return
  166. case events.DownloadProgress:
  167. data := ev.Data.(map[string]map[string]*pullerProgress)
  168. c.foldersMut.Lock()
  169. for folder := range data {
  170. c.folders[folder] = struct{}{}
  171. }
  172. c.foldersMut.Unlock()
  173. return
  174. case events.StateChanged:
  175. data := ev.Data.(map[string]interface{})
  176. if data["to"].(string) != "idle" {
  177. return
  178. }
  179. if from := data["from"].(string); from != "syncing" && from != "sync-preparing" {
  180. return
  181. }
  182. // The folder changed to idle from syncing. We should do an
  183. // immediate refresh to update the GUI. The send to
  184. // c.immediate must be nonblocking so that we can continue
  185. // handling events.
  186. folder = data["folder"].(string)
  187. select {
  188. case c.immediate <- folder:
  189. c.foldersMut.Lock()
  190. delete(c.folders, folder)
  191. c.foldersMut.Unlock()
  192. return
  193. default:
  194. // Refresh whenever we do the next summary.
  195. }
  196. default:
  197. // The other events all have a "folder" attribute that they
  198. // affect. Whenever the local or remote index is updated for a
  199. // given folder we make a note of it.
  200. // This folder needs to be refreshed whenever we do the next
  201. // refresh.
  202. folder = ev.Data.(map[string]interface{})["folder"].(string)
  203. }
  204. c.foldersMut.Lock()
  205. c.folders[folder] = struct{}{}
  206. c.foldersMut.Unlock()
  207. }
  208. // calculateSummaries periodically recalculates folder summaries and
  209. // completion percentage, and sends the results on the event bus.
  210. func (c *folderSummaryService) calculateSummaries(ctx context.Context) {
  211. const pumpInterval = 2 * time.Second
  212. pump := time.NewTimer(pumpInterval)
  213. for {
  214. select {
  215. case <-pump.C:
  216. t0 := time.Now()
  217. for _, folder := range c.foldersToHandle() {
  218. c.sendSummary(folder)
  219. }
  220. // We don't want to spend all our time calculating summaries. Lets
  221. // set an arbitrary limit at not spending more than about 30% of
  222. // our time here...
  223. wait := 2*time.Since(t0) + pumpInterval
  224. pump.Reset(wait)
  225. case folder := <-c.immediate:
  226. c.sendSummary(folder)
  227. case <-ctx.Done():
  228. return
  229. }
  230. }
  231. }
  232. // foldersToHandle returns the list of folders needing a summary update, and
  233. // clears the list.
  234. func (c *folderSummaryService) foldersToHandle() []string {
  235. // We only recalculate summaries if someone is listening to events
  236. // (a request to /rest/events has been made within the last
  237. // pingEventInterval).
  238. c.lastEventReqMut.Lock()
  239. last := c.lastEventReq
  240. c.lastEventReqMut.Unlock()
  241. if time.Since(last) > minSummaryInterval {
  242. return nil
  243. }
  244. c.foldersMut.Lock()
  245. res := make([]string, 0, len(c.folders))
  246. for folder := range c.folders {
  247. res = append(res, folder)
  248. delete(c.folders, folder)
  249. }
  250. c.foldersMut.Unlock()
  251. return res
  252. }
  253. // sendSummary send the summary events for a single folder
  254. func (c *folderSummaryService) sendSummary(folder string) {
  255. // The folder summary contains how many bytes, files etc
  256. // are in the folder and how in sync we are.
  257. data, err := c.Summary(folder)
  258. if err != nil {
  259. return
  260. }
  261. c.evLogger.Log(events.FolderSummary, map[string]interface{}{
  262. "folder": folder,
  263. "summary": data,
  264. })
  265. for _, devCfg := range c.cfg.Folders()[folder].Devices {
  266. if devCfg.DeviceID.Equals(c.id) {
  267. // We already know about ourselves.
  268. continue
  269. }
  270. if _, ok := c.model.Connection(devCfg.DeviceID); !ok {
  271. // We're not interested in disconnected devices.
  272. continue
  273. }
  274. // Get completion percentage of this folder for the
  275. // remote device.
  276. comp := c.model.Completion(devCfg.DeviceID, folder).Map()
  277. comp["folder"] = folder
  278. comp["device"] = devCfg.DeviceID.String()
  279. c.evLogger.Log(events.FolderCompletion, comp)
  280. }
  281. }