Repository navigation
Expand file tree
/
Copy pathstats.go
More file actions
463 lines (433 loc) · 17.1 KB
/
Copy pathstats.go
File metadata and controls
463 lines (433 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
// Copyright (c) 2026 The liustack/sqlite Authors.
// SPDX-License-Identifier: MIT
// Use of this source code is governed by the MIT license in LICENSE at the
// root of this repository.
//go:build ((linux || darwin) && (amd64 || arm64)) || (windows && (amd64 || arm64))
package sqlite
import (
"errors"
"slices"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/liustack/sqlite/internal/csqlite"
"github.com/liustack/sqlite/internal/queuehook"
"github.com/liustack/sqlite/internal/replhook"
)
// Report is what Stats gives: the numbers of the driver in this process, for
// a status page. It is plain data, for encoding/json as it is.
//
// A counter counts from the start of the process and never goes back, while
// its file stays open. A gauge, marked as such, is a value of now. Each field
// is read on its own as Stats runs, so the fields are not of one instant: a
// commit that ends while Stats runs may be in Commits and not yet in Merged.
// On windows the clock the times are read on moves in steps of the system's
// timer, up to 15.6ms: one commit, wait or checkpoint can be off by up to a
// step (a short one often reads 0), and only a sum over many is close.
type Report struct {
// Memory is SQLite's memory, of the whole process.
Memory MemoryStats
// Files has a FileStats for each database file the driver has open now,
// sorted by Path. A file drops out once its last connection closes and
// no replicator runs on it, its numbers with it: opened again, it starts
// from zero. Open's pool closes a connection idle for 5 minutes, so a
// database no one used for that long is not listed.
Files []FileStats
}
// MemoryStats is the memory SQLite takes from the system for its heap: the
// pages it caches, its statements and the rest of what it allocates. Blocks
// it freed are counted while the heap keeps them for reuse. The stacks of
// the connections are not counted.
type MemoryStats struct {
// InUseBytes is what the heap holds now. A gauge.
InUseBytes int64
// HighWaterBytes is the most it held since the process started.
HighWaterBytes int64
}
// FileStats is the numbers of one database file.
type FileStats struct {
// Path is the file, as SQLite named it when the driver first opened it.
Path string
// Writes is how the writes of the process go.
Writes WriteStats
// WAL is the checkpoints the driver runs, and the length of the WAL.
WAL WALStats
// Errors counts the errors of SQLite that calls on the file returned.
Errors ErrorStats
// Statements counts how often a query or a write found its statement
// kept by its connection.
Statements StatementStats
// Queues are the queues of package queue that this process opened on
// the file with a database (sql.DB) that has a connection to it now,
// sorted by Table and then Name. A queue that two of them opened is
// listed once, with the later count.
Queues []QueueStats
// Replica is how replication of the file stands, nil when this process
// does not replicate it.
Replica *ReplicaStats
}
// WriteStats is how the writes of the process to a file go.
type WriteStats struct {
// Commits counts the transactions that changed rows and committed:
// each batch of group commit, and each write or transaction that ran on
// its own. One that changed only the schema is not counted. Rows are
// those SQLite counts for the connection (total_changes()), which tells
// neither the database they are in nor whether a ROLLBACK TO undid
// them: a transaction that wrote only temporary tables counts, and so
// does one whose rows a ROLLBACK TO all undid.
Commits int64
// Merged counts the writes that ran without an error in the batches of
// group commit that Commits counts.
Merged int64
// CommitTime is the time those commits took: the COMMIT of a batch, of
// a sql.Tx or of a transaction run with Exec, and the whole of a write
// that ran alone, as its commit is part of it. A write run with Query
// commits inside Query or the reading of its rows (a COMMIT in Query
// itself, an INSERT ... RETURNING as its rows are read to the end or
// close), and counts once its rows close, without its time. Divided by
// Commits it is about what a commit costs.
CommitTime time.Duration
// LockWaits counts the times a write, a transaction or the replicator
// found the write lock of the file held, and waited.
LockWaits int64
// LockWaitTime is the time they waited: until the lock was theirs, or
// a batch took their write, or they gave up.
LockWaitTime time.Duration
// Busy counts the calls that returned SQLITE_BUSY, "database is
// locked": a lock stayed held past the busy timeout, or SQLite gave up
// at once, as with a busy timeout of 0 (docs/database-is-locked.md).
// Errors counts them too, under Other.
Busy int64
}
// WALStats is the WAL of a file.
type WALStats struct {
// Checkpoints counts the checkpoints the driver ran on the file, those
// that failed too: those it runs each wal_autocheckpoint pages, and
// those that start the WAL over past _wal_limit. Not counted: those of
// a replicated file, which its replicator runs, those SQLite runs for
// a connection with an attached database, and a program's own PRAGMA
// wal_checkpoint.
Checkpoints int64
// CheckpointTime is the time they took, the writers of the file
// waiting meanwhile.
CheckpointTime time.Duration
// SizeBytes is the length of the WAL as the last write of the process
// left it, 0 once the driver started it over, and 0 before the process
// first wrote to the file in WAL mode. A gauge. A checkpoint of the
// replicator shows at the next write, and a file that leaves WAL mode
// keeps its last length. The -wal file on the disk can be longer:
// SQLite writes it from the start again once it starts over.
SizeBytes int64
}
// ErrorStats counts the errors of SQLite that calls on a file returned to
// the program, by their primary result code (Error.Code). The error of a
// context that ended is not counted, nor an error of the driver itself, as
// for a transaction that already ended or an argument it cannot bind.
type ErrorStats struct {
// Full counts SQLITE_FULL, a full disk.
Full int64
// IO counts SQLITE_IOERR, a file that could not be read or written.
IO int64
// Corrupt counts SQLITE_CORRUPT, a database file that is damaged.
Corrupt int64
// Constraint counts SQLITE_CONSTRAINT: a UNIQUE, NOT NULL, CHECK or
// FOREIGN KEY constraint that failed.
Constraint int64
// Other counts every other code. OtherCodes says which, by the name of
// the code as in codes.go ("BUSY", "ERROR"), with only the codes seen.
Other int64
OtherCodes map[string]int64
}
// StatementStats counts the queries (QueryContext) and writes (ExecContext)
// of the connections of a file, by whether their connection kept their
// statement (docs/query-cache.md). The statements a program prepares itself
// (Prepare) are not counted.
type StatementStats struct {
// Hits counts those that found their statement kept by their
// connection.
Hits int64
// Misses counts those that did not, and so prepared it.
Misses int64
}
// QueueStats is a queue of package queue. Its numbers are those the last
// round of cleanup of the queue in this process counted, once a minute at
// most: q.Stats(ctx) counts them now.
type QueueStats struct {
// Table is the table of its messages, as given to queue.Table.
Table string
// Name is the name of the queue.
Name string
// AsOf is when Subs was counted, the zero time until a round has.
AsOf time.Time
// Subs is how the messages of each subscription stood, by its name: of
// the default subscription when the queue has no named one.
Subs []QueueSubStats
}
// QueueSubStats is how the messages of a subscription stood at AsOf, as
// queue.SubStats says. Each count is a gauge.
type QueueSubStats struct {
Sub string
Waiting, Delayed, Held, Dead int64
OldestWaitTime time.Duration
}
// ReplicaStats is how replication of a file stands, as the Status of
// package replica says.
type ReplicaStats struct {
// StagedTXID is the last TXID in the staging folder.
StagedTXID uint64
// UploadedTXID is the last TXID in the replica.
UploadedTXID uint64
// PendingBytes is what is staged and not uploaded yet. A gauge.
PendingBytes int64
// UploadError is the error of the last upload, "" once one succeeds.
UploadError string
}
// Stats gives the numbers of the driver in this process. It runs no SQL and
// waits for no write: what it reads is counted with atomics as the driver
// runs, and the list of files is held only while a connection opens or
// closes. The numbers of a queue come from its last round of cleanup.
//
// A program puts it on its status page as it is, as JSON for example:
//
// json.NewEncoder(w).Encode(sqlite.Stats())
func Stats() Report {
inUse, high := csqlite.Memory()
r := Report{Memory: MemoryStats{InUseBytes: inUse, HighWaterBytes: high}, Files: []FileStats{}}
type open struct {
l *writeLock
hits, misses int64
queues []*queuehook.Queues // those of the connectors of its connections
}
// The counts of the connections are read with the list held, as a
// connection that closes adds its own to those of its file then: read
// apart, they could be counted twice, or not at all.
writeLocks.Lock()
files := make([]open, 0, len(writeLocks.all))
for _, l := range writeLocks.all {
f := open{l: l, hits: l.n.hits.Load(), misses: l.n.misses.Load()}
for _, c := range l.conns {
f.hits += c.hits.Load()
f.misses += c.misses.Load()
if !slices.Contains(f.queues, c.queues) {
f.queues = append(f.queues, c.queues)
}
}
files = append(files, f)
}
writeLocks.Unlock()
for _, f := range files {
r.Files = append(r.Files, f.l.report(f.hits, f.misses, f.queues))
}
slices.SortStableFunc(r.Files, func(a, b FileStats) int { return strings.Compare(a.Path, b.Path) })
return r
}
// counters are the numbers of a file that Stats reports, beside those
// writeLock keeps for its own work (batchStats, walCheckpoints, walTries).
// Each is written atomically where it moves.
type counters struct {
// commits counts the transactions that changed rows and committed
// (countCommit, runBatch), commitTime is their time in nanoseconds, and
// merged counts the writes of the batches among them.
commits, commitTime, merged atomic.Int64
// lockWaits counts the waits for the write lock, and lockWaitTime is
// their time in nanoseconds (acquire, submit).
lockWaits, lockWaitTime atomic.Int64
// checkpoints counts the checkpoints the driver ran, those that failed
// too (checkpoint, restartWAL), and checkpointTime is their time in
// nanoseconds.
checkpoints, checkpointTime atomic.Int64
// walFrames is the length of the WAL in frames as the last writer left
// it, and pageSize the page size of the file, 0 until a connection read
// it.
walFrames, pageSize atomic.Int64
// errs counts the errors calls returned, by primary result code.
errs [256]atomic.Int64
// hits and misses are those of the connections of the file that closed
// (conn.hits).
hits, misses atomic.Int64
// replica gives how replication of the file stands, nil while it is
// not attached (replhook.SetStats).
replica atomic.Pointer[func() replhook.Stats]
}
// report is what Stats says of the file of l, whose connections had hits
// and misses and whose connectors have queues.
func (l *writeLock) report(hits, misses int64, queues []*queuehook.Queues) FileStats {
n := &l.n
f := FileStats{
Path: l.path,
Writes: WriteStats{
Commits: n.commits.Load(),
Merged: n.merged.Load(),
CommitTime: time.Duration(n.commitTime.Load()),
LockWaits: n.lockWaits.Load(),
LockWaitTime: time.Duration(n.lockWaitTime.Load()),
Busy: n.errs[BUSY].Load(),
},
WAL: WALStats{
Checkpoints: n.checkpoints.Load(),
CheckpointTime: time.Duration(n.checkpointTime.Load()),
},
Errors: n.errors(),
Statements: StatementStats{Hits: hits, Misses: misses},
Queues: []QueueStats{},
}
if page := n.pageSize.Load(); page > 0 {
f.WAL.SizeBytes = n.walFrames.Load() * (page + walFrameHeader)
}
var all []*queuehook.Queue
for _, r := range queues {
all = append(all, r.All()...)
}
// Two sql.DB of the file may each have opened the queue: their last
// counts are of the same rows, and the later one is given.
slices.SortStableFunc(all, queuehook.CompareQueues)
for i, q := range all {
if i+1 < len(all) && queuehook.CompareQueues(q, all[i+1]) == 0 {
if a, b := q.Counted(), all[i+1].Counted(); a != nil && (b == nil || a.At.After(b.At)) {
all[i+1] = q
}
continue
}
f.Queues = append(f.Queues, queueStats(q))
}
if g := n.replica.Load(); g != nil {
s := (*g)()
f.Replica = &ReplicaStats{StagedTXID: s.Staged, UploadedTXID: s.Uploaded, PendingBytes: s.Pending, UploadError: s.Err}
}
return f
}
// statsPageSize reads the page size of the file of c, which holds the write
// lock l and has read the WAL of the file, for the length of the WAL that
// Stats gives. It does not change in WAL mode, and SQLite has it from the
// file already, so the read does nothing on the file. It is called without
// l.mu, and leaves walPage, which the WAL limit reads, to restartWAL.
func (c *conn) statsPageSize(l *writeLock) {
size, err := pragmaInt(c.c, "page_size")
if err != nil || size <= 0 {
return // the next writer reads it
}
l.n.pageSize.Store(size)
l.pageRead = true
}
// queueStats is what Stats says of q.
func queueStats(q *queuehook.Queue) QueueStats {
s := QueueStats{Table: q.Table, Name: q.Name, Subs: []QueueSubStats{}}
if c := q.Counted(); c != nil {
s.AsOf = c.At
for _, b := range c.Subs {
s.Subs = append(s.Subs, QueueSubStats{
Sub: b.Sub, Waiting: int64(b.Waiting), Delayed: int64(b.Delayed), Held: int64(b.Held), Dead: int64(b.Dead),
OldestWaitTime: b.OldestWait,
})
}
}
return s
}
// errors is what Stats says of the errors counted.
func (n *counters) errors() ErrorStats {
e := ErrorStats{OtherCodes: map[string]int64{}}
for code := range n.errs {
v := n.errs[code].Load()
if v == 0 {
continue
}
switch code {
case FULL:
e.Full = v
case IOERR:
e.IO = v
case CORRUPT:
e.Corrupt = v
case CONSTRAINT:
e.Constraint = v
default:
e.Other += v
e.OtherCodes[codeName(code)] = v
}
}
return e
}
// codeNames are the names of the primary result codes, as in codes.go.
var codeNames = [...]string{
ERROR: "ERROR", INTERNAL: "INTERNAL", PERM: "PERM", ABORT: "ABORT", BUSY: "BUSY",
LOCKED: "LOCKED", NOMEM: "NOMEM", READONLY: "READONLY", INTERRUPT: "INTERRUPT",
IOERR: "IOERR", CORRUPT: "CORRUPT", NOTFOUND: "NOTFOUND", FULL: "FULL",
CANTOPEN: "CANTOPEN", PROTOCOL: "PROTOCOL", EMPTY: "EMPTY", SCHEMA: "SCHEMA",
TOOBIG: "TOOBIG", CONSTRAINT: "CONSTRAINT", MISMATCH: "MISMATCH", MISUSE: "MISUSE",
NOLFS: "NOLFS", AUTH: "AUTH", FORMAT: "FORMAT", RANGE: "RANGE", NOTADB: "NOTADB",
NOTICE: "NOTICE", WARNING: "WARNING",
}
// codeName is the name of a primary result code, its number for one SQLite
// 3.54.1 does not have.
func codeName(code int) string {
if code < len(codeNames) && codeNames[code] != "" {
return codeNames[code]
}
return strconv.Itoa(code)
}
// noteErr counts err, which a call of the program on c returns, for Stats,
// and returns it. A database in memory has no file to count it for.
func (c *conn) noteErr(err error) error {
if err != nil && c.wl != nil {
c.countErr(err)
}
return err
}
// countErr counts err by its result code, when it is SQLite's.
func (c *conn) countErr(err error) {
var e *Error
if errors.As(err, &e) {
c.wl.n.errs[e.Code()].Add(1)
}
}
// started is the start of clock.
var started = time.Now()
// clock is the time since started, on the monotonic clock: a request keeps
// the time a batch took it in 8 bytes this way, where a time.Time takes 24
// and would make every request of group commit larger.
func clock() time.Duration { return time.Since(started) }
// hold marks c as holding the write lock, which it was just given.
func (c *conn) hold() {
c.writing = true
c.noteHeld()
}
// noteHeld notes the rows c changed and the transactions it rolled back so
// far, so that countCommit counts only what comes after. Rows change only
// while a connection holds the write lock, but a read transaction ends
// with a rollback, also without it.
func (c *conn) noteHeld() {
c.runTime = 0
if !c.c.Broken() {
c.heldChanges, c.heldRollbacks = c.c.TotalChanges(), c.c.Rollbacks()
}
}
// countCommit counts a commit of c, which gives the write lock l back out
// of any transaction, when c changed rows since it took the lock and rolled
// nothing back: it committed them.
func (c *conn) countCommit(l *writeLock) {
if c.c.Broken() {
return // it runs no C
}
changes, rollbacks := c.c.TotalChanges(), c.c.Rollbacks()
if changes != c.heldChanges && rollbacks == c.heldRollbacks {
l.n.commits.Add(1)
l.n.commitTime.Add(int64(c.runTime))
}
c.heldChanges, c.heldRollbacks, c.runTime = changes, rollbacks, 0
}
// setReplicaStats is replhook.SetStats.
func setReplicaStats(path string, stats func() replhook.Stats) error {
file, err := fileOf(path)
if err != nil {
return err
}
writeLocks.Lock()
defer writeLocks.Unlock()
l := findWriteLock(file)
if l == nil || !l.attached {
return errors.New("sqlite: " + path + " is not replicated")
}
l.n.replica.Store(&stats)
return nil
}