diff --git a/CLAUDE.md b/CLAUDE.md index cec0eccf5..f385fdb5e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -271,6 +271,11 @@ shipped. `Core.AlarmHistorian` now carries a surgical direct pin of SQLite 3.50.2+ patch), overriding the `2.1.11` that `Microsoft.Data.Sqlite` pulls transitively. `dotnet restore`/`build` is clean with the audit active. +**Before upgrading a populated ConfigDb, run the upgrade preflight** (`src/Tooling/ZB.MOM.WW.OtOpcUa.UpgradePreflight`, +exe `otopcua-preflight`, `OTOPCUA_CONFIG_CONNECTION`): read-only; names every row a pending migration's pre-check or the +next deploy would refuse; exit 1 on any. A new constraint-adding migration must add its row-naming twin to +`ControlPlane/Preflight/MigrationPreChecks.cs`. See `docs/v2/upgrade-preflight.md`. + Test projects live under `tests//` (Core, Server, Drivers, Drivers/Cli, Client, Tooling) — there is no single unit-test project. Unit suites are named `*.Tests`; integration suites are `*.IntegrationTests` diff --git a/ZB.MOM.WW.OtOpcUa.slnx b/ZB.MOM.WW.OtOpcUa.slnx index ee8036a72..f738137ca 100644 --- a/ZB.MOM.WW.OtOpcUa.slnx +++ b/ZB.MOM.WW.OtOpcUa.slnx @@ -80,6 +80,7 @@ + diff --git a/docs/README.md b/docs/README.md index e5beea750..c420cbf68 100644 --- a/docs/README.md +++ b/docs/README.md @@ -90,6 +90,7 @@ Integration-test fixtures: [Modbus](drivers/Modbus-Test-Fixture.md) · [S7](driv | [StatusDashboard.md](StatusDashboard.md) | Pointer — superseded by [v2/admin-ui.md](v2/admin-ui.md) | | [ui-consistency-validation.md](ui-consistency-validation.md) | Shared UI consistency validation record (2026-11) | | [v2/dev-environment.md](v2/dev-environment.md) | Dev-box bootstrap + endpoint inventory | +| [v2/upgrade-preflight.md](v2/upgrade-preflight.md) | `otopcua-preflight` — read-only pre-upgrade ConfigDb check (migration pre-checks, deploy gate, script gate) | | [v2/redundancy-interop-playbook.md](v2/redundancy-interop-playbook.md) | Redundancy interop playbook | ### Client tooling diff --git a/docs/v2/upgrade-preflight.md b/docs/v2/upgrade-preflight.md new file mode 100644 index 000000000..e02656769 --- /dev/null +++ b/docs/v2/upgrade-preflight.md @@ -0,0 +1,83 @@ +# Upgrade preflight (`otopcua-preflight`) + +A **read-only** check of an OtOpcUa ConfigDb, run from the **new** build **before** its migrations are applied. +It reports every row that the upgrade — or the first deploy after it — would refuse, so the clean-up happens +before the maintenance window instead of in the middle of it. It issues only `SELECT`s. + +Introduced for the 2026-12-02 review remediation follow-ups lmxopcua#1013, #1015, #1021 and #1058. + +## What it checks + +| Section | What | Severity | Issue | +|---|---|---|---| +| `schema` | Applied vs pending migrations; tables/columns a pending migration creates (read as empty/default — see below); whether `ALLOW_SNAPSHOT_ISOLATION` is on. | Info / Warning | — | +| `migration:ConfigurationGapsIndexesAndRowVersions` | Duplicate `NodeAcl` rows per (cluster, principal, scope kind, scope id) — typically several Cluster-scope rows for one principal — and duplicate `LdapGroupRoleMapping` rows per (group, cluster), incl. system-wide. The migration THROWs on either. | Blocking | #1021 | +| `migration:ScriptForeignKeysAndExternalIdUniqueness` | `Script.ScriptId` NULL; a VirtualTag / ScriptedAlarm naming a script that does not exist; a non-blank ZTag or SAPID on more than one equipment (case-insensitive, as the new unique index); any `ExternalIdReservation` row (the table is dropped). The migration THROWs on any of them. | Blocking | #1040, #1049 | +| `deploy-gate` | The deploy gate's own rule pass (`DeployGateRules` — the code `AdminOperationsActor` runs): every `DraftValidator` rule, incl. the #978 rules `VirtualTagNameInvalid`, `UnsEffectiveNameInvalid` (illegal VirtualTag names / display-name overrides), `VirtualTagScriptNotFound`, `ScriptedAlarmScriptNotFound` (dangling script references), the #998 rules (`BadDuplicateExternalIdentifier`, `DanglingReference`, `HistorianTagnameDuplicate`), and `SqlNamedQueryInvalid`; the per-cluster topology check; the TagConfig inspection (Warning unless `--tagconfig-mode Error`). | Blocking (rules) / Warning | #1015, #1058 | +| `script-gate` | Every script the runtime will compile (enabled VirtualTags, enabled scripted-alarm predicates, Calculation tags, `{{equip}}` resolved) through the Roslyn compile + sandbox allow-list (`RoslynDeployScriptChecker`, as the deploy gate). Also every **unused** stored script, compiled as a value script — a Warning, since binding it later would be refused. | Blocking (Error mode) / Warning | #1013 | + +`SqlNamedQueryInvalid` (#1058) is a deploy-gate rule added with the preflight: the Sql driver checks every named +query with `SqlNamedQueryRules.Describe` under its provider at construction and one refused query fails the whole +driver. Since #974 that includes a T-SQL ScriptDom parse for SqlServer, Odbc and no-provider configs, so an **Odbc** +query written in another dialect (`LIMIT`, `ILIKE`, `'a'::text`, `(x)::numeric`) is refused — the deploy gate now +says so before the driver goes dark. (A bare `col::type` parses as T-SQL static-member syntax and is accepted.) + +### Reading an older schema + +The preflight reads the snapshot through **this build's** EF model, but the database is still on the old schema. +A table a pending migration creates is mapped to a typed zero-row query (it will be empty right after the +migration); a column a pending migration adds is left out of the model (the property keeps its default). The +`schema` section lists exactly which. A schema change the tolerance cannot bridge (e.g. a NULL in a column the new +model requires) is reported as `deploy-gate/SnapshotUnreadable`; fix the migration pre-check findings and re-run. + +Only v3 ConfigDbs (with `20260715230637_V3Initial` applied) are accepted; anything else exits 2. + +## Running it + +Build or publish it from the **new** source tree (it must carry the new rules and migrations): + +```bash +dotnet publish src/Tooling/ZB.MOM.WW.OtOpcUa.UpgradePreflight -c Release -o out/preflight +# Windows target: add -r win-x64 --self-contained to run it on the box without an SDK +``` + +Pass the connection string through the environment (a command-line argument is visible in the process list and +shell history). A login with `db_datareader` on the ConfigDb is enough. + +```bash +export OTOPCUA_CONFIG_CONNECTION='Server=,;Database=;User Id=;Password=<...>;TrustServerCertificate=True' +out/preflight/otopcua-preflight # human-readable; Blocking + Warning findings +out/preflight/otopcua-preflight --verbose # + Info (pending migrations, clean sections) +out/preflight/otopcua-preflight --json > preflight.json +``` + +| Option | Default | Meaning | +|---|---|---| +| `--connection ""` | `OTOPCUA_CONFIG_CONNECTION` | ConfigDb connection string | +| `--tagconfig-mode Warn\|Error` | `Warn` | the target's `Deployment:TagConfigValidationMode` | +| `--script-gate Error\|Warn\|Off` | `Error` | the target's `Deployment:ScriptCompileGateMode` | +| `--no-unused-scripts` | off | skip compiling scripts nothing uses | +| `--json` / `--verbose` | off | output format | + +**Exit codes:** `0` nothing blocks the upgrade or the next deploy · `1` at least one Blocking finding · `2` usage +error, unreachable database, or not a v3 ConfigDb. + +## Upgrade procedure + +1. On the running (old) build's ConfigDb, run the preflight from the new build. It is read-only and safe to run + against a live database; under SNAPSHOT isolation it does not block editors. +2. Fix every Blocking finding through the AdminUI (re-point or delete the VirtualTag/ScriptedAlarm, clear the + duplicate ZTag, merge the duplicate ACL rows, rewrite the Odbc query, fix the script) — or, for + `ExternalIdReservation` rows, export them if their history matters and delete them. Re-run until exit 0. +3. Apply the new build (its migrations). A migration that still finds a bad row THROWs (error 50998 / 51049) and + changes nothing; re-run the preflight to see why. +4. Deploy. The deploy gate runs the same rules the preflight ran. + +## Results recorded + +| Date | Target | Schema at | Result | +|---|---|---|---| +| 2026-12-03 | docker-dev ConfigDb `OtOpcUa` (read from a copy of the stopped rig's SQL volume; the rig was not touched) | `EnableSnapshotIsolation` (6 pending) | exit 0 — both migration pre-checks clean, deploy gate clean, 3 in-use scripts compile; no Sql drivers | +| 2026-12-03 | `10.100.0.35,14330` / `OtOpcUaCfg_gate_scratch` | `V3Initial` (14 pending) | exit 0 — empty config; the NodeAcl duplicate pre-check could not run on the pre-#520 `LdapGroup` column (Warning) | +| 2026-12-03 | `10.100.0.35,14330` / `OtOpcUaConfig`, `OtOpcUaConfig_Dev` | v2 schema | exit 2 — not v3 ConfigDbs (nothing to check) | +| — | **production (wonder-app-vd03 / vq03 / vq04)** | — | **not run — user-gated.** Remote commands on the wonder boxes are on hold (see `CLAUDE.md`); an operator with SQL access runs step 1 there. | diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs index 93bf189d0..6aa2e13b7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs @@ -532,77 +532,21 @@ public sealed class AdminOperationsActor : ReceiveActor // is the last guard before a bad address space (or a non-derived EquipmentId) ships. var draft = await DraftSnapshotFactory.FromConfigDbAsync(db); phases.Mark("snapshot-read"); - var errors = DraftValidator.Validate(draft).ToList(); - - // Cluster-topology guard. The SQL - // CK_ServerCluster_RedundancyMode_NodeCount CHECK enforces the (NodeCount, RedundancyMode) - // pair on the row itself, but it cannot see the per-node ClusterNode.Enabled flag — an - // operator can disable a node (effective enabled-count = 1) while leaving RedundancyMode at - // Hot/Warm and the constraint stays green, which would boot the runtime into an - // InvalidTopology band. ValidateClusterTopology catches that drift; it is not part of - // DraftValidator.Validate, so it runs separately here over the snapshot's cluster/node rows. - // Errors fold into the same reject summary alongside the snapshot rules so a deploy failing - // either check is rejected with both sets of messages. ClusterId-ordered for a deterministic summary. - // R03:3.2 — both come off the SAME snapshot read as every other table (one SNAPSHOT - // transaction), not a second query that could observe a later edit. - var clusters = draft.ServerClusters.OrderBy(c => c.ClusterId, StringComparer.Ordinal).ToList(); - var nodesByCluster = draft.ClusterNodes - .GroupBy(n => n.ClusterId, StringComparer.Ordinal) - .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.Ordinal); - foreach (var cluster in clusters) - { - var nodes = nodesByCluster.TryGetValue(cluster.ClusterId, out var ns) - ? (IReadOnlyList)ns - : []; - errors.AddRange(DraftValidator.ValidateClusterTopology(cluster, nodes)); - } - - // Deploy-time TagConfig strictness inspection over equipment tags. The - // driver-typed EquipmentTagConfigInspector surfaces every blob the driver's own reader would - // REJECT — a present-but-invalid enum value, an absent or malformed address field, a - // structurally-unparseable TagConfig — each of which makes the driver skip the tag so it reads - // BadNodeIdUnknown forever. (The runtime used to silently default a typo'd enum; - // it now rejects the tag, so these warnings describe rejections.) In Warn mode - // (default) these are non-blocking (logged + appended to the accepted result Message); in Error - // mode they fold into the reject list so a typo'd config cannot be re-deployed until fixed. - // Running servers are untouched either way — the gate only sees re-deploys. - // v3: a raw Tag's driver is resolved via its Device (Tag no longer carries EquipmentId / - // DriverInstanceId). Inspect EVERY raw tag's TagConfig against its device's driver type. - var driverTypeById = draft.DriverInstances - .GroupBy(d => d.DriverInstanceId, StringComparer.Ordinal) - .ToDictionary(g => g.Key, g => g.First().DriverType, StringComparer.Ordinal); - var driverByDevice = draft.Devices - .GroupBy(d => d.DeviceId, StringComparer.Ordinal) - .ToDictionary(g => g.Key, g => g.First().DriverInstanceId, StringComparer.Ordinal); - var deviceConfigById = draft.Devices - .GroupBy(d => d.DeviceId, StringComparer.Ordinal) - .ToDictionary(g => g.Key, g => g.First().DeviceConfig, StringComparer.Ordinal); - var tagConfigWarnings = new List<(string TagId, string Text)>(); - foreach (var t in draft.Tags) - { - if (!driverByDevice.TryGetValue(t.DeviceId, out var driverInstanceId)) continue; - if (!driverTypeById.TryGetValue(driverInstanceId, out var driverType)) continue; - foreach (var w in EquipmentTagConfigInspector.Inspect( - driverType, t.TagConfig, deviceConfigById.GetValueOrDefault(t.DeviceId))) - tagConfigWarnings.Add((t.TagId, $"tag '{t.TagId}': {w}")); - } - if (tagConfigWarnings.Count > 0) - { - if (_tagConfigValidationMode == TagConfigValidationMode.Error) - errors.AddRange(tagConfigWarnings.Select(x => new ValidationError("TagConfigInvalid", x.Text, x.TagId))); - else - foreach (var x in tagConfigWarnings) - _log.Warning("StartDeployment: TagConfig warning (Warn mode, non-blocking): {Warning}", x.Text); - } + // The rule pass — DraftValidator, per-cluster topology, TagConfig inspection, the non-blocking Sql / data- + // connection warnings — is DeployGateRules (shared with the upgrade preflight, lmxopcua#1013/#1015/#1058). + // R03:3.2: every check runs off this ONE snapshot read. + var gate = DeployGateRules.Evaluate(draft, _tagConfigValidationMode); + var errors = gate.Errors.ToList(); + foreach (var w in gate.TagConfigWarnings) + _log.Warning("StartDeployment: TagConfig warning (Warn mode, non-blocking): {Warning}", w.Message); // lmxopcua#781 item 3: always non-blocking (independent of TagConfigValidationMode) — the Tag // entity's Writable flag and the Sql blob's "writable" disagree. - var writableWarnings = SqlTagDeployChecks.WritableMismatchWarnings(draft); - foreach (var w in writableWarnings) + foreach (var w in gate.SqlWritableWarnings) _log.Warning("StartDeployment: Sql writable mismatch (non-blocking): {Warning}", w); // A2b (plan §6): Σ MaxConditions × 49 of a consumer node's alarm mappings over the host cap — non-blocking. - foreach (var w in DataConnectionValidator.DeployWarnings(draft)) + foreach (var w in gate.DataConnectionWarnings) _log.Warning("StartDeployment: data-connection warning (non-blocking): {Warning}", w); phases.Mark("validate"); @@ -725,8 +669,8 @@ public sealed class AdminOperationsActor : ReceiveActor // the operator sees the non-blocking strictness findings on a successful deploy. var messageParts = new List(); if (advisory is not null) messageParts.Add(advisory); - messageParts.AddRange(tagConfigWarnings.Select(x => x.Text)); - messageParts.AddRange(writableWarnings); + messageParts.AddRange(gate.TagConfigWarnings.Select(x => x.Message)); + messageParts.AddRange(gate.SqlWritableWarnings); messageParts.AddRange(scriptWarnings); var acceptedMessage = messageParts.Count > 0 ? string.Join("; ", messageParts) : null; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/DeployGateRules.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/DeployGateRules.cs new file mode 100644 index 000000000..547d2de33 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/DeployGateRules.cs @@ -0,0 +1,85 @@ +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; + +/// +/// The deploy gate's rule pass over one — everything AdminOperationsActor checks +/// before the script compile gate (), stated once so the upgrade preflight +/// (Preflight.UpgradePreflight, lmxopcua#1013/#1015/#1021/#1058) reports exactly what the next deploy would +/// refuse instead of a re-implementation that drifts. +/// +public static class DeployGateRules +{ + /// The deploy-gate error code a TagConfig inspection finding carries in Error mode. + public const string TagConfigInvalidCode = "TagConfigInvalid"; + + /// What the rule pass found. + /// Blocking: , the per-cluster topology check, and — in + /// — the TagConfig inspection. + /// The TagConfig inspection in mode + /// (non-blocking); empty in Error mode, where they are in . + /// Always non-blocking (lmxopcua#781 item 3). + /// Always non-blocking (data-connection alarm-mapping budget). + public sealed record Result( + IReadOnlyList Errors, + IReadOnlyList TagConfigWarnings, + IReadOnlyList SqlWritableWarnings, + IReadOnlyList DataConnectionWarnings); + + /// Runs every rule over the snapshot. + /// The whole-DB snapshot (). + /// The configured Deployment:TagConfigValidationMode. + /// The findings. + public static Result Evaluate(DraftSnapshot draft, TagConfigValidationMode tagConfigMode) + { + ArgumentNullException.ThrowIfNull(draft); + + // Full pre-seal gate: the complete DraftValidator (one pass, all rules). + var errors = DraftValidator.Validate(draft).ToList(); + + // Cluster-topology guard. The SQL CK_ServerCluster_RedundancyMode_NodeCount CHECK enforces the + // (NodeCount, RedundancyMode) pair on the row itself, but it cannot see the per-node ClusterNode.Enabled + // flag — an operator can disable a node (effective enabled-count = 1) while leaving RedundancyMode at + // Hot/Warm, which would boot the runtime into an InvalidTopology band. Not part of DraftValidator.Validate, + // so it runs here over the snapshot's cluster/node rows, ClusterId-ordered for a deterministic summary. + // R03:3.2 — both come off the SAME snapshot read as every other table. + var nodesByCluster = draft.ClusterNodes + .GroupBy(n => n.ClusterId, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.ToList(), StringComparer.Ordinal); + foreach (var cluster in draft.ServerClusters.OrderBy(c => c.ClusterId, StringComparer.Ordinal)) + { + var nodes = nodesByCluster.TryGetValue(cluster.ClusterId, out var ns) ? (IReadOnlyList)ns : []; + errors.AddRange(DraftValidator.ValidateClusterTopology(cluster, nodes)); + } + + // Deploy-time TagConfig strictness inspection. The driver-typed EquipmentTagConfigInspector surfaces every + // blob the driver's own reader would REJECT — each of which makes the driver skip the tag so it reads + // BadNodeIdUnknown forever. Warn mode (default): non-blocking; Error mode: blocking. A raw Tag's driver is + // resolved via its Device. + var driverTypeById = draft.DriverInstances + .GroupBy(d => d.DriverInstanceId, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.First().DriverType, StringComparer.Ordinal); + var deviceById = draft.Devices + .GroupBy(d => d.DeviceId, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal); + var tagConfigFindings = new List(); + foreach (var t in draft.Tags) + { + if (!deviceById.TryGetValue(t.DeviceId, out var device)) continue; + if (!driverTypeById.TryGetValue(device.DriverInstanceId, out var driverType)) continue; + foreach (var w in EquipmentTagConfigInspector.Inspect(driverType, t.TagConfig, device.DeviceConfig)) + tagConfigFindings.Add(new ValidationError(TagConfigInvalidCode, $"tag '{t.TagId}': {w}", t.TagId)); + } + + IReadOnlyList tagConfigWarnings = []; + if (tagConfigMode == TagConfigValidationMode.Error) errors.AddRange(tagConfigFindings); + else tagConfigWarnings = tagConfigFindings; + + return new Result( + errors, + tagConfigWarnings, + SqlTagDeployChecks.WritableMismatchWarnings(draft), + DataConnectionValidator.DeployWarnings(draft)); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Preflight/LegacySchemaTolerance.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Preflight/LegacySchemaTolerance.cs new file mode 100644 index 000000000..c453c80d7 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Preflight/LegacySchemaTolerance.cs @@ -0,0 +1,151 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.DependencyInjection; +using ZB.MOM.WW.OtOpcUa.Configuration; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight; + +/// +/// Lets THIS build's read a ConfigDb that is still on an OLDER schema — the +/// whole point of a pre-upgrade preflight is to run before the pending migrations. A table a pending migration +/// creates is read as empty (mapped to a typed zero-row query); a column a pending migration adds is left out of +/// the model (the property keeps its CLR default). Nothing else is changed, so every rule sees exactly the rows a +/// deploy right after the upgrade would see, minus data that cannot exist yet. +/// +internal static class LegacySchemaTolerance +{ + /// The tables / columns of the current model that are absent from the database. + /// Table names, case-insensitive. + /// (table, column) pairs on tables that exist. + internal sealed record SchemaGaps(IReadOnlySet MissingTables, IReadOnlySet<(string Table, string Column)> MissingColumns) + { + /// No gap at all — the plain model reads the database. + public bool IsEmpty => MissingTables.Count == 0 && MissingColumns.Count == 0; + + /// Stable text form; also the model-cache discriminator. + public string Signature => + string.Join(";", MissingTables.Order(StringComparer.OrdinalIgnoreCase)) + "|" + + string.Join(";", MissingColumns.Select(c => $"{c.Table}.{c.Column}").Order(StringComparer.OrdinalIgnoreCase)); + } + + /// Compares the model's tables/columns with the database's (dbo schema). + /// The current model. + /// Database table → its columns. + /// The gaps. + internal static SchemaGaps Compare(IModel model, IReadOnlyDictionary> present) + { + var tables = new HashSet(StringComparer.OrdinalIgnoreCase); + var columns = new HashSet<(string, string)>(); + foreach (var entity in model.GetEntityTypes()) + { + var table = entity.GetTableName(); + if (table is null) continue; + if (!present.TryGetValue(table, out var have)) + { + tables.Add(table); + continue; + } + + var store = StoreObjectIdentifier.Table(table, entity.GetSchema()); + foreach (var p in entity.GetProperties()) + if (p.GetColumnName(store) is { } column && !have.Contains(column)) + columns.Add((table, column)); + } + + return new SchemaGaps(tables, columns); + } + + /// Configures to read through . + /// The options builder (SQL Server already selected). + /// The gaps; nothing is changed when empty. + internal static void Apply(DbContextOptionsBuilder builder, SchemaGaps gaps) + { + if (gaps.IsEmpty) return; + ((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(new GapsExtension(gaps)); + builder.ReplaceService(); + builder.ReplaceService(); + } + + /// Carries the gaps to the model customizer (and into the internal service-provider/model caches). + private sealed class GapsExtension(SchemaGaps gaps) : IDbContextOptionsExtension + { + public SchemaGaps Gaps { get; } = gaps; + + public DbContextOptionsExtensionInfo Info => new ExtensionInfo(this); + + public void ApplyServices(IServiceCollection services) + { + } + + public void Validate(IDbContextOptions options) + { + } + + private sealed class ExtensionInfo(GapsExtension extension) : DbContextOptionsExtensionInfo(extension) + { + public override bool IsDatabaseProvider => false; + + public override string LogFragment => "LegacySchemaTolerance "; + + public override int GetServiceProviderHashCode() => + StringComparer.Ordinal.GetHashCode(((GapsExtension)Extension).Gaps.Signature); + + public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => + other is ExtensionInfo o && o.Extension is GapsExtension g && + string.Equals(g.Gaps.Signature, ((GapsExtension)Extension).Gaps.Signature, StringComparison.Ordinal); + + public override void PopulateDebugInfo(IDictionary debugInfo) => + debugInfo["LegacySchemaTolerance"] = ((GapsExtension)Extension).Gaps.Signature; + } + } + + /// Runs the context's own model building, then maps the gaps. + private sealed class TolerantModelCustomizer(ModelCustomizerDependencies dependencies) : RelationalModelCustomizer(dependencies) + { + public override void Customize(ModelBuilder modelBuilder, DbContext context) + { + base.Customize(modelBuilder, context); + var gaps = context.GetService().FindExtension()?.Gaps; + if (gaps is null) return; + var typeMappings = context.GetService(); + + foreach (var entity in modelBuilder.Model.GetEntityTypes().ToList()) + { + var table = entity.GetTableName(); + if (table is null) continue; + + if (gaps.MissingTables.Contains(table)) + { + // A typed, zero-row stand-in: the deploy reads the table as empty, as it will be right after the + // migration creates it. Types matter only so predicates/ORDER BY over it compile. + var store = StoreObjectIdentifier.Table(table, entity.GetSchema()); + var columns = entity.GetProperties().Select(p => + { + var clr = p.GetValueConverter()?.ProviderClrType ?? p.GetProviderClrType() ?? p.ClrType; + var type = p.GetColumnType() ?? typeMappings.FindMapping(Nullable.GetUnderlyingType(clr) ?? clr)?.StoreType ?? "sql_variant"; + if (type.Equals("rowversion", StringComparison.OrdinalIgnoreCase)) type = "binary(8)"; + return $"CAST(NULL AS {type}) AS [{p.GetColumnName(store) ?? p.Name}]"; + }); + modelBuilder.Entity(entity.ClrType).ToSqlQuery($"SELECT TOP (0) {string.Join(", ", columns)}"); + continue; + } + + foreach (var p in entity.GetProperties().ToList()) + { + var column = p.GetColumnName(StoreObjectIdentifier.Table(table, entity.GetSchema())) ?? p.Name; + if (gaps.MissingColumns.Contains((table, column))) + modelBuilder.Entity(entity.ClrType).Ignore(p.Name); + } + } + } + } + + /// Two contexts over databases with different gaps must not share a cached model. + private sealed class GapsAwareModelCacheKeyFactory : IModelCacheKeyFactory + { + public object Create(DbContext context, bool designTime) => + (context.GetType(), designTime, context.GetService().FindExtension()?.Gaps.Signature); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Preflight/MigrationPreChecks.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Preflight/MigrationPreChecks.cs new file mode 100644 index 000000000..7596f6124 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Preflight/MigrationPreChecks.cs @@ -0,0 +1,146 @@ +using Microsoft.Data.SqlClient; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight; + +/// +/// The read-only, row-naming twins of the pre-checks inside the migrations that add constraints over existing data +/// (lmxopcua#1021): each migration THROWs and changes nothing when its data cannot hold the new constraint; these +/// list every offending row up front, so the operator can clean up before the upgrade window instead of during it. +/// Keep a new constraint-adding migration's pre-check and its entry here in step. +/// +internal static class MigrationPreChecks +{ + /// One check: a SELECT whose rows are the offenders (group key in column 0, row id in column 1). + /// The migration name suffix (the part after the timestamp). + /// Finding code. + /// The SELECT. Column 0 = group label (rows sharing it are one problem), column 1 = row id. + /// Builds the message from the group label and its row ids. + internal sealed record Check(string Migration, string Code, string Sql, Func, string> Describe); + + internal const string ConfigurationGaps = "ConfigurationGapsIndexesAndRowVersions"; + internal const string ScriptForeignKeys = "ScriptForeignKeysAndExternalIdUniqueness"; + + /// Every known check, in migration order. + internal static readonly IReadOnlyList All = + [ + // lmxopcua#998 C-8: UX_NodeAcl_PrincipalScope / UX_LdapGroupRoleMapping_Group_Cluster become unfiltered, so + // NULL-keyed rows (Cluster-scope ACLs, system-wide mappings) must be unique too. PARTITION BY groups NULLs + // together and compares with the column collation — exactly what the unique index will do. + new(ConfigurationGaps, "DuplicateNodeAcl", """ + SELECT CONCAT(N'cluster ''', ClusterId, N''', principal ''', Principal, N''', scope ', ScopeKind, N' ''', ISNULL(ScopeId, N'(cluster)'), N''''), NodeAclId + FROM (SELECT *, COUNT(*) OVER (PARTITION BY ClusterId, Principal, ScopeKind, ScopeId) AS n FROM [NodeAcl]) x + WHERE n > 1 ORDER BY ClusterId, Principal, ScopeKind, ScopeId, NodeAclId + """, + (key, ids) => $"{ids.Count} NodeAcl rows share {key}: {Join(ids)}. Delete or merge all but one."), + new(ConfigurationGaps, "DuplicateLdapGroupRoleMapping", """ + SELECT CONCAT(N'group ''', LdapGroup, N''' in ', ISNULL(N'cluster ''' + ClusterId + N'''', N'(system-wide)')), CONVERT(nvarchar(36), Id) + FROM (SELECT *, COUNT(*) OVER (PARTITION BY LdapGroup, ClusterId) AS n FROM [LdapGroupRoleMapping]) x + WHERE n > 1 ORDER BY LdapGroup, ClusterId, Id + """, + (key, ids) => $"{ids.Count} LdapGroupRoleMapping rows share {key}: {Join(ids)}. Delete or merge all but one."), + + // lmxopcua#1040 / #1049: script FKs, Script.ScriptId NOT NULL, unique ZTag / SAPID, reservation ledger dropped. + new(ScriptForeignKeys, "ScriptIdNull", """ + SELECT N'Script rows with a NULL ScriptId', CONCAT(CONVERT(nvarchar(36), ScriptRowId), N' (', Name, N')') + FROM [Script] WHERE ScriptId IS NULL ORDER BY Name + """, + (_, ids) => $"{ids.Count} Script row(s) have a NULL ScriptId: {Join(ids)}. Give each a unique ScriptId or delete it."), + new(ScriptForeignKeys, "VirtualTagScriptDangling", """ + SELECT CONCAT(N'missing script ''', v.ScriptId, N''''), CONCAT(v.VirtualTagId, N' (equipment ', v.EquipmentId, N', ''', v.Name, N''')') + FROM [VirtualTag] v WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.ScriptId = v.ScriptId) ORDER BY v.ScriptId, v.VirtualTagId + """, + (key, ids) => $"VirtualTag row(s) name {key}: {Join(ids)}. Point them at an existing script or delete them."), + new(ScriptForeignKeys, "ScriptedAlarmScriptDangling", """ + SELECT CONCAT(N'missing predicate script ''', a.PredicateScriptId, N''''), CONCAT(a.ScriptedAlarmId, N' (equipment ', a.EquipmentId, N', ''', a.Name, N''')') + FROM [ScriptedAlarm] a WHERE NOT EXISTS (SELECT 1 FROM [Script] s WHERE s.ScriptId = a.PredicateScriptId) ORDER BY a.PredicateScriptId, a.ScriptedAlarmId + """, + (key, ids) => $"ScriptedAlarm row(s) name {key}: {Join(ids)}. Point them at an existing script or delete them."), + new(ScriptForeignKeys, "DuplicateZTag", """ + SELECT CONCAT(N'ZTag ''', ZTag, N''''), EquipmentId + FROM (SELECT *, COUNT(*) OVER (PARTITION BY ZTag) AS n FROM [Equipment] WHERE ZTag IS NOT NULL AND ZTag <> N'') x + WHERE n > 1 ORDER BY ZTag, EquipmentId + """, + (key, ids) => $"{key} is set on {ids.Count} equipment rows: {Join(ids)}. Keep it on one and clear or change the others."), + new(ScriptForeignKeys, "DuplicateSAPID", """ + SELECT CONCAT(N'SAPID ''', SAPID, N''''), EquipmentId + FROM (SELECT *, COUNT(*) OVER (PARTITION BY SAPID) AS n FROM [Equipment] WHERE SAPID IS NOT NULL AND SAPID <> N'') x + WHERE n > 1 ORDER BY SAPID, EquipmentId + """, + (key, ids) => $"{key} is set on {ids.Count} equipment rows: {Join(ids)}. Keep it on one and clear or change the others."), + new(ScriptForeignKeys, "ExternalIdReservationRows", """ + IF OBJECT_ID(N'[ExternalIdReservation]', N'U') IS NOT NULL + EXEC(N'SELECT N''ExternalIdReservation rows'', CONCAT(Kind, N'' '''''', Value, N'''''' -> '', CONVERT(nvarchar(36), EquipmentUuid), CASE WHEN ReleasedAt IS NULL THEN N'' (active)'' ELSE N'' (released)'' END) FROM [ExternalIdReservation] ORDER BY Kind, Value'); + """, + (_, ids) => $"{ids.Count} ExternalIdReservation row(s): {Join(ids)}. The ledger is retired and its table is dropped by the migration, " + + "which refuses while it holds rows. Export them if their history matters, then DELETE FROM [ExternalIdReservation]."), + ]; + + private const int MaxIdsNamed = 25; + + private static string Join(IReadOnlyList ids) => + string.Join(", ", ids.Take(MaxIdsNamed)) + (ids.Count > MaxIdsNamed ? $" (+{ids.Count - MaxIdsNamed} more)" : string.Empty); + + /// Runs every check whose migration is pending; already-applied migrations are reported as Info. + /// An open connection to the ConfigDb. + /// The pending migration ids (timestamp-prefixed). + /// Cancellation. + /// The findings. + internal static async Task> RunAsync( + SqlConnection connection, IReadOnlyCollection pendingMigrationIds, CancellationToken ct) + { + var findings = new List(); + foreach (var migration in All.Select(c => c.Migration).Distinct()) + { + var check = $"migration:{migration}"; + if (!pendingMigrationIds.Any(id => id.EndsWith("_" + migration, StringComparison.Ordinal))) + { + findings.Add(new(check, "AlreadyApplied", PreflightSeverity.Info, + $"{migration} is already applied (or not part of this build); its pre-check is not needed.")); + continue; + } + + var clean = true; + foreach (var c in All.Where(c => c.Migration == migration)) + { + List<(string Key, string Id)> rows; + try + { + rows = await QueryAsync(connection, c.Sql, ct).ConfigureAwait(false); + } + catch (SqlException ex) + { + clean = false; + findings.Add(new(check, c.Code, PreflightSeverity.Warning, + $"pre-check {c.Code} could not run against this schema ({OneLine(ex.Message)}); the migration's own pre-check will still refuse bad rows.")); + continue; + } + + foreach (var group in rows.GroupBy(r => r.Key, StringComparer.Ordinal)) + { + clean = false; + var ids = group.Select(r => r.Id).ToList(); + findings.Add(new(check, c.Code, PreflightSeverity.Blocking, c.Describe(group.Key, ids), ids.Count == 1 ? ids[0] : null)); + } + } + + if (clean) + findings.Add(new(check, "Clean", PreflightSeverity.Info, $"{migration} will apply: no row breaks its new constraints.")); + } + + return findings; + } + + private static string OneLine(string message) => + string.Join(" ", message.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Distinct(StringComparer.Ordinal)); + + private static async Task> QueryAsync(SqlConnection connection, string sql, CancellationToken ct) + { + var rows = new List<(string, string)>(); + await using var cmd = connection.CreateCommand(); + cmd.CommandText = sql; + await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + while (await reader.ReadAsync(ct).ConfigureAwait(false)) + rows.Add((reader.IsDBNull(0) ? string.Empty : reader.GetString(0), reader.IsDBNull(1) ? string.Empty : reader.GetString(1))); + return rows; + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Preflight/PreflightReport.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Preflight/PreflightReport.cs new file mode 100644 index 000000000..abaf55449 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Preflight/PreflightReport.cs @@ -0,0 +1,55 @@ +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight; + +/// How much a preflight finding matters for the upgrade. +public enum PreflightSeverity +{ + /// The upgrade (a migration) or the next deploy will be REFUSED until this is fixed. + Blocking, + + /// Not refused, but worth fixing (behaviour change, or refused only in a non-default mode). + Warning, + + /// Context only. + Info, +} + +/// One preflight finding. +/// Which check produced it (schema, migration:<name>, deploy-gate, script-gate). +/// The rule code — the deploy gate's own code for gate findings. +/// How much it matters. +/// Operator-facing text naming the rows. +/// The offending row's id, when there is one. +public sealed record PreflightFinding(string Check, string Code, PreflightSeverity Severity, string Message, string? Subject = null); + +/// The whole preflight result for one ConfigDb. +/// The SQL Server data source (never the credentials). +/// The database name. +/// Migrations already applied, oldest first. +/// Migrations this build would apply, oldest first. +/// Every finding, in check order. +public sealed record PreflightReport( + string Server, + string Database, + IReadOnlyList AppliedMigrations, + IReadOnlyList PendingMigrations, + IReadOnlyList Findings) +{ + /// True when any finding would refuse the upgrade or the next deploy. + public bool HasBlocking => Findings.Any(f => f.Severity == PreflightSeverity.Blocking); +} + +/// Preflight knobs — set them as the target deployment's appsettings are. +public sealed record UpgradePreflightOptions +{ + /// Deployment:TagConfigValidationMode of the target (Warn is the shipped default). + public AdminOperations.TagConfigValidationMode TagConfigMode { get; init; } = AdminOperations.TagConfigValidationMode.Warn; + + /// Deployment:ScriptCompileGateMode of the target (Error is the shipped default). + public AdminOperations.ScriptCompileGateMode ScriptGateMode { get; init; } = AdminOperations.ScriptCompileGateMode.Error; + + /// Also compile scripts no enabled VirtualTag / scripted alarm / Calculation tag uses (Warning only). + public bool CheckUnusedScripts { get; init; } = true; +} + +/// The target is not something the preflight can check (not a v3 ConfigDb, unreachable). +public sealed class PreflightUnsupportedException(string message, Exception? inner = null) : Exception(message, inner); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Preflight/UpgradePreflight.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Preflight/UpgradePreflight.cs new file mode 100644 index 000000000..b230da9b4 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Preflight/UpgradePreflight.cs @@ -0,0 +1,201 @@ +using System.Data; +using Microsoft.Data.SqlClient; +using Microsoft.EntityFrameworkCore; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; +using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight; + +/// +/// The read-only pre-upgrade preflight (lmxopcua#1013, #1015, #1021, #1058): connects to a ConfigDb — normally +/// BEFORE this build's migrations are applied to it — and reports every row the upgrade would refuse: +/// +/// Migration pre-checks () — the rows each pending constraint-adding +/// migration would THROW on, named. +/// The deploy gate — (every DraftValidator rule incl. the new +/// VirtualTag name / effective-name / script-reference / ZTag / dangling-reference / Sql named-query rules, the +/// topology check, the TagConfig inspection) over the same whole-DB snapshot a deploy reads, through this build's +/// code. The first deploy after the upgrade is refused for every Blocking one. +/// The script compile gate — through the supplied +/// (the Roslyn compile + sandbox allow-list the runtime runs); optionally +/// also every stored script nothing currently uses. +/// +/// Only SELECTs are issued. The snapshot is read under SNAPSHOT isolation when the database allows it (the deploy +/// path's own read), else READ COMMITTED. +/// +public static class UpgradePreflight +{ + private const string V3InitialSuffix = "_V3Initial"; + + /// Runs every check against the ConfigDb at . + /// The ConfigDb connection string. + /// The compile checker (the Host's RoslynDeployScriptChecker); null skips the script gate. + /// Mode knobs matching the target deployment. + /// Cancellation. + /// The report. + /// The database is unreachable or not a v3 ConfigDb. + public static async Task RunAsync( + string connectionString, IDeployScriptChecker? scriptChecker, UpgradePreflightOptions? options = null, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(connectionString); + options ??= new UpgradePreflightOptions(); + var csb = new SqlConnectionStringBuilder(connectionString); + var findings = new List(); + + await using var connection = new SqlConnection(connectionString); + try + { + await connection.OpenAsync(ct).ConfigureAwait(false); + } + catch (SqlException ex) + { + throw new PreflightUnsupportedException($"cannot connect to '{csb.DataSource}' / '{csb.InitialCatalog}': {ex.Message}", ex); + } + + var applied = await ReadAppliedMigrationsAsync(connection, ct).ConfigureAwait(false); + if (!applied.Any(id => id.EndsWith(V3InitialSuffix, StringComparison.Ordinal))) + throw new PreflightUnsupportedException( + $"'{connection.Database}' is not a v3 OtOpcUa ConfigDb (no {V3InitialSuffix[1..]} migration in __EFMigrationsHistory); " + + "this preflight checks an upgrade between v3 builds only."); + + var plainOptions = new DbContextOptionsBuilder().UseSqlServer(connectionString).Options; + IReadOnlyList pending; + Microsoft.EntityFrameworkCore.Metadata.IModel model; + await using (var plain = new OtOpcUaConfigDbContext(plainOptions)) + { + pending = plain.Database.GetMigrations().Except(applied, StringComparer.Ordinal).ToList(); + model = plain.Model; + var unknown = applied.Except(plain.Database.GetMigrations(), StringComparer.Ordinal).ToList(); + if (unknown.Count > 0) + findings.Add(new("schema", "UnknownMigrations", PreflightSeverity.Warning, + $"the database has migration(s) this build does not know ({string.Join(", ", unknown)}) — it is NEWER than this build; " + + "the checks below may not match what it will do.")); + } + + findings.Add(new("schema", "PendingMigrations", PreflightSeverity.Info, pending.Count == 0 + ? "no pending migrations — the schema is already this build's." + : $"{pending.Count} pending migration(s) this build would apply: {string.Join(", ", pending)}.")); + + // 1. Migration pre-checks (raw SQL against the current schema). + findings.AddRange(await MigrationPreChecks.RunAsync(connection, pending, ct).ConfigureAwait(false)); + + // 2 + 3. The deploy gate, on a snapshot read through this build's model, tolerant of an older schema. + var gaps = LegacySchemaTolerance.Compare(model, await ReadSchemaAsync(connection, ct).ConfigureAwait(false)); + if (!gaps.IsEmpty) + findings.Add(new("schema", "ReadAsEmpty", PreflightSeverity.Info, + "tables / columns a pending migration creates are read as empty / default: " + gaps.Signature.Replace("|", " | ", StringComparison.Ordinal))); + + DraftSnapshot draft; + try + { + draft = await ReadSnapshotAsync(connectionString, gaps, await SnapshotIsolationAllowedAsync(connection, ct).ConfigureAwait(false), findings, ct) + .ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + findings.Add(new("deploy-gate", "SnapshotUnreadable", PreflightSeverity.Blocking, + $"this build could not read the configuration snapshot ({ex.GetType().Name}: {ex.Message}) — the deploy would fail the same way. " + + "Fix the migration pre-check findings above (a NULL Script.ScriptId is one cause) and re-run.")); + return new PreflightReport(csb.DataSource, connection.Database, applied, pending, findings); + } + + var gate = DeployGateRules.Evaluate(draft, options.TagConfigMode); + findings.AddRange(gate.Errors.Select(e => new PreflightFinding("deploy-gate", e.Code, PreflightSeverity.Blocking, e.Message, e.Context))); + findings.AddRange(gate.TagConfigWarnings.Select(e => new PreflightFinding("deploy-gate", e.Code, PreflightSeverity.Warning, + e.Message + " (blocking only with Deployment:TagConfigValidationMode=Error)", e.Context))); + findings.AddRange(gate.SqlWritableWarnings.Select(w => new PreflightFinding("deploy-gate", "SqlWritableMismatch", PreflightSeverity.Warning, w))); + findings.AddRange(gate.DataConnectionWarnings.Select(w => new PreflightFinding("deploy-gate", "DataConnectionWarning", PreflightSeverity.Warning, w))); + if (gate.Errors.Count == 0) + findings.Add(new("deploy-gate", "Clean", PreflightSeverity.Info, "every deploy-gate rule passes.")); + + RunScriptGate(scriptChecker, draft, options, findings, ct); + + return new PreflightReport(csb.DataSource, connection.Database, applied, pending, findings); + } + + private static void RunScriptGate( + IDeployScriptChecker? checker, DraftSnapshot draft, UpgradePreflightOptions options, List findings, CancellationToken ct) + { + if (checker is null || options.ScriptGateMode == ScriptCompileGateMode.Off) + { + findings.Add(new("script-gate", "Skipped", PreflightSeverity.Info, "script compile gate not run.")); + return; + } + + var severity = options.ScriptGateMode == ScriptCompileGateMode.Error ? PreflightSeverity.Blocking : PreflightSeverity.Warning; + var refused = DeployScriptGate.Run(checker, draft, ct); + findings.AddRange(refused.Select(f => new PreflightFinding("script-gate", DeployScriptGate.ErrorCode, severity, f.Text, f.ScriptId))); + + var used = DeployScriptGate.CollectUses(draft).Select(u => u.ScriptId).ToHashSet(StringComparer.Ordinal); + var unused = draft.Scripts.Where(s => !used.Contains(s.ScriptId)).OrderBy(s => s.ScriptId, StringComparer.Ordinal).ToList(); + if (options.CheckUnusedScripts && unused.Count > 0) + { + // Nothing compiles these today, so they block nothing — but binding one to a VirtualTag / alarm later is + // refused at that deploy. Checked as a value script (the seam a VirtualTag or Calculation tag compiles for). + var results = checker.Check(unused.Select(s => new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, s.SourceCode ?? string.Empty)).ToList(), ct); + for (var i = 0; i < unused.Count; i++) + if (!results[i].Passed) + findings.Add(new("script-gate", "UnusedScriptDoesNotCompile", PreflightSeverity.Warning, + $"script '{unused[i].ScriptId}' ('{unused[i].Name}') is not used by any enabled VirtualTag, scripted alarm or Calculation tag, " + + $"and would not compile as a value script: {string.Join("; ", results[i].Problems)}", + unused[i].ScriptId)); + } + + findings.Add(new("script-gate", refused.Count == 0 ? "Clean" : "Summary", PreflightSeverity.Info, + $"{used.Count} script(s) in use checked, {refused.Count} refused" + + (options.CheckUnusedScripts ? $"; {unused.Count} unused script(s) checked." : "."))); + } + + private static async Task ReadSnapshotAsync( + string connectionString, LegacySchemaTolerance.SchemaGaps gaps, bool snapshotAllowed, List findings, CancellationToken ct) + { + var builder = new DbContextOptionsBuilder().UseSqlServer(connectionString); + LegacySchemaTolerance.Apply(builder, gaps); + await using var db = new OtOpcUaConfigDbContext(builder.Options); + if (snapshotAllowed) return await DraftSnapshotFactory.FromConfigDbAsync(db, ct).ConfigureAwait(false); + + findings.Add(new("schema", "NoSnapshotIsolation", PreflightSeverity.Warning, + "ALLOW_SNAPSHOT_ISOLATION is OFF (migration EnableSnapshotIsolation not applied?) — read under READ COMMITTED, so an edit " + + "committed mid-read could show as a transient finding; re-run to confirm. The deploy itself requires snapshot isolation.")); + await using var tx = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct).ConfigureAwait(false); + var draft = await DraftSnapshotFactory.FromConfigDbAsync(db, ct).ConfigureAwait(false); + await tx.RollbackAsync(ct).ConfigureAwait(false); + return draft; + } + + private static async Task> ReadAppliedMigrationsAsync(SqlConnection connection, CancellationToken ct) + { + await using var cmd = connection.CreateCommand(); + cmd.CommandText = "IF OBJECT_ID(N'[__EFMigrationsHistory]', N'U') IS NOT NULL SELECT MigrationId FROM [__EFMigrationsHistory] ORDER BY MigrationId"; + var ids = new List(); + await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + while (await reader.ReadAsync(ct).ConfigureAwait(false)) ids.Add(reader.GetString(0)); + return ids; + } + + private static async Task>> ReadSchemaAsync(SqlConnection connection, CancellationToken ct) + { + await using var cmd = connection.CreateCommand(); + cmd.CommandText = "SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = N'dbo'"; + var schema = new Dictionary>(StringComparer.OrdinalIgnoreCase); + await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + while (await reader.ReadAsync(ct).ConfigureAwait(false)) + { + var table = reader.GetString(0); + if (!schema.TryGetValue(table, out var columns)) + schema[table] = columns = new HashSet(StringComparer.OrdinalIgnoreCase); + columns.Add(reader.GetString(1)); + } + + return schema; + } + + private static async Task SnapshotIsolationAllowedAsync(SqlConnection connection, CancellationToken ct) + { + await using var cmd = connection.CreateCommand(); + cmd.CommandText = "SELECT snapshot_isolation_state FROM sys.databases WHERE name = DB_NAME()"; + return await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false) is byte state && state == 1; + } +} diff --git a/src/Tooling/ZB.MOM.WW.OtOpcUa.UpgradePreflight/Program.cs b/src/Tooling/ZB.MOM.WW.OtOpcUa.UpgradePreflight/Program.cs new file mode 100644 index 000000000..c8ba18ed0 --- /dev/null +++ b/src/Tooling/ZB.MOM.WW.OtOpcUa.UpgradePreflight/Program.cs @@ -0,0 +1,109 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; + +// otopcua-preflight — read-only pre-upgrade check of an OtOpcUa ConfigDb (docs/v2/upgrade-preflight.md). +// Exit codes: 0 = nothing blocks the upgrade or the next deploy; 1 = at least one Blocking finding; +// 2 = usage error, unreachable database, or not a v3 ConfigDb. + +const string Usage = """ + otopcua-preflight — read-only pre-upgrade check of an OtOpcUa ConfigDb (issues only SELECTs). + + Usage: + otopcua-preflight [--connection ""] [options] + + The connection string defaults to the OTOPCUA_CONFIG_CONNECTION environment variable (prefer it: a + command-line argument is visible in the process list and shell history). + + Options: + --tagconfig-mode Warn|Error the target's Deployment:TagConfigValidationMode (default Warn) + --script-gate Error|Warn|Off the target's Deployment:ScriptCompileGateMode (default Error) + --no-unused-scripts do not compile scripts nothing uses + --json machine-readable report on stdout + --verbose also print Info findings + -h, --help this text + + Exit codes: 0 nothing blocks; 1 blocking findings; 2 usage / connection / not a v3 ConfigDb. + """; + +string? connection = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_CONNECTION"); +var options = new UpgradePreflightOptions(); +var json = false; +var verbose = false; + +for (var i = 0; i < args.Length; i++) +{ + string Next() => i + 1 < args.Length ? args[++i] : throw new ArgumentException($"{args[i]} needs a value"); + try + { + switch (args[i]) + { + case "--connection": connection = Next(); break; + case "--tagconfig-mode": options = options with { TagConfigMode = Enum.Parse(Next(), ignoreCase: true) }; break; + case "--script-gate": options = options with { ScriptGateMode = Enum.Parse(Next(), ignoreCase: true) }; break; + case "--no-unused-scripts": options = options with { CheckUnusedScripts = false }; break; + case "--json": json = true; break; + case "--verbose": verbose = true; break; + case "-h" or "--help": Console.Out.WriteLine(Usage); return 0; + default: throw new ArgumentException($"unknown argument '{args[i]}'"); + } + } + catch (ArgumentException ex) + { + Console.Error.WriteLine($"error: {ex.Message}\n\n{Usage}"); + return 2; + } +} + +if (string.IsNullOrWhiteSpace(connection)) +{ + Console.Error.WriteLine($"error: no connection string (--connection or OTOPCUA_CONFIG_CONNECTION)\n\n{Usage}"); + return 2; +} + +PreflightReport report; +try +{ + report = await UpgradePreflight.RunAsync(connection, new RoslynDeployScriptChecker(), options); +} +catch (PreflightUnsupportedException ex) +{ + Console.Error.WriteLine($"error: {ex.Message}"); + return 2; +} + +if (json) +{ + Console.Out.WriteLine(JsonSerializer.Serialize(report, new JsonSerializerOptions + { + WriteIndented = true, + Converters = { new JsonStringEnumConverter() }, + })); + return report.HasBlocking ? 1 : 0; +} + +Console.Out.WriteLine($"OtOpcUa upgrade preflight — server '{report.Server}', database '{report.Database}'"); +Console.Out.WriteLine($" applied migrations: {report.AppliedMigrations.Count} (latest {report.AppliedMigrations.LastOrDefault() ?? "-"})"); +Console.Out.WriteLine($" pending migrations: {report.PendingMigrations.Count}"); +foreach (var group in report.Findings.GroupBy(f => f.Check)) +{ + var shown = group.Where(f => verbose || f.Severity != PreflightSeverity.Info).ToList(); + var blocking = group.Count(f => f.Severity == PreflightSeverity.Blocking); + var warnings = group.Count(f => f.Severity == PreflightSeverity.Warning); + Console.Out.WriteLine(); + Console.Out.WriteLine($"[{group.Key}] {blocking} blocking, {warnings} warning(s)"); + foreach (var f in shown) + Console.Out.WriteLine($" {f.Severity.ToString().ToUpperInvariant(),-8} {f.Code}: {f.Message}"); + if (!verbose) + foreach (var f in group.Where(f => f.Severity == PreflightSeverity.Info && f.Code is "Clean" or "Summary" or "PendingMigrations")) + Console.Out.WriteLine($" {f.Message}"); +} + +var total = report.Findings.Count(f => f.Severity == PreflightSeverity.Blocking); +Console.Out.WriteLine(); +Console.Out.WriteLine(report.HasBlocking + ? $"RESULT: {total} blocking finding(s) — fix them before upgrading (exit 1)." + : "RESULT: nothing blocks the upgrade or the next deploy (exit 0)."); +return report.HasBlocking ? 1 : 0; diff --git a/src/Tooling/ZB.MOM.WW.OtOpcUa.UpgradePreflight/ZB.MOM.WW.OtOpcUa.UpgradePreflight.csproj b/src/Tooling/ZB.MOM.WW.OtOpcUa.UpgradePreflight/ZB.MOM.WW.OtOpcUa.UpgradePreflight.csproj new file mode 100644 index 000000000..2c582d2b2 --- /dev/null +++ b/src/Tooling/ZB.MOM.WW.OtOpcUa.UpgradePreflight/ZB.MOM.WW.OtOpcUa.UpgradePreflight.csproj @@ -0,0 +1,20 @@ + + + + + Exe + ZB.MOM.WW.OtOpcUa.UpgradePreflight + otopcua-preflight + + + + + + + + diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlServerTestDatabase.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlServerTestDatabase.cs index 3415bb996..8aa841de8 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlServerTestDatabase.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlServerTestDatabase.cs @@ -1,5 +1,6 @@ using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; using ZB.MOM.WW.OtOpcUa.Configuration; namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness; @@ -23,7 +24,13 @@ public sealed class SqlServerTestDatabase : IDisposable private readonly string _databaseName; /// Creates and migrates the database. - public SqlServerTestDatabase() + public SqlServerTestDatabase() : this(null) + { + } + + /// Creates the database migrated up to (latest when null). + /// A migration id or name to stop at — e.g. to seed rows a later migration refuses. + public SqlServerTestDatabase(string? targetMigration) { var server = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SERVER") ?? DefaultServer; var saPassword = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SA_PASSWORD") ?? DefaultSaPassword; @@ -31,7 +38,8 @@ public sealed class SqlServerTestDatabase : IDisposable ConnectionString = $"Server={server};Database={_databaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;"; using var ctx = NewContext(); - ctx.Database.Migrate(); + if (targetMigration is null) ctx.Database.Migrate(); + else ctx.GetService().Migrate(targetMigration); } /// A new context on the database. diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/UpgradePreflightSqlServerTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/UpgradePreflightSqlServerTests.cs new file mode 100644 index 000000000..d28f7a747 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/UpgradePreflightSqlServerTests.cs @@ -0,0 +1,190 @@ +using Microsoft.Data.SqlClient; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests; + +/// +/// lmxopcua#1013 / #1015 / #1021 / #1058: the read-only upgrade preflight against real SQL Server. A ConfigDb still +/// on an OLDER schema (pending migrations add tables and columns) is read through this build's model, and every row +/// a pending migration or the next deploy would refuse is named — with nothing written. Positive controls: a clean +/// database reports no blocking finding; a database that is not a v3 ConfigDb is refused, not guessed at. +/// +[Trait("Category", "SchemaCompliance")] +public sealed class UpgradePreflightSqlServerTests +{ + /// Before the gRPC data-connection tables, the #998 RowVersion columns and the #1040/#1049 constraints. + private const string OldSchema = "20261022102459_EnableSnapshotIsolation"; + + private static readonly RoslynDeployScriptChecker Checker = new(); + + private static async Task ExecAsync(SqlServerTestDatabase sql, string text) + { + await using var conn = new SqlConnection(sql.ConnectionString); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await using var cmd = conn.CreateCommand(); + cmd.CommandText = text; + await cmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken); + } + + private static async Task RowCountAsync(SqlServerTestDatabase sql) + { + await using var conn = new SqlConnection(sql.ConnectionString); + await conn.OpenAsync(TestContext.Current.CancellationToken); + await using var cmd = conn.CreateCommand(); + cmd.CommandText = "SELECT SUM(p.rows) FROM sys.partitions p JOIN sys.tables t ON t.object_id = p.object_id WHERE p.index_id IN (0, 1)"; + return Convert.ToInt64(await cmd.ExecuteScalarAsync(TestContext.Current.CancellationToken)); + } + + private static Equipment NewEquipment(string lineId, string name, string? zTag) + { + var uuid = Guid.NewGuid(); + return new Equipment + { + EquipmentId = "EQ-" + uuid.ToString("N")[..12], EquipmentUuid = uuid, UnsLineId = lineId, Name = name, + MachineCode = "mc-" + uuid.ToString("N"), ZTag = zTag, + }; + } + + /// + /// Every class of finding on one old-schema database: the migration pre-checks (#1021), the new VirtualTag / + /// script-reference / ZTag gate rules (#1015), the Sql named-query rule (#1058) and the script compile gate (#1013). + /// + [Fact] + public async Task An_old_schema_database_is_read_and_every_blocking_row_is_named_without_writing() + { + var ct = TestContext.Current.CancellationToken; + using var sql = new SqlServerTestDatabase(OldSchema); + + // Rows the old schema allows and the new one refuses. ServerCluster / NodeAcl by SQL: this build's model has + // columns (RowVersion) the old tables do not. + await ExecAsync(sql, """ + INSERT ServerCluster (ClusterId, Name, Enterprise, Site, NodeCount, RedundancyMode, Enabled, CreatedBy) + VALUES ('C1', 'Cluster one', 'zb', 's1', 1, 'None', 1, 't'); + INSERT NodeAcl (NodeAclId, ClusterId, Principal, ScopeKind, ScopeId, PermissionFlags) + VALUES ('acl-1', 'C1', 'ops', 'Cluster', NULL, 1), ('acl-2', 'C1', 'ops', 'Cluster', NULL, 1); + INSERT ExternalIdReservation (Kind, Value, EquipmentUuid, ClusterId, FirstPublishedBy) + VALUES ('ZTag', 'ZT-OLD', NEWID(), 'C1', 't'); + """); + await using (var db = sql.NewContext()) + { + db.UnsAreas.Add(new UnsArea { UnsAreaId = "AREA-1", ClusterId = "C1", Name = "area" }); + db.UnsLines.Add(new UnsLine { UnsLineId = "LINE-1", UnsAreaId = "AREA-1", Name = "line" }); + var eq1 = NewEquipment("LINE-1", "press1", "ZT-1"); + db.Equipment.AddRange(eq1, NewEquipment("LINE-1", "press2", "zt-1")); + db.Scripts.Add(new Script { ScriptId = "SC-ok", Name = "ok", SourceCode = "return 1;", SourceHash = new string('a', 64) }); + db.Scripts.Add(new Script + { + ScriptId = "SC-file", Name = "reads a file", SourceHash = new string('b', 64), + SourceCode = "return System.IO.File.ReadAllText(\"c:/x\");", + }); + db.VirtualTags.AddRange( + new VirtualTag { VirtualTagId = "VT-dangling", EquipmentId = eq1.EquipmentId, Name = "dangling", DataType = "Int32", ScriptId = "SC-gone" }, + new VirtualTag { VirtualTagId = "VT-slash", EquipmentId = eq1.EquipmentId, Name = "a/b", DataType = "Int32", ScriptId = "SC-ok" }, + new VirtualTag { VirtualTagId = "VT-file", EquipmentId = eq1.EquipmentId, Name = "file", DataType = "String", ScriptId = "SC-file" }); + db.DriverInstances.Add(new DriverInstance + { + DriverInstanceId = "DRV-odbc", ClusterId = "C1", Name = "odbc", DriverType = "Sql", + DriverConfig = """{"provider":"Odbc","queries":{"line":{"sql":"SELECT v FROM t WHERE v ILIKE 'a%'"}}}""", + }); + await db.SaveChangesAsync(ct); + } + + var before = await RowCountAsync(sql); + var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: ct); + + report.PendingMigrations.ShouldContain(m => m.EndsWith("_ConfigurationGapsIndexesAndRowVersions", StringComparison.Ordinal)); + report.PendingMigrations.ShouldContain(m => m.EndsWith("_ScriptForeignKeysAndExternalIdUniqueness", StringComparison.Ordinal)); + report.Findings.ShouldContain(f => f.Check == "schema" && f.Code == "ReadAsEmpty" && f.Message.Contains("DataConnection")); + + void Blocking(string check, string code, string text) => + report.Findings.ShouldContain(f => f.Check == check && f.Code == code && f.Severity == PreflightSeverity.Blocking && f.Message.Contains(text), + $"expected {check}/{code} naming '{text}'"); + + // #1021: the migrations' own pre-checks, row-named. + Blocking("migration:ConfigurationGapsIndexesAndRowVersions", "DuplicateNodeAcl", "acl-1, acl-2"); + Blocking("migration:ScriptForeignKeysAndExternalIdUniqueness", "VirtualTagScriptDangling", "VT-dangling"); + Blocking("migration:ScriptForeignKeysAndExternalIdUniqueness", "DuplicateZTag", "ZT-1"); + Blocking("migration:ScriptForeignKeysAndExternalIdUniqueness", "ExternalIdReservationRows", "ZT-OLD"); + // #1015: the new deploy-gate rules. + Blocking("deploy-gate", "VirtualTagScriptNotFound", "VT-dangling"); + Blocking("deploy-gate", "VirtualTagNameInvalid", "VT-slash"); + Blocking("deploy-gate", "BadDuplicateExternalIdentifier", "ZT-1"); + // #1058: an Odbc named query that does not parse as T-SQL. + Blocking("deploy-gate", "SqlNamedQueryInvalid", "DRV-odbc"); + // #1013: the sandbox analyzer over the scripts in use. + Blocking("script-gate", "ScriptCompileFailed", "SC-file"); + report.HasBlocking.ShouldBeTrue(); + + // Read-only: nothing written, no migration applied. + (await RowCountAsync(sql)).ShouldBe(before); + await using var verify = sql.NewContext(); + verify.Database.GetAppliedMigrations().Last().ShouldBe(OldSchema); + } + + /// Positive control: a clean, current database has no blocking finding; an unused broken script is a Warning only. + [Fact] + public async Task A_clean_current_database_has_no_blocking_finding() + { + var ct = TestContext.Current.CancellationToken; + using var sql = new SqlServerTestDatabase(); + await using (var db = sql.NewContext()) + { + db.Scripts.Add(new Script { ScriptId = "SC-unused", Name = "unused", SourceHash = new string('c', 64), SourceCode = "this is not C#" }); + await db.SaveChangesAsync(ct); + } + + var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: ct); + + report.PendingMigrations.ShouldBeEmpty(); + report.HasBlocking.ShouldBeFalse(string.Join("\n", report.Findings.Select(f => $"{f.Check}/{f.Code}: {f.Message}"))); + report.Findings.ShouldContain(f => f.Check == "deploy-gate" && f.Code == "Clean"); + report.Findings.ShouldContain(f => f.Code == "UnusedScriptDoesNotCompile" && f.Severity == PreflightSeverity.Warning && f.Subject == "SC-unused"); + } + + /// Positive control for the migration pre-checks: an old schema with clean data reports each pending check Clean. + [Fact] + public async Task An_old_schema_database_with_clean_data_reports_the_migrations_will_apply() + { + using var sql = new SqlServerTestDatabase(OldSchema); + + var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: TestContext.Current.CancellationToken); + + report.HasBlocking.ShouldBeFalse(string.Join("\n", report.Findings.Select(f => $"{f.Check}/{f.Code}: {f.Message}"))); + report.Findings.Count(f => f.Check.StartsWith("migration:", StringComparison.Ordinal) && f.Code == "Clean").ShouldBe(2); + } + + /// + /// A NULL Script.ScriptId (legal in the old schema) is named by the migration pre-check, and the snapshot + /// this build cannot read is reported as Blocking instead of crashing the tool. + /// + [Fact] + public async Task A_null_script_id_is_named_and_the_unreadable_snapshot_is_reported() + { + using var sql = new SqlServerTestDatabase(OldSchema); + await ExecAsync(sql, "INSERT Script (ScriptId, Name, SourceCode, SourceHash, Language) VALUES (NULL, 'orphan', 'return 1;', 'h', 'CSharp')"); + + var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: TestContext.Current.CancellationToken); + + report.Findings.ShouldContain(f => f.Code == "ScriptIdNull" && f.Severity == PreflightSeverity.Blocking && f.Message.Contains("orphan")); + report.Findings.ShouldContain(f => f.Code == "SnapshotUnreadable" && f.Severity == PreflightSeverity.Blocking); + report.HasBlocking.ShouldBeTrue(); + } + + /// A database without the v3 migration history is refused, never checked against the wrong model. + [Fact] + public async Task A_database_that_is_not_a_v3_ConfigDb_is_refused() + { + using var sql = new SqlServerTestDatabase("0"); // created, nothing applied + + var ex = await Should.ThrowAsync(() => + UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: TestContext.Current.CancellationToken)); + ex.Message.ShouldContain("is not a v3 OtOpcUa ConfigDb"); + } +}