usage_report.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. "log/slog"
  13. "math/rand"
  14. "net"
  15. "net/http"
  16. "os"
  17. "runtime"
  18. "slices"
  19. "strings"
  20. "sync"
  21. "time"
  22. "github.com/shirou/gopsutil/v4/process"
  23. "github.com/syncthing/syncthing/internal/db"
  24. "github.com/syncthing/syncthing/internal/slogutil"
  25. "github.com/syncthing/syncthing/lib/build"
  26. "github.com/syncthing/syncthing/lib/config"
  27. "github.com/syncthing/syncthing/lib/connections"
  28. "github.com/syncthing/syncthing/lib/dialer"
  29. "github.com/syncthing/syncthing/lib/protocol"
  30. "github.com/syncthing/syncthing/lib/scanner"
  31. "github.com/syncthing/syncthing/lib/upgrade"
  32. "github.com/syncthing/syncthing/lib/ur/contract"
  33. )
  34. // Current version number of the usage report, for acceptance purposes. If
  35. // fields are added or changed this integer must be incremented so that users
  36. // are prompted for acceptance of the new report.
  37. const Version = 3
  38. var StartTime = time.Now().Truncate(time.Second)
  39. type Model interface {
  40. GlobalSize(folder string) (db.Counts, error)
  41. UsageReportingStats(report *contract.Report, version int, preview bool)
  42. }
  43. type Service struct {
  44. cfg config.Wrapper
  45. model Model
  46. connectionsService connections.Service
  47. noUpgrade bool
  48. forceRun chan struct{}
  49. }
  50. func New(cfg config.Wrapper, m Model, connectionsService connections.Service, noUpgrade bool) *Service {
  51. return &Service{
  52. cfg: cfg,
  53. model: m,
  54. connectionsService: connectionsService,
  55. noUpgrade: noUpgrade,
  56. forceRun: make(chan struct{}, 1), // Buffered to prevent locking
  57. }
  58. }
  59. // ReportData returns the data to be sent in a usage report with the currently
  60. // configured usage reporting version.
  61. func (s *Service) ReportData(ctx context.Context) (*contract.Report, error) {
  62. urVersion := s.cfg.Options().URAccepted
  63. return s.reportData(ctx, urVersion, false)
  64. }
  65. // ReportDataPreview returns a preview of the data to be sent in a usage report
  66. // with the given version.
  67. func (s *Service) ReportDataPreview(ctx context.Context, urVersion int) (*contract.Report, error) {
  68. return s.reportData(ctx, urVersion, true)
  69. }
  70. func (s *Service) reportData(ctx context.Context, urVersion int, preview bool) (*contract.Report, error) {
  71. opts := s.cfg.Options()
  72. defaultFolder := s.cfg.DefaultFolder()
  73. var totFiles, maxFiles int
  74. var totBytes, maxBytes int64
  75. for folderID := range s.cfg.Folders() {
  76. global, err := s.model.GlobalSize(folderID)
  77. if err != nil {
  78. return nil, err
  79. }
  80. totFiles += global.Files
  81. totBytes += global.Bytes
  82. if global.Files > maxFiles {
  83. maxFiles = 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)
  105. report.HashPerf = report.SHA256Perf
  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 "simple":
  134. report.FolderUses.SimpleVersioning++
  135. case "staggered":
  136. report.FolderUses.StaggeredVersioning++
  137. case "external":
  138. report.FolderUses.ExternalVersioning++
  139. case "trashcan":
  140. report.FolderUses.TrashcanVersioning++
  141. }
  142. }
  143. slices.Sort(report.RescanIntvs)
  144. for _, cfg := range s.cfg.Devices() {
  145. if cfg.Introducer {
  146. report.DeviceUses.Introducer++
  147. }
  148. if cfg.CertName != "" && cfg.CertName != "syncthing" {
  149. report.DeviceUses.CustomCertName++
  150. }
  151. switch cfg.Compression {
  152. case config.CompressionAlways:
  153. report.DeviceUses.CompressAlways++
  154. case config.CompressionMetadata:
  155. report.DeviceUses.CompressMetadata++
  156. case config.CompressionNever:
  157. report.DeviceUses.CompressNever++
  158. }
  159. for _, addr := range cfg.Addresses {
  160. if addr == "dynamic" {
  161. report.DeviceUses.DynamicAddr++
  162. } else {
  163. report.DeviceUses.StaticAddr++
  164. }
  165. }
  166. }
  167. report.Announce.GlobalEnabled = opts.GlobalAnnEnabled
  168. report.Announce.LocalEnabled = opts.LocalAnnEnabled
  169. for _, addr := range opts.RawGlobalAnnServers {
  170. if addr == "default" || addr == "default-v4" || addr == "default-v6" {
  171. report.Announce.DefaultServersDNS++
  172. } else {
  173. report.Announce.OtherServers++
  174. }
  175. }
  176. report.Relays.Enabled = opts.RelaysEnabled
  177. for _, addr := range s.cfg.Options().ListenAddresses() {
  178. switch {
  179. case addr == "dynamic+https://relays.syncthing.net/endpoint":
  180. report.Relays.DefaultServers++
  181. case strings.HasPrefix(addr, "relay://") || strings.HasPrefix(addr, "dynamic+http"):
  182. report.Relays.OtherServers++
  183. }
  184. }
  185. report.UsesRateLimit = opts.MaxRecvKbps > 0 || opts.MaxSendKbps > 0
  186. report.UpgradeAllowedManual = !(upgrade.DisabledByCompilation || s.noUpgrade)
  187. report.UpgradeAllowedAuto = !(upgrade.DisabledByCompilation || s.noUpgrade) && opts.AutoUpgradeEnabled()
  188. report.UpgradeAllowedPre = !(upgrade.DisabledByCompilation || s.noUpgrade) && opts.AutoUpgradeEnabled() && opts.UpgradeToPreReleases
  189. // V3
  190. if urVersion >= 3 {
  191. report.Uptime = s.UptimeS()
  192. report.NATType = s.connectionsService.NATType()
  193. report.AlwaysLocalNets = len(opts.AlwaysLocalNets) > 0
  194. report.CacheIgnoredFiles = opts.CacheIgnoredFiles
  195. report.OverwriteRemoteDeviceNames = opts.OverwriteRemoteDevNames
  196. report.ProgressEmitterEnabled = opts.ProgressUpdateIntervalS > -1
  197. report.CustomDefaultFolderPath = defaultFolder.Path != "~"
  198. report.CustomTrafficClass = opts.TrafficClass != 0
  199. report.CustomTempIndexMinBlocks = opts.TempIndexMinBlocks != 10
  200. report.TemporariesDisabled = opts.KeepTemporariesH == 0
  201. report.TemporariesCustom = opts.KeepTemporariesH != 24
  202. report.LimitBandwidthInLan = opts.LimitBandwidthInLan
  203. report.CustomReleaseURL = opts.ReleasesURL != "https://upgrades.syncthing.net/meta.json"
  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.FSWatcherEnabled {
  220. report.FolderUsesV3.FsWatcherEnabled++
  221. }
  222. report.FolderUsesV3.PullOrder[cfg.Order.String()]++
  223. report.FolderUsesV3.FilesystemType[cfg.FilesystemType.String()]++
  224. report.FolderUsesV3.FsWatcherDelays = append(report.FolderUsesV3.FsWatcherDelays, int(cfg.FSWatcherDelayS))
  225. if cfg.MarkerName != config.DefaultMarkerName {
  226. report.FolderUsesV3.CustomMarkerName++
  227. }
  228. if cfg.CopyOwnershipFromParent {
  229. report.FolderUsesV3.CopyOwnershipFromParent++
  230. }
  231. report.FolderUsesV3.ModTimeWindowS = append(report.FolderUsesV3.ModTimeWindowS, int(cfg.ModTimeWindow().Seconds()))
  232. report.FolderUsesV3.MaxConcurrentWrites = append(report.FolderUsesV3.MaxConcurrentWrites, cfg.MaxConcurrentWrites)
  233. if cfg.DisableFsync {
  234. report.FolderUsesV3.DisableFsync++
  235. }
  236. report.FolderUsesV3.BlockPullOrder[cfg.BlockPullOrder.String()]++
  237. report.FolderUsesV3.CopyRangeMethod[cfg.CopyRangeMethod.String()]++
  238. if cfg.CaseSensitiveFS {
  239. report.FolderUsesV3.CaseSensitiveFS++
  240. }
  241. if cfg.Type == config.FolderTypeReceiveEncrypted {
  242. report.FolderUsesV3.ReceiveEncrypted++
  243. }
  244. if cfg.SendXattrs {
  245. report.FolderUsesV3.SendXattrs++
  246. }
  247. if cfg.SyncXattrs {
  248. report.FolderUsesV3.SyncXattrs++
  249. }
  250. if cfg.SendOwnership {
  251. report.FolderUsesV3.SendOwnership++
  252. }
  253. if cfg.SyncOwnership {
  254. report.FolderUsesV3.SyncOwnership++
  255. }
  256. }
  257. slices.Sort(report.FolderUsesV3.FsWatcherDelays)
  258. for _, cfg := range s.cfg.Devices() {
  259. if cfg.Untrusted {
  260. report.DeviceUsesV3.Untrusted++
  261. }
  262. if cfg.MaxRecvKbps > 0 || cfg.MaxSendKbps > 0 {
  263. report.DeviceUsesV3.UsesRateLimit++
  264. }
  265. if cfg.RawNumConnections > 1 {
  266. report.DeviceUsesV3.MultipleConnections++
  267. }
  268. }
  269. guiCfg := s.cfg.GUI()
  270. // Anticipate multiple GUI configs in the future, hence store counts.
  271. if guiCfg.Enabled {
  272. report.GUIStats.Enabled++
  273. if guiCfg.UseTLS() {
  274. report.GUIStats.UseTLS++
  275. }
  276. if len(guiCfg.User) > 0 && len(guiCfg.Password) > 0 {
  277. report.GUIStats.UseAuth++
  278. }
  279. if guiCfg.InsecureAdminAccess {
  280. report.GUIStats.InsecureAdminAccess++
  281. }
  282. if guiCfg.InsecureSkipHostCheck {
  283. report.GUIStats.InsecureSkipHostCheck++
  284. }
  285. if guiCfg.InsecureAllowFrameLoading {
  286. report.GUIStats.InsecureAllowFrameLoading++
  287. }
  288. addr, err := net.ResolveTCPAddr("tcp", guiCfg.Address())
  289. if err == nil {
  290. if addr.IP.IsLoopback() {
  291. report.GUIStats.ListenLocal++
  292. } else if addr.IP.IsUnspecified() {
  293. report.GUIStats.ListenUnspecified++
  294. }
  295. }
  296. report.GUIStats.Theme[guiCfg.Theme]++
  297. }
  298. }
  299. s.model.UsageReportingStats(report, urVersion, preview)
  300. if err := report.ClearForVersion(urVersion); err != nil {
  301. return nil, err
  302. }
  303. return report, nil
  304. }
  305. func (*Service) UptimeS() int {
  306. // Handle nonexistent or wildly incorrect system clock.
  307. // This code was written in 2023, it can't run in the past.
  308. if StartTime.Year() < 2023 {
  309. return 0
  310. }
  311. return int(time.Since(StartTime).Seconds())
  312. }
  313. func (s *Service) sendUsageReport(ctx context.Context) error {
  314. d, err := s.ReportData(ctx)
  315. if err != nil {
  316. return err
  317. }
  318. var b bytes.Buffer
  319. if err := json.NewEncoder(&b).Encode(d); err != nil {
  320. return err
  321. }
  322. client := &http.Client{
  323. Transport: &http.Transport{
  324. DialContext: dialer.DialContext,
  325. Proxy: http.ProxyFromEnvironment,
  326. TLSClientConfig: &tls.Config{
  327. InsecureSkipVerify: s.cfg.Options().URPostInsecurely,
  328. MinVersion: tls.VersionTLS12,
  329. ClientSessionCache: tls.NewLRUClientSessionCache(0),
  330. },
  331. },
  332. }
  333. req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.cfg.Options().URURL, &b)
  334. if err != nil {
  335. return err
  336. }
  337. req.Header.Set("Content-Type", "application/json")
  338. resp, err := client.Do(req)
  339. if err != nil {
  340. return err
  341. }
  342. resp.Body.Close()
  343. return nil
  344. }
  345. func (s *Service) Serve(ctx context.Context) error {
  346. s.cfg.Subscribe(s)
  347. defer s.cfg.Unsubscribe(s)
  348. t := time.NewTimer(time.Duration(s.cfg.Options().URInitialDelayS) * time.Second)
  349. for {
  350. select {
  351. case <-ctx.Done():
  352. return ctx.Err()
  353. case <-s.forceRun:
  354. t.Reset(0)
  355. case <-t.C:
  356. if s.cfg.Options().URAccepted >= 2 {
  357. err := s.sendUsageReport(ctx)
  358. if err != nil {
  359. slog.WarnContext(ctx, "Failed to send usage report", slogutil.Error(err))
  360. } else {
  361. slog.InfoContext(ctx, "Sent usage report", "version", s.cfg.Options().URAccepted)
  362. }
  363. }
  364. t.Reset(24 * time.Hour) // next report tomorrow
  365. }
  366. }
  367. }
  368. func (s *Service) CommitConfiguration(from, to config.Configuration) bool {
  369. if from.Options.URAccepted != to.Options.URAccepted || from.Options.URUniqueID != to.Options.URUniqueID || from.Options.URURL != to.Options.URURL {
  370. select {
  371. case s.forceRun <- struct{}{}:
  372. default:
  373. // s.forceRun is one buffered, so even though nothing
  374. // was sent, a run will still happen after this point.
  375. }
  376. }
  377. return true
  378. }
  379. func (*Service) String() string {
  380. return "ur.Service"
  381. }
  382. var (
  383. blocksResult []protocol.BlockInfo // so the result is not optimized away
  384. blocksResultMut sync.Mutex
  385. )
  386. // CpuBench returns CPU performance as a measure of single threaded SHA-256 MiB/s
  387. func CpuBench(ctx context.Context, iterations int, duration time.Duration) float64 {
  388. blocksResultMut.Lock()
  389. defer blocksResultMut.Unlock()
  390. dataSize := 16 * protocol.MinBlockSize
  391. bs := make([]byte, dataSize)
  392. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  393. r.Read(bs)
  394. var perf float64
  395. for range iterations {
  396. if v := cpuBenchOnce(ctx, duration, bs); v > perf {
  397. perf = v
  398. }
  399. }
  400. // not looking at the blocksResult makes it unused from a static
  401. // analysis / compiler standpoint...
  402. // blocksResult may be nil at this point if the context is cancelled
  403. if blocksResult != nil {
  404. blocksResult = nil
  405. }
  406. return perf
  407. }
  408. func cpuBenchOnce(ctx context.Context, duration time.Duration, bs []byte) float64 {
  409. t0 := time.Now()
  410. b := 0
  411. var err error
  412. for time.Since(t0) < duration {
  413. r := bytes.NewReader(bs)
  414. blocksResult, err = scanner.Blocks(ctx, r, protocol.MinBlockSize, int64(len(bs)), nil)
  415. if err != nil {
  416. return 0 // Context done
  417. }
  418. b += len(bs)
  419. }
  420. d := time.Since(t0)
  421. return float64(int(float64(b)/d.Seconds()/(1<<20)*100)) / 100
  422. }