usage_report.go 13 KB

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