1
0

folder_summary.go 10 KB

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