forked from trimble-oss/dba-dash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDBCollector.cs
1755 lines (1610 loc) · 75.4 KB
/
DBCollector.cs
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.Data.SqlClient;
using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Options;
using Microsoft.SqlServer.Management.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Polly;
using Serilog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Text.RegularExpressions;
namespace DBADash
{
[JsonConverter(typeof(StringEnumConverter))]
public enum CollectionType
{
AgentJobs,
Databases,
DatabasesHADR,
SysConfig,
Drives,
DBConfig,
DBFiles,
Corruption,
OSInfo,
TraceFlags,
DriversWMI,
CPU,
BlockingSnapshot,
IOStats,
Waits,
Backups,
LogRestores,
ServerProperties,
ServerExtraProperties,
OSLoadedModules,
DBTuningOptions,
AzureDBResourceStats,
AzureDBServiceObjectives,
AzureDBElasticPoolResourceStats,
SlowQueries,
LastGoodCheckDB,
Alerts,
ObjectExecutionStats,
ServerPrincipals,
ServerRoleMembers,
ServerPermissions,
DatabasePrincipals,
DatabaseRoleMembers,
DatabasePermissions,
CustomChecks,
PerformanceCounters,
VLF,
DatabaseMirroring,
Jobs,
JobHistory,
AvailabilityReplicas,
AvailabilityGroups,
ResourceGovernorConfiguration,
DatabaseQueryStoreOptions,
AzureDBResourceGovernance,
RunningQueries,
MemoryUsage,
SchemaSnapshot,
IdentityColumns,
Instance,
RunningJobs,
TableSize,
ServerServices
}
public enum HostPlatform
{
Linux,
Windows
}
public class DBCollector : IErrorLogger
{
public DataSet Data;
private string ConnectionString => Source.SourceConnection.ConnectionString;
private DataTable dtErrors;
public bool LogInternalPerformanceCounters = false;
private DataTable dtInternalPerfCounters;
public int PerformanceCollectionPeriodMins = 60;
private string computerName;
private readonly CollectionType[] azureCollectionTypes = new[] { CollectionType.SlowQueries, CollectionType.AzureDBElasticPoolResourceStats, CollectionType.AzureDBServiceObjectives, CollectionType.AzureDBResourceStats, CollectionType.CPU, CollectionType.DBFiles, CollectionType.Databases, CollectionType.DBConfig, CollectionType.TraceFlags, CollectionType.ObjectExecutionStats, CollectionType.BlockingSnapshot, CollectionType.IOStats, CollectionType.Waits, CollectionType.ServerProperties, CollectionType.DBTuningOptions, CollectionType.SysConfig, CollectionType.DatabasePrincipals, CollectionType.DatabaseRoleMembers, CollectionType.DatabasePermissions, CollectionType.OSInfo, CollectionType.CustomChecks, CollectionType.PerformanceCounters, CollectionType.VLF, CollectionType.DatabaseQueryStoreOptions, CollectionType.AzureDBResourceGovernance, CollectionType.RunningQueries, CollectionType.IdentityColumns, CollectionType.TableSize };
private readonly CollectionType[] azureOnlyCollectionTypes = new[] { CollectionType.AzureDBElasticPoolResourceStats, CollectionType.AzureDBResourceStats, CollectionType.AzureDBServiceObjectives, CollectionType.AzureDBResourceGovernance };
private readonly CollectionType[] azureMasterOnlyCollectionTypes = new[] { CollectionType.AzureDBElasticPoolResourceStats };
public DBADashSource Source;
private bool noWMI;
private bool IsAzureDB;
private bool isAzureMasterDB;
private bool IsRDS;
private string instanceName;
private string dbName;
private string productVersion;
private HostPlatform platform;
public DateTime JobLastModified = DateTime.MinValue;
private bool IsHadrEnabled;
private Policy retryPolicy;
private DatabaseEngineEdition engineEdition;
private DBADashAgent dashAgent;
public bool IsExtendedEventsNotSupportedException;
private readonly bool DisableRetry;
public const int DefaultIdentityCollectionThreshold = 5;
/// <summary>
/// % Used threshold for IdentityColumns collection
/// </summary>
public int IdentityCollectionThreshold = DefaultIdentityCollectionThreshold;
private readonly CacheItemPolicy policy = new()
{
SlidingExpiration = TimeSpan.FromMinutes(60)
};
private readonly MemoryCache cache = MemoryCache.Default;
private readonly Stopwatch swatch = new();
private string currentCollection;
private Version SQLVersion = new();
private bool IsTableValuedConstructorsSupported => SQLVersion.Major > 9;
private const int TableSizeCollectionThresholdMBDefault = 100;
private const string TableSizeDatabasesDefault = "*";
private const int TableSizeMaxTableThresholdDefault = 2000;
private const int TableSizeMaxDatabaseThreshold = 500;
public string ConnectionID => Data.Tables["DBADash"]?.Rows[0]["ConnectionID"].ToString();
public int Job_instance_id
{
get
{
if (!Data.Tables.Contains("JobHistory")) return job_instance_id;
var jh = Data.Tables["JobHistory"];
if (jh is { Rows.Count: > 0 })
{
job_instance_id = Convert.ToInt32(jh.Compute("max(instance_id)", string.Empty));
}
return job_instance_id;
}
set => job_instance_id = value;
}
private int job_instance_id;
public DateTime GetJobLastModified()
{
using SqlConnection cn = new(ConnectionString);
using SqlCommand cmd = new("SELECT MAX(date_modified) FROM msdb.dbo.sysjobs", cn);
cn.Open();
var result = cmd.ExecuteScalar();
return result == DBNull.Value ? DateTime.MinValue : (DateTime)result;
}
public bool IsXESupported => !IsExtendedEventsNotSupportedException && DBADashConnection.IsXESupported(productVersion);
public bool IsQueryStoreSupported => IsAzureDB || (!productVersion.StartsWith("8.") && !productVersion.StartsWith("9.") && !productVersion.StartsWith("10.") && !productVersion.StartsWith("11.") && !productVersion.StartsWith("12."));
public DBCollector(DBADashSource source, string serviceName, bool disableRetry = false)
{
DisableRetry = disableRetry;
Source = source;
Startup();
}
public void LogError(Exception ex, string errorSource, string errorContext = "Collect")
{
Log.Error(ex, "{ErrorContext} {ErrorSource} {Connection}", errorContext, errorSource, Source.SourceConnection.ConnectionForPrint);
LogDBError(errorSource, ex.ToString(), errorContext);
}
public void ClearErrors()
{
dtErrors.Rows.Clear();
}
public int ErrorCount => dtErrors.Rows.Count;
private void LogDBError(string errorSource, string errorMessage, string errorContext = "Collect")
{
var rError = dtErrors.NewRow();
rError["ErrorSource"] = errorSource;
rError["ErrorMessage"] = errorMessage;
rError["ErrorContext"] = errorContext;
dtErrors.Rows.Add(rError);
}
private void CreateInternalPerformanceCountersDataTable()
{
dtInternalPerfCounters = new("InternalPerformanceCounters")
{
Columns =
{
new DataColumn("SnapshotDate", typeof(DateTime)),
new DataColumn("object_name"),
new DataColumn("counter_name"),
new DataColumn("instance_name"),
new DataColumn("cntr_value", typeof(decimal)),
new DataColumn("cntr_type", typeof(int))
}
};
Data.Tables.Add(dtInternalPerfCounters);
}
private void LogInternalPerformanceCounter(string objectName, string counterName, string instance, decimal counterValue)
{
if (!LogInternalPerformanceCounters) return;
if (dtInternalPerfCounters == null)
{
CreateInternalPerformanceCountersDataTable();
}
var row = dtInternalPerfCounters!.NewRow();
row["SnapshotDate"] = DateTime.UtcNow;
row["object_name"] = objectName;
row["counter_name"] = counterName;
row["instance_name"] = instance;
row["cntr_value"] = counterValue;
row["cntr_type"] = 65792;
dtInternalPerfCounters.Rows.Add(row);
}
private void StartCollection(string type)
{
swatch.Reset();
swatch.Start();
currentCollection = type;
}
private void StopCollection()
{
if (!swatch.IsRunning) return;
swatch.Stop();
Log.Debug("Collect {0} on {1} completed in {2}ms", currentCollection, instanceName, swatch.ElapsedMilliseconds);
LogInternalPerformanceCounter("DBADash", "Collection Duration (ms)", currentCollection, Convert.ToDecimal(swatch.Elapsed.TotalMilliseconds));
}
private static readonly HashSet<int> ExcludedErrorCodes = new()
{
-2, // retryPolicy excludes query timeout #581
218, // Could not find the type '%.*ls'. Either it does not exist or you do not have the necessary permission.
219, // The type '%.*ls' already exists, or you do not have permission to create it.
229, // The %ls permission was denied on the object '%.*ls', database '%.*ls', schema '%.*ls'.
230, // The %ls permission was denied on the column '%.*ls' of the object '%.*ls', database '%.*ls', schema '%.*ls'.
245, // Conversion failed when converting the %ls value '%.*ls' to data type %ls.
262, // %ls permission denied in database '%.*ls'.
297, //The user does not have permission to perform this action.
300, // %ls permission was denied on object '%.*ls', database '%.*ls'.
349, // The procedure "%.*ls" has no parameter named "%.*ls".
500, // Trying to pass a table-valued parameter with %d column(s) where the corresponding user-defined table type requires %d column(s).
2812, // Could not find stored procedure '%.*ls'.
6335, // XML data type instance has too many levels of nested nodes. Maximum allowed depth is %d levels.
};
public bool ShouldRetry(Exception ex)
{
if (DisableRetry) return false;
if (ex is SqlException sqlEx)
{
return !ExcludedErrorCodes.Contains(sqlEx.Number) && sqlEx.Message != "Max databases exceeded for Table Size collection";
}
return true;
}
private void Startup()
{
noWMI = Source.NoWMI;
dashAgent = DBADashAgent.GetCurrent();
retryPolicy = Policy.Handle<Exception>(ShouldRetry)
.WaitAndRetry(new[]
{
TimeSpan.FromSeconds(2),
TimeSpan.FromSeconds(10)
}, (exception, _, _, context) =>
{
LogError(exception, context.OperationKey, "Collect[Retrying]");
});
Data = new DataSet("DBADash");
dtErrors = new("Errors")
{
Columns =
{
new DataColumn("ErrorSource"),
new DataColumn("ErrorMessage"),
new DataColumn("ErrorContext")
}
};
Data.Tables.Add(dtErrors);
retryPolicy.Execute(
_ => GetInstance(),
new Context("Instance")
);
}
public async Task RemoveEventSessionsAsync()
{
if (IsXESupported)
{
var removeSQL = IsAzureDB ? SqlStrings.RemoveEventSessionsAzure : SqlStrings.RemoveEventSessions;
await using var cn = new SqlConnection(ConnectionString);
await using var cmd = new SqlCommand(removeSQL, cn);
await cn.OpenAsync();
await cmd.ExecuteNonQueryAsync();
}
}
public async Task StopEventSessionsAsync()
{
if (IsXESupported)
{
var removeSQL = IsAzureDB ? SqlStrings.StopEventSessionsAzure : SqlStrings.StopEventSessions;
await using var cn = new SqlConnection(ConnectionString);
await using var cmd = new SqlCommand(removeSQL, cn);
await cn.OpenAsync();
await cmd.ExecuteNonQueryAsync();
}
}
/// <summary>
/// Add MetaData relating to the DBA Dash service used for collection.
/// </summary>
private void AddDBADashServiceMetaData(ref DataTable dt)
{
dt.Columns.AddRange(new[]
{
new DataColumn("AgentVersion", typeof(string)),
new DataColumn("ConnectionID", typeof(string)),
new DataColumn("AgentHostName", typeof(string)),
new DataColumn("AgentServiceName", typeof(string)),
new DataColumn("AgentPath", typeof(string)),
new DataColumn("ServiceSQSQueueUrl",typeof(string)),
new DataColumn("S3Path",typeof(string)),
new DataColumn("MessagingEnabled", typeof(bool))
});
dt.Rows[0]["AgentVersion"] = dashAgent.AgentVersion;
dt.Rows[0]["AgentHostName"] = dashAgent.AgentHostName;
dt.Rows[0]["AgentServiceName"] = dashAgent.AgentServiceName;
dt.Rows[0]["AgentPath"] = dashAgent.AgentPath;
dt.Rows[0]["ServiceSQSQueueUrl"] = dashAgent.ServiceSQSQueueUrl;
dt.Rows[0]["MessagingEnabled"] = dashAgent.MessagingEnabled;
}
public void GetInstance()
{
StartCollection(CollectionType.Instance.ToString());
var dt = GetDT("DBADash", SqlStrings.Instance, CollectionCommandTimeout.GetDefaultCommandTimeout());
AddDBADashServiceMetaData(ref dt);
var clusterOrComputerName = (string)dt.Rows[0]["MachineName"];
computerName = (string)dt.Rows[0]["ComputerNamePhysicalNetBIOS"];
dbName = (string)dt.Rows[0]["DBName"];
if (dt.Rows[0]["Instance"] == DBNull.Value)
{
dt.Rows[0]["Instance"] = "";
Log.Warning("@@SERVERNAME returned NULL for {connection}. Consider fixing with sp_addserver", Source.SourceConnection.ConnectionForPrint);
}
instanceName = (string)dt.Rows[0]["Instance"];
productVersion = (string)dt.Rows[0]["ProductVersion"];
if (!Version.TryParse(productVersion, out SQLVersion))
{
Log.Warning("Unable to parse ProductVersion to Version object");
}
string hostPlatform = (string)dt.Rows[0]["host_platform"];
engineEdition = (DatabaseEngineEdition)Convert.ToInt32(dt.Rows[0]["EngineEdition"]);
string containedAGName = Convert.ToString(dt.Rows[0]["contained_availability_group_name"]);
if (!Enum.TryParse(hostPlatform, out platform))
{
Log.Error("GetInstance: host_platform parse error");
LogDBError("Instance", "host_platform parse error");
platform = HostPlatform.Windows;
}
if (platform == HostPlatform.Linux) // Disable WMI collection for Linux
{
Log.Debug("Instance {0} is a Linux instance. WMI collections are disabled.", instanceName);
noWMI = true;
}
if (computerName.StartsWith("EC2AMAZ-")) // Disable WMI collection for RDS
{
Log.Debug("Instance {0} is a RDS instance. WMI collections are disabled.", instanceName);
IsRDS = true;
noWMI = true;
}
if (engineEdition == DatabaseEngineEdition.SqlDatabase)
{
IsAzureDB = true;
if (dbName == "master")
{
isAzureMasterDB = true;
}
}
if (computerName.Length == 0)
{
noWMI = true;
}
if (string.IsNullOrEmpty(Source.ConnectionID))
{
if (IsAzureDB)
{
dt.Rows[0]["ConnectionID"] = instanceName + "|" + dbName;
noWMI = true;
}
else if (!string.IsNullOrEmpty(containedAGName)) // Use the name of the contained AG as the ConnectionID.
{
dt.Rows[0]["ConnectionID"] = containedAGName;
}
else if (string.IsNullOrEmpty(instanceName))
{
dt.Rows[0]["ConnectionID"] = clusterOrComputerName;
}
else
{
dt.Rows[0]["ConnectionID"] = instanceName;
}
}
else
{
dt.Rows[0]["ConnectionID"] = Source.ConnectionID;
}
IsHadrEnabled = dt.Rows[0]["IsHadrEnabled"] != DBNull.Value && Convert.ToBoolean(dt.Rows[0]["IsHadrEnabled"]);
Data.Tables.Add(dt);
StopCollection();
}
public void Collect(CollectionType[] collectionTypes)
{
foreach (CollectionType type in collectionTypes)
{
Collect(type);
}
}
public void Collect(Dictionary<string, CustomCollection> customCollections)
{
foreach (var customCollection in customCollections)
{
var collectionReference = "UserData." + customCollection.Key;
try
{
retryPolicy.Execute(
_ =>
{
StartCollection(collectionReference);
Collect(customCollection);
StopCollection();
},
new Context(collectionReference)
);
}
catch (SqlException ex) when (ex.Number == 2812)
{
var message = $"Warning: Custom collection stored procedure {customCollection.Value.ProcedureName} doesn't exist";
LogDBError(collectionReference, message);
Log.Error(ex, message);
}
catch (Exception ex)
{
StopCollection();
LogError(ex, collectionReference);
}
}
}
public void Collect(KeyValuePair<string, CustomCollection> customCollection)
{
using var cn = new SqlConnection(ConnectionString);
using var cmd = new SqlCommand(customCollection.Value.ProcedureName, cn) { CommandType = CommandType.StoredProcedure, CommandTimeout = customCollection.Value.CommandTimeout ?? CollectionCommandTimeout.GetDefaultCommandTimeout() };
using var da = new SqlDataAdapter(cmd);
var dt = new DataTable("UserData." + customCollection.Key);
da.Fill(dt);
Data.Tables.Add(dt);
}
private static string EnumToString(Enum en)
{
return Enum.GetName(en.GetType(), en);
}
private bool CollectionTypeIsApplicable(CollectionType collectionType)
{
var collectionTypeString = EnumToString(collectionType);
if (collectionType == CollectionType.DatabaseQueryStoreOptions && !IsQueryStoreSupported)
{
// Query store not supported on this instance
return false;
}
else if (Data.Tables.Contains(collectionTypeString))
{
// Already collected
return false;
}
else if (IsAzureDB && (!azureCollectionTypes.Contains(collectionType)))
{
// Collection Type doesn't apply to AzureDB
return false;
}
else if (!IsAzureDB && azureOnlyCollectionTypes.Contains(collectionType))
{
// Collection Type doesn't apply to normal standalone instance
return false;
}
else if (azureMasterOnlyCollectionTypes.Contains(collectionType) && !isAzureMasterDB)
{
// Collection type only applies to Azure master db
return false;
}
else if (!IsHadrEnabled & (collectionType == CollectionType.AvailabilityGroups || collectionType == CollectionType.AvailabilityReplicas || collectionType == CollectionType.DatabasesHADR))
{
// Availability group collection and Hadr isn't enabled.
return false;
}
else if (collectionType == CollectionType.SchemaSnapshot)
{
//Schema snapshots are not handled via DBCollector
return false;
}
else if (collectionType == CollectionType.ResourceGovernorConfiguration)
{
return SQLVersion.Major > 9 && engineEdition == DatabaseEngineEdition.Enterprise && !IsAzureDB; // Must be enterprise edition and not AzureDB, SQL 2005
}
else if ((new[] { CollectionType.Backups, CollectionType.DatabaseMirroring, CollectionType.LogRestores, CollectionType.AvailabilityGroups, CollectionType.AvailabilityReplicas, CollectionType.DatabasesHADR }).Contains(collectionType)
&& engineEdition == DatabaseEngineEdition.SqlManagedInstance)
{
// Don't need to collect these types for Azure MI
return false;
}
else if ((new[] { CollectionType.JobHistory, CollectionType.AgentJobs, CollectionType.Jobs, CollectionType.RunningJobs }).Contains(collectionType) && engineEdition == DatabaseEngineEdition.Express)
{
// SQL Agent not supported on express
return false;
}
else if (collectionType == CollectionType.Drives && platform != HostPlatform.Windows) // drive collection not supported on linux
{
return false;
}
else if (collectionType == CollectionType.SlowQueries)
{
return Source.SlowQueryThresholdMs >= 0 && (!(IsAzureDB && isAzureMasterDB)); // Threshold must be set. Azure master DB is excluded
}
else if (collectionType == CollectionType.Instance)
{
return false; // Required & collected by default
}
else if (collectionType == CollectionType.TableSize && SQLVersion.Major <= 12 && !IsAzureDB)
{
return false; // Table size collection not supported on SQL 2014 and below
}
else if (collectionType == CollectionType.ServerServices && SQLVersion.Major < 11)
{
return false;
}
else
{
return true;
}
}
public void Collect(CollectionType collectionType)
{
var collectionTypeString = EnumToString(collectionType);
if (!CollectionTypeIsApplicable(collectionType))
{
return;
}
try
{
retryPolicy.Execute(
_ =>
{
StartCollection(collectionType.ToString());
ExecuteCollection(collectionType);
StopCollection();
},
new Context(collectionTypeString)
);
}
catch (Exception ex)
{
LogError(ex, collectionTypeString);
StopCollection();
}
if (collectionType == CollectionType.RunningQueries)
{
try
{
CollectText();
}
catch (Exception ex)
{
LogError(new Exception("Error collecting text for Running Queries", ex), "RunningQueries");
}
try
{
CollectPlans();
}
catch (Exception ex)
{
LogError(new Exception("Error collecting plans for Running Queries", ex), "RunningQueries");
}
}
}
private static string ByteArrayToHexString(byte[] bytes)
{
string hex = BitConverter.ToString(bytes);
return hex.Replace("-", "");
}
private DataTable GetPlans(string plansSQL)
{
if (string.IsNullOrEmpty(plansSQL)) return null;
using var cn = new SqlConnection(ConnectionString);
using var da = new SqlDataAdapter(plansSQL, cn);
var dt = new DataTable("QueryPlans");
da.Fill(dt);
return dt;
}
private void CollectPlans()
{
if (!Data.Tables.Contains("RunningQueries") || !Source.PlanCollectionEnabled) return;
var plansSQL = GetPlansSQL();
var dt = GetPlans(plansSQL);
if (dt is { Rows.Count: > 0 })
{
dt.Columns.Add("query_plan_hash", typeof(byte[]));
dt.Columns.Add("query_plan_compressed", typeof(byte[]));
foreach (DataRow r in dt.Rows)
{
try
{
string strPlan = r["query_plan"] == DBNull.Value ? string.Empty : (string)r["query_plan"];
r["query_plan_compressed"] = SMOBaseClass.Zip(strPlan);
var hash = GetPlanHash(strPlan);
r["query_plan_hash"] = hash;
}
catch (Exception ex)
{
Log.Error(ex, "Error processing query plans");
}
}
dt.Columns.Remove("query_plan");
var nullRows = dt.Select("query_plan_hash IS NULL");
// Remove rows with null query plan hash
if (nullRows.Length > 0)
{
Log.Information("Removing {0} rows with NULL query_plan_hash", nullRows.Length);
foreach (var row in nullRows)
{
row.Delete();
}
dt.AcceptChanges();
}
if (dt.Rows.Count > 0) // Check if we still have rows
{
Data.Tables.Add(dt);
}
}
LogInternalPerformanceCounter("DBADash", "Count of plans collected", "", dt?.Rows.Count ?? 0); // Count of plans actually collected - might be less than the list of plans we wanted to collect
}
///<summary>
///Get the query plan hash from a string of the plan XML
///</summary>
public static byte[] GetPlanHash(string strPlan)
{
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(strPlan)))
{
ms.Position = 0;
using (var xr = new XmlTextReader(ms))
{
while (xr.Read())
{
if (xr.Name == "StmtSimple")
{
string strHash = xr.GetAttribute("QueryPlanHash");
return StringToByteArray(strHash);
}
}
}
}
return Array.Empty<byte>();
}
public static byte[] StringToByteArray(string hex)
{
if (hex.StartsWith("0x"))
{
hex = hex.Remove(0, 2);
}
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
///<summary>
///Generate a SQL query to get the query plan text for running queries. Captured plan handles get cached with a call to CacheCollectedPlans later <br/>
///Limits the cost associated with plan capture - less plans to capture, send and process<br/>
///Note: Caching takes query_plan_hash into account as a statement can get recompiled without the plan handle changing.
///</summary>
public string GetPlansSQL()
{
var plans = GetPlansList();
var sb = new StringBuilder();
sb.Append(@"DECLARE @plans TABLE(plan_handle VARBINARY(64),statement_start_offset int,statement_end_offset int)
INSERT INTO @plans(plan_handle,statement_start_offset,statement_end_offset)
VALUES");
// Already have a distinct list by plan handle, hash and offsets.
// Filter this list by plans not already collected and get a distinct list by handle and offsets (excluding the hash as this can cause duplicates in rare cases)
var collectList = plans.Where(p => !cache.Contains(p.Key))
.GroupBy(p => Convert.ToBase64String(p.PlanHandle.Concat(BitConverter.GetBytes(p.StartOffset)).Concat(BitConverter.GetBytes(p.EndOffset)).ToArray()))
.Select(p => p.First())
.ToList();
collectList.ForEach(p => sb.AppendFormat("{3}(0x{0},{1},{2}),", ByteArrayToHexString(p.PlanHandle), p.StartOffset, p.EndOffset, Environment.NewLine));
Log.Information("Plans {0}, {1} to collect from {2}", plans.Count, collectList.Count, instanceName);
LogInternalPerformanceCounter("DBADash", "Count of plans meeting threshold for collection", "", plans.Count); // Total number of plans that meet the threshold for collection
LogInternalPerformanceCounter("DBADash", "Count of plans to collect", "", collectList.Count); // Total number of plans we want to collect (plans that meet the threshold that are not cached)
LogInternalPerformanceCounter("DBADash", "Count of plans from cache", "", plans.Count - collectList.Count); // Plan count we didn't collect because they have been collected previously and we cached the handles/hashes.
if (collectList.Count == 0)
{
return string.Empty;
}
else
{
sb.Remove(sb.Length - 1, 1);
sb.AppendLine("OPTION(RECOMPILE)"); // Plan caching is not beneficial. RECOMPILE hint to avoid polluting the plan cache
sb.AppendLine();
sb.Append(@"SELECT t.plan_handle,
t.statement_start_offset,
t.statement_end_offset,
pln.dbid,
pln.objectid,
pln.encrypted,
pln.query_plan
FROM @plans t
CROSS APPLY sys.dm_exec_text_query_plan(t.plan_handle,t.statement_start_offset,t.statement_end_offset) pln
OPTION(RECOMPILE)"); // Plan caching is not beneficial. RECOMPILE hint to avoid polluting the plan cache
return sb.ToString();
}
}
///<summary>
///Get a list of plan handles from RunningQueries including statement start/end offsets as we want to capture plans at the statement level. Query plan hash is used to detect changes in the plan for caching purposes <br/>
///Capture a distinct list so we collect the plan for each statement once even if there are multiple instances of statements running with the same plan.<br/>
///Filter for plans matching the specified threshold to limit the plans captured to the ones that are likely to be of interest<br/>
///</summary>
private List<Plan> GetPlansList()
{
if (Data.Tables.Contains("RunningQueries"))
{
DataTable dt = Data.Tables["RunningQueries"];
var plans = (from r in dt!.AsEnumerable()
where r["plan_handle"] != DBNull.Value
&& r["query_plan_hash"] != DBNull.Value
&& r["statement_start_offset"] != DBNull.Value
&& r["statement_end_offset"] != DBNull.Value
&& ((byte[])r["query_plan_hash"]).Any(b => b != 0) // Not 0x00000000
group r by new Plan((byte[])r["plan_handle"], (byte[])r["query_plan_hash"], (int)r["statement_start_offset"], (int)r["statement_end_offset"]) into g
where g.Sum(r => Convert.ToInt64(r["cpu_time"])) >= Source.PlanCollectionCPUThreshold || g.Sum(r => Convert.ToInt64(r["granted_query_memory"])) >= Source.PlanCollectionMemoryGrantThreshold || g.Count() >= Source.PlanCollectionCountThreshold || g.Max(r => ((DateTime)r["SnapshotDateUTC"]).Subtract((DateTime)r["last_request_start_time_utc"])).TotalMilliseconds >= Source.PlanCollectionDurationThreshold
select g.Key).Distinct().ToList();
return plans;
}
else
{
return new List<Plan>();
}
}
///<summary>
///Collect query text associated with captured running queries
///</summary>
private void CollectText()
{
if (!Data.Tables.Contains("RunningQueries")) return;
var handlesSQL = GetTextFromHandlesSQL();
if (string.IsNullOrEmpty(handlesSQL)) return;
using var cn = new SqlConnection(ConnectionString);
using var da = new SqlDataAdapter(handlesSQL, cn);
var dt = new DataTable("QueryText");
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Data.Tables.Add(dt);
}
LogInternalPerformanceCounter("DBADash", "Count of text collected", "", dt.Rows.Count); // Count of text collected from sql_handles
LogInternalPerformanceCounter("DBADash", "Count of running queries", "", Data.Tables["RunningQueries"]!.Rows.Count); // Total number of running queries
}
///<summary>
///Once written to the destination, call this function to cache the plan handles and query plan hash. If the plan is cached it won't be collected in future.<br/>
///Note: We are just caching the plan handle and hash with the statement offsets.
///</summary>
public void CacheCollectedPlans()
{
if (!Data.Tables.Contains("QueryPlans")) return;
var dt = Data.Tables["QueryPlans"];
foreach (DataRow r in dt!.Rows)
{
if (r["query_plan_hash"] != DBNull.Value)
{
var plan = new Plan((byte[])r["plan_handle"], (byte[])r["query_plan_hash"], (int)r["statement_start_offset"], (int)r["statement_end_offset"]);
cache.Add(plan.Key, "", policy);
}
}
}
///<summary>
///Once written to the destination, call this function to cache the sql_handles for captured query text. If the handle is cached it won't be collected in future.<br/>
///Note: We capture text at the batch level and can use the statement offsets to get the statement text.
///</summary>
public void CacheCollectedText()
{
if (!Data.Tables.Contains("QueryText")) return;
var dt = Data.Tables["QueryText"];
foreach (DataRow r in dt!.Rows)
{
cache.Add(ByteArrayToHexString((byte[])r["sql_handle"]), "", policy);
}
}
///<summary>
///Generate a SQL query to get the query text associated with the plan handles for running queries
///</summary>
private string GetTextFromHandlesSQL()
{
var handles = RunningQueriesHandles();
int cnt = 0;
int cacheCount = 0;
var sb = new StringBuilder();
sb.Append(@"DECLARE @handles TABLE(sql_handle VARBINARY(64))
INSERT INTO @handles(sql_handle)");
if (IsTableValuedConstructorsSupported)
{
sb.Append("\nVALUES");
}
foreach (string strHandle in handles)
{
if (!cache.Contains(strHandle))
{
if (IsTableValuedConstructorsSupported)
{
if (cnt > 0) sb.Append(',');
sb.Append($"(0x{strHandle})");
}
else
{
if (cnt > 0) sb.Append("\nUNION ALL");
sb.Append($"\nSELECT 0x{strHandle}");
}
cnt++;
}
else
{
cacheCount += 1;
}
}
LogInternalPerformanceCounter("DBADash", "Distinct count of text (sql_handle)", "", handles.Count); // Total number of distinct sql_handles
LogInternalPerformanceCounter("DBADash", "Count of text (sql_handle) to collect", "", cnt); // Count of sql_handles we need to collect
LogInternalPerformanceCounter("DBADash", "Count of text (sql_handle) from cache", "", handles.Count - cnt); // Count of sql_handles we didn't need to collect because they were collected previously and we cached the sql_handle.
if ((cnt + cacheCount) > 0)
{
Log.Information("QueryText: {0} from cache, {1} to collect from {2}", cacheCount, cnt, instanceName);
}
if (cnt == 0)
{
return string.Empty;
}
else
{
sb.AppendLine("OPTION(RECOMPILE)"); // Plan caching is not beneficial. RECOMPILE hint to avoid polluting the plan cache
sb.AppendLine();
sb.AppendLine();
sb.Append(@"SELECT H.sql_handle,
txt.dbid,
txt.objectid as object_id,
txt.encrypted,
txt.text
FROM @handles H
CROSS APPLY sys.dm_exec_sql_text(H.sql_handle) txt
OPTION(RECOMPILE)"); // Plan caching is not beneficial. RECOMPILE hint to avoid polluting the plan cache
return sb.ToString();
}
}
///<summary>
///Get a distinct list of sql_handle for running queries. The handles are later used to capture query text
///</summary>
private List<string> RunningQueriesHandles()
{
var handles = (from r in Data.Tables["RunningQueries"]!.AsEnumerable()
where r["sql_handle"] != DBNull.Value
select ByteArrayToHexString((byte[])r["sql_handle"])).Distinct().ToList();
return handles;
}
private void ExecuteCollection(CollectionType collectionType)
{
var collectionTypeString = EnumToString(collectionType);
// Add params where required
SqlParameter[] param = null;
if (collectionType == CollectionType.JobHistory)
{
param = new[] { new SqlParameter { DbType = DbType.Int32, Value = Job_instance_id, ParameterName = "instance_id" }, new SqlParameter { DbType = DbType.Int32, ParameterName = "run_date", Value = Convert.ToInt32(DateTime.Now.AddDays(-7).ToString("yyyyMMdd")) } };
Log.Debug("JobHistory From {JobInstanceID} on {Instance}", Job_instance_id, Source.SourceConnection.ConnectionForPrint);
}
else if (collectionType is CollectionType.AzureDBResourceStats or CollectionType.AzureDBElasticPoolResourceStats)
{
param = new[] { new SqlParameter("Date", DateTime.UtcNow.AddMinutes(-PerformanceCollectionPeriodMins)) };
}
else if (collectionType == CollectionType.CPU)
{
param = new[] { new SqlParameter("TOP", PerformanceCollectionPeriodMins) };
}
else if (collectionType == CollectionType.IdentityColumns)
{
param = new[] { new SqlParameter("IdentityCollectionThreshold", IdentityCollectionThreshold) };
}
else if (collectionType == CollectionType.IOStats)
{
param = new[] { new SqlParameter("IOCollectionLevel", Source.IOCollectionLevel) };
}
else if (collectionType == CollectionType.TableSize)
{
param = new[] { new SqlParameter("SizeThresholdMB", Source.TableSizeCollectionThresholdMB ?? TableSizeCollectionThresholdMBDefault),
new SqlParameter("TableSizeDatabases", Source.TableSizeDatabases ?? TableSizeDatabasesDefault),
new SqlParameter("MaxTables", Source.TableSizeMaxTableThreshold ?? TableSizeMaxTableThresholdDefault ),
new SqlParameter("MaxDatabases", Source.TableSizeMaxDatabaseThreshold ?? TableSizeMaxDatabaseThreshold)
};
}
if (collectionType == CollectionType.Drives)
{
CollectDrives();
}
else if (collectionType == CollectionType.ServerExtraProperties)
{
CollectServerExtraProperties();
}
else if (collectionType == CollectionType.DriversWMI)
{
CollectDriversWMI();
}
else if (collectionType == CollectionType.SlowQueries)
{
try
{
CollectSlowQueries();
}
catch (SqlException ex) when (ex.Message.StartsWith("Unable to create/alter extended events session: RDS for SQL Server supports extended events"))
{
// RDS instances only support extended events for Standard and Enterprise editions. If we encounter an error because it's not supported, log the error and continue
// Set IsExtendedEventsNotSupportedException which is used to disable the collection for future schedules
Log.Warning("Slow query capture relies on extended events which is not supported for {0}: {1}", instanceName, ex.Message);
LogDBError(collectionTypeString, "Slow query capture relies on extended events which is not supported for this instance", "Collect[Warning]");
IsExtendedEventsNotSupportedException = true;
}
}
else if (collectionType == CollectionType.PerformanceCounters)
{
CollectPerformanceCounters();
}
else if (collectionType == CollectionType.Jobs)
{
var currentJobModified = GetJobLastModified();
if (currentJobModified > JobLastModified)
{
var ss = new AgentJobs(Source.SourceConnection, new SchemaSnapshotDBOptions());