Files
biztalk-checkmk-pulse/tests/BizTalkCheckmkPulse.Tests/Program.cs
T

489 lines
23 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace BizTalkCheckmkPulse.Tests
{
internal static class Program
{
private static readonly List<string> Failures = new List<string>();
private static int ExecutedTests;
private static int Main()
{
Run("SelfTestEmitsAllStableServices", SelfTestEmitsAllStableServices);
Run("UnavailableSourcesAreUnknown", UnavailableSourcesAreUnknown);
Run("UnknownApplicationDoesNotCreateService", UnknownApplicationDoesNotCreateService);
Run("KnownApplicationCreatesService", KnownApplicationCreatesService);
Run("ServerNamesAreComparedWithoutWql", ServerNamesAreComparedWithoutWql);
Run("GroupSettingQueryUsesDocumentedSchema", GroupSettingQueryUsesDocumentedSchema);
Run("ProviderSqlLoginFailureIsPermission", ProviderSqlLoginFailureIsPermission);
Run("RejectedSqlPrincipalIsExtracted", RejectedSqlPrincipalIsExtracted);
Run("PlatformPermissionPropagatesToSqlDiscovery", PlatformPermissionPropagatesToSqlDiscovery);
Run("RoutingFailureReportsAreCounted", RoutingFailureReportsAreCounted);
Run("ReceiveLocationAllowlistSeparatesExpectedState", ReceiveLocationAllowlistSeparatesExpectedState);
Run("UnknownReceiveLocationStateIsNotGreen", UnknownReceiveLocationStateIsNotGreen);
Run("SendPortAllowlistSeparatesExpectedState", SendPortAllowlistSeparatesExpectedState);
Run("ArtifactSummaryIsBounded", ArtifactSummaryIsBounded);
Run("SnapshotRoundTripPreservesLines", SnapshotRoundTripPreservesLines);
Run("SnapshotRejectsTampering", SnapshotRejectsTampering);
Run("SnapshotRejectsStaleData", SnapshotRejectsStaleData);
Run("SnapshotRejectsDifferentMachine", SnapshotRejectsDifferentMachine);
Run("SnapshotReportsMissingFile", SnapshotReportsMissingFile);
Run("SnapshotFailureEmitsStableUnknownServices", SnapshotFailureEmitsStableUnknownServices);
if (Failures.Count == 0)
{
Console.WriteLine("PASS: " + ExecutedTests + " tests");
return 0;
}
foreach (var failure in Failures)
{
Console.Error.WriteLine("FAIL: " + failure);
}
return 1;
}
private static void SelfTestEmitsAllStableServices()
{
var lines = new CheckmkLocalFormatter(new MonitoringOptions()).FormatSelfTest().ToArray();
AssertEqual(8, lines.Length, "self-test line count");
AssertEqual(8, lines.Distinct(StringComparer.Ordinal).Count(), "unique self-test lines");
Assert(lines.All(x => x.StartsWith("0 \"BizTalk ", StringComparison.Ordinal)), "every self-test line must be OK");
Assert(lines.Any(x => x.Contains("\"BizTalk Event Log\"")), "Event Log service missing");
Assert(lines.Any(x => x.Contains("\"BizTalk Receive Locations\"")), "Receive Locations service missing");
Assert(lines.Any(x => x.Contains("\"BizTalk Send Ports\"")), "Send Ports service missing");
Assert(lines.Any(x => x.Contains("\"BizTalk Orchestrations\"")), "Orchestrations service missing");
}
private static void UnavailableSourcesAreUnknown()
{
var lines = new CheckmkLocalFormatter(new MonitoringOptions()).Format(new ProbeResult()).Take(8).ToArray();
AssertEqual(8, lines.Length, "stable service count");
Assert(lines.All(x => x.StartsWith("3 \"BizTalk ", StringComparison.Ordinal)), "unavailable sources must be UNKNOWN");
}
private static void UnknownApplicationDoesNotCreateService()
{
var options = new MonitoringOptions { EmitPerApplicationSuspensionServices = true };
var result = CreateSuspensionResult("(unknown)");
var lines = new CheckmkLocalFormatter(options).Format(result).ToArray();
AssertEqual(8, lines.Length, "unknown application must not create a dynamic service");
}
private static void KnownApplicationCreatesService()
{
var options = new MonitoringOptions { EmitPerApplicationSuspensionServices = true };
var result = CreateSuspensionResult("Orders");
var lines = new CheckmkLocalFormatter(options).Format(result).ToArray();
AssertEqual(9, lines.Length, "known application should create one dynamic service");
Assert(lines.Any(x => x.Contains("\"BizTalk Suspended Orders\"")), "known application service missing");
}
private static void ServerNamesAreComparedWithoutWql()
{
Assert(WmiBizTalkProbe.IsSameServer("BIZTALK01.corp.example", "biztalk01"), "FQDN and short name must match");
Assert(WmiBizTalkProbe.IsSameServer(@"\\BIZ-TALK+01", "biz-talk+01.example"), "special characters must be compared client-side");
Assert(!WmiBizTalkProbe.IsSameServer("BIZTALK01", "BIZTALK02"), "different servers must not match");
}
private static void GroupSettingQueryUsesDocumentedSchema()
{
var query = WmiBizTalkProbe.GroupSettingQuery;
Assert(query.Contains("FROM MSBTS_GroupSetting"), "MSBTS_GroupSetting query missing");
Assert(query.Contains("BizTalkOperatorGroup"), "configured operator group property missing");
Assert(query.Contains("BizTalkReadOnlyUserGroup"), "configured read-only group property missing");
Assert(query.Contains("SubscriptionDBServerName"), "master MessageBox server property missing");
Assert(query.Contains("SubscriptionDBName"), "master MessageBox database property missing");
Assert(query.IndexOf("MessageBoxSetting", StringComparison.OrdinalIgnoreCase) < 0, "unsupported MessageBoxSetting class present");
Assert(WmiBizTalkProbe.SuspendedInstancesQuery.Contains("ServiceClass = 64"), "routing failure report filter missing");
}
private static void ProviderSqlLoginFailureIsPermission()
{
var exception = new COMException(
"Internal error from OLEDB provider: 'Login failed for user 'BEW\\AV23AGPWBIO1$'.'",
unchecked((int)0x80131904));
AssertEqual(
DiagnosticCategory.Permission,
WmiBizTalkProbe.ClassifyWmiException(exception),
"provider SQL login classification");
}
private static void RejectedSqlPrincipalIsExtracted()
{
var message = "Internal error from OLEDB provider: 'Login failed for user 'BEW\\AV23AGPWBIO1$'.'";
AssertEqual(
"BEW\\AV23AGPWBIO1$",
WmiBizTalkProbe.ExtractSqlLoginPrincipal(message),
"rejected SQL principal");
}
private static void PlatformPermissionPropagatesToSqlDiscovery()
{
var result = new ProbeResult();
result.Diagnostics.Add(new ProbeDiagnostic
{
Area = DiagnosticArea.Wmi,
Category = DiagnosticCategory.Permission,
Component = "MSBTS_GroupSetting",
Required = true
});
new SqlConnectivityProbe(new MonitoringOptions()).Query(result);
var discovery = result.Diagnostics.Single(x =>
x.Area == DiagnosticArea.Sql
&& x.Component == "BizTalk database discovery");
AssertEqual(
DiagnosticCategory.Permission,
discovery.Category,
"SQL discovery classification");
}
private static void RoutingFailureReportsAreCounted()
{
var result = new ProbeResult();
result.Platform.SuspendedInstancesDataAvailable = true;
result.SuspendedInstances.Add(new SuspendedInstance
{
ApplicationName = "(unknown)",
ServiceName = string.Empty,
ServiceClassId = 64,
Kind = SuspendedKind.NonResumable
});
result.SuspendedInstances.Add(new SuspendedInstance
{
ApplicationName = "Orders",
ServiceName = "Receive.Order",
Kind = SuspendedKind.Resumable
});
var line = FindServiceLine(result, "Suspended Instances");
Assert(line.StartsWith("2 \"BizTalk Suspended Instances\"", StringComparison.Ordinal), "routing failure must be CRIT");
Assert(line.Contains("biztalk_suspended_total=2"), "suspended total metric missing");
Assert(line.Contains("biztalk_suspended_nonresumable=1"), "non-resumable metric missing");
Assert(line.Contains("biztalk_routing_failure_reports=1"), "routing failure metric missing");
Assert(line.Contains("routing_failure_reports=1"), "routing failure summary missing");
}
private static void ReceiveLocationAllowlistSeparatesExpectedState()
{
var options = new MonitoringOptions
{
ExpectedDisabledReceiveLocations = new[] { "Maintenance\\RL Expected" }
};
var result = new ProbeResult();
result.Platform.ReceiveLocationsDataAvailable = true;
result.ReceiveLocations.Add(new ReceiveLocationState
{
ApplicationName = "Maintenance",
Name = "RL Expected",
IsDisabled = true
});
result.ReceiveLocations.Add(new ReceiveLocationState
{
ApplicationName = "Orders",
Name = "RL Orders",
IsDisabled = true
});
result.ReceiveLocations.Add(new ReceiveLocationState
{
ApplicationName = "Orders",
Name = "RL Active",
IsDisabled = false
});
var line = FindServiceLine(result, "Receive Locations", options);
Assert(line.StartsWith("2 \"BizTalk Receive Locations\"", StringComparison.Ordinal), "unexpected disabled receive location must be CRIT");
Assert(line.Contains("biztalk_receive_locations_enabled=1"), "enabled receive metric missing");
Assert(line.Contains("biztalk_receive_locations_unexpected_disabled=1"), "unexpected disabled metric missing");
Assert(line.Contains("biztalk_receive_locations_expected_disabled=1"), "expected disabled metric missing");
Assert(line.Contains(@"Orders\RL Orders"), "affected receive location missing");
Assert(line.IndexOf("RL Expected", StringComparison.Ordinal) < 0, "expected disabled receive location should not clutter affected list");
options.ExpectedDisabledReceiveLocations = new[] { "Maintenance\\RL Expected", "RL Orders" };
var allExpected = FindServiceLine(result, "Receive Locations", options);
Assert(allExpected.StartsWith("0 \"BizTalk Receive Locations\"", StringComparison.Ordinal), "all expected disabled receive locations should be OK");
Assert(allExpected.Contains("biztalk_receive_locations_expected_disabled=2"), "all expected receive count missing");
}
private static void SendPortAllowlistSeparatesExpectedState()
{
var options = new MonitoringOptions
{
ExpectedInactiveSendPorts = new[] { "Maintenance\\SP Expected" }
};
var result = new ProbeResult();
result.Platform.SendPortsDataAvailable = true;
result.SendPorts.Add(new SendPortState
{
ApplicationName = "Maintenance",
Name = "SP Expected",
Status = 2
});
result.SendPorts.Add(new SendPortState
{
ApplicationName = "Orders",
Name = "SP Orders",
Status = 1
});
result.SendPorts.Add(new SendPortState
{
ApplicationName = "Orders",
Name = "SP Active",
Status = 3
});
var line = FindServiceLine(result, "Send Ports", options);
Assert(line.StartsWith("2 \"BizTalk Send Ports\"", StringComparison.Ordinal), "unexpected inactive send port must be CRIT");
Assert(line.Contains("biztalk_send_ports_started=1"), "started send port metric missing");
Assert(line.Contains("biztalk_send_ports_unexpected_inactive=1"), "unexpected inactive send metric missing");
Assert(line.Contains("biztalk_send_ports_expected_inactive=1"), "expected inactive send metric missing");
Assert(line.Contains(@"Orders\SP Orders(bound)"), "affected send port missing");
Assert(line.IndexOf("SP Expected", StringComparison.Ordinal) < 0, "expected inactive send port should not clutter affected list");
options.ExpectedInactiveSendPorts = new[] { "Maintenance\\SP Expected", "SP Orders" };
var allExpected = FindServiceLine(result, "Send Ports", options);
Assert(allExpected.StartsWith("0 \"BizTalk Send Ports\"", StringComparison.Ordinal), "all expected inactive send ports should be OK");
Assert(allExpected.Contains("biztalk_send_ports_expected_inactive=2"), "all expected send count missing");
}
private static void UnknownReceiveLocationStateIsNotGreen()
{
var result = new ProbeResult();
result.Platform.ReceiveLocationsDataAvailable = true;
result.ReceiveLocations.Add(new ReceiveLocationState
{
ApplicationName = "Orders",
Name = "RL Missing State",
IsDisabled = null
});
var line = FindServiceLine(result, "Receive Locations");
Assert(line.StartsWith("3 \"BizTalk Receive Locations\"", StringComparison.Ordinal), "unknown receive state must be UNKNOWN");
Assert(line.Contains("biztalk_receive_locations_unknown=1"), "unknown receive metric missing");
Assert(line.Contains(@"Orders\RL Missing State"), "unknown receive location must be visible");
}
private static void ArtifactSummaryIsBounded()
{
var options = new MonitoringOptions
{
MaxSummaryItems = 2,
MaxDetailCharacters = 256
};
var result = new ProbeResult();
result.Platform.ReceiveLocationsDataAvailable = true;
for (var i = 1; i <= 6; i++)
{
result.ReceiveLocations.Add(new ReceiveLocationState
{
ApplicationName = "Application",
Name = "Disabled-" + i,
IsDisabled = true
});
}
var line = FindServiceLine(result, "Receive Locations", options);
Assert(line.Contains("(+4 more)"), "omitted item count missing");
Assert(line.Length < 700, "local check line should remain compact");
var longResult = new ProbeResult();
longResult.Platform.ReceiveLocationsDataAvailable = true;
longResult.ReceiveLocations.Add(new ReceiveLocationState
{
ApplicationName = new string('A', 400),
Name = new string('R', 400),
IsDisabled = true
});
var truncated = FindServiceLine(longResult, "Receive Locations", options);
Assert(truncated.Contains("[truncated]"), "detail character limit should be visible");
Assert(truncated.Length < 700, "truncated local check line should remain bounded");
}
private static void SnapshotRoundTripPreservesLines()
{
WithTemporarySnapshot((path, store) =>
{
var lines = new CheckmkLocalFormatter(new MonitoringOptions()).FormatSelfTest().ToArray();
var generated = DateTime.UtcNow;
store.Write(lines, generated, "DOMAIN\\collector$");
var result = store.Read(generated.AddSeconds(10), TimeSpan.FromMinutes(3));
Assert(result.IsSuccess, "snapshot should be readable: " + result.Error);
AssertEqual(lines.Length, result.Lines.Count, "snapshot line count");
Assert(lines.SequenceEqual(result.Lines), "snapshot payload changed");
var replacement = lines.Select(x => x.Replace("Self test OK", "Replacement OK")).ToArray();
store.Write(replacement, generated.AddSeconds(30), "DOMAIN\\collector$");
var replaced = store.Read(generated.AddSeconds(40), TimeSpan.FromMinutes(3));
Assert(replaced.IsSuccess, "replaced snapshot should be readable");
Assert(replacement.SequenceEqual(replaced.Lines), "atomic replacement payload changed");
});
}
private static void SnapshotRejectsTampering()
{
WithTemporarySnapshot((path, store) =>
{
var lines = new CheckmkLocalFormatter(new MonitoringOptions()).FormatSelfTest().ToArray();
store.Write(lines, DateTime.UtcNow, "DOMAIN\\collector$");
var content = File.ReadAllText(path, Encoding.UTF8);
File.WriteAllText(path, content.Replace("Self test OK", "Tampered output"), new UTF8Encoding(false));
var result = store.Read(DateTime.UtcNow, TimeSpan.FromMinutes(3));
Assert(!result.IsSuccess, "tampered snapshot must be rejected");
Assert(result.Error.IndexOf("SHA-256", StringComparison.OrdinalIgnoreCase) >= 0, "tamper reason should mention SHA-256");
});
}
private static void SnapshotRejectsStaleData()
{
WithTemporarySnapshot((path, store) =>
{
var lines = new CheckmkLocalFormatter(new MonitoringOptions()).FormatSelfTest().ToArray();
var generated = DateTime.UtcNow.AddMinutes(-10);
store.Write(lines, generated, "DOMAIN\\collector$");
var result = store.Read(DateTime.UtcNow, TimeSpan.FromMinutes(3));
Assert(!result.IsSuccess, "stale snapshot must be rejected");
Assert(result.Error.IndexOf("stale", StringComparison.OrdinalIgnoreCase) >= 0, "stale reason missing");
});
}
private static void SnapshotRejectsDifferentMachine()
{
WithTemporarySnapshot((path, store) =>
{
var lines = new CheckmkLocalFormatter(new MonitoringOptions()).FormatSelfTest().ToArray();
store.Write(lines, DateTime.UtcNow, "DOMAIN\\collector$");
var content = File.ReadAllText(path, Encoding.UTF8);
var currentMachine = Convert.ToBase64String(Encoding.UTF8.GetBytes(Environment.MachineName));
var otherMachine = Convert.ToBase64String(Encoding.UTF8.GetBytes("OTHER-SERVER"));
File.WriteAllText(
path,
content.Replace("machineBase64=" + currentMachine, "machineBase64=" + otherMachine),
new UTF8Encoding(false));
var result = store.Read(DateTime.UtcNow, TimeSpan.FromMinutes(3));
Assert(!result.IsSuccess, "snapshot for another machine must be rejected");
Assert(result.Error.IndexOf("different machine", StringComparison.OrdinalIgnoreCase) >= 0, "machine mismatch reason missing");
});
}
private static void SnapshotReportsMissingFile()
{
WithTemporarySnapshot((path, store) =>
{
var result = store.Read(DateTime.UtcNow, TimeSpan.FromMinutes(3));
Assert(!result.IsSuccess, "missing snapshot must be rejected");
Assert(result.Error.IndexOf("does not exist", StringComparison.OrdinalIgnoreCase) >= 0, "missing file reason missing");
});
}
private static void SnapshotFailureEmitsStableUnknownServices()
{
var lines = new CheckmkLocalFormatter(new MonitoringOptions())
.FormatSnapshotFailure("Snapshot file does not exist.")
.ToArray();
AssertEqual(8, lines.Length, "snapshot failure stable service count");
Assert(lines.All(x => x.StartsWith("3 \"BizTalk ", StringComparison.Ordinal)), "snapshot failure must be UNKNOWN");
Assert(lines.All(x => x.Contains("Scheduled Task")), "snapshot failure must contain provider action");
}
private static void WithTemporarySnapshot(Action<string, SnapshotStore> test)
{
var directory = Path.Combine(Path.GetTempPath(), "BizTalkCheckmkPulse.Tests." + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(directory);
var path = Path.Combine(directory, "snapshot.txt");
try
{
test(path, new SnapshotStore(path, 1048576));
}
finally
{
if (Directory.Exists(directory))
{
Directory.Delete(directory, true);
}
}
}
private static ProbeResult CreateSuspensionResult(string applicationName)
{
var result = new ProbeResult();
result.Platform.SuspendedInstancesDataAvailable = true;
result.SuspendedInstances.Add(new SuspendedInstance
{
ApplicationName = applicationName,
ServiceName = "TestService",
Kind = SuspendedKind.Resumable
});
return result;
}
private static string FindServiceLine(
ProbeResult result,
string serviceSuffix,
MonitoringOptions options = null)
{
var effectiveOptions = options ?? new MonitoringOptions();
var token = "\"" + effectiveOptions.ServiceName(serviceSuffix) + "\"";
return new CheckmkLocalFormatter(effectiveOptions)
.Format(result)
.Single(x => x.Contains(token));
}
private static void Run(string name, Action test)
{
ExecutedTests++;
try
{
test();
}
catch (Exception ex)
{
Failures.Add(name + ": " + ex.Message);
}
}
private static void Assert(bool condition, string message)
{
if (!condition)
{
throw new InvalidOperationException(message);
}
}
private static void AssertEqual(int expected, int actual, string label)
{
if (expected != actual)
{
throw new InvalidOperationException(label + ": expected " + expected + ", actual " + actual);
}
}
private static void AssertEqual(DiagnosticCategory expected, DiagnosticCategory actual, string label)
{
if (expected != actual)
{
throw new InvalidOperationException(label + ": expected " + expected + ", actual " + actual);
}
}
private static void AssertEqual(string expected, string actual, string label)
{
if (!string.Equals(expected, actual, StringComparison.Ordinal))
{
throw new InvalidOperationException(label + ": expected " + expected + ", actual " + actual);
}
}
}
}