usage_report.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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/tls"
  11. "encoding/json"
  12. "math/rand"
  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/db"
  24. "github.com/syncthing/syncthing/lib/dialer"
  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. )
  30. // Current version number of the usage report, for acceptance purposes. If
  31. // fields are added or changed this integer must be incremented so that users
  32. // are prompted for acceptance of the new report.
  33. const Version = 3
  34. var StartTime = time.Now().Truncate(time.Second)
  35. type Model interface {
  36. DBSnapshot(folder string) (*db.Snapshot, error)
  37. UsageReportingStats(report *contract.Report, version int, preview bool)
  38. }
  39. type Service struct {
  40. cfg config.Wrapper
  41. model Model
  42. connectionsService connections.Service
  43. noUpgrade bool
  44. forceRun chan struct{}
  45. }
  46. func New(cfg config.Wrapper, m Model, connectionsService connections.Service, noUpgrade bool) *Service {
  47. return &Service{
  48. cfg: cfg,
  49. model: m,
  50. connectionsService: connectionsService,
  51. noUpgrade: noUpgrade,
  52. forceRun: make(chan struct{}, 1), // Buffered to prevent locking
  53. }
  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(ctx context.Context) (*contract.Report, error) {
  58. urVersion := s.cfg.Options().URAccepted
  59. return s.reportData(ctx, 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(ctx context.Context, urVersion int) (*contract.Report, error) {
  64. return s.reportData(ctx, urVersion, true)
  65. }
  66. func (s *Service) reportData(ctx context.Context, urVersion int, preview bool) (*contract.Report, error) {
  67. opts := s.cfg.Options()
  68. defaultFolder := s.cfg.DefaultFolder()
  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.CompressionAlways:
  150. report.DeviceUses.CompressAlways++
  151. case protocol.CompressionMetadata:
  152. report.DeviceUses.CompressMetadata++
  153. case protocol.CompressionNever:
  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.AutoUpgradeEnabled()
  187. report.UpgradeAllowedPre = !(upgrade.DisabledByCompilation || s.noUpgrade) && opts.AutoUpgradeEnabled() && 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 = defaultFolder.Path != "~"
  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. if cfg.CaseSensitiveFS {
  247. report.FolderUsesV3.CaseSensitiveFS++
  248. }
  249. if cfg.Type == config.FolderTypeReceiveEncrypted {
  250. report.FolderUsesV3.ReceiveEncrypted++
  251. }
  252. }
  253. sort.Ints(report.FolderUsesV3.FsWatcherDelays)
  254. for _, cfg := range s.cfg.Devices() {
  255. if cfg.Untrusted {
  256. report.DeviceUsesV3.Untrusted++
  257. }
  258. }
  259. guiCfg := s.cfg.GUI()
  260. // Anticipate multiple GUI configs in the future, hence store counts.
  261. if guiCfg.Enabled {
  262. report.GUIStats.Enabled++
  263. if guiCfg.UseTLS() {
  264. report.GUIStats.UseTLS++
  265. }
  266. if len(guiCfg.User) > 0 && len(guiCfg.Password) > 0 {
  267. report.GUIStats.UseAuth++
  268. }
  269. if guiCfg.InsecureAdminAccess {
  270. report.GUIStats.InsecureAdminAccess++
  271. }
  272. if guiCfg.Debugging {
  273. report.GUIStats.Debugging++
  274. }
  275. if guiCfg.InsecureSkipHostCheck {
  276. report.GUIStats.InsecureSkipHostCheck++
  277. }
  278. if guiCfg.InsecureAllowFrameLoading {
  279. report.GUIStats.InsecureAllowFrameLoading++
  280. }
  281. addr, err := net.ResolveTCPAddr("tcp", guiCfg.Address())
  282. if err == nil {
  283. if addr.IP.IsLoopback() {
  284. report.GUIStats.ListenLocal++
  285. } else if addr.IP.IsUnspecified() {
  286. report.GUIStats.ListenUnspecified++
  287. }
  288. }
  289. report.GUIStats.Theme[guiCfg.Theme]++
  290. }
  291. }
  292. s.model.UsageReportingStats(report, urVersion, preview)
  293. if err := report.ClearForVersion(urVersion); err != nil {
  294. return nil, err
  295. }
  296. return report, nil
  297. }
  298. func (s *Service) UptimeS() int {
  299. return int(time.Since(StartTime).Seconds())
  300. }
  301. func (s *Service) sendUsageReport(ctx context.Context) error {
  302. d, err := s.ReportData(ctx)
  303. if err != nil {
  304. return err
  305. }
  306. var b bytes.Buffer
  307. if err := json.NewEncoder(&b).Encode(d); err != nil {
  308. return err
  309. }
  310. client := &http.Client{
  311. Transport: &http.Transport{
  312. DialContext: dialer.DialContext,
  313. Proxy: http.ProxyFromEnvironment,
  314. TLSClientConfig: &tls.Config{
  315. InsecureSkipVerify: s.cfg.Options().URPostInsecurely,
  316. },
  317. },
  318. }
  319. req, err := http.NewRequestWithContext(ctx, "POST", s.cfg.Options().URURL, &b)
  320. if err != nil {
  321. return err
  322. }
  323. req.Header.Set("Content-Type", "application/json")
  324. resp, err := client.Do(req)
  325. if err != nil {
  326. return err
  327. }
  328. resp.Body.Close()
  329. return nil
  330. }
  331. func (s *Service) Serve(ctx context.Context) error {
  332. s.cfg.Subscribe(s)
  333. defer s.cfg.Unsubscribe(s)
  334. t := time.NewTimer(time.Duration(s.cfg.Options().URInitialDelayS) * time.Second)
  335. for {
  336. select {
  337. case <-ctx.Done():
  338. return ctx.Err()
  339. case <-s.forceRun:
  340. t.Reset(0)
  341. case <-t.C:
  342. if s.cfg.Options().URAccepted >= 2 {
  343. err := s.sendUsageReport(ctx)
  344. if err != nil {
  345. l.Infoln("Usage report:", err)
  346. } else {
  347. l.Infof("Sent usage report (version %d)", s.cfg.Options().URAccepted)
  348. }
  349. }
  350. t.Reset(24 * time.Hour) // next report tomorrow
  351. }
  352. }
  353. }
  354. func (s *Service) VerifyConfiguration(from, to config.Configuration) error {
  355. return nil
  356. }
  357. func (s *Service) CommitConfiguration(from, to config.Configuration) bool {
  358. if from.Options.URAccepted != to.Options.URAccepted || from.Options.URUniqueID != to.Options.URUniqueID || from.Options.URURL != to.Options.URURL {
  359. select {
  360. case s.forceRun <- struct{}{}:
  361. default:
  362. // s.forceRun is one buffered, so even though nothing
  363. // was sent, a run will still happen after this point.
  364. }
  365. }
  366. return true
  367. }
  368. func (*Service) String() string {
  369. return "ur.Service"
  370. }
  371. var (
  372. blocksResult []protocol.BlockInfo // so the result is not optimized away
  373. blocksResultMut sync.Mutex
  374. )
  375. // CpuBench returns CPU performance as a measure of single threaded SHA-256 MiB/s
  376. func CpuBench(ctx context.Context, iterations int, duration time.Duration, useWeakHash bool) float64 {
  377. blocksResultMut.Lock()
  378. defer blocksResultMut.Unlock()
  379. dataSize := 16 * protocol.MinBlockSize
  380. bs := make([]byte, dataSize)
  381. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  382. r.Read(bs)
  383. var perf float64
  384. for i := 0; i < iterations; i++ {
  385. if v := cpuBenchOnce(ctx, duration, useWeakHash, bs); v > perf {
  386. perf = v
  387. }
  388. }
  389. // not looking at the blocksResult makes it unused from a static
  390. // analysis / compiler standpoint...
  391. // blocksResult may be nil at this point if the context is cancelled
  392. if blocksResult != nil {
  393. blocksResult = nil
  394. }
  395. return perf
  396. }
  397. func cpuBenchOnce(ctx context.Context, duration time.Duration, useWeakHash bool, bs []byte) float64 {
  398. t0 := time.Now()
  399. b := 0
  400. var err error
  401. for time.Since(t0) < duration {
  402. r := bytes.NewReader(bs)
  403. blocksResult, err = scanner.Blocks(ctx, r, protocol.MinBlockSize, int64(len(bs)), nil, useWeakHash)
  404. if err != nil {
  405. return 0 // Context done
  406. }
  407. b += len(bs)
  408. }
  409. d := time.Since(t0)
  410. return float64(int(float64(b)/d.Seconds()/(1<<20)*100)) / 100
  411. }