usage_report.go 14 KB

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