usage_report.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // Copyright (C) 2014 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 ur
  7. import (
  8. "bytes"
  9. "context"
  10. "crypto/rand"
  11. "crypto/tls"
  12. "encoding/json"
  13. "net"
  14. "net/http"
  15. "runtime"
  16. "sort"
  17. "strings"
  18. "sync"
  19. "time"
  20. "github.com/syncthing/syncthing/lib/build"
  21. "github.com/syncthing/syncthing/lib/config"
  22. "github.com/syncthing/syncthing/lib/connections"
  23. "github.com/syncthing/syncthing/lib/dialer"
  24. "github.com/syncthing/syncthing/lib/model"
  25. "github.com/syncthing/syncthing/lib/protocol"
  26. "github.com/syncthing/syncthing/lib/scanner"
  27. "github.com/syncthing/syncthing/lib/upgrade"
  28. "github.com/syncthing/syncthing/lib/ur/contract"
  29. "github.com/syncthing/syncthing/lib/util"
  30. "github.com/thejerf/suture"
  31. )
  32. // Current version number of the usage report, for acceptance purposes. If
  33. // fields are added or changed this integer must be incremented so that users
  34. // are prompted for acceptance of the new report.
  35. const Version = 3
  36. var StartTime = time.Now()
  37. type Service struct {
  38. suture.Service
  39. cfg config.Wrapper
  40. model model.Model
  41. connectionsService connections.Service
  42. noUpgrade bool
  43. forceRun chan struct{}
  44. }
  45. func New(cfg config.Wrapper, m model.Model, connectionsService connections.Service, noUpgrade bool) *Service {
  46. svc := &Service{
  47. cfg: cfg,
  48. model: m,
  49. connectionsService: connectionsService,
  50. noUpgrade: noUpgrade,
  51. forceRun: make(chan struct{}, 1), // Buffered to prevent locking
  52. }
  53. svc.Service = util.AsService(svc.serve, svc.String())
  54. return svc
  55. }
  56. // ReportData returns the data to be sent in a usage report with the currently
  57. // configured usage reporting version.
  58. func (s *Service) ReportData(ctx context.Context) (*contract.Report, error) {
  59. urVersion := s.cfg.Options().URAccepted
  60. return s.reportData(ctx, urVersion, false)
  61. }
  62. // ReportDataPreview returns a preview of the data to be sent in a usage report
  63. // with the given version.
  64. func (s *Service) ReportDataPreview(ctx context.Context, urVersion int) (*contract.Report, error) {
  65. return s.reportData(ctx, urVersion, true)
  66. }
  67. func (s *Service) reportData(ctx context.Context, urVersion int, preview bool) (*contract.Report, error) {
  68. opts := s.cfg.Options()
  69. var totFiles, maxFiles int
  70. var totBytes, maxBytes int64
  71. for folderID := range s.cfg.Folders() {
  72. snap, err := s.model.DBSnapshot(folderID)
  73. if err != nil {
  74. continue
  75. }
  76. global := snap.GlobalSize()
  77. snap.Release()
  78. totFiles += int(global.Files)
  79. totBytes += global.Bytes
  80. if int(global.Files) > maxFiles {
  81. maxFiles = int(global.Files)
  82. }
  83. if global.Bytes > maxBytes {
  84. maxBytes = global.Bytes
  85. }
  86. }
  87. var mem runtime.MemStats
  88. runtime.ReadMemStats(&mem)
  89. report := contract.New()
  90. report.URVersion = urVersion
  91. report.UniqueID = opts.URUniqueID
  92. report.Version = build.Version
  93. report.LongVersion = build.LongVersion
  94. report.Platform = runtime.GOOS + "-" + runtime.GOARCH
  95. report.NumFolders = len(s.cfg.Folders())
  96. report.NumDevices = len(s.cfg.Devices())
  97. report.TotFiles = totFiles
  98. report.FolderMaxFiles = maxFiles
  99. report.TotMiB = int(totBytes / 1024 / 1024)
  100. report.FolderMaxMiB = int(maxBytes / 1024 / 1024)
  101. report.MemoryUsageMiB = int((mem.Sys - mem.HeapReleased) / 1024 / 1024)
  102. report.SHA256Perf = CpuBench(ctx, 5, 125*time.Millisecond, false)
  103. report.HashPerf = CpuBench(ctx, 5, 125*time.Millisecond, true)
  104. report.MemorySize = int(memorySize() / 1024 / 1024)
  105. report.NumCPU = runtime.NumCPU()
  106. for _, cfg := range s.cfg.Folders() {
  107. report.RescanIntvs = append(report.RescanIntvs, cfg.RescanIntervalS)
  108. switch cfg.Type {
  109. case config.FolderTypeSendOnly:
  110. report.FolderUses.SendOnly++
  111. case config.FolderTypeSendReceive:
  112. report.FolderUses.SendReceive++
  113. case config.FolderTypeReceiveOnly:
  114. report.FolderUses.ReceiveOnly++
  115. }
  116. if cfg.IgnorePerms {
  117. report.FolderUses.IgnorePerms++
  118. }
  119. if cfg.IgnoreDelete {
  120. report.FolderUses.IgnoreDelete++
  121. }
  122. if cfg.AutoNormalize {
  123. report.FolderUses.AutoNormalize++
  124. }
  125. switch cfg.Versioning.Type {
  126. case "":
  127. // None
  128. case "simple":
  129. report.FolderUses.SimpleVersioning++
  130. case "staggered":
  131. report.FolderUses.StaggeredVersioning++
  132. case "external":
  133. report.FolderUses.ExternalVersioning++
  134. case "trashcan":
  135. report.FolderUses.TrashcanVersioning++
  136. default:
  137. l.Warnf("Unhandled versioning type for usage reports: %s", cfg.Versioning.Type)
  138. }
  139. }
  140. sort.Ints(report.RescanIntvs)
  141. for _, cfg := range s.cfg.Devices() {
  142. if cfg.Introducer {
  143. report.DeviceUses.Introducer++
  144. }
  145. if cfg.CertName != "" && cfg.CertName != "syncthing" {
  146. report.DeviceUses.CustomCertName++
  147. }
  148. switch cfg.Compression {
  149. case protocol.CompressAlways:
  150. report.DeviceUses.CompressAlways++
  151. case protocol.CompressMetadata:
  152. report.DeviceUses.CompressMetadata++
  153. case protocol.CompressNever:
  154. report.DeviceUses.CompressNever++
  155. default:
  156. l.Warnf("Unhandled versioning type for usage reports: %s", cfg.Compression)
  157. }
  158. for _, addr := range cfg.Addresses {
  159. if addr == "dynamic" {
  160. report.DeviceUses.DynamicAddr++
  161. } else {
  162. report.DeviceUses.StaticAddr++
  163. }
  164. }
  165. }
  166. report.Announce.GlobalEnabled = opts.GlobalAnnEnabled
  167. report.Announce.LocalEnabled = opts.LocalAnnEnabled
  168. for _, addr := range opts.RawGlobalAnnServers {
  169. if addr == "default" || addr == "default-v4" || addr == "default-v6" {
  170. report.Announce.DefaultServersDNS++
  171. } else {
  172. report.Announce.OtherServers++
  173. }
  174. }
  175. report.Relays.Enabled = opts.RelaysEnabled
  176. for _, addr := range s.cfg.Options().ListenAddresses() {
  177. switch {
  178. case addr == "dynamic+https://relays.syncthing.net/endpoint":
  179. report.Relays.DefaultServers++
  180. case strings.HasPrefix(addr, "relay://") || strings.HasPrefix(addr, "dynamic+http"):
  181. report.Relays.OtherServers++
  182. }
  183. }
  184. report.UsesRateLimit = opts.MaxRecvKbps > 0 || opts.MaxSendKbps > 0
  185. report.UpgradeAllowedManual = !(upgrade.DisabledByCompilation || s.noUpgrade)
  186. report.UpgradeAllowedAuto = !(upgrade.DisabledByCompilation || s.noUpgrade) && opts.AutoUpgradeIntervalH > 0
  187. report.UpgradeAllowedPre = !(upgrade.DisabledByCompilation || s.noUpgrade) && opts.AutoUpgradeIntervalH > 0 && opts.UpgradeToPreReleases
  188. // V3
  189. if urVersion >= 3 {
  190. report.Uptime = s.UptimeS()
  191. report.NATType = s.connectionsService.NATType()
  192. report.AlwaysLocalNets = len(opts.AlwaysLocalNets) > 0
  193. report.CacheIgnoredFiles = opts.CacheIgnoredFiles
  194. report.OverwriteRemoteDeviceNames = opts.OverwriteRemoteDevNames
  195. report.ProgressEmitterEnabled = opts.ProgressUpdateIntervalS > -1
  196. report.CustomDefaultFolderPath = opts.DefaultFolderPath != "~"
  197. report.CustomTrafficClass = opts.TrafficClass != 0
  198. report.CustomTempIndexMinBlocks = opts.TempIndexMinBlocks != 10
  199. report.TemporariesDisabled = opts.KeepTemporariesH == 0
  200. report.TemporariesCustom = opts.KeepTemporariesH != 24
  201. report.LimitBandwidthInLan = opts.LimitBandwidthInLan
  202. report.CustomReleaseURL = opts.ReleasesURL != "https=//upgrades.syncthing.net/meta.json"
  203. report.RestartOnWakeup = opts.RestartOnWakeup
  204. report.CustomStunServers = len(opts.RawStunServers) != 1 || opts.RawStunServers[0] != "default"
  205. for _, cfg := range s.cfg.Folders() {
  206. if cfg.ScanProgressIntervalS < 0 {
  207. report.FolderUsesV3.ScanProgressDisabled++
  208. }
  209. if cfg.MaxConflicts == 0 {
  210. report.FolderUsesV3.ConflictsDisabled++
  211. } else if cfg.MaxConflicts < 0 {
  212. report.FolderUsesV3.ConflictsUnlimited++
  213. } else {
  214. report.FolderUsesV3.ConflictsOther++
  215. }
  216. if cfg.DisableSparseFiles {
  217. report.FolderUsesV3.DisableSparseFiles++
  218. }
  219. if cfg.DisableTempIndexes {
  220. report.FolderUsesV3.DisableTempIndexes++
  221. }
  222. if cfg.WeakHashThresholdPct < 0 {
  223. report.FolderUsesV3.AlwaysWeakHash++
  224. } else if cfg.WeakHashThresholdPct != 25 {
  225. report.FolderUsesV3.CustomWeakHashThreshold++
  226. }
  227. if cfg.FSWatcherEnabled {
  228. report.FolderUsesV3.FsWatcherEnabled++
  229. }
  230. report.FolderUsesV3.PullOrder[cfg.Order.String()]++
  231. report.FolderUsesV3.FilesystemType[cfg.FilesystemType.String()]++
  232. report.FolderUsesV3.FsWatcherDelays = append(report.FolderUsesV3.FsWatcherDelays, cfg.FSWatcherDelayS)
  233. if cfg.MarkerName != config.DefaultMarkerName {
  234. report.FolderUsesV3.CustomMarkerName++
  235. }
  236. if cfg.CopyOwnershipFromParent {
  237. report.FolderUsesV3.CopyOwnershipFromParent++
  238. }
  239. report.FolderUsesV3.ModTimeWindowS = append(report.FolderUsesV3.ModTimeWindowS, int(cfg.ModTimeWindow().Seconds()))
  240. report.FolderUsesV3.MaxConcurrentWrites = append(report.FolderUsesV3.MaxConcurrentWrites, cfg.MaxConcurrentWrites)
  241. if cfg.DisableFsync {
  242. report.FolderUsesV3.DisableFsync++
  243. }
  244. report.FolderUsesV3.BlockPullOrder[cfg.BlockPullOrder.String()]++
  245. report.FolderUsesV3.CopyRangeMethod[cfg.CopyRangeMethod.String()]++
  246. }
  247. sort.Ints(report.FolderUsesV3.FsWatcherDelays)
  248. guiCfg := s.cfg.GUI()
  249. // Anticipate multiple GUI configs in the future, hence store counts.
  250. if guiCfg.Enabled {
  251. report.GUIStats.Enabled++
  252. if guiCfg.UseTLS() {
  253. report.GUIStats.UseTLS++
  254. }
  255. if len(guiCfg.User) > 0 && len(guiCfg.Password) > 0 {
  256. report.GUIStats.UseAuth++
  257. }
  258. if guiCfg.InsecureAdminAccess {
  259. report.GUIStats.InsecureAdminAccess++
  260. }
  261. if guiCfg.Debugging {
  262. report.GUIStats.Debugging++
  263. }
  264. if guiCfg.InsecureSkipHostCheck {
  265. report.GUIStats.InsecureSkipHostCheck++
  266. }
  267. if guiCfg.InsecureAllowFrameLoading {
  268. report.GUIStats.InsecureAllowFrameLoading++
  269. }
  270. addr, err := net.ResolveTCPAddr("tcp", guiCfg.Address())
  271. if err == nil {
  272. if addr.IP.IsLoopback() {
  273. report.GUIStats.ListenLocal++
  274. } else if addr.IP.IsUnspecified() {
  275. report.GUIStats.ListenUnspecified++
  276. }
  277. }
  278. report.GUIStats.Theme[guiCfg.Theme]++
  279. }
  280. }
  281. s.model.UsageReportingStats(report, urVersion, preview)
  282. if err := report.ClearForVersion(urVersion); err != nil {
  283. return nil, err
  284. }
  285. return report, nil
  286. }
  287. func (s *Service) UptimeS() int {
  288. return int(time.Since(StartTime).Seconds())
  289. }
  290. func (s *Service) sendUsageReport(ctx context.Context) error {
  291. d, err := s.ReportData(ctx)
  292. if err != nil {
  293. return err
  294. }
  295. var b bytes.Buffer
  296. if err := json.NewEncoder(&b).Encode(d); err != nil {
  297. return err
  298. }
  299. client := &http.Client{
  300. Transport: &http.Transport{
  301. DialContext: dialer.DialContext,
  302. Proxy: http.ProxyFromEnvironment,
  303. TLSClientConfig: &tls.Config{
  304. InsecureSkipVerify: s.cfg.Options().URPostInsecurely,
  305. },
  306. },
  307. }
  308. req, err := http.NewRequestWithContext(ctx, "POST", s.cfg.Options().URURL, &b)
  309. if err != nil {
  310. return err
  311. }
  312. req.Header.Set("Content-Type", "application/json")
  313. resp, err := client.Do(req)
  314. if err != nil {
  315. return err
  316. }
  317. resp.Body.Close()
  318. return nil
  319. }
  320. func (s *Service) serve(ctx context.Context) {
  321. s.cfg.Subscribe(s)
  322. defer s.cfg.Unsubscribe(s)
  323. t := time.NewTimer(time.Duration(s.cfg.Options().URInitialDelayS) * time.Second)
  324. for {
  325. select {
  326. case <-ctx.Done():
  327. return
  328. case <-s.forceRun:
  329. t.Reset(0)
  330. case <-t.C:
  331. if s.cfg.Options().URAccepted >= 2 {
  332. err := s.sendUsageReport(ctx)
  333. if err != nil {
  334. l.Infoln("Usage report:", err)
  335. } else {
  336. l.Infof("Sent usage report (version %d)", s.cfg.Options().URAccepted)
  337. }
  338. }
  339. t.Reset(24 * time.Hour) // next report tomorrow
  340. }
  341. }
  342. }
  343. func (s *Service) VerifyConfiguration(from, to config.Configuration) error {
  344. return nil
  345. }
  346. func (s *Service) CommitConfiguration(from, to config.Configuration) bool {
  347. if from.Options.URAccepted != to.Options.URAccepted || from.Options.URUniqueID != to.Options.URUniqueID || from.Options.URURL != to.Options.URURL {
  348. select {
  349. case s.forceRun <- struct{}{}:
  350. default:
  351. // s.forceRun is one buffered, so even though nothing
  352. // was sent, a run will still happen after this point.
  353. }
  354. }
  355. return true
  356. }
  357. func (*Service) String() string {
  358. return "ur.Service"
  359. }
  360. var (
  361. blocksResult []protocol.BlockInfo // so the result is not optimized away
  362. blocksResultMut sync.Mutex
  363. )
  364. // CpuBench returns CPU performance as a measure of single threaded SHA-256 MiB/s
  365. func CpuBench(ctx context.Context, iterations int, duration time.Duration, useWeakHash bool) float64 {
  366. blocksResultMut.Lock()
  367. defer blocksResultMut.Unlock()
  368. dataSize := 16 * protocol.MinBlockSize
  369. bs := make([]byte, dataSize)
  370. rand.Reader.Read(bs)
  371. var perf float64
  372. for i := 0; i < iterations; i++ {
  373. if v := cpuBenchOnce(ctx, duration, useWeakHash, bs); v > perf {
  374. perf = v
  375. }
  376. }
  377. blocksResult = nil
  378. return perf
  379. }
  380. func cpuBenchOnce(ctx context.Context, duration time.Duration, useWeakHash bool, bs []byte) float64 {
  381. t0 := time.Now()
  382. b := 0
  383. var err error
  384. for time.Since(t0) < duration {
  385. r := bytes.NewReader(bs)
  386. blocksResult, err = scanner.Blocks(ctx, r, protocol.MinBlockSize, int64(len(bs)), nil, useWeakHash)
  387. if err != nil {
  388. return 0 // Context done
  389. }
  390. b += len(bs)
  391. }
  392. d := time.Since(t0)
  393. return float64(int(float64(b)/d.Seconds()/(1<<20)*100)) / 100
  394. }