-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathProgram.cs
More file actions
1796 lines (1610 loc) · 82.8 KB
/
Program.cs
File metadata and controls
1796 lines (1610 loc) · 82.8 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
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
/*
* Copyright (c) 2026 Erik Darling, Darling Data LLC
*
* This file is part of the SQL Server Performance Monitor.
*
* Licensed under the MIT License. See LICENSE file in the project root for full license information.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Reflection;
using Microsoft.Data.SqlClient;
namespace PerformanceMonitorInstaller
{
class Program
{
/*
Pre-compiled regex patterns for performance
*/
private static readonly Regex GoBatchPattern = new Regex(
@"^\s*GO\s*(?:--[^\r\n]*)?\s*$",
RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase);
private static readonly Regex SqlFileNamePattern = new Regex(
@"^\d{2}[a-z]?_.*\.sql$",
RegexOptions.Compiled);
private static readonly Regex SqlCmdDirectivePattern = new Regex(
@"^:r\s+.*$",
RegexOptions.Compiled | RegexOptions.Multiline);
/*
SQL command timeout constants (in seconds)
*/
private const int ShortTimeoutSeconds = 60; // Quick operations (cleanup, queries)
private const int MediumTimeoutSeconds = 120; // Dependency installation
private const int LongTimeoutSeconds = 300; // SQL file execution (5 minutes)
/*
Exit codes for granular error reporting
*/
private static class ExitCodes
{
public const int Success = 0;
public const int InvalidArguments = 1;
public const int ConnectionFailed = 2;
public const int CriticalFileFailed = 3;
public const int PartialInstallation = 4;
public const int VersionCheckFailed = 5;
public const int SqlFilesNotFound = 6;
}
static async Task<int> Main(string[] args)
{
var version = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "Unknown";
var infoVersion = Assembly.GetExecutingAssembly()
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? version;
Console.WriteLine("================================================================================");
Console.WriteLine($"Performance Monitor Installation Utility v{infoVersion}");
Console.WriteLine("Copyright © 2026 Darling Data, LLC");
Console.WriteLine("Licensed under the MIT License");
Console.WriteLine("https://github.com/erikdarlingdata/PerformanceMonitor");
Console.WriteLine("================================================================================");
Console.WriteLine();
/*
Determine if running in automated mode (command-line arguments provided)
Usage: PerformanceMonitorInstaller.exe [server] [username] [password] [options]
If server is provided alone, uses Windows Authentication
If server, username, and password are provided, uses SQL Authentication
Options:
--reinstall Drop existing database and perform clean install
--encrypt=X Connection encryption: mandatory (default), optional, strict
--trust-cert Trust server certificate without validation (default: require valid cert)
*/
if (args.Any(a => a.Equals("--help", StringComparison.OrdinalIgnoreCase)
|| a.Equals("-h", StringComparison.OrdinalIgnoreCase)))
{
Console.WriteLine("Usage:");
Console.WriteLine(" PerformanceMonitorInstaller.exe Interactive mode");
Console.WriteLine(" PerformanceMonitorInstaller.exe <server> [options] Windows Auth");
Console.WriteLine(" PerformanceMonitorInstaller.exe <server> <username> <password> SQL Auth");
Console.WriteLine(" PerformanceMonitorInstaller.exe <server> <username> SQL Auth (password via env var)");
Console.WriteLine();
Console.WriteLine("Options:");
Console.WriteLine(" -h, --help Show this help message");
Console.WriteLine(" --reinstall Drop existing database and perform clean install");
Console.WriteLine(" --reset-schedule Reset collection schedule to recommended defaults");
Console.WriteLine(" --preserve-jobs Keep existing SQL Agent jobs (owner, schedule, notifications)");
Console.WriteLine(" --encrypt=<level> Connection encryption: mandatory (default), optional, strict");
Console.WriteLine(" --trust-cert Trust server certificate without validation");
Console.WriteLine();
Console.WriteLine("Environment Variables:");
Console.WriteLine(" PM_SQL_PASSWORD SQL Auth password (avoids passing on command line)");
Console.WriteLine();
Console.WriteLine("Exit Codes:");
Console.WriteLine(" 0 Success");
Console.WriteLine(" 1 Invalid arguments");
Console.WriteLine(" 2 Connection failed");
Console.WriteLine(" 3 Critical file failed");
Console.WriteLine(" 4 Partial installation (non-critical failures)");
Console.WriteLine(" 5 Version check failed");
Console.WriteLine(" 6 SQL files not found");
return 0;
}
bool automatedMode = args.Length > 0;
bool reinstallMode = args.Any(a => a.Equals("--reinstall", StringComparison.OrdinalIgnoreCase));
bool resetSchedule = args.Any(a => a.Equals("--reset-schedule", StringComparison.OrdinalIgnoreCase));
bool preserveJobs = args.Any(a => a.Equals("--preserve-jobs", StringComparison.OrdinalIgnoreCase));
bool trustCert = args.Any(a => a.Equals("--trust-cert", StringComparison.OrdinalIgnoreCase));
/*Parse encryption option (default: Mandatory)*/
var encryptArg = args.FirstOrDefault(a => a.StartsWith("--encrypt=", StringComparison.OrdinalIgnoreCase));
SqlConnectionEncryptOption encryptOption = SqlConnectionEncryptOption.Mandatory;
if (encryptArg != null)
{
string encryptValue = encryptArg.Substring("--encrypt=".Length).ToLowerInvariant();
encryptOption = encryptValue switch
{
"optional" => SqlConnectionEncryptOption.Optional,
"strict" => SqlConnectionEncryptOption.Strict,
_ => SqlConnectionEncryptOption.Mandatory
};
}
/*Filter out option flags to get positional arguments*/
var filteredArgs = args
.Where(a => !a.Equals("--reinstall", StringComparison.OrdinalIgnoreCase))
.Where(a => !a.Equals("--reset-schedule", StringComparison.OrdinalIgnoreCase))
.Where(a => !a.Equals("--preserve-jobs", StringComparison.OrdinalIgnoreCase))
.Where(a => !a.Equals("--trust-cert", StringComparison.OrdinalIgnoreCase))
.Where(a => !a.StartsWith("--encrypt=", StringComparison.OrdinalIgnoreCase))
.ToArray();
string? serverName;
string? username = null;
string? password = null;
bool useWindowsAuth;
if (automatedMode)
{
/*
Automated mode with command-line arguments
*/
serverName = filteredArgs.Length > 0 ? filteredArgs[0] : null;
if (filteredArgs.Length >= 2)
{
/*SQL Authentication - password from env var or command-line*/
useWindowsAuth = false;
username = filteredArgs[1];
string? envPassword = Environment.GetEnvironmentVariable("PM_SQL_PASSWORD");
if (filteredArgs.Length >= 3)
{
password = filteredArgs[2];
if (envPassword == null)
{
Console.WriteLine("Note: Password provided via command-line is visible in process listings.");
Console.WriteLine(" Consider using PM_SQL_PASSWORD environment variable instead.");
Console.WriteLine();
}
}
else if (envPassword != null)
{
password = envPassword;
}
else
{
Console.WriteLine("Error: Password is required for SQL Server Authentication.");
Console.WriteLine("Provide password as third argument or set PM_SQL_PASSWORD environment variable.");
return ExitCodes.InvalidArguments;
}
Console.WriteLine($"Server: {serverName}");
Console.WriteLine($"Authentication: SQL Server ({username})");
}
else if (filteredArgs.Length == 1)
{
/*Windows Authentication*/
useWindowsAuth = true;
Console.WriteLine($"Server: {serverName}");
Console.WriteLine($"Authentication: Windows");
}
else
{
Console.WriteLine("Error: Invalid arguments.");
Console.WriteLine("Usage:");
Console.WriteLine(" Windows Auth: PerformanceMonitorInstaller.exe <server> [options]");
Console.WriteLine(" SQL Auth: PerformanceMonitorInstaller.exe <server> <username> <password> [options]");
Console.WriteLine(" SQL Auth: PerformanceMonitorInstaller.exe <server> <username> [options]");
Console.WriteLine(" (with PM_SQL_PASSWORD environment variable set)");
Console.WriteLine();
Console.WriteLine("Options:");
Console.WriteLine(" --reinstall Drop existing database and perform clean install");
Console.WriteLine(" --reset-schedule Reset collection schedule to recommended defaults");
Console.WriteLine(" --encrypt=<level> Connection encryption: optional (default), mandatory, strict");
Console.WriteLine(" --trust-cert Trust server certificate without validation (default: require valid cert)");
return ExitCodes.InvalidArguments;
}
}
else
{
/*
Interactive mode - prompt for connection information
*/
Console.Write("SQL Server instance (e.g., localhost, SQL2022): ");
serverName = Console.ReadLine();
if (string.IsNullOrWhiteSpace(serverName))
{
Console.WriteLine("Error: Server name is required.");
WaitForExit();
return ExitCodes.InvalidArguments;
}
Console.Write("Use Windows Authentication? (Y/N, default Y): ");
string? authResponse = Console.ReadLine();
useWindowsAuth = string.IsNullOrWhiteSpace(authResponse) ||
authResponse.Trim().Equals("Y", StringComparison.OrdinalIgnoreCase);
if (!useWindowsAuth)
{
Console.Write("SQL Server login: ");
username = Console.ReadLine();
if (string.IsNullOrWhiteSpace(username))
{
Console.WriteLine("Error: Login is required for SQL Server Authentication.");
WaitForExit();
return ExitCodes.InvalidArguments;
}
Console.Write("Password: ");
password = ReadPassword();
Console.WriteLine();
if (string.IsNullOrWhiteSpace(password))
{
Console.WriteLine("Error: Password is required for SQL Server Authentication.");
WaitForExit();
return ExitCodes.InvalidArguments;
}
}
}
/*
Build connection string
*/
var builder = new SqlConnectionStringBuilder
{
DataSource = serverName,
InitialCatalog = "master",
Encrypt = encryptOption,
TrustServerCertificate = trustCert,
IntegratedSecurity = useWindowsAuth
};
if (!useWindowsAuth)
{
builder.UserID = username;
builder.Password = password;
}
/*
Test connection and get SQL Server version
*/
string sqlServerVersion = "";
string sqlServerEdition = "";
Console.WriteLine();
Console.WriteLine("Testing connection...");
try
{
using (var connection = new SqlConnection(builder.ConnectionString))
{
await connection.OpenAsync().ConfigureAwait(false);
Console.WriteLine("Connection successful!");
/*Capture SQL Server version for summary report*/
using (var versionCmd = new SqlCommand("SELECT @@VERSION, SERVERPROPERTY('Edition');", connection))
{
using (var reader = await versionCmd.ExecuteReaderAsync().ConfigureAwait(false))
{
if (await reader.ReadAsync().ConfigureAwait(false))
{
sqlServerVersion = reader.GetString(0);
sqlServerEdition = reader.GetString(1);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Connection failed: {ex.Message}");
Console.WriteLine($"Exception type: {ex.GetType().Name}");
if (ex.InnerException != null)
{
Console.WriteLine($"Inner exception: {ex.InnerException.Message}");
}
if (!automatedMode)
{
WaitForExit();
}
return ExitCodes.ConnectionFailed;
}
/*
Find SQL files to execute (do this once before the installation loop)
Search current directory and up to 5 parent directories
Prefer install/ subfolder if it exists (new structure)
*/
string? sqlDirectory = null;
string? monitorRootDirectory = null;
string currentDirectory = Directory.GetCurrentDirectory();
DirectoryInfo? searchDir = new DirectoryInfo(currentDirectory);
for (int i = 0; i < 6 && searchDir != null; i++)
{
/*Check for install/ subfolder first (new structure)*/
string installFolder = Path.Combine(searchDir.FullName, "install");
if (Directory.Exists(installFolder))
{
var installFiles = Directory.GetFiles(installFolder, "*.sql")
.Where(f => SqlFileNamePattern.IsMatch(Path.GetFileName(f)))
.ToList();
if (installFiles.Count > 0)
{
sqlDirectory = installFolder;
monitorRootDirectory = searchDir.FullName;
break;
}
}
/*Fall back to old structure (SQL files in root)*/
var files = Directory.GetFiles(searchDir.FullName, "*.sql")
.Where(f => SqlFileNamePattern.IsMatch(Path.GetFileName(f)))
.ToList();
if (files.Count > 0)
{
sqlDirectory = searchDir.FullName;
monitorRootDirectory = searchDir.FullName;
break;
}
searchDir = searchDir.Parent;
}
if (sqlDirectory == null)
{
Console.WriteLine($"Error: No SQL installation files found.");
Console.WriteLine($"Searched in: {currentDirectory}");
Console.WriteLine("Expected files in install/ folder or root directory:");
Console.WriteLine(" install/01_install_database.sql, install/02_create_tables.sql, etc.");
Console.WriteLine();
Console.WriteLine("Make sure the installer is in the Monitor directory or a subdirectory.");
if (!automatedMode)
{
WaitForExit();
}
return ExitCodes.SqlFilesNotFound;
}
var sqlFiles = Directory.GetFiles(sqlDirectory, "*.sql")
.Where(f =>
{
string fileName = Path.GetFileName(f);
if (!SqlFileNamePattern.IsMatch(fileName))
return false;
/*Exclude test and troubleshooting scripts from main install*/
if (fileName.StartsWith("97_", StringComparison.Ordinal) ||
fileName.StartsWith("99_", StringComparison.Ordinal))
return false;
return true;
})
.OrderBy(f => Path.GetFileName(f))
.ToList();
Console.WriteLine();
Console.WriteLine($"Found {sqlFiles.Count} SQL files in: {sqlDirectory}");
if (monitorRootDirectory != sqlDirectory)
{
Console.WriteLine($"Using new folder structure (install/ subfolder)");
}
/*
Main installation loop - allows retry on failure
*/
int upgradeSuccessCount = 0;
int upgradeFailureCount = 0;
int installSuccessCount = 0;
int installFailureCount = 0;
int totalSuccessCount = 0;
int totalFailureCount = 0;
var installationErrors = new List<(string FileName, string ErrorMessage)>();
bool installationSuccessful = false;
bool retry;
DateTime installationStartTime = DateTime.Now;
do
{
retry = false;
upgradeSuccessCount = 0;
upgradeFailureCount = 0;
installSuccessCount = 0;
installFailureCount = 0;
installationErrors.Clear();
installationSuccessful = false;
installationStartTime = DateTime.Now;
/*
Ask about clean install (automated mode preserves database unless --reinstall flag is used)
*/
bool dropExisting;
if (automatedMode)
{
dropExisting = reinstallMode;
Console.WriteLine();
if (reinstallMode)
{
Console.WriteLine("Automated mode: Performing clean reinstall (dropping existing database)...");
}
else
{
Console.WriteLine("Automated mode: Performing upgrade (preserving existing database)...");
}
}
else
{
Console.WriteLine();
Console.Write("Drop existing PerformanceMonitor database if it exists? (Y/N, default N): ");
string? cleanInstall = Console.ReadLine();
dropExisting = cleanInstall?.Trim().Equals("Y", StringComparison.OrdinalIgnoreCase) ?? false;
}
if (dropExisting)
{
Console.WriteLine();
Console.WriteLine("Performing clean install...");
try
{
using (var connection = new SqlConnection(builder.ConnectionString))
{
await connection.OpenAsync().ConfigureAwait(false);
/*
Stop any existing traces before dropping database
Traces are server-level and persist after database drops
Use existing procedure if database exists
*/
try
{
using (var command = new SqlCommand("EXECUTE PerformanceMonitor.collect.trace_management_collector @action = 'STOP';", connection))
{
command.CommandTimeout = ShortTimeoutSeconds;
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
Console.WriteLine("✓ Stopped existing traces");
}
}
catch (SqlException)
{
/*Database or procedure doesn't exist - no traces to clean*/
}
string cleanupSql = @"
/*
Remove any existing Agent jobs
*/
USE msdb;
IF EXISTS (SELECT 1 FROM msdb.dbo.sysjobs WHERE name = N'PerformanceMonitor - Collection')
BEGIN
EXECUTE msdb.dbo.sp_delete_job @job_name = N'PerformanceMonitor - Collection';
PRINT 'Dropped PerformanceMonitor - Collection job';
END;
IF EXISTS (SELECT 1 FROM msdb.dbo.sysjobs WHERE name = N'PerformanceMonitor - Data Retention')
BEGIN
EXECUTE msdb.dbo.sp_delete_job @job_name = N'PerformanceMonitor - Data Retention';
PRINT 'Dropped PerformanceMonitor - Data Retention job';
END;
/*
Drop the database
*/
USE master;
IF EXISTS (SELECT 1 FROM sys.databases WHERE name = N'PerformanceMonitor')
BEGIN
ALTER DATABASE PerformanceMonitor SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE PerformanceMonitor;
PRINT 'PerformanceMonitor database dropped successfully';
END
ELSE
BEGIN
PRINT 'PerformanceMonitor database does not exist';
END";
using (var command = new SqlCommand(cleanupSql, connection))
{
command.CommandTimeout = ShortTimeoutSeconds;
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
}
}
Console.WriteLine("✓ Clean install completed (jobs and database removed)");
}
catch (Exception ex)
{
Console.WriteLine($"Warning: Could not complete cleanup: {ex.Message}");
Console.WriteLine("Continuing with installation...");
}
}
else
{
/*
Upgrade mode - check for existing installation and apply upgrades
*/
string? currentVersion = null;
try
{
currentVersion = await GetInstalledVersion(builder.ConnectionString);
}
catch (InvalidOperationException ex)
{
Console.WriteLine();
Console.WriteLine("================================================================================");
Console.WriteLine("ERROR: Failed to check for existing installation");
Console.WriteLine("================================================================================");
Console.WriteLine(ex.Message);
if (ex.InnerException != null)
{
Console.WriteLine($"Details: {ex.InnerException.Message}");
}
Console.WriteLine();
Console.WriteLine("This may indicate a permissions issue or database corruption.");
Console.WriteLine("Please review the error log and report this issue if it persists.");
Console.WriteLine();
/*Write error log for bug reporting*/
string errorLogPath = WriteErrorLog(ex, serverName!, infoVersion);
Console.WriteLine($"Error log written to: {errorLogPath}");
if (!automatedMode)
{
WaitForExit();
}
return ExitCodes.VersionCheckFailed;
}
if (currentVersion != null && monitorRootDirectory != null)
{
Console.WriteLine();
Console.WriteLine($"Existing installation detected: v{currentVersion}");
Console.WriteLine("Checking for applicable upgrades...");
var upgrades = GetApplicableUpgrades(monitorRootDirectory, currentVersion, version);
if (upgrades.Count > 0)
{
Console.WriteLine($"Found {upgrades.Count} upgrade(s) to apply.");
Console.WriteLine();
Console.WriteLine("================================================================================" );
Console.WriteLine("Applying upgrades...");
Console.WriteLine("================================================================================");
using (var connection = new SqlConnection(builder.ConnectionString))
{
await connection.OpenAsync().ConfigureAwait(false);
foreach (var upgradeFolder in upgrades)
{
var (upgradeSuccess, upgradeFail) = await ExecuteUpgrade(upgradeFolder, connection);
upgradeSuccessCount += upgradeSuccess;
upgradeFailureCount += upgradeFail;
}
}
Console.WriteLine();
Console.WriteLine($"Upgrades complete: {upgradeSuccessCount} succeeded, {upgradeFailureCount} failed");
}
else
{
Console.WriteLine("No pending upgrades found.");
}
}
else
{
Console.WriteLine();
Console.WriteLine("No existing installation detected, proceeding with fresh install...");
}
}
/*
Execute SQL files in order
*/
Console.WriteLine();
Console.WriteLine("================================================================================");
Console.WriteLine("Starting installation...");
Console.WriteLine("================================================================================");
Console.WriteLine();
/*
Open a single connection for all SQL file execution
Connection pooling handles the underlying socket reuse
*/
bool communityDepsInstalled = false;
using (var connection = new SqlConnection(builder.ConnectionString))
{
await connection.OpenAsync().ConfigureAwait(false);
foreach (var sqlFile in sqlFiles)
{
string fileName = Path.GetFileName(sqlFile);
/*Install community dependencies before validation runs
Collectors in 98_validate need sp_WhoIsActive, sp_HealthParser, etc.*/
if (!communityDepsInstalled &&
fileName.StartsWith("98_", StringComparison.Ordinal))
{
communityDepsInstalled = true;
try
{
await InstallDependenciesAsync(builder.ConnectionString);
}
catch (Exception ex)
{
Console.WriteLine($"Warning: Dependency installation encountered errors: {ex.Message}");
Console.WriteLine("Continuing with installation...");
}
}
Console.Write($"Executing {fileName}... ");
try
{
string sqlContent = await File.ReadAllTextAsync(sqlFile);
/*
Reset schedule to defaults if requested — truncate before the
INSERT...WHERE NOT EXISTS re-populates with current recommended values
*/
if (resetSchedule && fileName.StartsWith("04_", StringComparison.Ordinal))
{
sqlContent = "TRUNCATE TABLE [PerformanceMonitor].[config].[collection_schedule];\nGO\n" + sqlContent;
Console.Write("(resetting schedule) ");
}
/*
Preserve existing SQL Agent jobs if requested — flip the T-SQL
variable so existing jobs are left untouched during upgrade
*/
if (preserveJobs && fileName.StartsWith("45_", StringComparison.Ordinal))
{
sqlContent = sqlContent.Replace("@preserve_jobs bit = 0", "@preserve_jobs bit = 1");
Console.Write("(preserving existing jobs) ");
}
/*
Remove SQLCMD directives (:r includes) as we're executing files directly
*/
sqlContent = SqlCmdDirectivePattern.Replace(sqlContent, "");
/*
Split by GO statements using pre-compiled regex
Match GO only when it's a whole word on its own line
*/
string[] batches = GoBatchPattern.Split(sqlContent);
int batchNumber = 0;
foreach (string batch in batches)
{
string trimmedBatch = batch.Trim();
/*Skip empty batches*/
if (string.IsNullOrWhiteSpace(trimmedBatch))
continue;
batchNumber++;
using (var command = new SqlCommand(trimmedBatch, connection))
{
command.CommandTimeout = LongTimeoutSeconds;
try
{
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
}
catch (SqlException ex)
{
/*Add batch info to error message*/
string batchPreview = trimmedBatch.Length > 500 ?
trimmedBatch.Substring(0, 500) + $"... [truncated, total length: {trimmedBatch.Length}]" :
trimmedBatch;
throw new InvalidOperationException($"Batch {batchNumber} failed:\n{batchPreview}\n\nOriginal error: {ex.Message}", ex);
}
}
}
Console.WriteLine("✓ Success");
installSuccessCount++;
}
catch (Exception ex)
{
Console.WriteLine($"✗ FAILED");
Console.WriteLine($" Error: {ex.Message}");
installFailureCount++;
installationErrors.Add((fileName, ex.Message));
if (fileName.StartsWith("01_", StringComparison.Ordinal) || fileName.StartsWith("02_", StringComparison.Ordinal) || fileName.StartsWith("03_", StringComparison.Ordinal))
{
Console.WriteLine();
Console.WriteLine("Critical installation file failed. Aborting installation.");
if (!automatedMode)
{
WaitForExit();
}
return ExitCodes.CriticalFileFailed;
}
}
}
}
Console.WriteLine();
Console.WriteLine("================================================================================");
Console.WriteLine("File Execution Summary");
Console.WriteLine("================================================================================");
if (upgradeSuccessCount > 0 || upgradeFailureCount > 0)
{
Console.WriteLine($"Upgrades: {upgradeSuccessCount} succeeded, {upgradeFailureCount} failed");
}
Console.WriteLine($"Installation: {installSuccessCount} succeeded, {installFailureCount} failed");
Console.WriteLine();
/*
Install community dependencies if not already done (no 98_ files in batch)
*/
if (!communityDepsInstalled && installFailureCount <= 1)
{
try
{
await InstallDependenciesAsync(builder.ConnectionString);
}
catch (Exception ex)
{
Console.WriteLine($"Warning: Dependency installation encountered errors: {ex.Message}");
Console.WriteLine("Continuing with validation...");
}
}
/*
Run initial collection and retry failed views
This validates the installation and creates dynamically-generated tables
*/
if (installFailureCount <= 1 && automatedMode) /* Allow 1 failure for query_snapshots view */
{
Console.WriteLine();
Console.WriteLine("================================================================================");
Console.WriteLine("Running initial collection to validate installation...");
Console.WriteLine("================================================================================");
Console.WriteLine();
try
{
using (var connection = new SqlConnection(builder.ConnectionString))
{
await connection.OpenAsync().ConfigureAwait(false);
/*Run master collector once with @force_run_all to collect everything immediately*/
Console.Write("Executing master collector... ");
using (var command = new SqlCommand("EXECUTE PerformanceMonitor.collect.scheduled_master_collector @force_run_all = 1, @debug = 0;", connection))
{
command.CommandTimeout = LongTimeoutSeconds;
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
}
Console.WriteLine("✓ Success");
/*
Verify data was collected
*/
Console.WriteLine();
Console.Write("Verifying data collection... ");
/* First check total count in collection_log */
int totalLogEntries = 0;
using (var command = new SqlCommand(@"
SELECT COUNT(*) FROM PerformanceMonitor.config.collection_log;", connection))
{
totalLogEntries = (int)(await command.ExecuteScalarAsync().ConfigureAwait(false) ?? 0);
}
/* Check successful collections (all time - we just installed) */
int collectedCount = 0;
using (var command = new SqlCommand(@"
SELECT
COUNT(DISTINCT collector_name)
FROM PerformanceMonitor.config.collection_log
WHERE collection_status = 'SUCCESS';", connection))
{
collectedCount = (int)(await command.ExecuteScalarAsync().ConfigureAwait(false) ?? 0);
}
Console.WriteLine($"✓ {collectedCount} collectors ran successfully (total log entries: {totalLogEntries})");
/* Show failed collectors if any */
int errorCount = 0;
using (var command = new SqlCommand(@"
SELECT COUNT(*) FROM PerformanceMonitor.config.collection_log WHERE collection_status = 'ERROR';", connection))
{
errorCount = (int)(await command.ExecuteScalarAsync().ConfigureAwait(false) ?? 0);
}
if (errorCount > 0)
{
Console.WriteLine();
Console.WriteLine($"⚠ {errorCount} collector(s) encountered errors:");
using (var command = new SqlCommand(@"
SELECT
collector_name,
error_message
FROM PerformanceMonitor.config.collection_log
WHERE collection_status = 'ERROR'
ORDER BY collection_time DESC;", connection))
{
using (var reader = await command.ExecuteReaderAsync().ConfigureAwait(false))
{
while (await reader.ReadAsync().ConfigureAwait(false))
{
string name = reader["collector_name"]?.ToString() ?? "";
string error = reader["error_message"] == DBNull.Value ? "(no error message)" : reader["error_message"]?.ToString() ?? "";
Console.WriteLine($" ✗ {name}");
Console.WriteLine($" {error}");
}
}
}
}
/* Show recent log entries for debugging */
if (totalLogEntries > 0 && errorCount == 0)
{
Console.WriteLine();
Console.WriteLine("Sample collection log entries:");
using (var command = new SqlCommand(@"
SELECT TOP 5
collector_name,
collection_status,
rows_collected,
error_message
FROM PerformanceMonitor.config.collection_log
WHERE collection_status = 'SUCCESS'
ORDER BY collection_time DESC;", connection))
{
using (var reader = await command.ExecuteReaderAsync().ConfigureAwait(false))
{
while (await reader.ReadAsync().ConfigureAwait(false))
{
string status = reader["collection_status"]?.ToString() ?? "";
string name = reader["collector_name"]?.ToString() ?? "";
int rows = (int)reader["rows_collected"];
string error = reader["error_message"] == DBNull.Value ? "" : $" - {reader["error_message"]}";
Console.WriteLine($" {status,10}: {name,-35} ({rows,4} rows){error}");
}
}
}
}
/*
Check if sp_WhoIsActive created query_snapshots table
The collector creates daily tables like query_snapshots_20260102
*/
if (installFailureCount > 0)
{
Console.WriteLine();
Console.Write("Checking for query_snapshots table... ");
bool tableExists = false;
using (var command = new SqlCommand(@"
SELECT TOP (1) 1
FROM sys.tables AS t
WHERE t.name LIKE 'query_snapshots_%'
AND t.schema_id = SCHEMA_ID('collect');", connection))
{
var result = await command.ExecuteScalarAsync().ConfigureAwait(false);
tableExists = result != null && result != DBNull.Value;
}
if (tableExists)
{
Console.WriteLine("✓ Found");
Console.Write("Retrying query plan views... ");
try
{
string viewFile = Path.Combine(sqlDirectory, "46_create_query_plan_views.sql");
if (File.Exists(viewFile))
{
string sqlContent = await File.ReadAllTextAsync(viewFile);
sqlContent = SqlCmdDirectivePattern.Replace(sqlContent, "");
string[] batches = GoBatchPattern.Split(sqlContent);
foreach (string batch in batches)
{
string trimmedBatch = batch.Trim();
if (string.IsNullOrWhiteSpace(trimmedBatch)) continue;
using (var command = new SqlCommand(trimmedBatch, connection))
{
command.CommandTimeout = ShortTimeoutSeconds;
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
}
}
Console.WriteLine("✓ Success");
installFailureCount = 0; /* Reset failure count */
}
}
catch (SqlException)
{
Console.WriteLine("✗ Skipped (sp_WhoIsActive not installed or incompatible schema)");
/*This is expected if sp_WhoIsActive isn't installed - keep installFailureCount = 1 but don't error*/
}
catch (IOException)
{
Console.WriteLine("✗ Skipped (could not read view file)");
}
}
else
{
Console.WriteLine("✗ Not created (sp_WhoIsActive installation may have failed)");
Console.WriteLine();
Console.WriteLine("NOTE: The query_snapshots table creation depends on sp_WhoIsActive");
Console.WriteLine(" The view will be created automatically on next collection if available");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"✗ Failed");
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine();
Console.WriteLine("Installation completed but initial collection failed.");
Console.WriteLine("Check PerformanceMonitor.config.collection_log for details.");
}
}
/*
Installation summary
Calculate totals and determine success
Treat query_snapshots view failure as a warning, not an error
*/
totalSuccessCount = upgradeSuccessCount + installSuccessCount;
totalFailureCount = upgradeFailureCount + installFailureCount;
installationSuccessful = (totalFailureCount == 0) || (totalFailureCount == 1 && automatedMode);
/*
Log installation history to database
*/
try
{
await LogInstallationHistory(
builder.ConnectionString,
version,
infoVersion,
installationStartTime,
totalSuccessCount,
totalFailureCount,
installationSuccessful
);
}
catch (Exception ex)
{
Console.WriteLine($"Warning: Could not log installation history: {ex.Message}");
}
Console.WriteLine();
Console.WriteLine("================================================================================");
Console.WriteLine("Installation Summary");
Console.WriteLine("================================================================================");
if (installationSuccessful)
{
Console.WriteLine("Installation completed successfully!");
Console.WriteLine();
Console.WriteLine("WHAT WAS INSTALLED:");
Console.WriteLine("✓ PerformanceMonitor database and all collection tables");
Console.WriteLine("✓ All collector stored procedures");
Console.WriteLine("✓ Community dependencies (sp_WhoIsActive, DarlingData, First Responder Kit)");
Console.WriteLine("✓ SQL Agent Job: PerformanceMonitor - Collection (runs every 1 minute)");
Console.WriteLine("✓ SQL Agent Job: PerformanceMonitor - Data Retention (runs daily at 2:00 AM)");