-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathInstallationService.cs
More file actions
1322 lines (1149 loc) · 53.1 KB
/
InstallationService.cs
File metadata and controls
1322 lines (1149 loc) · 53.1 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.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
namespace PerformanceMonitorInstallerGui.Services
{
/// <summary>
/// Progress information for installation steps
/// </summary>
public class InstallationProgress
{
public string Message { get; set; } = string.Empty;
public string Status { get; set; } = "Info"; // Info, Success, Error, Warning
public int? CurrentStep { get; set; }
public int? TotalSteps { get; set; }
public int? ProgressPercent { get; set; }
}
/// <summary>
/// Server information returned from connection test
/// </summary>
public class ServerInfo
{
public string ServerName { get; set; } = string.Empty;
public string SqlServerVersion { get; set; } = string.Empty;
public string SqlServerEdition { get; set; } = string.Empty;
public bool IsConnected { get; set; }
public string? ErrorMessage { get; set; }
}
/// <summary>
/// Installation result summary
/// </summary>
public class InstallationResult
{
public bool Success { get; set; }
public int FilesSucceeded { get; set; }
public int FilesFailed { get; set; }
public List<(string FileName, string ErrorMessage)> Errors { get; } = new();
public List<(string Message, string Status)> LogMessages { get; } = new();
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string? ReportPath { get; set; }
}
/// <summary>
/// Service for installing the Performance Monitor database
/// </summary>
public class InstallationService : IDisposable
{
private readonly HttpClient _httpClient;
private bool _disposed;
/*
Compiled regex patterns for better performance
*/
private static readonly Regex SqlFilePattern = new(
@"^\d{2}[a-z]?_.*\.sql$",
RegexOptions.Compiled);
private static readonly Regex SqlCmdDirectivePattern = new(
@"^:r\s+.*$",
RegexOptions.Compiled | RegexOptions.Multiline);
private static readonly Regex GoBatchSplitter = new(
@"^\s*GO\s*(?:--[^\r\n]*)?\s*$",
RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase);
private static readonly char[] NewLineChars = { '\r', '\n' };
public InstallationService()
{
_httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(30)
};
}
/// <summary>
/// Build a connection string from the provided parameters
/// </summary>
public static string BuildConnectionString(
string server,
bool useWindowsAuth,
string? username = null,
string? password = null,
string encryption = "Mandatory",
bool trustCertificate = false)
{
var builder = new SqlConnectionStringBuilder
{
DataSource = server,
InitialCatalog = "master",
TrustServerCertificate = trustCertificate,
IntegratedSecurity = useWindowsAuth
};
/*Set encryption mode: Optional, Mandatory, or Strict*/
builder.Encrypt = encryption switch
{
"Mandatory" => SqlConnectionEncryptOption.Mandatory,
"Strict" => SqlConnectionEncryptOption.Strict,
_ => SqlConnectionEncryptOption.Mandatory
};
if (!useWindowsAuth)
{
builder.UserID = username;
builder.Password = password;
}
return builder.ConnectionString;
}
/// <summary>
/// Test connection to SQL Server and get server information
/// </summary>
public static async Task<ServerInfo> TestConnectionAsync(string connectionString, CancellationToken cancellationToken = default)
{
var info = new ServerInfo();
try
{
using var connection = new SqlConnection(connectionString);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
info.IsConnected = true;
using var command = new SqlCommand("SELECT @@VERSION, SERVERPROPERTY('Edition'), @@SERVERNAME;", connection);
using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
if (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
info.SqlServerVersion = reader.GetString(0);
info.SqlServerEdition = reader.GetString(1);
info.ServerName = reader.GetString(2);
}
}
catch (Exception ex)
{
info.IsConnected = false;
info.ErrorMessage = ex.Message;
if (ex.InnerException != null)
{
info.ErrorMessage += $"\n{ex.InnerException.Message}";
}
}
return info;
}
/// <summary>
/// Find SQL installation files
/// </summary>
public static (string? SqlDirectory, string? MonitorRootDirectory, List<string> SqlFiles) FindInstallationFiles()
{
string? sqlDirectory = null;
string? monitorRootDirectory = null;
var sqlFiles = new List<string>();
/*Try multiple starting locations: current directory and executable location*/
var startingDirectories = new List<string>
{
Directory.GetCurrentDirectory(),
AppDomain.CurrentDomain.BaseDirectory
};
foreach (string startDir in startingDirectories.Distinct())
{
if (sqlDirectory != null)
break;
DirectoryInfo? searchDir = new DirectoryInfo(startDir);
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 => SqlFilePattern.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 => SqlFilePattern.IsMatch(Path.GetFileName(f)))
.ToList();
if (files.Count > 0)
{
sqlDirectory = searchDir.FullName;
monitorRootDirectory = searchDir.FullName;
break;
}
searchDir = searchDir.Parent;
}
}
if (sqlDirectory != null)
{
sqlFiles = Directory.GetFiles(sqlDirectory, "*.sql")
.Where(f =>
{
string fileName = Path.GetFileName(f);
/*Match numbered SQL files but exclude 97 (tests) and 99 (troubleshooting)*/
if (!SqlFilePattern.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();
}
return (sqlDirectory, monitorRootDirectory, sqlFiles);
}
/// <summary>
/// Perform clean install (drop existing database and jobs)
/// </summary>
public static async Task CleanInstallAsync(
string connectionString,
IProgress<InstallationProgress>? progress = null,
CancellationToken cancellationToken = default)
{
progress?.Report(new InstallationProgress
{
Message = "Performing clean install...",
Status = "Info"
});
using var connection = new SqlConnection(connectionString);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
/*
Stop any existing traces before dropping database
*/
try
{
using var traceCmd = new SqlCommand(
"EXECUTE PerformanceMonitor.collect.trace_management_collector @action = 'STOP';",
connection);
traceCmd.CommandTimeout = 60;
await traceCmd.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
progress?.Report(new InstallationProgress
{
Message = "Stopped existing traces",
Status = "Success"
});
}
catch (SqlException)
{
/*Database or procedure doesn't exist - no traces to clean*/
}
/*
Remove Agent jobs and database
*/
string cleanupSql = @"
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';
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';
END;
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;
END;";
using var command = new SqlCommand(cleanupSql, connection);
command.CommandTimeout = 60;
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
progress?.Report(new InstallationProgress
{
Message = "Clean install completed (jobs and database removed)",
Status = "Success"
});
}
/// <summary>
/// Execute SQL installation files
/// </summary>
public static async Task<InstallationResult> ExecuteInstallationAsync(
string connectionString,
List<string> sqlFiles,
bool cleanInstall,
bool resetSchedule = false,
bool preserveJobs = false,
IProgress<InstallationProgress>? progress = null,
Func<Task>? preValidationAction = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(sqlFiles);
var result = new InstallationResult
{
StartTime = DateTime.Now
};
/*
Perform clean install if requested
*/
if (cleanInstall)
{
try
{
await CleanInstallAsync(connectionString, progress, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
progress?.Report(new InstallationProgress
{
Message = $"CLEAN INSTALL FAILED: {ex.Message}",
Status = "Error"
});
progress?.Report(new InstallationProgress
{
Message = "Installation aborted - clean install was requested but failed.",
Status = "Error"
});
result.EndTime = DateTime.Now;
result.Success = false;
result.FilesFailed = 1;
result.Errors.Add(("Clean Install", ex.Message));
return result;
}
}
/*
Execute SQL files
Note: Files execute without transaction wrapping because many contain DDL.
If installation fails mid-way, use clean install to reset and retry.
*/
progress?.Report(new InstallationProgress
{
Message = "Starting installation...",
Status = "Info",
CurrentStep = 0,
TotalSteps = sqlFiles.Count,
ProgressPercent = 0
});
bool preValidationActionRan = false;
for (int i = 0; i < sqlFiles.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
string sqlFile = sqlFiles[i];
string fileName = Path.GetFileName(sqlFile);
/*Install community dependencies before validation runs
Collectors in 98_validate need sp_WhoIsActive, sp_HealthParser, etc.*/
if (!preValidationActionRan &&
preValidationAction != null &&
fileName.StartsWith("98_", StringComparison.Ordinal))
{
preValidationActionRan = true;
await preValidationAction().ConfigureAwait(false);
}
progress?.Report(new InstallationProgress
{
Message = $"Executing {fileName}...",
Status = "Info",
CurrentStep = i + 1,
TotalSteps = sqlFiles.Count,
ProgressPercent = (int)(((i + 1) / (double)sqlFiles.Count) * 100)
});
try
{
string sqlContent = await File.ReadAllTextAsync(sqlFile, cancellationToken).ConfigureAwait(false);
/*Reset schedule to defaults if requested*/
if (resetSchedule && fileName.StartsWith("04_", StringComparison.Ordinal))
{
sqlContent = "TRUNCATE TABLE [PerformanceMonitor].[config].[collection_schedule];\nGO\n" + sqlContent;
progress?.Report(new InstallationProgress
{
Message = "Resetting schedule to recommended defaults...",
Status = "Info"
});
}
/*Preserve existing SQL Agent jobs if requested*/
if (preserveJobs && fileName.StartsWith("45_", StringComparison.Ordinal))
{
sqlContent = sqlContent.Replace("@preserve_jobs bit = 0", "@preserve_jobs bit = 1");
progress?.Report(new InstallationProgress
{
Message = "Preserving existing SQL Agent jobs...",
Status = "Info"
});
}
/*Remove SQLCMD directives*/
sqlContent = SqlCmdDirectivePattern.Replace(sqlContent, "");
/*Execute the SQL batch*/
using var connection = new SqlConnection(connectionString);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
/*Split by GO statements*/
string[] batches = GoBatchSplitter.Split(sqlContent);
int batchNumber = 0;
foreach (string batch in batches)
{
string trimmedBatch = batch.Trim();
if (string.IsNullOrWhiteSpace(trimmedBatch))
continue;
batchNumber++;
using var command = new SqlCommand(trimmedBatch, connection);
command.CommandTimeout = 300;
try
{
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
catch (SqlException ex)
{
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);
}
}
progress?.Report(new InstallationProgress
{
Message = $"{fileName} - Success",
Status = "Success",
CurrentStep = i + 1,
TotalSteps = sqlFiles.Count,
ProgressPercent = (int)(((i + 1) / (double)sqlFiles.Count) * 100)
});
result.FilesSucceeded++;
}
catch (Exception ex)
{
progress?.Report(new InstallationProgress
{
Message = $"{fileName} - FAILED: {ex.Message}",
Status = "Error",
CurrentStep = i + 1,
TotalSteps = sqlFiles.Count
});
result.FilesFailed++;
result.Errors.Add((fileName, ex.Message));
/*Critical files abort installation*/
if (fileName.StartsWith("01_", StringComparison.Ordinal) ||
fileName.StartsWith("02_", StringComparison.Ordinal) ||
fileName.StartsWith("03_", StringComparison.Ordinal))
{
progress?.Report(new InstallationProgress
{
Message = "Critical installation file failed. Aborting installation.",
Status = "Error"
});
break;
}
}
}
result.EndTime = DateTime.Now;
/*Allow query_snapshots to fail - those views get created eventually*/
bool onlyQuerySnapshotsFailed = result.FilesFailed == 1 &&
result.Errors.Any(e => e.FileName.Contains("query_snapshots", StringComparison.OrdinalIgnoreCase));
result.Success = result.FilesFailed == 0 || onlyQuerySnapshotsFailed;
return result;
}
/// <summary>
/// Install community dependencies (sp_WhoIsActive, DarlingData, First Responder Kit)
/// </summary>
public async Task<int> InstallDependenciesAsync(
string connectionString,
IProgress<InstallationProgress>? progress = null,
CancellationToken cancellationToken = default)
{
var dependencies = new List<(string Name, string Url, string Description)>
{
(
"sp_WhoIsActive",
"https://raw.githubusercontent.com/amachanic/sp_whoisactive/refs/heads/master/sp_WhoIsActive.sql",
"Query activity monitoring by Adam Machanic (GPLv3)"
),
(
"DarlingData",
"https://raw.githubusercontent.com/erikdarlingdata/DarlingData/main/Install-All/DarlingData.sql",
"sp_HealthParser, sp_HumanEventsBlockViewer by Erik Darling (MIT)"
),
(
"First Responder Kit",
"https://raw.githubusercontent.com/BrentOzarULTD/SQL-Server-First-Responder-Kit/refs/heads/main/Install-All-Scripts.sql",
"sp_BlitzLock and diagnostic tools by Brent Ozar Unlimited (MIT)"
)
};
progress?.Report(new InstallationProgress
{
Message = "Installing community dependencies...",
Status = "Info"
});
int successCount = 0;
foreach (var (name, url, description) in dependencies)
{
cancellationToken.ThrowIfCancellationRequested();
progress?.Report(new InstallationProgress
{
Message = $"Installing {name}...",
Status = "Info"
});
try
{
string sql = await DownloadWithRetryAsync(_httpClient, url, progress, cancellationToken: cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(sql))
{
progress?.Report(new InstallationProgress
{
Message = $"{name} - FAILED (empty response)",
Status = "Error"
});
continue;
}
using var connection = new SqlConnection(connectionString);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
using (var useDbCommand = new SqlCommand("USE PerformanceMonitor;", connection))
{
await useDbCommand.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
string[] batches = GoBatchSplitter.Split(sql);
foreach (string batch in batches)
{
string trimmedBatch = batch.Trim();
if (string.IsNullOrWhiteSpace(trimmedBatch))
continue;
using var command = new SqlCommand(trimmedBatch, connection);
command.CommandTimeout = 120;
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
progress?.Report(new InstallationProgress
{
Message = $"{name} - Success ({description})",
Status = "Success"
});
successCount++;
}
catch (HttpRequestException ex)
{
progress?.Report(new InstallationProgress
{
Message = $"{name} - Download failed: {ex.Message}",
Status = "Error"
});
}
catch (SqlException ex)
{
progress?.Report(new InstallationProgress
{
Message = $"{name} - SQL execution failed: {ex.Message}",
Status = "Error"
});
}
catch (Exception ex)
{
progress?.Report(new InstallationProgress
{
Message = $"{name} - Failed: {ex.Message}",
Status = "Error"
});
}
}
progress?.Report(new InstallationProgress
{
Message = $"Dependencies installed: {successCount}/{dependencies.Count}",
Status = successCount == dependencies.Count ? "Success" : "Warning"
});
return successCount;
}
/// <summary>
/// Run validation (master collector) after installation
/// </summary>
public static async Task<(int CollectorsSucceeded, int CollectorsFailed)> RunValidationAsync(
string connectionString,
IProgress<InstallationProgress>? progress = null,
CancellationToken cancellationToken = default)
{
progress?.Report(new InstallationProgress
{
Message = "Running initial collection to validate installation...",
Status = "Info"
});
using var connection = new SqlConnection(connectionString);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
/*Run master collector with @force_run_all*/
progress?.Report(new InstallationProgress
{
Message = "Executing master collector...",
Status = "Info"
});
using (var command = new SqlCommand(
"EXECUTE PerformanceMonitor.collect.scheduled_master_collector @force_run_all = 1, @debug = 0;",
connection))
{
command.CommandTimeout = 300;
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
progress?.Report(new InstallationProgress
{
Message = "Master collector completed",
Status = "Success"
});
/*Check results*/
int successCount = 0;
int errorCount = 0;
using (var command = new SqlCommand(@"
SELECT
success_count = COUNT_BIG(DISTINCT CASE WHEN collection_status = 'SUCCESS' THEN collector_name END),
error_count = SUM(CASE WHEN collection_status = 'ERROR' THEN 1 ELSE 0 END)
FROM PerformanceMonitor.config.collection_log;", connection))
{
using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
if (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
successCount = reader.IsDBNull(0) ? 0 : (int)reader.GetInt64(0);
errorCount = reader.IsDBNull(1) ? 0 : reader.GetInt32(1);
}
}
progress?.Report(new InstallationProgress
{
Message = $"Validation complete: {successCount} collectors succeeded, {errorCount} failed",
Status = errorCount == 0 ? "Success" : "Warning"
});
/*Show failed collectors if any*/
if (errorCount > 0)
{
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(cancellationToken).ConfigureAwait(false);
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
string name = reader["collector_name"]?.ToString() ?? "";
string error = reader["error_message"] == DBNull.Value
? "(no error message)"
: reader["error_message"]?.ToString() ?? "";
progress?.Report(new InstallationProgress
{
Message = $" {name}: {error}",
Status = "Error"
});
}
}
return (successCount, errorCount);
}
/// <summary>
/// Run installation verification diagnostics using 99_installer_troubleshooting.sql
/// </summary>
public static async Task<bool> RunTroubleshootingAsync(
string connectionString,
string sqlDirectory,
IProgress<InstallationProgress>? progress = null,
CancellationToken cancellationToken = default)
{
bool hasErrors = false;
try
{
/*Find the troubleshooting script*/
string scriptPath = Path.Combine(sqlDirectory, "99_installer_troubleshooting.sql");
if (!File.Exists(scriptPath))
{
/*Try parent directory (install folder might be one level up)*/
string? parentDir = Directory.GetParent(sqlDirectory)?.FullName;
if (parentDir != null)
{
string altPath = Path.Combine(parentDir, "install", "99_installer_troubleshooting.sql");
if (File.Exists(altPath))
scriptPath = altPath;
}
}
if (!File.Exists(scriptPath))
{
progress?.Report(new InstallationProgress
{
Message = $"Troubleshooting script not found: 99_installer_troubleshooting.sql",
Status = "Error"
});
return false;
}
progress?.Report(new InstallationProgress
{
Message = "Running installation diagnostics...",
Status = "Info"
});
/*Read and prepare the script*/
string scriptContent = await File.ReadAllTextAsync(scriptPath, cancellationToken).ConfigureAwait(false);
/*Remove SQLCMD directives*/
scriptContent = SqlCmdDirectivePattern.Replace(scriptContent, string.Empty);
/*Split into batches*/
var batches = GoBatchSplitter.Split(scriptContent)
.Where(b => !string.IsNullOrWhiteSpace(b))
.ToList();
/*Connect to master first (script will USE PerformanceMonitor)*/
using var connection = new SqlConnection(connectionString);
/*Capture PRINT messages and determine status*/
connection.InfoMessage += (sender, e) =>
{
string message = e.Message;
/*Determine status based on message content*/
string status = "Info";
if (message.Contains("[OK]", StringComparison.OrdinalIgnoreCase))
status = "Success";
else if (message.Contains("[WARN]", StringComparison.OrdinalIgnoreCase))
{
status = "Warning";
}
else if (message.Contains("[ERROR]", StringComparison.OrdinalIgnoreCase))
{
status = "Error";
hasErrors = true;
}
progress?.Report(new InstallationProgress
{
Message = message,
Status = status
});
};
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
/*Execute each batch*/
foreach (var batch in batches)
{
if (string.IsNullOrWhiteSpace(batch))
continue;
cancellationToken.ThrowIfCancellationRequested();
using var cmd = new SqlCommand(batch, connection)
{
CommandTimeout = 120
};
try
{
await cmd.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
catch (SqlException ex)
{
/*Report SQL errors but continue with remaining batches*/
progress?.Report(new InstallationProgress
{
Message = $"SQL Error: {ex.Message}",
Status = "Error"
});
hasErrors = true;
}
/*Small delay to allow UI to process messages*/
await Task.Delay(25, cancellationToken).ConfigureAwait(false);
}
return !hasErrors;
}
catch (Exception ex)
{
progress?.Report(new InstallationProgress
{
Message = $"Diagnostics failed: {ex.Message}",
Status = "Error"
});
return false;
}
}
/// <summary>
/// Generate installation summary report file
/// </summary>
public static string GenerateSummaryReport(
string serverName,
string sqlServerVersion,
string sqlServerEdition,
string installerVersion,
InstallationResult result)
{
ArgumentNullException.ThrowIfNull(serverName);
ArgumentNullException.ThrowIfNull(result);
var duration = result.EndTime - result.StartTime;
string timestamp = result.StartTime.ToString("yyyyMMdd_HHmmss");
string fileName = $"PerformanceMonitor_Install_{serverName.Replace("\\", "_", StringComparison.Ordinal)}_{timestamp}.txt";
string reportPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), fileName);
var sb = new StringBuilder();
sb.AppendLine("================================================================================");
sb.AppendLine("Performance Monitor Installation Report");
sb.AppendLine("================================================================================");
sb.AppendLine();
sb.AppendLine("INSTALLATION SUMMARY");
sb.AppendLine("--------------------------------------------------------------------------------");
sb.AppendLine($"Status: {(result.Success ? "SUCCESS" : "FAILED")}");
sb.AppendLine($"Start Time: {result.StartTime:yyyy-MM-dd HH:mm:ss}");
sb.AppendLine($"End Time: {result.EndTime:yyyy-MM-dd HH:mm:ss}");
sb.AppendLine($"Duration: {duration.TotalSeconds:F1} seconds");
sb.AppendLine($"Files Executed: {result.FilesSucceeded}");
sb.AppendLine($"Files Failed: {result.FilesFailed}");
sb.AppendLine();
sb.AppendLine("SERVER INFORMATION");
sb.AppendLine("--------------------------------------------------------------------------------");
sb.AppendLine($"Server Name: {serverName}");
sb.AppendLine($"SQL Server Edition: {sqlServerEdition}");
sb.AppendLine();
if (!string.IsNullOrEmpty(sqlServerVersion))
{
string[] versionLines = sqlServerVersion.Split(NewLineChars, StringSplitOptions.RemoveEmptyEntries);
if (versionLines.Length > 0)
{
sb.AppendLine($"SQL Server Version:");
foreach (var line in versionLines)
{
sb.AppendLine($" {line.Trim()}");
}
}
}
sb.AppendLine();
sb.AppendLine("INSTALLER INFORMATION");
sb.AppendLine("--------------------------------------------------------------------------------");
sb.AppendLine($"Installer Version: {installerVersion}");
sb.AppendLine($"Working Directory: {Directory.GetCurrentDirectory()}");
sb.AppendLine($"Machine Name: {Environment.MachineName}");
sb.AppendLine($"User Name: {Environment.UserName}");
sb.AppendLine();
if (result.Errors.Count > 0)
{
sb.AppendLine("ERRORS");
sb.AppendLine("--------------------------------------------------------------------------------");
foreach (var (file, error) in result.Errors)
{
sb.AppendLine($"File: {file}");
string errorMsg = error.Length > 500 ? error.Substring(0, 500) + "..." : error;
sb.AppendLine($"Error: {errorMsg}");
sb.AppendLine();
}
}
if (result.LogMessages.Count > 0)
{
sb.AppendLine("DETAILED INSTALLATION LOG");
sb.AppendLine("--------------------------------------------------------------------------------");
foreach (var (message, status) in result.LogMessages)
{
string prefix = status switch
{
"Success" => "[OK] ",
"Error" => "[ERROR] ",
"Warning" => "[WARN] ",
_ => ""
};
sb.AppendLine($"{prefix}{message}");
}
sb.AppendLine();
}
sb.AppendLine("================================================================================");
sb.AppendLine("Generated by Performance Monitor Installer GUI");
sb.AppendLine($"Copyright (c) {DateTime.Now.Year} Darling Data, LLC");
sb.AppendLine("================================================================================");
File.WriteAllText(reportPath, sb.ToString());
return reportPath;
}
/// <summary>
/// Information about an applicable upgrade
/// </summary>
public class UpgradeInfo
{
public string Path { get; set; } = string.Empty;
public string FolderName { get; set; } = string.Empty;
public Version? FromVersion { get; set; }
public Version? ToVersion { get; set; }
}
/// <summary>
/// Get the currently installed version from the database
/// Returns null if database doesn't exist or no successful installation found
/// </summary>
public static async Task<string?> GetInstalledVersionAsync(
string connectionString,
CancellationToken cancellationToken = default)
{
try
{
using var connection = new SqlConnection(connectionString);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
/*Check if PerformanceMonitor database exists*/
using var dbCheckCmd = new SqlCommand(@"
SELECT database_id
FROM sys.databases
WHERE name = N'PerformanceMonitor';", connection);
var dbExists = await dbCheckCmd.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);