MS SQL [Tab]
0) Big picture
On each managed device (Windows/Linux/k8s node):
- Agent (service/daemon)
- Collectors
- SQL collectors: instance inventory, configuration, storage, security, error log, databases/files, jobs, metrics, AG topology, backups, DB health.
- Service collectors: generalized service inventory + OS/k8s/cloud status, endpoints, and service-level metrics for SQL Engine/Agent/Browser and any other product (IIS, Redis, NGINX, Kafka, etc.).
- Synthetic checks (optional): TCP/HTTP probes for exposed endpoints.
- Scheduler: cadence tiers (discovery / snapshots / metrics).
- Local SQLite cache:
- Mirrors of selected server tables (trimmed types).
- Lookup catalogs mirror (ref_*) with code→id mapping.
- identity_map (natural-key→UUID), outbox (deltas), collection_ledger (when/what ran).
- Sync client: batches idempotent ops to server.
Server (PostgreSQL + API):
- Catalog endpoints to deliver ref_* lookup rows to agents (by code).
- Ingest API (idempotent upserts; resolves lookup codes→IDs).
- Merge/workers to compute rollups, findings, KPIs, and alerts.
Security: mutual TLS or signed bearer; store SQL creds in OS keystore (DPAPI/libsecret), never plaintext.
1) Lookup catalogs (how agents use them)
- Source of truth: server ref_* tables (service kind/product/provider/platform/environment, endpoint protocol/type, metric name, health status, service status, start mode).
- Agent boot:
- Call GET /v1/catalog?since=… to download active ref_*.
- Cache them in SQLite (ref_* mirrors). Index by code and store the server id.
- During collection:
- Always emit lookup values as code in payloads (e.g., product='MSSQL', service_status='Running', metric_name='CpuPct').
- Server resolves code→id. If a new code appears, server auto-creates an active ref row (or rejects if locked down, your choice) and returns its id.
- Benefits: agents don’t break when catalogs evolve; tenant overrides still work (server maps to correct per-org row).
2) Schedules & cadences
Tier | Interval (default) | What runs |
|---|---|---|
Discovery | on start & hourly | SQL instance discovery, databases list, service discovery (Engine/Agent/Browser/Other services), endpoints, AG membership |
Snapshots | 15–60 min | SQL config/storage/security/error log/backup coverage/DB health; service status & endpoints |
Metrics | 1–5 min | SQL perf metrics (CPU/PLE/BufferHit/BatchReq); service metrics (status, CPU, memory, restarts, port listening, latency) |
Heavy/nightly | 24h (off-peak) | Fragmentation sampling, extended security audits, long error-log scans |
3) Data collection (what to run and where it goes)
3.1 Service discovery & status (generic)
Windows (SCM/WMI/PowerShell)
- Enumerate: Get-Service 'MSSQL*','SQL*','SQLBrowser','SSRS*','SSIS*','SSAS*' (+ any extra services you support).
- Details: Win32_Service → Name (service_name), DisplayName, PathName (binary_path), StartMode (start mode), State→ runtime status.
- Process: map service → PID; Get-Process -Id for CPU %, WorkingSet MB, Handles, Threads.
- Ports: Get-NetTCPConnection or netstat -ano; join by PID to list endpoints.
- Restarts: EventLog (7031/7034/7036) in last 24h → crash_count_24h.
Linux (systemd)
- systemctl show <unit>: ActiveState, ExecMainPID, ExecMainStartTimestamp, FragmentPath.
- /proc/$PID or ps -o pcpu,rss for CPU/mem.
- ss -ltnup for port listeners; join by PID.
Kubernetes
- List Deployments/StatefulSets/Pods; compute service runtime status from pod phases & container restarts (crash_count_24h); capture ports from container specs; store platform='Kubernetes', cluster_name, namespace.
Cloud PaaS (e.g., AWS RDS/Azure SQL)
- Use cloud APIs (DescribeDBInstances/etc.) to map status and metadata; start_mode='NotApplicable'; no local PID.
Persist → monitored_service
- Natural key (agent):
- Host-bound: device_id|service_name
- Cloud: organization_id|provider|region|service_name
- Columns: taxonomy via lookup IDs (resolved server-side from code), identity fields, runtime service_status_id, start_mode_id, pid, uptime_seconds, last_start_time, crash_count_24h, listen_endpoints JSON (quick view), health rollup (see §5), detail JSON.
Normalize endpoints (optional) → monitored_service_endpoint
- For each port: upsert (service_id, protocol_id, port, ip, name, endpoint_type_id, tls_enabled, path).
- Keep the array in listen_endpoints too for quick reads; use the table when you need filtering/alerting by port/protocol.
Service metrics → service_health_metric
- Emit per metric:
- ServiceStatus (1/0)
- CpuPct, MemoryRSSMB, Threads, Handles
- Restarts24h
- PortListening (per endpoint; store port/protocol in extra)
- Optional synthetic: HTTP_2xxRate, LatencyMs, TLSExpiryDays
- Evaluate status via thresholds (see §5) and store status_id + threshold_snapshot.
Link to SQL domain
- For SQL Engine/Agent/Browser, one of:
- Set monitored_service.instance_id (if discovered SQL instance exists), and/or
- Add a service_binding row with bound_entity_type='sql_server_instance' & bound_entity_id=….
3.2 SQL instance inventory →
sql_server_instance
Use T-SQL (minimal round trips):
Ports
- Windows: registry ...SuperSocketNetLib\Tcp\IPAll\TcpPort.
- Linux: /var/opt/mssql/mssql.conf or SELECT local_tcp_port FROM sys.dm_exec_connections WHERE session_id = @@SPID;.
Persist
- Upsert (device_id, instance_name); fill columns; put extras in discovery_detail.
- Also populate sql_instance_config_snapshot (full sys.configurations into config_map + default paths), sql_instance_endpoint (TDS/DAC/HADR), sql_instance_storage_summary, sql_instance_security_summary, sql_instance_errorlog_summary.
3.3 Databases & files
- sql_database: name/status/owner/size/recovery/collation/TDE/created_at + latest backup times from msdb..backupset (join by db name).
- sql_database_file: per DB file: file_id, logical/physical, type, size/max, autogrowth settings.
3.4 Agent jobs
- sql_agent_job: metadata + last/next run (from msdb..sysjobs, sysjobhistory, sysjobschedules), steps/schedule in JSON.
- (Optional) sql_agent_job_run: one row per new outcome (step_id=0) with start/finish/outcome; keep excerpt of messages.
3.5 SQL metrics →
sql_instance_metric_sample
Every 1–5 min:
- CPU %, Memory %, PLE (sec), Buffer Cache Hit Ratio %, Batch Requests/sec.
- Evaluate with thresholds (see §5) → status.
- (If you later migrate to lookup-based metrics here, send metric_name codes that match ref_metric_name.code.)
3.6 AG topology
- sql_availability_group, sql_availability_replica from sys.availability_groups, sys.availability_replicas, sys.dm_hadr_* views.
3.7 Backup coverage snapshot
- sql_backup_status_snapshot: per instance rollup of full/diff/log backups in last 24h, max full age, lists of DBs missing coverage.
3.8 DB health snapshot
- CHECKDB recency (parse ErrorLog or maintenance tables), fragmentation (sampled dm_db_index_physical_stats), DBCC SQLPERF(LOGSPACE) for log %, approximate data free %.
- Persist → sql_database_health_snapshot.
4) Local SQLite design (agent)
Pragmas
Core meta
- identity_map(entity_type TEXT, natural_key TEXT, id TEXT PRIMARY KEY(entity_type,natural_key))
- outbox(id INTEGER PK AUTOINCREMENT, entity_type TEXT, entity_id TEXT, op TEXT CHECK(op IN ('UPSERT','DELETE')), payload TEXT, created_at TEXT)
- collection_ledger(collector TEXT PRIMARY KEY, last_started_at TEXT, last_finished_at TEXT, last_success_at TEXT, last_error TEXT)
Lookup mirrors
- Tables mirroring ref_* with id TEXT, code TEXT, label, active, plus needed joins (e.g., ref_metric_name with default_unit, default_comparator).
- Index by code. Agent always uses code internally.
Mirrors of domain tables
- Subset of columns, JSON fields as TEXT, booleans as 0/1, timestamps as ISO-8601 TEXT in UTC.
- Add a hash TEXT (SHA256 over canonical JSON sans audit) to each mutable mirror to detect deltas.
Natural keys (agent)
- monitored_service: host → device_id|service_name, cloud → organization_id|provider|region|service_name
- monitored_service_endpoint: service_id|protocol|port|ip|path
- service_health_metric: append-only (service_id|collected_at|metric_name)
- sql_server_instance: device_id|instance_name
- sql_database: instance_id|name
- sql_database_file: database_id|file_id
- sql_agent_job: instance_id|name
- Snapshots & metrics: append-only (use (parent_id, collected_at[, metric_name]) uniqueness).
Delta algorithm
- Build canonical JSON (sorted keys; drop id/created_at/updated_at/active).
- Compute hash.
- If new or hash changed → enqueue UPSERT to outbox.
- If entity disappeared → enqueue DELETE (or set active=0 locally).
Retention
- Metrics: keep N (e.g., 10k) rows. Snapshots: 30 days. Job runs: 30–90 days. Daily trim task.
5) Thresholds, statuses, and health rollups
Catalog
- All metric names live in ref_metric_name(code, default_unit, default_comparator, …).
- Agent emits metrics using code; server resolves to id.
Threshold table (server)
- Use your existing sql_metric_threshold and treat metric_name as a code that matches ref_metric_name.code.
- scope JSON can point to an instance or a service:
- For SQL metrics: {"instance_id":"…"}
- For service metrics: {"service_id":"…"} or by product/service_kind (you can expand to accept {"product":"MSSQL"}).
Evaluation
- For each sample (SQL or service), fetch applicable threshold (most specific wins), apply default_comparator unless overridden in row.
- Produce status/status_id and store threshold_snapshot with the exact numbers used.
Service health rollup (for monitored_service.health_status_id)
- Rule of thumb (compute at ingest):
- If service_status != Running → rollup = Critical.
- Else if any metric Critical in last N minutes → Critical.
- Else if any metric Warning in last N minutes → Warning.
- Else → Good.
- Persist rollup on the service row for fast list views.
6) Sync protocol (agents → server)
Batch envelope (example)
Server ingest
- Resolve codes→IDs using ref_* caches; auto-create unknown codes if allowed.
- Enforce natural-key uniqueness with ON CONFLICT on server tables:
- monitored_service: (organization_id, COALESCE(device_id,UUID_ZERO), service_name)
- Other entities per their unique constraints.
- Idempotency: ignore duplicate batch_id/op_id.
- DELETE ops → soft delete (active=false) and updated_at=now().
ACK & cleanup
- Return accepted_op_ids[] + rejected[].
- Agent deletes accepted from outbox, logs rejected with reason, and retries after exponential backoff.
7) What table stores what (cheat sheet)
Generic service layer
- monitored_service: one row per OS/cloud/k8s service (Engine, Agent, Browser, IIS, Redis, etc.). Holds taxonomy (via lookups), runtime service status, start mode, PID/uptime, endpoints (inline JSON), overall health rollup, and extended details.
- monitored_service_endpoint: normalized per-endpoint rows (protocol/port/ip/path/tls). Use when filtering, probing, or alerting by endpoint.
- service_health_metric: time-series for service-level KPIs (status, CPU, memory, restarts, port listening, HTTP latency/codes, etc.).
- service_binding: polymorphic links to domain objects (e.g., sql_server_instance, RDS resource, k8s deployment).
SQL domain
- sql_server_instance: instance identity, version, edition, sp_configure highlights, connectivity, HW/licensing, AG flags.
- sql_instance_config_snapshot: full sys.configurations + default paths.
- sql_instance_storage_summary: tempdb, drive space summaries, growth policy.
- sql_instance_security_summary: SA status, principals, TDE, auditing.
- sql_instance_errorlog_summary: 24h counts + last error, sample lines.
- sql_instance_endpoint: TDS/DAC/HADR endpoints (SQL-aware).
- sql_database & sql_database_file: database catalog and files.
- sql_agent_job & sql_agent_job_run: agent jobs & sampled run history.
- sql_instance_metric_sample: SQL perf counters (CPU, PLE, BufferHit, Batch/s).
- sql_availability_group & sql_availability_replica: AG topology.
- sql_backup_status_snapshot: backup coverage rollup.
- sql_database_health_snapshot: CHECKDB/fragmentation/capacity.
- sql_metric_threshold: thresholds for evaluating samples (both SQL & service metrics via scope).
- (Optional) sql_instance_daily_kpi: aggregated KPIs per day.
Lookup catalogs
- ref_*: service taxonomy, providers, platforms, environments; endpoint protocol/type; metric names; status/start-mode catalogs; (SQL-specific: recovery model/DB status/HADR roles if you choose to normalize them later).
8) Mapping rules (agent → server)
From raw values to lookup codes
- Service:
- service_kind_code: ‘Database’ for SQL Engine/Agent/Browser; other products accordingly.
- product_code: ‘MSSQL’, ‘Redis’, ‘IIS’, ‘NGINX’, etc.
- provider_code: ‘OnPrem’ | ‘AWS’ | ‘Azure’ | …
- platform_code: ‘Windows’ | ‘Linux’ | ‘Kubernetes’ | ‘CloudService’
- environment_code: customer-tagged (‘Prod’/’Dev’/…).
- service_status_code: map from OS states (Running/Stopped/…).
- start_mode_code: map from SCM/systemd modes (Auto/Manual/Disabled/NotApplicable).
- Endpoint:
- protocol_code: ‘TCP’ | ‘UDP’ | ‘HTTP’ | ‘HTTPS’ | ‘gRPC’ | …
- endpoint_type_code: ‘TSQL’ | ‘DAC’ | ‘HADR’ | ‘HTTP’ | …
- Metrics:
- metric_name_code: ‘CpuPct’, ‘MemoryRSSMB’, ‘PortListening’, ‘HTTP_5xxRate’, ‘ServiceStatus’, ‘BatchRequestsPerSec’, etc.
- status_code: ‘Good’ | ‘Warning’ | ‘Critical’ | ‘Unknown’ (after evaluation).
Joining service↔SQL
- Prefer setting monitored_service.instance_id for MSSQL Engine/Agent; additionally create a service_binding if you need many-to-one semantics (e.g., a proxy service that “backs” multiple instances).
9) Error handling, resilience, and guardrails
- Collectors must degrade gracefully (e.g., missing permission to read ErrorLog) and write messages to collection_errors on the snapshot table.
- SQL connectivity failures:
- Set sql_server_instance.connectable=false, still populate service rows (Engine/Agent status) so you can alert that SQL isn’t reachable while OS services might be up/down.
- Backoff on high CPU or long-running queries; enforce per-collector time budgets (e.g., 30–60s).
- Protect secrets (never send creds in payloads). Sign/verify batches (HMAC device key).
10) Retention & rollups
- SQLite: metrics 10k rows per entity; snapshots 30 days.
- Server:
- Raw metrics >90 days → downsample (hourly/daily).
- Job runs & error-logs: 90–180 days (configurable).
- Snapshots: 180–365 days.
- Daily KPIs: 13 months.
11) Testing checklist
- Catalog sync: unknown codes are created or rejected per policy; agent can continue.
- Identity stability: instance rename, service rename, AG failover; natural keys still map to same UUID or intentionally create new rows per design.
- Delta hashing: ensure stable canonicalization (sorted keys; normalized numbers/booleans) to avoid false positives.
- Load: 1 host with 3 instances, 100+ DBs, 400 files, 200 jobs, metrics at 1-min cadence — outbox size & server ingest throughput OK.
- Chaos: stop/start Engine/Agent; crash/restart spikes; block T-SQL — service layer continues to populate & alert.
- Cross-product: add a non-SQL service (Redis). Verify monitored_service + endpoints + metrics flow without any SQL dependencies.
12) Example “first run” flow (SQL + services)
- Catalog pull → cache ref_* by code.
- Service discovery
- Create/UPSERT monitored_service rows for MSSQL Engine (service_name='MSSQLSERVER', product='MSSQL', service_kind='Database', service_status='Running', start_mode='Auto', listeners [TCP:1433]).
- Create rows for SQLAgent and SQLBrowser (link instance_id if known).
- SQL discovery
- Connect to SQL; write sql_server_instance and supporting snapshots/endpoints.
- Link Engine service to instance_id.
- Metrics (minutely)
- Emit SQL metrics (sql_instance_metric_sample) and service metrics (service_health_metric).
- Threshold-evaluate → status codes.
- Sync
- Flush outbox in batches; server resolves codes→IDs, upserts, and computes health rollups.
- Nightly
- Run fragmentation sampling + CHECKDB recency parse; write sql_database_health_snapshot.
13) Implementation tips & gotchas
- Normalize what matters: keep endpoints in both JSON (fast UI) and rows (alerting/probing).
- Use views for legacy API if you later swap enum text → lookup IDs in SQL-domain tables.
- Avoid duplicate service rows on Windows named instances: use precise service names (MSSQL$FOO, SQLAgent$FOO) as the identity.
- DAC port often unset; handle NULL.
- Error log via xp_readerrorlog may require elevated rights; fallback to filesystem read (Windows service account permissions) or Extended Events.
- Kubernetes: for multi-pod services, you can either:
- Track a single logical monitored_service for the Deployment/StatefulSet (aggregate metrics), or
- Track per-pod services and bind them; pick one approach and stay consistent.
Appendix A — Minimal SQL for key collectors (reference)
- Instance uptime/version: sys.dm_os_sys_info, SERVERPROPERTY.
- Config snapshot: sys.configurations; default paths via SERVERPROPERTY('InstanceDefault*Path').
- Endpoints: sys.endpoints, sys.tcp_endpoints (TDS/DAC/HADR).
- Storage: sys.dm_os_volume_stats, sys.master_files, tempdb.sys.database_files.
- Security: sys.server_principals, sys.server_role_members, sys.sql_logins, sys.dm_server_audit_status.
- Databases: sys.databases + backup info from msdb..backupset.
- Files: sys.database_files.
- Agent jobs: msdb..sysjobs, sysjobschedules, sysjobhistory.
- Metrics: sys.dm_os_performance_counters, sys.dm_os_ring_buffers (or XE/perf counters as you prefer).
- AG: sys.availability_groups, sys.availability_replicas, sys.dm_hadr_*.
- Log space: DBCC SQLPERF(LOGSPACE).