NaviServer Programmable Web Server

ns_stats(n)

NaviServer Tcl Library – 5.2.0a


[ Main Table Of Contents | Table Of Contents | Keyword Index ]

Name

ns_stats - NX diagnostics, shared sampling and optional SQLite history

Table Of Contents

Synopsis

Description

ns_stats is an optional NSF/NX application in the standard Tcl library. It is available when NX is loaded at server initialization. Sampling and history are off by default. The interface requires the NaviServer 5.2 process-scoped nsv array support; copying this Tcl file into an older server does not enable the command. The command registers no HTTP endpoint and makes no authorization decisions. Consumers such as nsstats and MCP apply their own access and presentation policy.

CONFIGURATION

ns/stats

Startup configuration for process-wide ns_stats sampling and optional SQLite history. Requires Tcl 8.6 or newer and NSF/NX. Sampling covers every virtual server; server selects the interpreter and history-pool owner. These settings are independent of MCP and nsstats consumers. They are applied after module initialization. Runtime ns_stats commands can override them until restart without rewriting the configuration. Stop/start sampling to change its interval; disable/configure history to change active persistence settings.

 ns_section ns/stats {
     ns_param server           default
     ns_param sampling         true
     ns_param samplingInterval 10s
     ns_param samplingRetention 15m
     ns_param samplingMaxSamples 180
     ns_param historyPool      ns_stats
     ns_param historyRetention 24h
     ns_param historyMaxBytes  64MiB
 }
Parameter name: historyMaxBytes

Persistent history size budget in bytes, including reserved journal headroom. Minimum is 4MiB. Applies when historyPool is set.

  • Type: size

  • Default: 64MiB

Parameter name: historyPool

Dedicated native nsdbsqlite pool for persistent diagnostics. A nonempty value enables history; an empty value disables it. Configure the pool separately and make its directory writable by the NaviServer account. Do not share the access-log cache.

  • Type: string

  • Default:

Parameter name: historyRetention

Retention of persistent samples, normalized to seconds. Valid range is 60 seconds..7 days. Applies when historyPool is set.

  • Type: time

  • Default: 24h

Parameter name: sampling

Start the shared process-wide sampler at startup. Independent of history persistence; defaults to disabled.

  • Type: boolean

  • Default: false

Parameter name: samplingInterval

Sampling cadence, normalized with ns_baseunit to seconds, including fractional seconds. Valid range is 1..3600 seconds. Rates use the measured interval between observations.

  • Type: time

  • Default: 10s

Parameter name: samplingMaxSamples

Maximum number of samples retained in memory, 2..10000. A window needs at least ceil(window / samplingInterval) + 1 samples including both endpoints: at 10-second cadence a one-hour window requires at least 361. Larger age/count limits retain more data in memory. Restart after configuration changes.

  • Type: integer

  • Default: 180

Parameter name: samplingRetention

Maximum age of in-memory samples used for display windows. Valid range is 1 second..24 hours. Both this age limit and samplingMaxSamples apply. Restart after changing the configuration; allow the requested continuous history to accumulate. This is independent of SQLite historyRetention.

  • Type: time

  • Default: 15m

Parameter name: server

Virtual server whose interpreters run sampling and persistence. Specify explicitly on multi-server installations. Must be a configured virtual server with access to historyPool through ns/server/SERVER/db.

  • Type: string

  • Default: first entry returned by ns_info servers

COMMANDS

ns_stats describe ?-server value?

Returns a Tcl dictionary with schemaVersion, process identity/version/build, platform, drivers, virtual servers, pool limits, module metadata and database-pool associations. Driver bindings include the available host-mapping configuration. Only selected configuration fields are returned; callback scripts and credentials are not collected. Unsupported optional facilities have availability flags.

ns_stats snapshot ?-server value?

Collects current gauges and cumulative counters without advancing the shared sampling baseline. The result includes collection duration and a microsecond epoch timestamp. Servers/pools expose counters, threads, active and waiting requests. Pool gauges contain activeRequests, waitingRequests and threads; pool counters include requests, queued, spooled and dropped. queued counts cumulative queueing events, not current queue depth. Drivers expose cumulative counters (received, partial, spooled, errors) and current socketStates (reading, waitingForConnection, closing). waitingForConnection means parsed requests awaiting an available connection structure; pool waitingRequests await connection threads. Writer and spooler queue statistics are not collected. CPU counters are microseconds, matched by OS thread ID and creation time. Numeric allocator properties are bytes; they are not process RSS. No active-request URLs, peer addresses or thread callback arguments are retained.

On Linux, linuxNetwork contains cumulative counters, current socket queue gauges, and block-device disks observations. Unsupported or failed probes remain unavailable; availability.linuxNetwork indicates whether any observations were collected. Network counters cover the current network namespace, including other services; socket queue gauges aggregate only sockets owned by NaviServer. No socket identities or peer addresses are retained. These optional probes run as part of the existing snapshot, including scheduled sampling, and do not create another scheduler.

ns_stats sample ?-server value? ?-window value?

Without -window, reads the latest published record without collecting or modifying it. sampling contains ready, from/to epoch seconds, measured elapsedSeconds, ageSeconds, reset, intervalSeconds and running. Without a baseline, ready is false and interval values are empty. Published records add per-pool and per-driver deltas/rates, per-pool timingAverageSeconds and process-scoped cpuPercent. CPU 100 percent means one CPU core. cpuPercent reports observed/matched thread counts; group totals only include threads with a valid baseline. Counter decreases invalidate the affected metric and list it in resetCounters. New threads do not inherit old CPU baselines. Unavailable values are empty Tcl values with availability/readiness information; JSON consumers should represent these as null, never as zero.

Derived samples also contain previousLinuxNetwork, the Linux observations at the matching baseline endpoint, or an empty dictionary when no valid process baseline exists. Consumers derive Linux counter changes and disk latencies using these endpoints and sampling.elapsedSeconds; counter decreases and missing values are unknown. Both endpoints are retained in memory and persistent history without a database schema migration. Older records may lack these optional fields. Historical loss events can be located only to their measured intervals, not to an exact instant within an interval; missing history is not evidence of zero loss.

-window selects a display period from the bounded recent memory buffer, without changing the sampling schedule. The default 0 uses the latest single interval. Values up to the configured memory window limit accept time units, for example 60s. A fresh snapshot is compared with the retained endpoint nearest the requested age, within half a sampling interval. This does not publish a sample or advance the background sampler baseline. Rates, request timing averages and CPU use these endpoints; current gauges come from the fresh snapshot. The actual period is reported in sampling.elapsedSeconds. Insufficient history, a gap or a sampler restart leaves ready false and reports incompleteReason; the command does not silently substitute a shorter period. SQLite is not needed.

-server filters server/pool data. Drivers, CPU and allocator data remain explicitly process-scoped and must not be attributed to the selected virtual server. Snapshots are observations collected over a short interval, not an atomic freeze of the whole system. Capacity estimates and status thresholds belong to consumers.

process.cpuCapacity reports CPU ceilings on Linux: hostLogicalCpus, affinityCpus, cpusetCpus, quotaCores and effectiveCores. The collector resolves cgroup v1/v2 mounts and walks visible parents, taking the minimum observed ceiling, including fractional quotas. quotaStatus distinguishes limited, unlimited and unknown. constraintsComplete and incompleteReasons describe visible-limit availability, not a CPU reservation. Hidden ancestor constraints, CPU shares and host contention can reduce actual available capacity. Unsupported platforms or inaccessible files leave unknown values empty, never zero.

throttlingAvailable marks available cgroup CPU counters. throttling keeps each visible CPU group separate, with path, periods, throttledPeriods and throttledSeconds. Samples add deltaPeriods, deltaThrottledPeriods, deltaThrottledSeconds and throttledPeriodPercent when a valid same-process baseline exists; missing or decreased counters produce empty derived values. These counters include other processes, and ancestors may include siblings. Do not sum ancestors or interpret throttled period percentage as CPU utilization. Compare process CPU core equivalents with the qualified effectiveCores ceiling for the same sample period. Existing history without capacity data remains unknown.

ns_stats sampling start ?-interval value?

Time arguments accept NaviServer units and fractional seconds, for example 1500ms. They are normalized to seconds with ns_baseunit. Starts one process-wide sampler, defaulting to 10 seconds (range 1..3600). Definitions and configured interface objects are in the blueprint. Calling start again with the same interval reuses the scheduler; a different interval is rejected. The scheduler uses the activating server's interpreters. Its live state is held in the process-scoped ns_stats nsv array; coordinated updates use nsv_array eval. SQLite work occurs outside that coordination lock. The first sample has no interval baseline. Restarting a stopped sampler also discards its baseline rather than counting the stopped period.

ns_stats sampling status

Returns running, interval, scheduler, process instance, readiness, sample age, latest publication and collection failure counters. A sample's age is not a measurement of traffic latency. Also returns retentionSeconds, maxSamples, maxWindowSeconds (the smaller of the configured retention and the duration supported by the sample count/cadence), and availableWindowSeconds (continuous retained history in the current sampler instance). Available history may be shorter than the configured limit after startup, gaps or eviction.

ns_stats sampling stop

Stops scheduled collection and retains the last sample, which remains readable with running false and increasing age.

ns_stats storage stalls ?-server value? ?-limit integer?

Returns compact, sparse storage observations from the background sampler, oldest first. Does not probe devices, scan logs, issue SQL or change the sampler baseline. The default limit is 128 (1..10000). The result contains records, omittedRecords (older retained records excluded by the requested limit), retentionSeconds, maxRecords and source background-sampler. The buffer is bounded, not a complete incident log; age/count eviction is independent of SQLite history. Settings in ns/stats are storageStallThresholdMs (default 20), storageStallRetention (default 1h), and storageStallMaxRecords (default 128). Each record identifies interval bounds in epoch seconds, an epoch-microsecond timestamp, sampler instance, device, operation, completed operations, operationsPerSecond and mean latencyMs. When available it includes device-wide averageQueueDepth, utilizationPercent, endpoint inFlight and writeQueue. requestQueues maps server/pool names to endpoint waiting-request gauges; -server restricts this context, not host-wide disk observations. Missing metrics are omitted. Queue depth includes service as well as waiting, stacked devices must not be summed, and correlation does not establish causation. These are interval means, not individual I/O traces or maxima. SQL statements, slow-SQL events, file paths and peer identities are not collected. First, idle, reset and missing baselines do not produce records; intervals exceeding 1.5 times the sampling cadence are excluded. The buffer survives sampler stop/start and Tcl reload, but not process restart. Start sampling to enable recording.

ns_stats sampling history -from integer -to integer ?-server value? ?-limit integer? ?-cursor integer?

Reads compact recent samples from the existing process-wide NSV storage, without SQLite. Publication applies both ns/stats settings samplingRetention (default 15m, 1 second..24 hours) and samplingMaxSamples (default 180, 2..10000 samples). A one-hour display window at 10-second cadence needs samplingRetention 1h and at least 361 samples, including both endpoints. Restart after changing configuration and allow the requested continuous history to accumulate. Larger limits use more memory. The SQLite historyRetention setting is independent of these memory limits. Records contain interval rates, timing averages and grouped CPU percentages; raw and per-thread CPU maps are omitted. The buffer remains readable after sampling stops and survives sampler stop/start, but not a process restart. Use SQLite history for longer retention and persistence across restarts. The epoch window is limited to 24 hours, limit to 1..180 (default 180), and cursor to a nonnegative microsecond timestamp. Follow nextCursor while more is true. Coverage reports retained bounds, gaps, restart/reset boundaries and droppedThrough; missing intervals are not zero traffic. Reading does not collect or change sampling.

ns_stats history configure -pool value ?-retention value? ?-maxBytes value?

Enables the optional SQLiteHistory mixin using a configured native nsdbsqlite pool. No Tcl sqlite3 package is required. Use a dedicated persistent database; other application tables are rejected. Retention accepts time units and fractional seconds; maxBytes accepts memory-size units (for example 64MiB). Values are normalized with ns_baseunit. Defaults: retention 86400 seconds, maxBytes 67108864 bytes. Retention range is 60..604800 seconds; minimum budget is 4 MiB. Sampling must be activated separately. Identical configuration is idempotent; disable history before changing its settings. The configuring virtual server must have access to the pool. Pool handles are operation-local and never enter a blueprint.

Persistence runs on a separate scheduled callback, checking once per second for an unpublished timestamp. Database work never holds the live publication mutex. Samples are committed atomically, deduplicated by timestamp, compressed with zlib and stored as hex text. Repeated topology is stored separately. Age and byte pressure evict old samples. SQLite main-file pages are limited to 45 percent of maxBytes, reserving space for journal files and overhead. Freed pages are reused; actual retained duration can be shorter than the configured maximum. The file is private (0600); provision its writable parent directory separately.

SQLite connection policies belong to ns/db/pool/POOL/sqlite, including journalMode and synchronous. History does not override them. Unspecified policies retain the driver/SQLite defaults. Configure DELETE/NORMAL explicitly when that policy is desired, or WAL/NORMAL for overlapping readers. WAL/NORMAL permits concurrent readers and a writer while preserving consistency, but recent commits can be lost after a system crash. OFF can require rebuilding the history database after a system crash. Lost runtime samples cannot be reconstructed from access logs. Select FULL or EXTRA when stronger crash protection is required. Pool size is unchanged; a second handle only helps when operations overlap, and SQLite still permits only one writer.

The main-file page cap still reserves journal headroom. With WAL, a long-lived reader can prevent checkpoint completion and allow the WAL to exceed this headroom; maxBytes is not a hard aggregate WAL-file size limit.

Write failures keep live sampling available, increment status counters and report warnings (repeated identical failures are throttled to once per minute). A later successful write records the failed interval. After a crash while the database is unavailable, precise failure counts may be lost, but missing sample intervals and new process identities remain visible in history coverage.

ns_stats history status

Reports enabled, owner server, pool, retention/budget, latest saved timestamp, failure count and last failure. This reads shared state without opening the database.

ns_stats history disable

Stops future history callbacks without stopping live sampling or deleting rows. An already running write can complete. Disabled configured history remains queryable.

ns_stats history storage

Returns database-wide retainedFrom/retainedTo (epoch seconds, empty when no samples), retainedSeconds, sampleCount, pageSize, allocatedBytes, usedBytes, freeBytes, databaseLimitBytes, maxBytes, bytesPerSample and bytesPerSecond. Query in the history owner server. Reads SQLite metadata without decompressing sample payloads. Allocated bytes include reusable free pages; used bytes exclude them. A sample count of zero gives empty per-sample/rate estimates. These are database estimates, not total filesystem usage including temporary rollback journals.

Use retained bounds to measure actual history depth. maxBytes includes journal headroom: the database cap is approximately 45 percent of that budget, and size pruning targets 80 percent of the cap. With representative steady-state samples, estimate a desired budget as bytesPerSample times the desired sample count divided by 0.36, then add safety margin. Sample count is desired duration divided by sampling interval. Payload sizes, topology changes, gaps and restarts can change the estimate; repeat measurements under representative load. Changing the budget at runtime requires history disable followed by history configure; update ns/stats for future restarts.

ns_stats history allocator -from integer -to integer ?-limit integer? ?-cursor integer?

Returns compact, process-wide allocator history from the history owner server. The epoch interval is inclusive at from and exclusive at to, at most 24 hours, ending no later than now. Limit is 1..10000 (default 10000). records contain only timestamp (microseconds), instance, sampling.intervalSeconds and memory. Memory contains available current_allocated_bytes, heap_size and total_physical_bytes; missing gauges remain absent. Process identity and cadence allow callers to preserve restart boundaries and sampling gaps. more and nextCursor use the same paging convention as history query.

New persisted samples include a small allocator projection, avoiding full snapshot and topology decoding. Existing databases receive a nullable column automatically on configure/save; old rows are still readable by decoding their original payload. Queries do not backfill or modify stored samples. legacyDecoded reports the number of such rows decoded in this response. One bounded sample SELECT reads each page; there is no full-window coverage rescan. Consequently coverage.complete and coverage.windowExamined are false: this projection does not certify retained boundary coverage, eviction or write-failure absence. Use history query when that certification is required. timings reports checkoutMs, readMs, decodeMs and totalMs in milliseconds; checkout includes connection setup, read covers the sample SELECT, and decode includes compact-point construction and any legacy decompression.

ns_stats history query -from integer -to integer ?-server value? ?-limit integer? ?-cursor integer?

Returns historical records, referenced topologies and coverage. Query from the history owner server; the selected historical server need not still be configured. Windows are inclusive at from and exclusive at to, at most 24 hours, ending no later than now. Limit is 1..1000, default 1000. nextCursor is an opaque-to-the-consumer microsecond timestamp; pass it unchanged to retrieve the next page. more identifies pagination. Querying never rewinds sampling or writes new samples.

Coverage includes retained bounds, gaps, process restart boundaries, reset samples, eviction/failure events and the cumulative eviction high-water mark. Each process gets a new instance identity; interval rates are never calculated across restarts. Gaps are detected using recorded sampling cadence, including gaps spanning an empty query window. Events are bounded to the latest 64; cumulative droppedThrough retains conservative eviction coverage. complete is conservative and requires examination of the whole window (windowExamined), retained endpoint coverage and no observed gaps, resets or overlapping eviction/failure information. Intermediate pages have coverage.scope=page and windowExamined=false. The final page (more=false) re-examines the entire requested window in the same read transaction, independently of cursor, and returns coverage.scope=window and windowExamined=true. Earlier-page gaps and resets remain visible in this final summary. incompleteReasons explains failure to certify coverage. Reading batches is bounded; only the final page performs the additional whole-window scan. This describes retained data at query time, not a snapshot held across requests; intervening eviction can conservatively prevent certification. Clients must still follow every page to retrieve all records. The storage dictionary reports database-wide retained bounds/count and space usage, independent of the requested window or cursor.

EXAMPLES

 ns_stats describe -server openacs.org
 ns_stats snapshot -server openacs.org
 ns_stats sampling start -interval 10
 ns_stats sample -server openacs.org
 ns_stats history configure -pool diagnostics -retention 86400 -maxBytes 67108864
 ns_stats history query -from [expr {[clock seconds]-3600}] -to [clock seconds]
 ns_stats history disable
 ns_stats sampling stop

SQLite Pool Configuration

 # Load nsdb as a server module and configure nsdbsqlite normally.
 ns_section ns/db/pools {
     ns_param diagnostics {NaviServer diagnostics history}
 }
 ns_section ns/db/pool/diagnostics {
     ns_param driver sqlite
     ns_param connections 1
     ns_param datasource ns_stats.db
 }
 # Include diagnostics in the owner's existing allowed pool list.
 # Activate from startup Tcl code after libraries and modules are initialized:
 ns_stats sampling start -interval 10
 ns_stats history configure -pool diagnostics

EXTENSION

::ns::stats::Collector and ::ns::stats::Sampler supply the measurements and sampling lifecycle. The configured interface is the object ::ns_stats, an instance of ::ns::ns_stats. ::ns::stats::SQLiteHistory is an optional object mixin: consumers can subclass it or override collection/history methods. Load variants into the blueprint. The persistence callback restores the configured mixin list in its interpreter; no database handle or transient object is serialized. NX ensemble methods provide the command interface and typed option parsing. The interface class is explicitly exported to the NX serializer, whose default policy excludes classes directly in the ::ns namespace. Scheduled sampling and persistence callbacks invoke the corresponding methods on ::ns_stats.

TESTING

The regression tests are part of the standard NaviServer test suite:

 make test TESTFLAGS="-file ns_stats.test"
 make test TESTFLAGS="-file ns_stats.test -match stats-history-failure-event"

The normal make test environment supplies library paths, locale and the NAVISERVER installation prefix. No NS_STATS-specific environment variables are needed. Collection and sampling cases require NX; persistence cases also require the native nsdbsqlite driver under NAVISERVER/bin. Missing optional components are reported as tcltest constraint skips.

The tests reuse the standard test servers and listener, configure an isolated SQLite pool when available, restore shared sampler state and remove temporary history files. A fresh child process verifies that persisted history survives restart without using a previous process's counter baseline. Individual cases have their own fixtures and can be selected with the usual -match option.

See Also

ns_db, ns_driver, ns_info, ns_server

Keywords

NSF, NX, SQLite, diagnostics, history, sampling, statistics, utilization