sqlinsight-pro/SQL Scripts/SQLI-ANOM-001.sql
Søren Eggert Lundsteen Olsen 2284e7f082 SQL Scripts: one reviewable script per rule
A DBA should be able to review every statement SQLInsight sends to a
monitored server before granting it access. "SQL Scripts/<rule-id>.sql"
holds, per rule (82 built-in, 16 community), a Danish header (what and
why, how C# judges the data, thresholds with config keys, severity,
exact GRANTs, versions, collector file and member) and the collector's
SQL verbatim, every version variant as its own batch.
"_collectors/<Collector>.sql" holds each collector's queries once.

The only statement that is not strictly read-only is documented in the
scripts: the deadlock collector's session temp table (#system_health).

Inline SQL in the collectors moved to internal constants and Build*Sql
methods (no text changed), so SqlScriptTests can check that the scripts
still contain the SQL the code sends, that every rule has a script, that
every collector query is registered, and that nothing writes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-02 13:20:06 +02:00

130 lines
8.1 KiB
Transact-SQL

-- ===================================================================================================================
-- SQLI-ANOM-001: Usædvanlig belastning i forhold til det normale
-- ===================================================================================================================
-- Regel-id: SQLI-ANOM-001
-- Titel: Usædvanlig belastning i forhold til det normale
-- Alvor: CPU: Medium. Batch requests: Low ved stigning, Medium ved fald. Page life expectancy: Medium.
-- Versioner: SQL Server 2005 og nyere (CPU); tællerne fra 2000.
--
-- Hvad tjekkes, og hvorfor:
-- Om belastningen er usædvanlig i forhold til, hvad der er normalt for netop denne time på ugen.
--
-- Vurdering (sker i C# ud fra de indsamlede data, ikke i SQL'en, medmindre andet er nævnt):
-- Baseline beregnes af agenten i C# fra dens EGET repository (timegennemsnit de seneste 28 dage for samme time på
-- ugen +/- 1 time, mindst 6 målepunkter) - ikke fra den overvågede server. CPU: gns. af de seneste 15 minutters
-- ProcessUtilization >= 50 % og >= middel + max(3 x std.afv., 20). Batch requests/s (forskel mellem to
-- tællermålinger): >= 100 og >= middel + max(3 x std.afv., middel) giver stigning; middel >= 50 og nu <= 30 % af
-- middel giver fald. Page life expectancy: middel >= 300 s og nu <= 30 % af middel.
--
-- Grænseværdier (konfigurationsnøgle i agentens appsettings.json og standardværdi):
-- Fast i koden (AnomalyRule og BaselineCalculator.MinSamples = 6).
--
-- Rettigheder til agentens login (se db/permissions/grant-least-privilege.sql; [agent] = agentens login):
-- GRANT VIEW SERVER STATE TO [agent]; -- SQL Server 2005-2019
-- GRANT VIEW SERVER PERFORMANCE STATE TO [agent]; -- SQL Server 2022+ (erstatter VIEW SERVER STATE)
-- GRANT VIEW SERVER SECURITY STATE TO [agent]; -- SQL Server 2022+
-- SQL Server 2000 har ikke VIEW SERVER STATE; se docs/legacy-versions.md (fx kræver DBCC SQLPERF(WAITSTATS) forhøjede rettigheder).
--
-- Data kommer fra (collector, fil : medlemmer, interval):
-- CpuCollector
-- Fil: src/SQLInsight.Collectors/Performance/CpuCollector.cs
-- Medlemmer: CpuCollector.Sql, CpuCollector.HostPlatformSql
-- Interval: 5 min som standard (SQLInsight:CollectorIntervals:cpu)
-- Delt script: SQL Scripts/_collectors/CpuCollector.sql
-- PerformanceCounterCollector
-- Fil: src/SQLInsight.Collectors/Performance/PerformanceCounterCollector.cs
-- Medlemmer: Db.StartTimeSql(version), PerformanceCounterCollector.BuildSql(dmv: true),
-- PerformanceCounterCollector.BuildSql(dmv: false)
-- Interval: 5 min som standard (SQLInsight:CollectorIntervals:performance-counters)
-- Delt script: SQL Scripts/_collectors/PerformanceCounterCollector.sql
-- Regelkode: src/SQLInsight.Rules/Performance/AnomalyRule.cs : AnomalyRule.Evaluate
--
-- Read-only: Ja: kun SELECT samt lokale variabler, SET-sessionsindstillinger. Intet ændrer data, indstillinger
-- eller objekter.
-- Kørsel: Kør i SSMS som agentens login (eller et login med samme rettigheder). Hver variant er sin egen batch
-- (GO); en variant for en anden SQL Server-version end din kan fejle - det er forventet.
-- Per-database-forespørgsler er vist for databasen msdb, som findes overalt: ret navnet til den
-- database, du vil se.
-- ===================================================================================================================
-- -------------------------------------------------------------------------------------------------------------------
-- Forbindelsen: Sessionsindstillinger, agenten sætter på hver forbindelse
-- -------------------------------------------------------------------------------------------------------------------
-- Variant: Alle versioner: sættes på hver forbindelse, agenten åbner
-- Kilde: SqlConnectionFactory.SessionSettings
-- Kode: src/SQLInsight.Connectivity/SqlConnectionFactory.cs : SqlConnectionFactory.SessionSettings
SET LOCK_TIMEOUT 5000; SET DEADLOCK_PRIORITY LOW; SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
GO
-- -------------------------------------------------------------------------------------------------------------------
-- CpuCollector: SQL Servers og systemets CPU-forbrug pr. minut (scheduler monitor ring buffer, op til 60 minutter).
-- -------------------------------------------------------------------------------------------------------------------
-- Variant: SQL Server 2005 og nyere
-- Kilde: CpuCollector.Sql
-- Kode: src/SQLInsight.Collectors/Performance/CpuCollector.cs : CpuCollector.Sql
DECLARE @now_ticks bigint;
SELECT @now_ticks = ms_ticks FROM sys.dm_os_sys_info;
SELECT TOP (60)
DATEADD(second, CAST((rb.[timestamp] - @now_ticks) / 1000 AS int), GETUTCDATE()),
rb.record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]', 'int'),
rb.record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int')
FROM (
SELECT [timestamp], CONVERT(xml, record) AS record
FROM sys.dm_os_ring_buffers
WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' AND record LIKE N'%<SystemHealth>%'
) rb
ORDER BY rb.[timestamp] DESC
GO
-- Variant: SQL Server 2017 og nyere (Windows eller Linux)
-- Kilde: CpuCollector.HostPlatformSql
-- Kode: src/SQLInsight.Collectors/Performance/CpuCollector.cs : CpuCollector.HostPlatformSql
SELECT host_platform FROM sys.dm_os_host_info
GO
-- -------------------------------------------------------------------------------------------------------------------
-- PerformanceCounterCollector: Udvalgte performance counters: memory grants, page life expectancy, forbindelser,
-- blokerede processer, batch requests og kompileringer.
-- -------------------------------------------------------------------------------------------------------------------
-- Variant: SQL Server 2008 og nyere: starttidspunkt
-- Kilde: PerformanceCounterCollector.StartTimeSql(2008+)
-- Kode: src/SQLInsight.Collectors/Db.cs : Db.StartTimeSql(version)
SELECT (SELECT sqlserver_start_time FROM sys.dm_os_sys_info)
GO
-- Variant: SQL Server 2005: starttidspunkt
-- Kilde: PerformanceCounterCollector.StartTimeSql(2005)
-- Kode: src/SQLInsight.Collectors/Db.cs : Db.StartTimeSql(version)
SELECT (SELECT create_date FROM sys.databases WHERE database_id = 2)
GO
-- Variant: SQL Server 2000 (legacy ODBC-sti): starttidspunkt
-- Kilde: PerformanceCounterCollector.StartTimeSql(2000)
-- Kode: src/SQLInsight.Collectors/Db.cs : Db.StartTimeSql(version)
SELECT (SELECT login_time FROM master.dbo.sysprocesses WHERE spid = 1)
GO
-- Variant: SQL Server 2005 og nyere
-- Kilde: PerformanceCounterCollector.BuildSql(dmv)
-- Kode: src/SQLInsight.Collectors/Performance/PerformanceCounterCollector.cs : PerformanceCounterCollector.BuildSql(dmv: true)
SELECT RTRIM(object_name), RTRIM(counter_name), CAST(cntr_value AS bigint)
FROM sys.dm_os_performance_counters
WHERE (object_name LIKE N'%Memory Manager%' AND counter_name IN (N'Memory Grants Pending', N'Memory Grants Outstanding'))
OR (object_name LIKE N'%Buffer Manager%' AND counter_name = N'Page life expectancy')
OR (object_name LIKE N'%General Statistics%' AND counter_name IN (N'User Connections', N'Processes blocked'))
OR (object_name LIKE N'%SQL Statistics%' AND counter_name IN (N'Batch Requests/sec', N'SQL Compilations/sec', N'SQL Re-Compilations/sec'))
GO
-- Variant: SQL Server 2000 (legacy ODBC-sti)
-- Kilde: PerformanceCounterCollector.BuildSql(sysperfinfo)
-- Kode: src/SQLInsight.Collectors/Performance/PerformanceCounterCollector.cs : PerformanceCounterCollector.BuildSql(dmv: false)
SELECT RTRIM(object_name), RTRIM(counter_name), CAST(cntr_value AS bigint)
FROM master.dbo.sysperfinfo
WHERE (object_name LIKE N'%Memory Manager%' AND counter_name IN (N'Memory Grants Pending', N'Memory Grants Outstanding'))
OR (object_name LIKE N'%Buffer Manager%' AND counter_name = N'Page life expectancy')
OR (object_name LIKE N'%General Statistics%' AND counter_name IN (N'User Connections', N'Processes blocked'))
OR (object_name LIKE N'%SQL Statistics%' AND counter_name IN (N'Batch Requests/sec', N'SQL Compilations/sec', N'SQL Re-Compilations/sec'))
GO