usage_report.go 13 KB

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