folder_summary.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. //go:generate -command counterfeiter go run github.com/maxbrunsfeld/counterfeiter/v6
  7. //go:generate counterfeiter -o mocks/folderSummaryService.go --fake-name FolderSummaryService . FolderSummaryService
  8. package model
  9. import (
  10. "context"
  11. "fmt"
  12. "strings"
  13. "time"
  14. "github.com/thejerf/suture/v4"
  15. "github.com/syncthing/syncthing/lib/config"
  16. "github.com/syncthing/syncthing/lib/db"
  17. "github.com/syncthing/syncthing/lib/events"
  18. "github.com/syncthing/syncthing/lib/protocol"
  19. "github.com/syncthing/syncthing/lib/svcutil"
  20. "github.com/syncthing/syncthing/lib/sync"
  21. )
  22. type FolderSummaryService interface {
  23. suture.Service
  24. Summary(folder string) (*FolderSummary, error)
  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. }
  39. func NewFolderSummaryService(cfg config.Wrapper, m Model, id protocol.DeviceID, evLogger events.Logger) FolderSummaryService {
  40. service := &folderSummaryService{
  41. Supervisor: suture.New("folderSummaryService", svcutil.SpecWithDebugLogger(l)),
  42. cfg: cfg,
  43. model: m,
  44. id: id,
  45. evLogger: evLogger,
  46. immediate: make(chan string),
  47. folders: make(map[string]struct{}),
  48. foldersMut: sync.NewMutex(),
  49. }
  50. service.Add(svcutil.AsService(service.listenForUpdates, fmt.Sprintf("%s/listenForUpdates", service)))
  51. service.Add(svcutil.AsService(service.calculateSummaries, fmt.Sprintf("%s/calculateSummaries", service)))
  52. return service
  53. }
  54. func (c *folderSummaryService) String() string {
  55. return fmt.Sprintf("FolderSummaryService@%p", c)
  56. }
  57. // FolderSummary replaces the previously used map[string]interface{}, and needs
  58. // to keep the structure/naming for api backwards compatibility
  59. type FolderSummary struct {
  60. Errors int `json:"errors"`
  61. PullErrors int `json:"pullErrors"` // deprecated
  62. Invalid string `json:"invalid"` // deprecated
  63. GlobalFiles int `json:"globalFiles"`
  64. GlobalDirectories int `json:"globalDirectories"`
  65. GlobalSymlinks int `json:"globalSymlinks"`
  66. GlobalDeleted int `json:"globalDeleted"`
  67. GlobalBytes int64 `json:"globalBytes"`
  68. GlobalTotalItems int `json:"globalTotalItems"`
  69. LocalFiles int `json:"localFiles"`
  70. LocalDirectories int `json:"localDirectories"`
  71. LocalSymlinks int `json:"localSymlinks"`
  72. LocalDeleted int `json:"localDeleted"`
  73. LocalBytes int64 `json:"localBytes"`
  74. LocalTotalItems int `json:"localTotalItems"`
  75. NeedFiles int `json:"needFiles"`
  76. NeedDirectories int `json:"needDirectories"`
  77. NeedSymlinks int `json:"needSymlinks"`
  78. NeedDeletes int `json:"needDeletes"`
  79. NeedBytes int64 `json:"needBytes"`
  80. NeedTotalItems int `json:"needTotalItems"`
  81. ReceiveOnlyChangedFiles int `json:"receiveOnlyChangedFiles"`
  82. ReceiveOnlyChangedDirectories int `json:"receiveOnlyChangedDirectories"`
  83. ReceiveOnlyChangedSymlinks int `json:"receiveOnlyChangedSymlinks"`
  84. ReceiveOnlyChangedDeletes int `json:"receiveOnlyChangedDeletes"`
  85. ReceiveOnlyChangedBytes int64 `json:"receiveOnlyChangedBytes"`
  86. ReceiveOnlyTotalItems int `json:"receiveOnlyTotalItems"`
  87. InSyncFiles int `json:"inSyncFiles"`
  88. InSyncBytes int64 `json:"inSyncBytes"`
  89. State string `json:"state"`
  90. StateChanged time.Time `json:"stateChanged"`
  91. Error string `json:"error"`
  92. Version int64 `json:"version"` // deprecated
  93. Sequence int64 `json:"sequence"`
  94. RemoteSequence map[protocol.DeviceID]int64 `json:"remoteSequence"`
  95. IgnorePatterns bool `json:"ignorePatterns"`
  96. WatchError string `json:"watchError"`
  97. }
  98. func (c *folderSummaryService) Summary(folder string) (*FolderSummary, error) {
  99. res := new(FolderSummary)
  100. var local, global, need, ro db.Counts
  101. var ourSeq int64
  102. var remoteSeq map[protocol.DeviceID]int64
  103. errors, err := c.model.FolderErrors(folder)
  104. if err == nil {
  105. var snap *db.Snapshot
  106. if snap, err = c.model.DBSnapshot(folder); err == nil {
  107. global = snap.GlobalSize()
  108. local = snap.LocalSize()
  109. need = snap.NeedSize(protocol.LocalDeviceID)
  110. ro = snap.ReceiveOnlyChangedSize()
  111. ourSeq = snap.Sequence(protocol.LocalDeviceID)
  112. remoteSeq = snap.RemoteSequences()
  113. snap.Release()
  114. }
  115. }
  116. // For API backwards compatibility (SyncTrayzor needs it) an empty folder
  117. // summary is returned for not running folders, an error might actually be
  118. // more appropriate
  119. if err != nil && err != ErrFolderPaused && err != ErrFolderNotRunning {
  120. return nil, err
  121. }
  122. res.Errors = len(errors)
  123. res.PullErrors = len(errors) // deprecated
  124. res.Invalid = "" // Deprecated, retains external API for now
  125. res.GlobalFiles, res.GlobalDirectories, res.GlobalSymlinks, res.GlobalDeleted, res.GlobalBytes, res.GlobalTotalItems = global.Files, global.Directories, global.Symlinks, global.Deleted, global.Bytes, global.TotalItems()
  126. res.LocalFiles, res.LocalDirectories, res.LocalSymlinks, res.LocalDeleted, res.LocalBytes, res.LocalTotalItems = local.Files, local.Directories, local.Symlinks, local.Deleted, local.Bytes, local.TotalItems()
  127. fcfg, haveFcfg := c.cfg.Folder(folder)
  128. if haveFcfg && fcfg.IgnoreDelete {
  129. need.Deleted = 0
  130. }
  131. need.Bytes -= c.model.FolderProgressBytesCompleted(folder)
  132. // This may happen if we are in progress of pulling files that were
  133. // deleted globally after the pull started.
  134. if need.Bytes < 0 {
  135. need.Bytes = 0
  136. }
  137. res.NeedFiles, res.NeedDirectories, res.NeedSymlinks, res.NeedDeletes, res.NeedBytes, res.NeedTotalItems = need.Files, need.Directories, need.Symlinks, need.Deleted, need.Bytes, need.TotalItems()
  138. if haveFcfg && (fcfg.Type == config.FolderTypeReceiveOnly || fcfg.Type == config.FolderTypeReceiveEncrypted) {
  139. // Add statistics for things that have changed locally in a receive
  140. // only or receive encrypted folder.
  141. res.ReceiveOnlyChangedFiles = ro.Files
  142. res.ReceiveOnlyChangedDirectories = ro.Directories
  143. res.ReceiveOnlyChangedSymlinks = ro.Symlinks
  144. res.ReceiveOnlyChangedDeletes = ro.Deleted
  145. res.ReceiveOnlyChangedBytes = ro.Bytes
  146. res.ReceiveOnlyTotalItems = ro.TotalItems()
  147. }
  148. res.InSyncFiles, res.InSyncBytes = global.Files-need.Files, global.Bytes-need.Bytes
  149. res.State, res.StateChanged, err = c.model.State(folder)
  150. if err != nil {
  151. res.Error = err.Error()
  152. }
  153. res.Version = ourSeq // legacy
  154. res.Sequence = ourSeq
  155. res.RemoteSequence = remoteSeq
  156. ignorePatterns, _, _ := c.model.CurrentIgnores(folder)
  157. res.IgnorePatterns = false
  158. for _, line := range ignorePatterns {
  159. if len(line) > 0 && !strings.HasPrefix(line, "//") {
  160. res.IgnorePatterns = true
  161. break
  162. }
  163. }
  164. err = c.model.WatchError(folder)
  165. if err != nil {
  166. res.WatchError = err.Error()
  167. }
  168. return res, nil
  169. }
  170. // listenForUpdates subscribes to the event bus and makes note of folders that
  171. // need their data recalculated.
  172. func (c *folderSummaryService) listenForUpdates(ctx context.Context) error {
  173. sub := c.evLogger.Subscribe(events.LocalIndexUpdated | events.RemoteIndexUpdated | events.StateChanged | events.RemoteDownloadProgress | events.DeviceConnected | events.ClusterConfigReceived | events.FolderWatchStateChanged | events.DownloadProgress)
  174. defer sub.Unsubscribe()
  175. for {
  176. // This loop needs to be fast so we don't miss too many events.
  177. select {
  178. case ev, ok := <-sub.C():
  179. if !ok {
  180. <-ctx.Done()
  181. return ctx.Err()
  182. }
  183. c.processUpdate(ev)
  184. case <-ctx.Done():
  185. return ctx.Err()
  186. }
  187. }
  188. }
  189. func (c *folderSummaryService) processUpdate(ev events.Event) {
  190. var folder string
  191. switch ev.Type {
  192. case events.DeviceConnected, events.ClusterConfigReceived:
  193. // When a device connects we schedule a refresh of all
  194. // folders shared with that device.
  195. var deviceID protocol.DeviceID
  196. if ev.Type == events.DeviceConnected {
  197. data := ev.Data.(map[string]string)
  198. deviceID, _ = protocol.DeviceIDFromString(data["id"])
  199. } else {
  200. data := ev.Data.(ClusterConfigReceivedEventData)
  201. deviceID = data.Device
  202. }
  203. c.foldersMut.Lock()
  204. nextFolder:
  205. for _, folder := range c.cfg.Folders() {
  206. for _, dev := range folder.Devices {
  207. if dev.DeviceID == deviceID {
  208. c.folders[folder.ID] = struct{}{}
  209. continue nextFolder
  210. }
  211. }
  212. }
  213. c.foldersMut.Unlock()
  214. return
  215. case events.DownloadProgress:
  216. data := ev.Data.(map[string]map[string]*pullerProgress)
  217. c.foldersMut.Lock()
  218. for folder := range data {
  219. c.folders[folder] = struct{}{}
  220. }
  221. c.foldersMut.Unlock()
  222. return
  223. case events.StateChanged:
  224. data := ev.Data.(map[string]interface{})
  225. if data["to"].(string) != "idle" {
  226. return
  227. }
  228. if from := data["from"].(string); from != "syncing" && from != "sync-preparing" {
  229. return
  230. }
  231. // The folder changed to idle from syncing. We should do an
  232. // immediate refresh to update the GUI. The send to
  233. // c.immediate must be nonblocking so that we can continue
  234. // handling events.
  235. folder = data["folder"].(string)
  236. select {
  237. case c.immediate <- folder:
  238. c.foldersMut.Lock()
  239. delete(c.folders, folder)
  240. c.foldersMut.Unlock()
  241. return
  242. default:
  243. // Refresh whenever we do the next summary.
  244. }
  245. default:
  246. // The other events all have a "folder" attribute that they
  247. // affect. Whenever the local or remote index is updated for a
  248. // given folder we make a note of it.
  249. // This folder needs to be refreshed whenever we do the next
  250. // refresh.
  251. folder = ev.Data.(map[string]interface{})["folder"].(string)
  252. }
  253. c.foldersMut.Lock()
  254. c.folders[folder] = struct{}{}
  255. c.foldersMut.Unlock()
  256. }
  257. // calculateSummaries periodically recalculates folder summaries and
  258. // completion percentage, and sends the results on the event bus.
  259. func (c *folderSummaryService) calculateSummaries(ctx context.Context) error {
  260. const pumpInterval = 2 * time.Second
  261. pump := time.NewTimer(pumpInterval)
  262. for {
  263. select {
  264. case <-pump.C:
  265. t0 := time.Now()
  266. for _, folder := range c.foldersToHandle() {
  267. select {
  268. case <-ctx.Done():
  269. return ctx.Err()
  270. default:
  271. }
  272. c.sendSummary(ctx, folder)
  273. }
  274. // We don't want to spend all our time calculating summaries. Lets
  275. // set an arbitrary limit at not spending more than about 30% of
  276. // our time here...
  277. wait := 2*time.Since(t0) + pumpInterval
  278. pump.Reset(wait)
  279. case folder := <-c.immediate:
  280. c.sendSummary(ctx, folder)
  281. case <-ctx.Done():
  282. return ctx.Err()
  283. }
  284. }
  285. }
  286. // foldersToHandle returns the list of folders needing a summary update, and
  287. // clears the list.
  288. func (c *folderSummaryService) foldersToHandle() []string {
  289. c.foldersMut.Lock()
  290. res := make([]string, 0, len(c.folders))
  291. for folder := range c.folders {
  292. res = append(res, folder)
  293. delete(c.folders, folder)
  294. }
  295. c.foldersMut.Unlock()
  296. return res
  297. }
  298. type FolderSummaryEventData struct {
  299. Folder string `json:"folder"`
  300. Summary *FolderSummary `json:"summary"`
  301. }
  302. // sendSummary send the summary events for a single folder
  303. func (c *folderSummaryService) sendSummary(ctx context.Context, folder string) {
  304. // The folder summary contains how many bytes, files etc
  305. // are in the folder and how in sync we are.
  306. data, err := c.Summary(folder)
  307. if err != nil {
  308. return
  309. }
  310. c.evLogger.Log(events.FolderSummary, FolderSummaryEventData{
  311. Folder: folder,
  312. Summary: data,
  313. })
  314. metricFolderSummary.WithLabelValues(folder, metricScopeGlobal, metricTypeFiles).Set(float64(data.GlobalFiles))
  315. metricFolderSummary.WithLabelValues(folder, metricScopeGlobal, metricTypeDirectories).Set(float64(data.GlobalDirectories))
  316. metricFolderSummary.WithLabelValues(folder, metricScopeGlobal, metricTypeSymlinks).Set(float64(data.GlobalSymlinks))
  317. metricFolderSummary.WithLabelValues(folder, metricScopeGlobal, metricTypeDeleted).Set(float64(data.GlobalDeleted))
  318. metricFolderSummary.WithLabelValues(folder, metricScopeGlobal, metricTypeBytes).Set(float64(data.GlobalBytes))
  319. metricFolderSummary.WithLabelValues(folder, metricScopeLocal, metricTypeFiles).Set(float64(data.LocalFiles))
  320. metricFolderSummary.WithLabelValues(folder, metricScopeLocal, metricTypeDirectories).Set(float64(data.LocalDirectories))
  321. metricFolderSummary.WithLabelValues(folder, metricScopeLocal, metricTypeSymlinks).Set(float64(data.LocalSymlinks))
  322. metricFolderSummary.WithLabelValues(folder, metricScopeLocal, metricTypeDeleted).Set(float64(data.LocalDeleted))
  323. metricFolderSummary.WithLabelValues(folder, metricScopeLocal, metricTypeBytes).Set(float64(data.LocalBytes))
  324. metricFolderSummary.WithLabelValues(folder, metricScopeNeed, metricTypeFiles).Set(float64(data.NeedFiles))
  325. metricFolderSummary.WithLabelValues(folder, metricScopeNeed, metricTypeDirectories).Set(float64(data.NeedDirectories))
  326. metricFolderSummary.WithLabelValues(folder, metricScopeNeed, metricTypeSymlinks).Set(float64(data.NeedSymlinks))
  327. metricFolderSummary.WithLabelValues(folder, metricScopeNeed, metricTypeDeleted).Set(float64(data.NeedDeletes))
  328. metricFolderSummary.WithLabelValues(folder, metricScopeNeed, metricTypeBytes).Set(float64(data.NeedBytes))
  329. for _, devCfg := range c.cfg.Folders()[folder].Devices {
  330. select {
  331. case <-ctx.Done():
  332. return
  333. default:
  334. }
  335. if devCfg.DeviceID.Equals(c.id) {
  336. // We already know about ourselves.
  337. continue
  338. }
  339. // Get completion percentage of this folder for the
  340. // remote device.
  341. comp, err := c.model.Completion(devCfg.DeviceID, folder)
  342. if err != nil {
  343. l.Debugf("Error getting completion for folder %v, device %v: %v", folder, devCfg.DeviceID, err)
  344. continue
  345. }
  346. ev := comp.Map()
  347. ev["folder"] = folder
  348. ev["device"] = devCfg.DeviceID.String()
  349. c.evLogger.Log(events.FolderCompletion, ev)
  350. }
  351. }