usage_report.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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/util"
  29. "github.com/thejerf/suture"
  30. )
  31. // Current version number of the usage report, for acceptance purposes. If
  32. // fields are added or changed this integer must be incremented so that users
  33. // are prompted for acceptance of the new report.
  34. const Version = 3
  35. var StartTime = time.Now()
  36. type Service struct {
  37. suture.Service
  38. cfg config.Wrapper
  39. model model.Model
  40. connectionsService connections.Service
  41. noUpgrade bool
  42. forceRun chan struct{}
  43. }
  44. func New(cfg config.Wrapper, m model.Model, connectionsService connections.Service, noUpgrade bool) *Service {
  45. svc := &Service{
  46. cfg: cfg,
  47. model: m,
  48. connectionsService: connectionsService,
  49. noUpgrade: noUpgrade,
  50. forceRun: make(chan struct{}, 1), // Buffered to prevent locking
  51. }
  52. svc.Service = util.AsService(svc.serve, svc.String())
  53. cfg.Subscribe(svc)
  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() map[string]interface{} {
  59. urVersion := s.cfg.Options().URAccepted
  60. return s.reportData(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(urVersion int) map[string]interface{} {
  65. return s.reportData(urVersion, true)
  66. }
  67. func (s *Service) reportData(urVersion int, preview bool) map[string]interface{} {
  68. opts := s.cfg.Options()
  69. res := make(map[string]interface{})
  70. res["urVersion"] = urVersion
  71. res["uniqueID"] = opts.URUniqueID
  72. res["version"] = build.Version
  73. res["longVersion"] = build.LongVersion
  74. res["platform"] = runtime.GOOS + "-" + runtime.GOARCH
  75. res["numFolders"] = len(s.cfg.Folders())
  76. res["numDevices"] = len(s.cfg.Devices())
  77. var totFiles, maxFiles int
  78. var totBytes, maxBytes int64
  79. for folderID := range s.cfg.Folders() {
  80. global := s.model.GlobalSize(folderID)
  81. totFiles += int(global.Files)
  82. totBytes += global.Bytes
  83. if int(global.Files) > maxFiles {
  84. maxFiles = int(global.Files)
  85. }
  86. if global.Bytes > maxBytes {
  87. maxBytes = global.Bytes
  88. }
  89. }
  90. res["totFiles"] = totFiles
  91. res["folderMaxFiles"] = maxFiles
  92. res["totMiB"] = totBytes / 1024 / 1024
  93. res["folderMaxMiB"] = maxBytes / 1024 / 1024
  94. var mem runtime.MemStats
  95. runtime.ReadMemStats(&mem)
  96. res["memoryUsageMiB"] = (mem.Sys - mem.HeapReleased) / 1024 / 1024
  97. res["sha256Perf"] = CpuBench(5, 125*time.Millisecond, false)
  98. res["hashPerf"] = CpuBench(5, 125*time.Millisecond, true)
  99. bytes, err := memorySize()
  100. if err == nil {
  101. res["memorySize"] = bytes / 1024 / 1024
  102. }
  103. res["numCPU"] = runtime.NumCPU()
  104. var rescanIntvs []int
  105. folderUses := map[string]int{
  106. "sendonly": 0,
  107. "sendreceive": 0,
  108. "receiveonly": 0,
  109. "ignorePerms": 0,
  110. "ignoreDelete": 0,
  111. "autoNormalize": 0,
  112. "simpleVersioning": 0,
  113. "externalVersioning": 0,
  114. "staggeredVersioning": 0,
  115. "trashcanVersioning": 0,
  116. }
  117. for _, cfg := range s.cfg.Folders() {
  118. rescanIntvs = append(rescanIntvs, cfg.RescanIntervalS)
  119. switch cfg.Type {
  120. case config.FolderTypeSendOnly:
  121. folderUses["sendonly"]++
  122. case config.FolderTypeSendReceive:
  123. folderUses["sendreceive"]++
  124. case config.FolderTypeReceiveOnly:
  125. folderUses["receiveonly"]++
  126. }
  127. if cfg.IgnorePerms {
  128. folderUses["ignorePerms"]++
  129. }
  130. if cfg.IgnoreDelete {
  131. folderUses["ignoreDelete"]++
  132. }
  133. if cfg.AutoNormalize {
  134. folderUses["autoNormalize"]++
  135. }
  136. if cfg.Versioning.Type != "" {
  137. folderUses[cfg.Versioning.Type+"Versioning"]++
  138. }
  139. }
  140. sort.Ints(rescanIntvs)
  141. res["rescanIntvs"] = rescanIntvs
  142. res["folderUses"] = folderUses
  143. deviceUses := map[string]int{
  144. "introducer": 0,
  145. "customCertName": 0,
  146. "compressAlways": 0,
  147. "compressMetadata": 0,
  148. "compressNever": 0,
  149. "dynamicAddr": 0,
  150. "staticAddr": 0,
  151. }
  152. for _, cfg := range s.cfg.Devices() {
  153. if cfg.Introducer {
  154. deviceUses["introducer"]++
  155. }
  156. if cfg.CertName != "" && cfg.CertName != "syncthing" {
  157. deviceUses["customCertName"]++
  158. }
  159. if cfg.Compression == protocol.CompressAlways {
  160. deviceUses["compressAlways"]++
  161. } else if cfg.Compression == protocol.CompressMetadata {
  162. deviceUses["compressMetadata"]++
  163. } else if cfg.Compression == protocol.CompressNever {
  164. deviceUses["compressNever"]++
  165. }
  166. for _, addr := range cfg.Addresses {
  167. if addr == "dynamic" {
  168. deviceUses["dynamicAddr"]++
  169. } else {
  170. deviceUses["staticAddr"]++
  171. }
  172. }
  173. }
  174. res["deviceUses"] = deviceUses
  175. defaultAnnounceServersDNS, defaultAnnounceServersIP, otherAnnounceServers := 0, 0, 0
  176. for _, addr := range opts.GlobalAnnServers {
  177. if addr == "default" || addr == "default-v4" || addr == "default-v6" {
  178. defaultAnnounceServersDNS++
  179. } else {
  180. otherAnnounceServers++
  181. }
  182. }
  183. res["announce"] = map[string]interface{}{
  184. "globalEnabled": opts.GlobalAnnEnabled,
  185. "localEnabled": opts.LocalAnnEnabled,
  186. "defaultServersDNS": defaultAnnounceServersDNS,
  187. "defaultServersIP": defaultAnnounceServersIP,
  188. "otherServers": otherAnnounceServers,
  189. }
  190. defaultRelayServers, otherRelayServers := 0, 0
  191. for _, addr := range s.cfg.ListenAddresses() {
  192. switch {
  193. case addr == "dynamic+https://relays.syncthing.net/endpoint":
  194. defaultRelayServers++
  195. case strings.HasPrefix(addr, "relay://") || strings.HasPrefix(addr, "dynamic+http"):
  196. otherRelayServers++
  197. }
  198. }
  199. res["relays"] = map[string]interface{}{
  200. "enabled": defaultRelayServers+otherAnnounceServers > 0,
  201. "defaultServers": defaultRelayServers,
  202. "otherServers": otherRelayServers,
  203. }
  204. res["usesRateLimit"] = opts.MaxRecvKbps > 0 || opts.MaxSendKbps > 0
  205. res["upgradeAllowedManual"] = !(upgrade.DisabledByCompilation || s.noUpgrade)
  206. res["upgradeAllowedAuto"] = !(upgrade.DisabledByCompilation || s.noUpgrade) && opts.AutoUpgradeIntervalH > 0
  207. res["upgradeAllowedPre"] = !(upgrade.DisabledByCompilation || s.noUpgrade) && opts.AutoUpgradeIntervalH > 0 && opts.UpgradeToPreReleases
  208. if urVersion >= 3 {
  209. res["uptime"] = s.UptimeS()
  210. res["natType"] = s.connectionsService.NATType()
  211. res["alwaysLocalNets"] = len(opts.AlwaysLocalNets) > 0
  212. res["cacheIgnoredFiles"] = opts.CacheIgnoredFiles
  213. res["overwriteRemoteDeviceNames"] = opts.OverwriteRemoteDevNames
  214. res["progressEmitterEnabled"] = opts.ProgressUpdateIntervalS > -1
  215. res["customDefaultFolderPath"] = opts.DefaultFolderPath != "~"
  216. res["customTrafficClass"] = opts.TrafficClass != 0
  217. res["customTempIndexMinBlocks"] = opts.TempIndexMinBlocks != 10
  218. res["temporariesDisabled"] = opts.KeepTemporariesH == 0
  219. res["temporariesCustom"] = opts.KeepTemporariesH != 24
  220. res["limitBandwidthInLan"] = opts.LimitBandwidthInLan
  221. res["customReleaseURL"] = opts.ReleasesURL != "https://upgrades.syncthing.net/meta.json"
  222. res["restartOnWakeup"] = opts.RestartOnWakeup
  223. folderUsesV3 := map[string]int{
  224. "scanProgressDisabled": 0,
  225. "conflictsDisabled": 0,
  226. "conflictsUnlimited": 0,
  227. "conflictsOther": 0,
  228. "disableSparseFiles": 0,
  229. "disableTempIndexes": 0,
  230. "alwaysWeakHash": 0,
  231. "customWeakHashThreshold": 0,
  232. "fsWatcherEnabled": 0,
  233. }
  234. pullOrder := make(map[string]int)
  235. filesystemType := make(map[string]int)
  236. var fsWatcherDelays []int
  237. for _, cfg := range s.cfg.Folders() {
  238. if cfg.ScanProgressIntervalS < 0 {
  239. folderUsesV3["scanProgressDisabled"]++
  240. }
  241. if cfg.MaxConflicts == 0 {
  242. folderUsesV3["conflictsDisabled"]++
  243. } else if cfg.MaxConflicts < 0 {
  244. folderUsesV3["conflictsUnlimited"]++
  245. } else {
  246. folderUsesV3["conflictsOther"]++
  247. }
  248. if cfg.DisableSparseFiles {
  249. folderUsesV3["disableSparseFiles"]++
  250. }
  251. if cfg.DisableTempIndexes {
  252. folderUsesV3["disableTempIndexes"]++
  253. }
  254. if cfg.WeakHashThresholdPct < 0 {
  255. folderUsesV3["alwaysWeakHash"]++
  256. } else if cfg.WeakHashThresholdPct != 25 {
  257. folderUsesV3["customWeakHashThreshold"]++
  258. }
  259. if cfg.FSWatcherEnabled {
  260. folderUsesV3["fsWatcherEnabled"]++
  261. }
  262. pullOrder[cfg.Order.String()]++
  263. filesystemType[cfg.FilesystemType.String()]++
  264. fsWatcherDelays = append(fsWatcherDelays, cfg.FSWatcherDelayS)
  265. }
  266. sort.Ints(fsWatcherDelays)
  267. folderUsesV3Interface := map[string]interface{}{
  268. "pullOrder": pullOrder,
  269. "filesystemType": filesystemType,
  270. "fsWatcherDelays": fsWatcherDelays,
  271. }
  272. for key, value := range folderUsesV3 {
  273. folderUsesV3Interface[key] = value
  274. }
  275. res["folderUsesV3"] = folderUsesV3Interface
  276. guiCfg := s.cfg.GUI()
  277. // Anticipate multiple GUI configs in the future, hence store counts.
  278. guiStats := map[string]int{
  279. "enabled": 0,
  280. "useTLS": 0,
  281. "useAuth": 0,
  282. "insecureAdminAccess": 0,
  283. "debugging": 0,
  284. "insecureSkipHostCheck": 0,
  285. "insecureAllowFrameLoading": 0,
  286. "listenLocal": 0,
  287. "listenUnspecified": 0,
  288. }
  289. theme := make(map[string]int)
  290. if guiCfg.Enabled {
  291. guiStats["enabled"]++
  292. if guiCfg.UseTLS() {
  293. guiStats["useTLS"]++
  294. }
  295. if len(guiCfg.User) > 0 && len(guiCfg.Password) > 0 {
  296. guiStats["useAuth"]++
  297. }
  298. if guiCfg.InsecureAdminAccess {
  299. guiStats["insecureAdminAccess"]++
  300. }
  301. if guiCfg.Debugging {
  302. guiStats["debugging"]++
  303. }
  304. if guiCfg.InsecureSkipHostCheck {
  305. guiStats["insecureSkipHostCheck"]++
  306. }
  307. if guiCfg.InsecureAllowFrameLoading {
  308. guiStats["insecureAllowFrameLoading"]++
  309. }
  310. addr, err := net.ResolveTCPAddr("tcp", guiCfg.Address())
  311. if err == nil {
  312. if addr.IP.IsLoopback() {
  313. guiStats["listenLocal"]++
  314. } else if addr.IP.IsUnspecified() {
  315. guiStats["listenUnspecified"]++
  316. }
  317. }
  318. theme[guiCfg.Theme]++
  319. }
  320. guiStatsInterface := map[string]interface{}{
  321. "theme": theme,
  322. }
  323. for key, value := range guiStats {
  324. guiStatsInterface[key] = value
  325. }
  326. res["guiStats"] = guiStatsInterface
  327. }
  328. for key, value := range s.model.UsageReportingStats(urVersion, preview) {
  329. res[key] = value
  330. }
  331. return res
  332. }
  333. func (s *Service) UptimeS() int {
  334. return int(time.Since(StartTime).Seconds())
  335. }
  336. func (s *Service) sendUsageReport() error {
  337. d := s.ReportData()
  338. var b bytes.Buffer
  339. if err := json.NewEncoder(&b).Encode(d); err != nil {
  340. return err
  341. }
  342. client := &http.Client{
  343. Transport: &http.Transport{
  344. DialContext: dialer.DialContext,
  345. Proxy: http.ProxyFromEnvironment,
  346. TLSClientConfig: &tls.Config{
  347. InsecureSkipVerify: s.cfg.Options().URPostInsecurely,
  348. },
  349. },
  350. }
  351. _, err := client.Post(s.cfg.Options().URURL, "application/json", &b)
  352. return err
  353. }
  354. func (s *Service) serve(ctx context.Context) {
  355. t := time.NewTimer(time.Duration(s.cfg.Options().URInitialDelayS) * time.Second)
  356. for {
  357. select {
  358. case <-ctx.Done():
  359. return
  360. case <-s.forceRun:
  361. t.Reset(0)
  362. case <-t.C:
  363. if s.cfg.Options().URAccepted >= 2 {
  364. err := s.sendUsageReport()
  365. if err != nil {
  366. l.Infoln("Usage report:", err)
  367. } else {
  368. l.Infof("Sent usage report (version %d)", s.cfg.Options().URAccepted)
  369. }
  370. }
  371. t.Reset(24 * time.Hour) // next report tomorrow
  372. }
  373. }
  374. }
  375. func (s *Service) VerifyConfiguration(from, to config.Configuration) error {
  376. return nil
  377. }
  378. func (s *Service) CommitConfiguration(from, to config.Configuration) bool {
  379. if from.Options.URAccepted != to.Options.URAccepted || from.Options.URUniqueID != to.Options.URUniqueID || from.Options.URURL != to.Options.URURL {
  380. select {
  381. case s.forceRun <- struct{}{}:
  382. default:
  383. // s.forceRun is one buffered, so even though nothing
  384. // was sent, a run will still happen after this point.
  385. }
  386. }
  387. return true
  388. }
  389. func (*Service) String() string {
  390. return "ur.Service"
  391. }
  392. var (
  393. blocksResult []protocol.BlockInfo // so the result is not optimized away
  394. blocksResultMut sync.Mutex
  395. )
  396. // CpuBench returns CPU performance as a measure of single threaded SHA-256 MiB/s
  397. func CpuBench(iterations int, duration time.Duration, useWeakHash bool) float64 {
  398. blocksResultMut.Lock()
  399. defer blocksResultMut.Unlock()
  400. dataSize := 16 * protocol.MinBlockSize
  401. bs := make([]byte, dataSize)
  402. rand.Reader.Read(bs)
  403. var perf float64
  404. for i := 0; i < iterations; i++ {
  405. if v := cpuBenchOnce(duration, useWeakHash, bs); v > perf {
  406. perf = v
  407. }
  408. }
  409. blocksResult = nil
  410. return perf
  411. }
  412. func cpuBenchOnce(duration time.Duration, useWeakHash bool, bs []byte) float64 {
  413. t0 := time.Now()
  414. b := 0
  415. for time.Since(t0) < duration {
  416. r := bytes.NewReader(bs)
  417. blocksResult, _ = scanner.Blocks(context.TODO(), r, protocol.MinBlockSize, int64(len(bs)), nil, useWeakHash)
  418. b += len(bs)
  419. }
  420. d := time.Since(t0)
  421. return float64(int(float64(b)/d.Seconds()/(1<<20)*100)) / 100
  422. }