db_service.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. // Copyright (C) 2025 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 sqlite
  7. import (
  8. "context"
  9. "encoding/binary"
  10. "fmt"
  11. "log/slog"
  12. "math/rand"
  13. "strings"
  14. "time"
  15. "github.com/jmoiron/sqlx"
  16. "github.com/syncthing/syncthing/internal/db"
  17. "github.com/syncthing/syncthing/internal/slogutil"
  18. "github.com/syncthing/syncthing/lib/protocol"
  19. "github.com/thejerf/suture/v4"
  20. )
  21. const (
  22. internalMetaPrefix = "dbsvc"
  23. lastMaintKey = "lastMaint"
  24. lastSuccessfulGCSeqKey = "lastSuccessfulGCSeq"
  25. gcMinChunks = 5
  26. gcChunkSize = 100_000 // approximate number of rows to process in a single gc query
  27. gcMaxRuntime = 5 * time.Minute // max time to spend on gc, per table, per run
  28. )
  29. func (s *DB) Service(maintenanceInterval time.Duration) suture.Service {
  30. return newService(s, maintenanceInterval)
  31. }
  32. type Service struct {
  33. sdb *DB
  34. maintenanceInterval time.Duration
  35. internalMeta *db.Typed
  36. }
  37. func (s *Service) String() string {
  38. return fmt.Sprintf("sqlite.service@%p", s)
  39. }
  40. func newService(sdb *DB, maintenanceInterval time.Duration) *Service {
  41. return &Service{
  42. sdb: sdb,
  43. maintenanceInterval: maintenanceInterval,
  44. internalMeta: db.NewTyped(sdb, internalMetaPrefix),
  45. }
  46. }
  47. func (s *Service) Serve(ctx context.Context) error {
  48. // Run periodic maintenance
  49. // Figure out when we last ran maintenance and schedule accordingly. If
  50. // it was never, do it now.
  51. lastMaint, _, _ := s.internalMeta.Time(lastMaintKey)
  52. nextMaint := lastMaint.Add(s.maintenanceInterval)
  53. wait := time.Until(nextMaint)
  54. if wait < 0 {
  55. wait = time.Minute
  56. }
  57. slog.DebugContext(ctx, "Next periodic run due", "after", wait)
  58. timer := time.NewTimer(wait)
  59. for {
  60. select {
  61. case <-ctx.Done():
  62. return ctx.Err()
  63. case <-timer.C:
  64. }
  65. if err := s.periodic(ctx); err != nil {
  66. return wrap(err)
  67. }
  68. timer.Reset(s.maintenanceInterval)
  69. slog.DebugContext(ctx, "Next periodic run due", "after", s.maintenanceInterval)
  70. _ = s.internalMeta.PutTime(lastMaintKey, time.Now())
  71. }
  72. }
  73. func (s *Service) periodic(ctx context.Context) error {
  74. t0 := time.Now()
  75. slog.DebugContext(ctx, "Periodic start")
  76. t1 := time.Now()
  77. defer func() { slog.DebugContext(ctx, "Periodic done in", "t1", time.Since(t1), "t0t1", t1.Sub(t0)) }()
  78. s.sdb.updateLock.Lock()
  79. err := tidy(ctx, s.sdb.sql)
  80. s.sdb.updateLock.Unlock()
  81. if err != nil {
  82. return err
  83. }
  84. return wrap(s.sdb.forEachFolder(func(fdb *folderDB) error {
  85. // Get the current device sequence, for comparison in the next step.
  86. seq, err := fdb.GetDeviceSequence(protocol.LocalDeviceID)
  87. if err != nil {
  88. return wrap(err)
  89. }
  90. // Get the last successful GC sequence. If it's the same as the
  91. // current sequence, nothing has changed and we can skip the GC
  92. // entirely.
  93. meta := db.NewTyped(fdb, internalMetaPrefix)
  94. if prev, _, err := meta.Int64(lastSuccessfulGCSeqKey); err != nil {
  95. return wrap(err)
  96. } else if seq == prev {
  97. slog.DebugContext(ctx, "Skipping unnecessary GC", "folder", fdb.folderID, "fdb", fdb.baseName)
  98. return nil
  99. }
  100. // Run the GC steps, in a function to be able to use a deferred
  101. // unlock.
  102. if err := func() error {
  103. fdb.updateLock.Lock()
  104. defer fdb.updateLock.Unlock()
  105. if err := garbageCollectOldDeletedLocked(ctx, fdb); err != nil {
  106. return wrap(err)
  107. }
  108. if err := garbageCollectNamesAndVersions(ctx, fdb); err != nil {
  109. return wrap(err)
  110. }
  111. if err := garbageCollectBlocklistsAndBlocksLocked(ctx, fdb); err != nil {
  112. return wrap(err)
  113. }
  114. return tidy(ctx, fdb.sql)
  115. }(); err != nil {
  116. return wrap(err)
  117. }
  118. // Update the successful GC sequence.
  119. return wrap(meta.PutInt64(lastSuccessfulGCSeqKey, seq))
  120. }))
  121. }
  122. func tidy(ctx context.Context, db *sqlx.DB) error {
  123. conn, err := db.Conn(ctx)
  124. if err != nil {
  125. return wrap(err)
  126. }
  127. defer conn.Close()
  128. _, _ = conn.ExecContext(ctx, `ANALYZE`)
  129. _, _ = conn.ExecContext(ctx, `PRAGMA optimize`)
  130. _, _ = conn.ExecContext(ctx, `PRAGMA incremental_vacuum`)
  131. _, _ = conn.ExecContext(ctx, `PRAGMA journal_size_limit = 8388608`)
  132. _, _ = conn.ExecContext(ctx, `PRAGMA wal_checkpoint(TRUNCATE)`)
  133. return nil
  134. }
  135. func garbageCollectNamesAndVersions(ctx context.Context, fdb *folderDB) error {
  136. l := slog.With("folder", fdb.folderID, "fdb", fdb.baseName)
  137. res, err := fdb.stmt(`
  138. DELETE FROM file_names
  139. WHERE NOT EXISTS (SELECT 1 FROM files f WHERE f.name_idx = idx)
  140. `).Exec()
  141. if err != nil {
  142. return wrap(err, "delete names")
  143. }
  144. if aff, err := res.RowsAffected(); err == nil {
  145. l.DebugContext(ctx, "Removed old file names", "affected", aff)
  146. }
  147. res, err = fdb.stmt(`
  148. DELETE FROM file_versions
  149. WHERE NOT EXISTS (SELECT 1 FROM files f WHERE f.version_idx = idx)
  150. `).Exec()
  151. if err != nil {
  152. return wrap(err, "delete versions")
  153. }
  154. if aff, err := res.RowsAffected(); err == nil {
  155. l.DebugContext(ctx, "Removed old file versions", "affected", aff)
  156. }
  157. return nil
  158. }
  159. func garbageCollectOldDeletedLocked(ctx context.Context, fdb *folderDB) error {
  160. l := slog.With("folder", fdb.folderID, "fdb", fdb.baseName)
  161. if fdb.deleteRetention <= 0 {
  162. slog.DebugContext(ctx, "Delete retention is infinite, skipping cleanup")
  163. return nil
  164. }
  165. // Remove deleted files that are marked as not needed (we have processed
  166. // them) and they were deleted more than MaxDeletedFileAge ago.
  167. l.DebugContext(ctx, "Forgetting deleted files", "retention", fdb.deleteRetention)
  168. res, err := fdb.stmt(`
  169. DELETE FROM files
  170. WHERE deleted AND modified < ? AND local_flags & {{.FlagLocalNeeded}} == 0
  171. `).Exec(time.Now().Add(-fdb.deleteRetention).UnixNano())
  172. if err != nil {
  173. return wrap(err)
  174. }
  175. if aff, err := res.RowsAffected(); err == nil {
  176. l.DebugContext(ctx, "Removed old deleted file records", "affected", aff)
  177. }
  178. return nil
  179. }
  180. func garbageCollectBlocklistsAndBlocksLocked(ctx context.Context, fdb *folderDB) error {
  181. // Remove all blocklists not referred to by any files and, by extension,
  182. // any blocks not referred to by a blocklist. This is an expensive
  183. // operation when run normally, especially if there are a lot of blocks
  184. // to collect.
  185. //
  186. // We make this orders of magnitude faster by disabling foreign keys for
  187. // the transaction and doing the cleanup manually. This requires using
  188. // an explicit connection and disabling foreign keys before starting the
  189. // transaction. We make sure to clean up on the way out.
  190. conn, err := fdb.sql.Connx(ctx)
  191. if err != nil {
  192. return wrap(err)
  193. }
  194. defer conn.Close()
  195. if _, err := conn.ExecContext(ctx, `PRAGMA foreign_keys = 0`); err != nil {
  196. return wrap(err)
  197. }
  198. defer func() { //nolint:contextcheck
  199. _, _ = conn.ExecContext(context.Background(), `PRAGMA foreign_keys = 1`)
  200. }()
  201. tx, err := conn.BeginTxx(ctx, nil)
  202. if err != nil {
  203. return wrap(err)
  204. }
  205. defer tx.Rollback() //nolint:errcheck
  206. // Both blocklists and blocks refer to blocklists_hash from the files table.
  207. for _, table := range []string{"blocklists", "blocks"} {
  208. // Count the number of rows
  209. var rows int64
  210. if err := tx.GetContext(ctx, &rows, `SELECT count(*) FROM `+table); err != nil {
  211. return wrap(err)
  212. }
  213. chunks := max(gcMinChunks, rows/gcChunkSize)
  214. l := slog.With("folder", fdb.folderID, "fdb", fdb.baseName, "table", table, "rows", rows, "chunks", chunks)
  215. // Process rows in chunks up to a given time limit. We always use at
  216. // least gcMinChunks chunks, then increase the number as the number of rows
  217. // exceeds gcMinChunks*gcChunkSize.
  218. t0 := time.Now()
  219. for i, br := range randomBlobRanges(int(chunks)) {
  220. if d := time.Since(t0); d > gcMaxRuntime {
  221. l.InfoContext(ctx, "GC was interrupted due to exceeding time limit", "processed", i, "runtime", time.Since(t0))
  222. break
  223. }
  224. // The limit column must be an indexed column with a mostly random distribution of blobs.
  225. // That's the blocklist_hash column for blocklists, and the hash column for blocks.
  226. limitColumn := table + ".blocklist_hash"
  227. if table == "blocks" {
  228. limitColumn = "blocks.hash"
  229. }
  230. q := fmt.Sprintf(`
  231. DELETE FROM %s
  232. WHERE %s AND NOT EXISTS (
  233. SELECT 1 FROM files WHERE files.blocklist_hash = %s.blocklist_hash
  234. )`, table, br.SQL(limitColumn), table)
  235. if res, err := tx.ExecContext(ctx, q); err != nil {
  236. return wrap(err, "delete from "+table)
  237. } else {
  238. l.DebugContext(ctx, "GC query result", "processed", i, "runtime", time.Since(t0), "result", slogutil.Expensive(func() any {
  239. rows, err := res.RowsAffected()
  240. if err != nil {
  241. return slogutil.Error(err)
  242. }
  243. return slog.Int64("rows", rows)
  244. }))
  245. }
  246. }
  247. }
  248. return wrap(tx.Commit())
  249. }
  250. // blobRange defines a range for blob searching. A range is open ended if
  251. // start or end is nil.
  252. type blobRange struct {
  253. start, end []byte
  254. }
  255. // SQL returns the SQL where clause for the given range, e.g.
  256. // `column >= x'49249248' AND column < x'6db6db6c'`
  257. func (r blobRange) SQL(name string) string {
  258. var sb strings.Builder
  259. if r.start != nil {
  260. fmt.Fprintf(&sb, "%s >= x'%x'", name, r.start)
  261. }
  262. if r.start != nil && r.end != nil {
  263. sb.WriteString(" AND ")
  264. }
  265. if r.end != nil {
  266. fmt.Fprintf(&sb, "%s < x'%x'", name, r.end)
  267. }
  268. return sb.String()
  269. }
  270. // randomBlobRanges returns n blobRanges in random order
  271. func randomBlobRanges(n int) []blobRange {
  272. ranges := blobRanges(n)
  273. rand.Shuffle(len(ranges), func(i, j int) { ranges[i], ranges[j] = ranges[j], ranges[i] })
  274. return ranges
  275. }
  276. // blobRanges returns n blobRanges
  277. func blobRanges(n int) []blobRange {
  278. // We use three byte (24 bit) prefixes to get fairly granular ranges and easy bit
  279. // conversions.
  280. rangeSize := (1 << 24) / n
  281. ranges := make([]blobRange, 0, n)
  282. var prev []byte
  283. for i := range n {
  284. var pref []byte
  285. if i < n-1 {
  286. end := (i + 1) * rangeSize
  287. pref = intToBlob(end)
  288. }
  289. ranges = append(ranges, blobRange{prev, pref})
  290. prev = pref
  291. }
  292. return ranges
  293. }
  294. func intToBlob(n int) []byte {
  295. var pref [4]byte
  296. binary.BigEndian.PutUint32(pref[:], uint32(n)) //nolint:gosec
  297. // first byte is always zero and not part of the range
  298. return pref[1:]
  299. }