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.CustomStunServers = len(opts.RawStunServers) != 1 || opts.RawStunServers[0] != "default"
  204. for _, cfg := range s.cfg.Folders() {
  205. if cfg.ScanProgressIntervalS < 0 {
  206. report.FolderUsesV3.ScanProgressDisabled++
  207. }
  208. if cfg.MaxConflicts == 0 {
  209. report.FolderUsesV3.ConflictsDisabled++
  210. } else if cfg.MaxConflicts < 0 {
  211. report.FolderUsesV3.ConflictsUnlimited++
  212. } else {
  213. report.FolderUsesV3.ConflictsOther++
  214. }
  215. if cfg.DisableSparseFiles {
  216. report.FolderUsesV3.DisableSparseFiles++
  217. }
  218. if cfg.DisableTempIndexes {
  219. report.FolderUsesV3.DisableTempIndexes++
  220. }
  221. if cfg.WeakHashThresholdPct < 0 {
  222. report.FolderUsesV3.AlwaysWeakHash++
  223. } else if cfg.WeakHashThresholdPct != 25 {
  224. report.FolderUsesV3.CustomWeakHashThreshold++
  225. }
  226. if cfg.FSWatcherEnabled {
  227. report.FolderUsesV3.FsWatcherEnabled++
  228. }
  229. report.FolderUsesV3.PullOrder[cfg.Order.String()]++
  230. report.FolderUsesV3.FilesystemType[cfg.FilesystemType.String()]++
  231. report.FolderUsesV3.FsWatcherDelays = append(report.FolderUsesV3.FsWatcherDelays, int(cfg.FSWatcherDelayS))
  232. if cfg.MarkerName != config.DefaultMarkerName {
  233. report.FolderUsesV3.CustomMarkerName++
  234. }
  235. if cfg.CopyOwnershipFromParent {
  236. report.FolderUsesV3.CopyOwnershipFromParent++
  237. }
  238. report.FolderUsesV3.ModTimeWindowS = append(report.FolderUsesV3.ModTimeWindowS, int(cfg.ModTimeWindow().Seconds()))
  239. report.FolderUsesV3.MaxConcurrentWrites = append(report.FolderUsesV3.MaxConcurrentWrites, cfg.MaxConcurrentWrites)
  240. if cfg.DisableFsync {
  241. report.FolderUsesV3.DisableFsync++
  242. }
  243. report.FolderUsesV3.BlockPullOrder[cfg.BlockPullOrder.String()]++
  244. report.FolderUsesV3.CopyRangeMethod[cfg.CopyRangeMethod.String()]++
  245. if cfg.CaseSensitiveFS {
  246. report.FolderUsesV3.CaseSensitiveFS++
  247. }
  248. if cfg.Type == config.FolderTypeReceiveEncrypted {
  249. report.FolderUsesV3.ReceiveEncrypted++
  250. }
  251. }
  252. sort.Ints(report.FolderUsesV3.FsWatcherDelays)
  253. for _, cfg := range s.cfg.Devices() {
  254. if cfg.Untrusted {
  255. report.DeviceUsesV3.Untrusted++
  256. }
  257. }
  258. guiCfg := s.cfg.GUI()
  259. // Anticipate multiple GUI configs in the future, hence store counts.
  260. if guiCfg.Enabled {
  261. report.GUIStats.Enabled++
  262. if guiCfg.UseTLS() {
  263. report.GUIStats.UseTLS++
  264. }
  265. if len(guiCfg.User) > 0 && len(guiCfg.Password) > 0 {
  266. report.GUIStats.UseAuth++
  267. }
  268. if guiCfg.InsecureAdminAccess {
  269. report.GUIStats.InsecureAdminAccess++
  270. }
  271. if guiCfg.Debugging {
  272. report.GUIStats.Debugging++
  273. }
  274. if guiCfg.InsecureSkipHostCheck {
  275. report.GUIStats.InsecureSkipHostCheck++
  276. }
  277. if guiCfg.InsecureAllowFrameLoading {
  278. report.GUIStats.InsecureAllowFrameLoading++
  279. }
  280. addr, err := net.ResolveTCPAddr("tcp", guiCfg.Address())
  281. if err == nil {
  282. if addr.IP.IsLoopback() {
  283. report.GUIStats.ListenLocal++
  284. } else if addr.IP.IsUnspecified() {
  285. report.GUIStats.ListenUnspecified++
  286. }
  287. }
  288. report.GUIStats.Theme[guiCfg.Theme]++
  289. }
  290. }
  291. s.model.UsageReportingStats(report, urVersion, preview)
  292. if err := report.ClearForVersion(urVersion); err != nil {
  293. return nil, err
  294. }
  295. return report, nil
  296. }
  297. func (*Service) UptimeS() int {
  298. // Handle nonexistent or wildly incorrect system clock.
  299. // This code was written in 2023, it can't run in the past.
  300. if StartTime.Year() < 2023 {
  301. return 0
  302. }
  303. return int(time.Since(StartTime).Seconds())
  304. }
  305. func (s *Service) sendUsageReport(ctx context.Context) error {
  306. d, err := s.ReportData(ctx)
  307. if err != nil {
  308. return err
  309. }
  310. var b bytes.Buffer
  311. if err := json.NewEncoder(&b).Encode(d); err != nil {
  312. return err
  313. }
  314. client := &http.Client{
  315. Transport: &http.Transport{
  316. DialContext: dialer.DialContext,
  317. Proxy: http.ProxyFromEnvironment,
  318. TLSClientConfig: &tls.Config{
  319. InsecureSkipVerify: s.cfg.Options().URPostInsecurely,
  320. },
  321. },
  322. }
  323. req, err := http.NewRequestWithContext(ctx, "POST", s.cfg.Options().URURL, &b)
  324. if err != nil {
  325. return err
  326. }
  327. req.Header.Set("Content-Type", "application/json")
  328. resp, err := client.Do(req)
  329. if err != nil {
  330. return err
  331. }
  332. resp.Body.Close()
  333. return nil
  334. }
  335. func (s *Service) Serve(ctx context.Context) error {
  336. s.cfg.Subscribe(s)
  337. defer s.cfg.Unsubscribe(s)
  338. t := time.NewTimer(time.Duration(s.cfg.Options().URInitialDelayS) * time.Second)
  339. for {
  340. select {
  341. case <-ctx.Done():
  342. return ctx.Err()
  343. case <-s.forceRun:
  344. t.Reset(0)
  345. case <-t.C:
  346. if s.cfg.Options().URAccepted >= 2 {
  347. err := s.sendUsageReport(ctx)
  348. if err != nil {
  349. l.Infoln("Usage report:", err)
  350. } else {
  351. l.Infof("Sent usage report (version %d)", s.cfg.Options().URAccepted)
  352. }
  353. }
  354. t.Reset(24 * time.Hour) // next report tomorrow
  355. }
  356. }
  357. }
  358. func (s *Service) CommitConfiguration(from, to config.Configuration) bool {
  359. if from.Options.URAccepted != to.Options.URAccepted || from.Options.URUniqueID != to.Options.URUniqueID || from.Options.URURL != to.Options.URURL {
  360. select {
  361. case s.forceRun <- struct{}{}:
  362. default:
  363. // s.forceRun is one buffered, so even though nothing
  364. // was sent, a run will still happen after this point.
  365. }
  366. }
  367. return true
  368. }
  369. func (*Service) String() string {
  370. return "ur.Service"
  371. }
  372. var (
  373. blocksResult []protocol.BlockInfo // so the result is not optimized away
  374. blocksResultMut sync.Mutex
  375. )
  376. // CpuBench returns CPU performance as a measure of single threaded SHA-256 MiB/s
  377. func CpuBench(ctx context.Context, iterations int, duration time.Duration, useWeakHash bool) float64 {
  378. blocksResultMut.Lock()
  379. defer blocksResultMut.Unlock()
  380. dataSize := 16 * protocol.MinBlockSize
  381. bs := make([]byte, dataSize)
  382. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  383. r.Read(bs)
  384. var perf float64
  385. for i := 0; i < iterations; i++ {
  386. if v := cpuBenchOnce(ctx, duration, useWeakHash, bs); v > perf {
  387. perf = v
  388. }
  389. }
  390. // not looking at the blocksResult makes it unused from a static
  391. // analysis / compiler standpoint...
  392. // blocksResult may be nil at this point if the context is cancelled
  393. if blocksResult != nil {
  394. blocksResult = nil
  395. }
  396. return perf
  397. }
  398. func cpuBenchOnce(ctx context.Context, duration time.Duration, useWeakHash bool, bs []byte) float64 {
  399. t0 := time.Now()
  400. b := 0
  401. var err error
  402. for time.Since(t0) < duration {
  403. r := bytes.NewReader(bs)
  404. blocksResult, err = scanner.Blocks(ctx, r, protocol.MinBlockSize, int64(len(bs)), nil, useWeakHash)
  405. if err != nil {
  406. return 0 // Context done
  407. }
  408. b += len(bs)
  409. }
  410. d := time.Since(t0)
  411. return float64(int(float64(b)/d.Seconds()/(1<<20)*100)) / 100
  412. }