diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CommandHelpers.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CommandHelpers.cs index 0341ef5d..2ce0f6ae 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CommandHelpers.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CommandHelpers.cs @@ -93,6 +93,7 @@ internal static class CommandHelpers // Every alias of a deploy contract shares the same policy. The server bounds // the operation; a shorter client deadline can report failure while it applies. var requestTimeout = timeout ?? (command is MgmtDeployInstanceCommand or MgmtDeployArtifactsCommand or MgmtDeploySiteCommand + or MgmtDeployAreaCommand ? Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(30)); var response = await client.SendCommandAsync(commandName, command, requestTimeout); diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DeployCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DeployCommands.cs index 7c4ec842..62a20704 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DeployCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DeployCommands.cs @@ -21,6 +21,7 @@ public static class DeployCommands command.Add(BuildInstance(urlOption, formatOption, usernameOption, passwordOption)); command.Add(BuildSite(urlOption, formatOption, usernameOption, passwordOption)); + command.Add(BuildArea(urlOption, formatOption, usernameOption, passwordOption)); command.Add(BuildArtifacts(urlOption, formatOption, usernameOption, passwordOption)); command.Add(BuildStatus(urlOption, formatOption, usernameOption, passwordOption)); @@ -84,6 +85,41 @@ public static class DeployCommands return cmd; } + /// + /// Builds deploy area — bulk-deploy every instance in one area subtree + /// (the area plus all of its descendant areas), Gitea #40. + /// + /// + /// deploy site narrowed to an area: same skip rules (Disabled always, + /// up-to-date unless --force), same not-all-or-nothing summary, same + /// server-owned deadline and the same exit-code contract. + /// + /// + private static Command BuildArea(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption) + { + var idOption = new Option("--id") { Description = "Area ID (its whole subtree is deployed)", Required = true }; + var forceOption = new Option("--force") + { + Description = + "Redeploy instances whose config is unchanged (default: skip them — a redeploy " + + "resets static overrides and native alarm state at the site)", + }; + var cmd = new Command("area") { Description = "Deploy every deployable instance in an area and its descendant areas" }; + cmd.Add(idOption); + cmd.Add(forceOption); + cmd.SetAction(async (ParseResult result) => + { + var areaId = result.GetValue(idOption); + var force = result.GetValue(forceOption); + return await CommandHelpers.ExecuteCommandAsync( + result, urlOption, formatOption, usernameOption, passwordOption, + new MgmtDeployAreaCommand(areaId, force), + timeout: BulkDeployTimeout, + onSuccess: json => HandleSiteDeploymentResponse(json, CommandHelpers.ResolveFormat(result, formatOption, CliConfig.Load()))); + }); + return cmd; + } + /// /// The server owns the bounded overall bulk deadline; do not abandon it with a shorter client timer. /// @@ -91,8 +127,8 @@ public static class DeployCommands /// /// Renders a deployment summary and turns its failureCount into the exit code: - /// 0 when every site/instance succeeded, 1 when any failed. Shared by deploy site - /// and both artifact-deploy commands (deploy artifacts, site deploy-artifacts), + /// 0 when every site/instance succeeded, 1 when any failed. Shared by deploy site, + /// deploy area and both artifact-deploy commands (deploy artifacts, site deploy-artifacts), /// whose summaries all carry failureCount — a per-site failure is a successful HTTP /// call, so without this the process exited 0 and scripts could not detect it. /// diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/README.md b/src/ZB.MOM.WW.ScadaBridge.CLI/README.md index 8a7fb7a5..874798ec 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/README.md +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/README.md @@ -1101,6 +1101,25 @@ Output is a per-instance result matrix (`instanceId`, `uniqueName`, `deploymentI `success`, `errorMessage`) plus `successCount` / `failureCount`, and `skippedInstances` (`instanceId`, `uniqueName`, `reason`). +#### `deploy area` + +Deploy every deployable instance in one **area subtree** — the area itself plus every +area nested beneath it at any depth (Gitea #40). It is `deploy site` narrowed to that +subtree, with identical rules: Disabled instances are always skipped, up-to-date ones +are skipped unless `--force`, the batch is not all-or-nothing, and the output is the +same summary (`siteIdentifier` is the area's site). Instances with no area are only +reachable through `deploy site`. Same deadline policy as `deploy site`, and the same +exit-code rule: `1` when any instance failed (or the summary is invalid), else `0`. + +```sh +scadabridge --url deploy area --id [--force] +``` + +| Option | Required | Description | +|--------|----------|-------------| +| `--id` | yes | Area ID. A site-scoped (non-Administrator) Deployer must name an area of an in-scope site; an unknown area is denied to them exactly like an out-of-scope one. | +| `--force` | no | Redeploy instances whose config is unchanged (default: skip them). Disabled instances are still skipped. | + #### `deploy artifacts` Deploy compiled artifacts to one or all sites (same as `site deploy-artifacts`). @@ -2665,7 +2684,7 @@ run's outbound API / DB / notification rows, which are always audited. ## Deployment deadlines `deploy instance`, `instance deploy`, `deploy artifacts`, `site deploy-artifacts`, -and `deploy site` defer the overall deadline to the Management API. They keep the +`deploy site` and `deploy area` defer the overall deadline to the Management API. They keep the bounded socket-connect timeout but do not impose the ordinary 30-second client request deadline on a deployment that may still be applying. The API's configured long-running timeout remains authoritative. Ordinary commands retain a 30-second diff --git a/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/CommandTreeTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/CommandTreeTests.cs index d2cb044e..c185c1ca 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/CommandTreeTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/CommandTreeTests.cs @@ -175,6 +175,28 @@ public class CommandTreeTests Assert.True(withForce.GetValue(forceOption)); } + /// Verifies that the deploy group has an area verb with a required id and a force flag (Gitea #40). + [Fact] + public void Deploy_HasAreaVerb_WithRequiredId_AndForceFlag() + { + // Area-subtree bulk deploy: the scope is the verb, like `deploy site`. The + // area id is required (never an accidental site- or fleet-wide push) and + // --force is a flag whose absence is the non-destructive default. + var deploy = DeployCommands.Build(Url, Format, Username, Password); + var area = deploy.Subcommands.Single(c => c.Name == "area"); + var forceOption = (Option)area.Options.Single(o => o.Name == "--force"); + + Assert.NotEmpty(area.Parse([]).Errors); + + var withoutForce = area.Parse(["--id", "12"]); + Assert.Empty(withoutForce.Errors); + Assert.False(withoutForce.GetValue(forceOption)); + + var withForce = area.Parse(["--id", "12", "--force"]); + Assert.Empty(withForce.Errors); + Assert.True(withForce.GetValue(forceOption)); + } + /// Verifies that the instance native alarm source group has set and clear subcommands. [Fact] public void InstanceNativeAlarmSource_HasSetAndClear() @@ -465,6 +487,7 @@ public class CommandTreeTests [InlineData(typeof(DebugSnapshotCommand))] [InlineData(typeof(MgmtDeployInstanceCommand))] [InlineData(typeof(MgmtDeploySiteCommand))] + [InlineData(typeof(MgmtDeployAreaCommand))] [InlineData(typeof(QueryAuditLogCommand))] [InlineData(typeof(ExportBundleCommand))] [InlineData(typeof(PreviewBundleCommand))] diff --git a/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/DeployAreaExitCodeTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/DeployAreaExitCodeTests.cs new file mode 100644 index 00000000..557154ac --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/DeployAreaExitCodeTests.cs @@ -0,0 +1,83 @@ +using System.CommandLine; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json; +using ZB.MOM.WW.ScadaBridge.CLI.Commands; + +namespace ZB.MOM.WW.ScadaBridge.CLI.Tests; + +/// +/// deploy area (Gitea #40) sends MgmtDeployArea with the area id and +/// force flag, and derives its exit code from the summary's failureCount +/// exactly like deploy site: a per-instance failure is a successful HTTP +/// call, so without that a script could not detect it. +/// +public class DeployAreaExitCodeTests +{ + /// Verifies the wire payload and the exit code derived from the summary. + /// The JSON response body served by the fake management endpoint. + /// Whether --force is passed. + /// The expected process exit code. + /// A task that represents the asynchronous operation. + [Theory] + [InlineData("{\"successCount\":2,\"failureCount\":0}", false, 0)] + [InlineData("{\"successCount\":1,\"failureCount\":1}", true, 1)] + [InlineData("{\"unexpected\":true}", false, 1)] + public async Task DeployArea_SendsAreaCommand_AndReturnsDomainExitCode(string response, bool force, int expected) + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + try + { + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + string? requestBody = null; + var server = Task.Run(async () => + { + using var client = await listener.AcceptTcpClientAsync(); + await using var stream = client.GetStream(); + using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true); + var length = 0; + while (await reader.ReadLineAsync() is { Length: > 0 } line) + if (line.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase)) + length = int.Parse(line[15..].Trim()); + var buffer = new char[length]; + var read = 0; + while (read < length) + { + var count = await reader.ReadAsync(buffer.AsMemory(read)); + if (count == 0) throw new EndOfStreamException(); + read += count; + } + requestBody = new string(buffer); + var body = Encoding.UTF8.GetBytes(response); + var headers = Encoding.ASCII.GetBytes($"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n"); + await stream.WriteAsync(headers); + await stream.WriteAsync(body); + }); + var root = new RootCommand(); + var url = new Option("--url") { Recursive = true }; + var format = new Option("--format") { Recursive = true }; + var user = new Option("--username") { Recursive = true }; + var password = new Option("--password") { Recursive = true }; + root.Add(url); root.Add(format); root.Add(user); root.Add(password); + root.Add(DeployCommands.Build(url, format, user, password)); + string[] args = ["deploy", "area", "--id", "12", "--url", $"http://127.0.0.1:{port}", + "--username", "test", "--password", "test", "--format", "json"]; + if (force) args = [.. args, "--force"]; + var exit = await root.Parse(args).InvokeAsync(); + await server.WaitAsync(TimeSpan.FromSeconds(5)); + + Assert.Equal(expected, exit); + using var payload = JsonDocument.Parse(requestBody!); + Assert.Equal("MgmtDeployArea", payload.RootElement.GetProperty("command").GetString()); + var command = payload.RootElement.GetProperty("payload"); + Assert.Equal(12, GetPropertyIgnoreCase(command, "areaId").GetInt32()); + Assert.Equal(force, GetPropertyIgnoreCase(command, "force").GetBoolean()); + } + finally { listener.Stop(); } + } + + private static JsonElement GetPropertyIgnoreCase(JsonElement element, string name) => + element.EnumerateObject().First(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)).Value; +}