-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy path29_collect_default_trace.sql
More file actions
513 lines (473 loc) · 16.4 KB
/
29_collect_default_trace.sql
File metadata and controls
513 lines (473 loc) · 16.4 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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
/*
Copyright 2026 Darling Data, LLC
https://www.erikdarling.com/
*/
SET ANSI_NULLS ON;
SET ANSI_PADDING ON;
SET ANSI_WARNINGS ON;
SET ARITHABORT ON;
SET CONCAT_NULL_YIELDS_NULL ON;
SET QUOTED_IDENTIFIER ON;
SET NUMERIC_ROUNDABORT OFF;
SET IMPLICIT_TRANSACTIONS OFF;
SET STATISTICS TIME, IO OFF;
GO
USE PerformanceMonitor;
GO
IF OBJECT_ID(N'collect.default_trace_collector', N'P') IS NULL
BEGIN
EXECUTE(N'CREATE PROCEDURE collect.default_trace_collector AS RETURN 138;');
END;
GO
ALTER PROCEDURE
collect.default_trace_collector
(
@hours_back integer = 2, /*how many hours back to collect events*/
@include_memory_events bit = 1, /*include Server Memory Change events*/
@include_autogrow_events bit = 1, /*include Database Auto Grow/Shrink events*/
@include_config_events bit = 1, /*include configuration change events*/
@include_errorlog_events bit = 1, /*include ErrorLog events*/
@include_object_events bit = 1, /*include Object Created/Altered/Deleted events*/
@include_audit_events bit = 1, /*include Security Audit events*/
@debug bit = 0 /*prints additional diagnostic information*/
)
WITH RECOMPILE
AS
BEGIN
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
/*
Variable declarations for default trace processing
*/
DECLARE
@collection_start_time datetime2(7) = SYSDATETIME(),
@rows_collected bigint = 0,
@error_message nvarchar(2048) = N'',
@cutoff_time datetime2(7) = DATEADD(HOUR, -@hours_back, SYSDATETIME()),
@trace_path nvarchar(260) = N'',
@max_files integer = 0;
BEGIN TRY
/*
Parameter validation
*/
IF @hours_back <= 0 OR @hours_back > 168 -- 1 week
BEGIN
SET @error_message = N'@hours_back must be between 1 and 168 hours';
RAISERROR(@error_message, 16, 1);
RETURN;
END;
/*
Ensure target table exists
*/
IF OBJECT_ID(N'collect.default_trace_events', N'U') IS NULL
BEGIN
/*
Log missing table before attempting to create
*/
INSERT INTO
config.collection_log
(
collection_time,
collector_name,
collection_status,
rows_collected,
duration_ms,
error_message
)
VALUES
(
@collection_start_time,
N'default_trace_collector',
N'TABLE_MISSING',
0,
0,
N'Table collect.default_trace_events does not exist, calling ensure procedure'
);
/*
Call procedure to create table
*/
EXECUTE config.ensure_collection_table
@table_name = N'default_trace_events',
@debug = @debug;
/*
Verify table now exists
*/
IF OBJECT_ID(N'collect.default_trace_events', N'U') IS NULL
BEGIN
RAISERROR(N'Table collect.default_trace_events still missing after ensure procedure', 16, 1);
RETURN;
END;
END;
/*
First run detection - collect last 1 hour of trace data if this is the first execution
Ignore CONFIG_CHANGE entries when checking for first run (those are just from enabling the trace)
*/
IF NOT EXISTS (SELECT 1/0 FROM collect.default_trace_events)
AND NOT EXISTS (SELECT 1/0 FROM config.collection_log WHERE collector_name = N'default_trace_collector' AND collection_status = N'SUCCESS')
BEGIN
SET @cutoff_time = DATEADD(HOUR, -1, SYSDATETIME());
IF @debug = 1
BEGIN
RAISERROR(N'First run detected - collecting last 1 hour of default trace events', 0, 1) WITH NOWAIT;
END;
END;
/*
Check if default trace is enabled and running
SQL Server bug: sometimes the trace is configured to be enabled but doesn't actually start
*/
DECLARE @trace_configured bit = 0;
SELECT
@trace_configured = CONVERT(integer, c.value_in_use)
FROM sys.configurations AS c
WHERE c.name = N'default trace enabled';
IF NOT EXISTS (SELECT 1/0 FROM sys.traces WHERE is_default = 1)
BEGIN
/*
Trace not running - check if it's configured
*/
IF @trace_configured = 0
BEGIN
IF @debug = 1
BEGIN
RAISERROR(N'Default trace not enabled - enabling now', 0, 1) WITH NOWAIT;
END;
/*
Enable default trace
*/
EXECUTE sys.sp_configure
@configname = N'default trace enabled',
@configvalue = 1;
RECONFIGURE;
/*
Log that we enabled it
*/
INSERT INTO
config.collection_log
(
collection_time,
collector_name,
collection_status,
rows_collected,
duration_ms,
error_message
)
VALUES
(
@collection_start_time,
N'default_trace_collector',
N'CONFIG_CHANGE',
0,
DATEDIFF(MILLISECOND, @collection_start_time, SYSDATETIME()),
N'Enabled default trace (sp_configure ''default trace enabled'', 1) - trace will start on next collection run'
);
/*
Return after enabling - trace needs to start before we can collect from it
Next run will collect data once trace is active
*/
RETURN;
END;
ELSE
BEGIN
/*
SQL Server bug: trace is configured to be enabled but not actually running
Attempt to restart it by disabling and re-enabling
*/
IF @debug = 1
BEGIN
RAISERROR(N'Default trace configured but not running - attempting disable/re-enable cycle', 0, 1) WITH NOWAIT;
END;
/*
Disable the trace
*/
EXECUTE sys.sp_configure
@configname = N'default trace enabled',
@configvalue = 0;
RECONFIGURE;
/*
Re-enable the trace
*/
EXECUTE sys.sp_configure
@configname = N'default trace enabled',
@configvalue = 1;
RECONFIGURE;
/*
Verify the trace is now running
*/
IF NOT EXISTS (SELECT 1/0 FROM sys.traces WHERE is_default = 1)
BEGIN
/*
Restart failed - log and return
*/
INSERT INTO
config.collection_log
(
collection_time,
collector_name,
collection_status,
rows_collected,
duration_ms,
error_message
)
VALUES
(
@collection_start_time,
N'default_trace_collector',
N'ERROR',
0,
DATEDIFF(MILLISECOND, @collection_start_time, SYSDATETIME()),
N'Default trace restart failed - performed disable/re-enable but trace still not running - may require SQL Server restart'
);
RETURN;
END;
/*
Log that we restarted it successfully
*/
INSERT INTO
config.collection_log
(
collection_time,
collector_name,
collection_status,
rows_collected,
duration_ms,
error_message
)
VALUES
(
@collection_start_time,
N'default_trace_collector',
N'CONFIG_CHANGE',
0,
DATEDIFF(MILLISECOND, @collection_start_time, SYSDATETIME()),
N'Default trace restarted successfully - proceeding to collect data'
);
IF @debug = 1
BEGIN
RAISERROR(N'Default trace restart successful - proceeding to collect data', 0, 1) WITH NOWAIT;
END;
/*
Continue to data collection below (don't return)
*/
END;
END;
/*
Get default trace path and configuration
*/
SELECT
@trace_path = st.path,
@max_files = st.max_files
FROM sys.traces AS st
WHERE st.is_default = 1;
IF @debug = 1
BEGIN
DECLARE @cutoff_time_string nvarchar(30) = CONVERT(nvarchar(30), @cutoff_time, 120);
RAISERROR(N'Default trace path: %s', 0, 1, @trace_path) WITH NOWAIT;
RAISERROR(N'Processing events from: %s onward', 0, 1, @cutoff_time_string) WITH NOWAIT;
END;
/*
Collect default trace events with filtering
*/
INSERT INTO
collect.default_trace_events
(
collection_time,
event_time,
event_name,
event_class,
spid,
database_name,
database_id,
login_name,
host_name,
application_name,
server_name,
object_name,
filename,
integer_data,
integer_data_2,
text_data,
binary_data,
session_login_name,
error_number,
severity,
state,
event_sequence,
is_system,
request_id,
duration_us,
end_time
)
SELECT
collection_time = @collection_start_time,
event_time = ft.StartTime,
event_name = te.name,
event_class = ft.EventClass,
spid = ft.SPID,
database_name = ft.DatabaseName,
database_id = ft.DatabaseID,
login_name = ft.LoginName,
host_name = ft.HostName,
application_name = ft.ApplicationName,
server_name = ft.ServerName,
object_name = ft.ObjectName,
filename = ft.FileName,
integer_data = ft.IntegerData,
integer_data_2 = ft.IntegerData2,
text_data = ft.TextData,
binary_data = ft.BinaryData,
session_login_name = ft.SessionLoginName,
error_number = ft.Error,
severity = ft.Severity,
state = ft.State,
event_sequence = ft.EventSequence,
is_system = ft.IsSystem,
request_id = ft.RequestID,
duration_us = ft.Duration,
end_time = ft.EndTime
FROM sys.traces AS st
CROSS APPLY sys.fn_trace_gettable
(
LEFT(st.path, LEN(st.path) - CHARINDEX('_', REVERSE(st.path))) +
RIGHT(st.path, 4),
st.max_files
) AS ft
INNER JOIN sys.trace_events AS te
ON ft.EventClass = te.trace_event_id
WHERE st.is_default = 1
AND st.status = 1
AND ft.StartTime >= @cutoff_time
AND ISNULL(ft.DatabaseID, 0) NOT IN (DB_ID(N'PerformanceMonitor'), 1, 3, 4)
AND ISNULL(ft.DatabaseID, 0) < 32761 /*exclude contained AG system databases*/
/*
Filter for useful system events, excluding login failures
*/
AND
(
/*Server Memory Change events*/
(@include_memory_events = 1 AND te.name LIKE N'%Server Memory Change%')
OR
/*Database Auto Grow/Shrink events (only collect if duration > 1 second)*/
(@include_autogrow_events = 1 AND
ISNULL(ft.Duration, 0) > 1000000 AND
(te.name LIKE N'%Data File Auto Grow%' OR
te.name LIKE N'%Log File Auto Grow%' OR
te.name LIKE N'%Data File Auto Shrink%' OR
te.name LIKE N'%Log File Auto Shrink%'))
OR
/*Configuration change events*/
(@include_config_events = 1 AND
(te.name LIKE N'%Server Configuration Change%' OR
te.name LIKE N'%Database Configuration Change%' OR
te.name LIKE N'%Alter Database%'))
OR
/*ErrorLog events*/
(@include_errorlog_events = 1 AND te.name = N'ErrorLog')
OR
/*Object DDL events (exclude tempdb and auto-stats)*/
(@include_object_events = 1 AND
ISNULL(ft.DatabaseID, 0) <> 2 AND
ISNULL(ft.ObjectName, N'') NOT LIKE N'[_]WA[_]%' AND
(te.name = N'Object:Created' OR
te.name = N'Object:Altered' OR
te.name = N'Object:Deleted'))
OR
/*Security Audit events*/
(@include_audit_events = 1 AND
(te.name = N'Audit Change Audit Event' OR
te.name = N'Audit DBCC Event' OR
te.name = N'Audit Server Alter Trace Event'))
)
/*
Avoid duplicates by checking if we've already processed this event
*/
AND NOT EXISTS
(
SELECT
1/0
FROM collect.default_trace_events AS dte
WHERE dte.event_time = ft.StartTime
AND dte.event_class = ft.EventClass
AND dte.spid = ft.SPID
AND dte.event_sequence = ft.EventSequence
AND dte.collection_time >= DATEADD(HOUR, -1, @collection_start_time)
)
ORDER BY
ft.StartTime DESC;
SELECT @rows_collected = ROWCOUNT_BIG();
IF @debug = 1
BEGIN
RAISERROR(N'Collected %d default trace events', 0, 1, @rows_collected) WITH NOWAIT;
END;
/*
Log collection activity
*/
INSERT INTO
config.collection_log
(
collection_time,
collector_name,
collection_status,
rows_collected,
duration_ms,
error_message
)
VALUES
(
@collection_start_time,
N'default_trace_collector',
N'SUCCESS',
@rows_collected,
DATEDIFF(MILLISECOND, @collection_start_time, SYSDATETIME()),
NULL
);
/*
Return summary information
*/
SELECT
collection_time = @collection_start_time,
rows_collected = @rows_collected,
hours_processed = @hours_back,
cutoff_time = @cutoff_time,
trace_path = @trace_path,
include_memory_events = @include_memory_events,
include_autogrow_events = @include_autogrow_events,
include_config_events = @include_config_events,
include_errorlog_events = @include_errorlog_events,
include_object_events = @include_object_events,
include_audit_events = @include_audit_events,
success = 1;
END TRY
BEGIN CATCH
SET @error_message = ERROR_MESSAGE();
/*
Log errors to collection log
*/
INSERT INTO
config.collection_log
(
collection_time,
collector_name,
collection_status,
rows_collected,
duration_ms,
error_message
)
VALUES
(
@collection_start_time,
N'default_trace_collector',
N'ERROR',
@rows_collected,
DATEDIFF(MILLISECOND, @collection_start_time, SYSDATETIME()),
@error_message
);
IF @@TRANCOUNT > 0
BEGIN
ROLLBACK;
END;
THROW;
END CATCH;
END;
GO
PRINT 'Default trace collector created successfully';
GO