diff --git a/.github/actions/cloud-database/create-iam-user-postgresql.cs b/.github/actions/cloud-database/create-iam-user-postgresql.cs index e9821e68b5..baa47ef128 100644 --- a/.github/actions/cloud-database/create-iam-user-postgresql.cs +++ b/.github/actions/cloud-database/create-iam-user-postgresql.cs @@ -1,4 +1,4 @@ -#:package Npgsql@10.0.3 +#:package Npgsql@10.0.4 // Creates a login that signs in with an IAM token and can create its own schema in the test database. A role that is granted rds_iam can no longer sign in with a password. diff --git a/.github/actions/cloud-database/verify-postgresql.cs b/.github/actions/cloud-database/verify-postgresql.cs index 72d55a4f28..fd1bee3406 100644 --- a/.github/actions/cloud-database/verify-postgresql.cs +++ b/.github/actions/cloud-database/verify-postgresql.cs @@ -1,4 +1,4 @@ -#:package Npgsql@10.0.3 +#:package Npgsql@10.0.4 // Waits until the server actually accepts connections on the test database. diff --git a/.github/actions/cloud-database/verify-sqlserver.cs b/.github/actions/cloud-database/verify-sqlserver.cs index 55d13f27e5..a8c31ed710 100644 --- a/.github/actions/cloud-database/verify-sqlserver.cs +++ b/.github/actions/cloud-database/verify-sqlserver.cs @@ -1,4 +1,4 @@ -#:package Microsoft.Data.SqlClient@7.1.1 +#:package Microsoft.Data.SqlClient@7.1.2 // Waits until the server accepts connections, creates the test database if the provisioning CLI // could not, fails the run if the server has no Full-Text Search, and waits until a full-text diff --git a/.github/workflows/build-containers.yml b/.github/workflows/build-containers.yml index 8710d14f86..41904264b4 100644 --- a/.github/workflows/build-containers.yml +++ b/.github/workflows/build-containers.yml @@ -57,9 +57,9 @@ jobs: } echo "RuntimeVersion=$runtimeVersion" | Out-File -FilePath $Env:GITHUB_ENV -Encoding utf-8 -Append - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v4.0.0 + uses: docker/setup-buildx-action@v4.4.1 - name: Log in to GitHub container registry - uses: docker/login-action@v4.2.0 + uses: docker/login-action@v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} @@ -68,7 +68,7 @@ jobs: id: date run: echo "date=$(date '+%FT%TZ')" >> $GITHUB_OUTPUT - name: Build and push image to GitHub container registry - uses: docker/build-push-action@v7.2.0 + uses: docker/build-push-action@v7.4.0 with: context: . push: true diff --git a/.github/workflows/build-db-container.yml b/.github/workflows/build-db-container.yml index c3e0692a6f..c1f7e0c665 100644 --- a/.github/workflows/build-db-container.yml +++ b/.github/workflows/build-db-container.yml @@ -31,9 +31,9 @@ jobs: with: version: ${{ env.MinVerVersion }} - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v4.0.0 + uses: docker/setup-buildx-action@v4.4.1 - name: Log in to GitHub container registry - uses: docker/login-action@v4.2.0 + uses: docker/login-action@v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} diff --git a/.github/workflows/container-integration-test.yml b/.github/workflows/container-integration-test.yml index 4a75b5f702..ee86189845 100644 --- a/.github/workflows/container-integration-test.yml +++ b/.github/workflows/container-integration-test.yml @@ -63,13 +63,13 @@ jobs: - name: Run MinVer uses: Particular/run-minver-action@v1.0.0 - name: Log in to GitHub container registry - uses: docker/login-action@v4 + uses: docker/login-action@v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Log in to Docker Hub - uses: docker/login-action@v4.2.0 + uses: docker/login-action@v4.8.0 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} diff --git a/.github/workflows/push-container-images.yml b/.github/workflows/push-container-images.yml index 50dbe757af..4f74aa6a3c 100644 --- a/.github/workflows/push-container-images.yml +++ b/.github/workflows/push-container-images.yml @@ -22,18 +22,18 @@ jobs: with: version: ${{ inputs.version }} - name: Log in to GitHub container registry - uses: docker/login-action@v4.2.0 + uses: docker/login-action@v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Login to Docker Hub - uses: docker/login-action@v4.2.0 + uses: docker/login-action@v4.8.0 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v4.0.0 + uses: docker/setup-buildx-action@v4.4.1 - name: Publish to Docker Hub run: | $containers = @('servicecontrol', 'servicecontrol-audit', 'servicecontrol-monitoring', 'servicecontrol-ravendb') diff --git a/.github/workflows/testing-tool-ci.yml b/.github/workflows/testing-tool-ci.yml index 215ed014e2..b264a5205c 100644 --- a/.github/workflows/testing-tool-ci.yml +++ b/.github/workflows/testing-tool-ci.yml @@ -39,8 +39,11 @@ jobs: - name: Build run: dotnet build tools/testing-tool/TestingTool.slnx --configuration Release + - name: Test + run: dotnet test tools/testing-tool/TestingTool.slnx --configuration Release --no-build + - name: Build container image - uses: docker/build-push-action@v7.2.0 + uses: docker/build-push-action@v7.4.0 with: context: . file: tools/testing-tool/Dockerfile diff --git a/README.md b/README.md index d9a8edeb65..acde17004e 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,7 @@ Steps: -ConnectionString 'host=localhost;username=guest;password=guest' ` -ErrorQueue errormq ` -ErrorRetentionPeriod 10:00:00:00 ` + -StorageType RavenDB ` -Acknowledgements RabbitMQBrokerVersion310 ``` diff --git a/docs/bulk-retries-design.md b/docs/bulk-retries-design.md index c218ce40fc..2d51fb7123 100644 --- a/docs/bulk-retries-design.md +++ b/docs/bulk-retries-design.md @@ -82,7 +82,7 @@ When all batches of a retry operation complete, ServiceControl adds two entries ## Other notes -1. A message can be part of only one batch at a time. The `FailedMessageRetry/{messageId}` document prevents a message from being added to a second batch. ServiceControl removes this document only when the message comes back through the error queue. +1. A message can be part of only one batch at a time. The `FailedMessageRetry/{messageId}` document prevents a message from being added to a second batch. ServiceControl removes this document when the message no longer belongs to a retry, for example when the message comes back through the error queue, when the retry is confirmed, or when forwarding the message fails. 2. A batch that is created is eventually forwarded. If the ServiceControl process stops while the batch is in `Marking Documents`, the Adopt Orphan Batches process picks it up and moves it into `Staging`. Once a batch is in `Staging`, the Retry Processor repeatedly attempts to stage it until it succeeds. ServiceControl then selects the batch for `Forwarding`. 3. ServiceControl processes only one batch at a time in the `Forwarding` or `Staging` status. A batch in `Forwarding` must be fully forwarded and deleted before ServiceControl can stage a new batch. A batch selected for staging moves to the `Forwarding` status once it is fully staged. All of this happens on a single background thread that sleeps for 30 seconds if it finds nothing to do. 4. A batch can be forwarded only if it is completely staged. diff --git a/docs/cloud-database-tests.md b/docs/cloud-database-tests.md index 6efb31467c..66701cd5b6 100644 --- a/docs/cloud-database-tests.md +++ b/docs/cloud-database-tests.md @@ -13,7 +13,11 @@ The `Cloud database tests` workflow (`.github/workflows/cloud-database-tests.yml The cloud workflow sets `ServiceControl_TESTS_SKIP_SCHEMA_CLEANUP=true` on its test step. SQL Server and PostgreSQL test helpers leave each test's schema in place, avoiding schema-drop timeouts. Tests still use unique schemas and retain host shutdown, connection disposal, and temporary-file cleanup. The provisioning action deletes the server in its post step, including on test failure or cancellation. -Schema cleanup remains enabled when the variable is unset or has any value other than `true` (case-insensitive). Set it only for disposable databases whose owner deletes the database after the run. Retained schemas and full-text indexes consume resources until deletion; this setting does not address full-text indexing failures. +When schema cleanup is disabled, SQL Server cleanup disables each completed test's full-text indexes after its host stops. This stops unfinished populations and automatic updates without dropping tables or schemas, so retained indexes do not keep indexing for later tests. Cleanup uses a separate connection because host disposal can dispose the test's data source. PostgreSQL cleanup remains a no-op. + +Disabling an index still executes DDL and can encounter lock contention. This does not remove contention from concurrent schema creation or migrations, or guarantee that a live test's full-text population completes. See [ALTER FULLTEXT INDEX](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-fulltext-index-transact-sql#arguments) for the effects of `DISABLE`. + +Schema cleanup remains enabled when the variable is unset or has any value other than `true` (case-insensitive). Set it only for disposable databases whose owner deletes the database after the run. Retained tables and indexes consume storage until deletion. ## Token authentication fixtures diff --git a/docs/error-ingestion-design.md b/docs/error-ingestion-design.md index e9fcbcab6b..93d7cec8ae 100644 --- a/docs/error-ingestion-design.md +++ b/docs/error-ingestion-design.md @@ -63,6 +63,8 @@ When `BodyStoredExternally` is true the external copy is authoritative and `Body search aid only; it must never be served as the body. `BodySize` is always the original size. External writes happen before the row that points at them is committed. +Error ingestion resolves the unique message id to a GUID once, before the external write. It parses a valid GUID in `ServiceControl.Retry.UniqueMessageId` and converts any other value with `DeterministicGuid.MakeId(value)`, matching Audit ingestion. Without that header, it derives the GUID from the message id and processing endpoint. The external body id uses the canonical string representation of the database `UniqueMessageId`, so a malformed header value never becomes a file path. + ### Groups, endpoints, retention - **Failure groups** live in `FailedMessageGroups`, an association table. A message's group rows diff --git a/docs/eventlog-design.md b/docs/eventlog-design.md index a28178958c..547af77cc0 100644 --- a/docs/eventlog-design.md +++ b/docs/eventlog-design.md @@ -2,7 +2,7 @@ ## What it is -The event log is the primary instance's activity feed: the chronological "what has this instance noticed" list that ServicePulse shows. Message failures, retries, redirects, heartbeats, custom checks and integration failures all surface here. +The event log is the primary instance's activity feed: the chronological "what has this instance noticed" list that ServicePulse shows. Retries, redirects, heartbeats, custom checks and integration failures all surface here. Message failures do not: they are visible on the failed messages screen instead, and recording one row per failure in the feed was removed as write and retention overhead on the hot ingest path. It is a **projection of domain events, not a log file**. Nothing writes to it directly. Components raise domain events for their own reasons, and the event log turns a chosen subset of those into feed items. An event appears only if someone has declared how it should read, so the feed is an editorial selection. diff --git a/docs/load-testing.md b/docs/load-testing.md index 7ed99b96f1..a063b0061a 100644 --- a/docs/load-testing.md +++ b/docs/load-testing.md @@ -1,12 +1,12 @@ # Load testing -The [ServiceControl Testing Tool](../tools/testing-tool/README.md) is a stateless .NET service that generates error load and real-world failure scenarios against a test ServiceControl instance, to validate error-ingestion performance. It has a web UI for manual control, built-in failure scenarios (third-party outage, timeout spike, poison message, and more), and OpenTelemetry telemetry. +The [ServiceControl Testing Tool](../tools/testing-tool/README.md) is a .NET service that generates error load and real-world failure scenarios against a test ServiceControl instance, to validate error-ingestion performance. It has a web UI for manual control, built-in failure scenarios (third-party outage, timeout spike, poison message, and more), and OpenTelemetry telemetry. The [testing tool README](../tools/testing-tool/README.md) is the full reference: every scenario, API endpoint, configuration setting, container usage, and scaling notes. ## Quick start: full stack with Aspire -The Aspire AppHost starts the whole system with a single command: the ServiceControl platform (Learning transport), the testing tool, and a complete observability stack (OTel Collector, Jaeger, Prometheus, and Grafana with a prebuilt dashboard). +The Aspire AppHost starts the whole system with a single command: the ServiceControl platform (RabbitMQ by default), the testing tool, and a complete observability stack (OTel Collector, Jaeger, Prometheus, and Grafana with a prebuilt dashboard). ```bash aspire run tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj @@ -14,12 +14,14 @@ aspire run tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj Aspire assigns dynamic ports. Open the web UI of the testing tool through the link in the Aspire dashboard. +The AppHost enables external integration-event publishing on the error instances, so ServiceControl writes and publishes a `MessageFailed` event for each ingested failure. This can change ingestion baselines compared with a run without it. + Useful flags, passed after `--`: | Flag | Description | |---|---| | `--tag ` | Test a specific ServiceControl image tag, for example a PR prerelease like `pr-1234` | -| `--persistence ` | Persistence for the error instance: `RavenDb` (default), `SqlServer`, or `PostgreSql` | +| `--storage ` | Storage for the error instance: `RavenDb` (default), `SqlServer`, or `PostgreSql` | | `--error-ingestion-scale-unit ` | Start `n` additional error-ingestion-only ServiceControl instances | | `--azure-blob-body-storage ""` | Store message bodies in Azure Blob Storage instead of the container file system. Applies only to `SqlServer` and `PostgreSql`. The error instance and its scale-out units share one container, and each audit instance gets its own | | `--s3-body-storage ` | Store message bodies in S3 instead of the container file system. Applies only to `SqlServer` and `PostgreSql`, and is mutually exclusive with `--azure-blob-body-storage`. The error instance and its scale-out units share the `error-bodies/` prefix, and each audit instance gets its own | @@ -43,6 +45,7 @@ Everything is controllable from the web UI, or via the HTTP API: - Scenarios: the six built-in scenarios (`third-party-outage`, `timeout-spike`, `poison-message`, `deserialization-failure`, `background-noise`, `large-messages`), each producing errors that group naturally. `large-messages` starts at 3 messages per second unless `rate` is set, sends bodies of about 256 KiB (the wire envelope is slightly larger), fails 20% of them to the error queue, and audits the rest. The bypass writer fails every message by design, so it sends the large bodies only as failures. Start with `POST /api/scenarios/{name}/start` (optional `rate` and `durationSeconds`). - Bypass writer: high-throughput load that writes failed-message envelopes directly to the ServiceControl error queue, skipping the message handler (`POST /api/bypass/start`). - Jobs: retry, archive, search, retention sweep, and custom-check-failure jobs exercise ServiceControl's recoverability, FTS search, and retention pipelines against the load. Jobs do not start automatically. Start them from the UI or `/api/jobs`. +- Smoke tests: the **Smoke tests** tab runs an API-verified version of the functionality checklist in the [testing scenarios](testing-scenarios.md) against the instance under test, with manual rows for what only a person can verify. Do not confuse it with the load presets: it sends a few messages per check and reads the results back through the ServiceControl APIs. The [testing tool README](../tools/testing-tool/README.md#smoke-tests) lists each check, its prerequisites and its limits. - Release-test presets: named presets mapped from the [testing scenarios](testing-scenarios.md), for example `POST /api/release-tests/ingestion-load/start`. ## Observing the run diff --git a/docs/message-body-storage.md b/docs/message-body-storage.md index 404bc4fb9e..de2cddbf1d 100644 --- a/docs/message-body-storage.md +++ b/docs/message-body-storage.md @@ -29,7 +29,7 @@ Ingestion writes external bodies before the batch transaction that inserts the r Audit stores a body through `IAuditBodyStoragePersistence` under the UTC ingestion hour of its batch and the unique message id: `yyyyMMddHH/{unique message id}`. The file system store writes `{StoragePath}/yyyyMMddHH/{unique message id}.body`, the Azure Blob store uses the blob name `yyyyMMddHH/{unique message id}`, and the S3 store prepends its key prefix. Callers pass the hour explicitly and the stores do not parse it from the id, so reads use the `CreatedOn` of the row. Storage keeps the first write for an hour and id and ignores later writes. -The body URL keeps the audit body id, `yyyyMMddHH-{unique message id}`, which routes the request to the row. The Error (primary) persisters use `IBodyStoragePersistence` with the body id alone; their file system layout remains `{StoragePath}/{body id}.body`. +The body URL keeps the audit body id, `yyyyMMddHH-{unique message id}`, which routes the request to the row. The Error (primary) persisters use `IBodyStoragePersistence` with the body id alone; their file system layout remains `{StoragePath}/{body id}.body`. Both file system stores validate body ids with `Guid.TryParse` before file system access and throw `ArgumentException` for invalid ids. Audit requires a GUID. Error accepts a GUID or `failedimport-{guid}`, the id of a failed import body. Reading a body streams it from storage with the stored content type, size, and a version derived from the row. A body missing from storage answers 204. diff --git a/docs/testing-scenarios.md b/docs/testing-scenarios.md index a344192632..dfd7f5d6ba 100644 --- a/docs/testing-scenarios.md +++ b/docs/testing-scenarios.md @@ -12,6 +12,8 @@ This list is long but not exhaustive. Not every change needs every test. ## Functionality +The **Smoke tests** tab of the [testing tool](../tools/testing-tool/README.md#smoke-tests) automates the API-level part of the custom checks, heartbeats, recoverability, audits, saga auditing, integration events and monitoring items below: it generates the messages and verifies the results through the ServiceControl APIs. The ServicePulse screens, the installation steps, the public integration events sample, chaos testing and performance testing stay manual. The manual rows of the tab list them. + - [ ] Install and run ServiceControl Primary, Audit, and Monitoring instances - [ ] [Install the ServiceControl.SmokeTesting tool](https://github.com/Particular/ServiceControl.SmokeTest#installing) - [ ] Start the smoke testing tool, for example `dotnet servicecontrol.smoketest rabbitmq` diff --git a/docs/testing.md b/docs/testing.md index 7ffe8d1abf..a360f3d9ec 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -113,4 +113,8 @@ Containers built by a PR and stored on GitHub Container Registry can be tested l * Audit API * Monitoring API * ServicePulse (latest from Docker Hub) -6. Exit the CLI process. Aspire stops the application automatically. \ No newline at end of file +6. Exit the CLI process. Aspire stops the application automatically. + +## Smoke tests with the testing tool + +The [testing tool](../tools/testing-tool/README.md#smoke-tests) has a **Smoke tests** tab that sends deterministic messages with a run-specific identifier and verifies custom checks, heartbeats, retries, message editing, redirects, audit data, conversations, sagas, integration events and monitoring data through the ServiceControl APIs. Start it with the Aspire AppHost and `--audit-instances 1`, as described in the [load testing](load-testing.md) page. It complements the [testing scenarios](testing-scenarios.md) checklist: the rows it does not automate stay manual. diff --git a/docs/usage-report.md b/docs/usage-report.md index 7baad9478c..de35263c28 100644 --- a/docs/usage-report.md +++ b/docs/usage-report.md @@ -133,7 +133,7 @@ The primary's `TransportEnvironmentDataProvider` emits `Transport.Type` and adds | --- | --- | --- | --- | | `Features.IntegratedServicePulse` | `Enabled`, `Disabled` | `ServiceControl/EnableIntegratedServicePulse` | 6.13.0 | | `Features.MessageEditing` | `Enabled`, `Disabled` | `ServiceControl/AllowMessageEditing` | 6.20.0 | -| `Features.ExternalIntegrationsPublishing` | `Enabled`, `Disabled` | `ServiceControl/DisableExternalIntegrationsPublishing`, inverted | 6.20.0 | +| `Features.ExternalIntegrationsPublishing` | `Enabled`, `Disabled` | `ServiceControl/EnableExternalIntegrationsPublishing` | 6.20.0 | | `Features.ForwardErrorMessages` | `Enabled`, `Disabled` | `ServiceControl/ForwardErrorMessages` | 6.20.0 | | `Features.EmailNotifications` | `Enabled`, `Disabled`, `NotConfigured` | the stored email settings | 6.20.0 | | `Features.ErrorIngestion` | `Enabled`, `Disabled` | `ServiceControl/IngestErrorMessages` | Unreleased | diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props index e115097156..70db5dd3cd 100644 --- a/src/Directory.Packages.props +++ b/src/Directory.Packages.props @@ -5,18 +5,17 @@ - - - - + + + + - - + + - @@ -25,7 +24,7 @@ - + @@ -33,20 +32,20 @@ - - - + + + - + - - - + + + @@ -57,67 +56,68 @@ - + - - + + - - - - - - + + + + + + - - + + - + - + - - - - + + + + - - + + - - + + - + + - - + + diff --git a/src/LegacyArtifacts/Particular.ServiceControl.Audit/Persisters/RavenDB35/persistence.manifest b/src/LegacyArtifacts/Particular.ServiceControl.Audit/Persisters/RavenDB35/persistence.manifest index 9e4acddc85..af39167cb9 100644 --- a/src/LegacyArtifacts/Particular.ServiceControl.Audit/Persisters/RavenDB35/persistence.manifest +++ b/src/LegacyArtifacts/Particular.ServiceControl.Audit/Persisters/RavenDB35/persistence.manifest @@ -24,6 +24,9 @@ { "Name": "ServiceControl.Audit/DatabaseMaintenancePort", "Mandatory": true + }, + { + "Name": "ServiceControl.Audit/EnableFullTextSearchOnBodies" } ], "SettingsWithPathsToCleanup": [ diff --git a/src/LegacyArtifacts/Particular.ServiceControl/Persisters/RavenDB35/persistence.manifest b/src/LegacyArtifacts/Particular.ServiceControl/Persisters/RavenDB35/persistence.manifest index 916073dabb..027f73a019 100644 --- a/src/LegacyArtifacts/Particular.ServiceControl/Persisters/RavenDB35/persistence.manifest +++ b/src/LegacyArtifacts/Particular.ServiceControl/Persisters/RavenDB35/persistence.manifest @@ -24,6 +24,9 @@ { "Name": "ServiceControl/DatabaseMaintenancePort", "Mandatory": true + }, + { + "Name": "ServiceControl/EnableFullTextSearchOnBodies" } ], "SettingsWithPathsToCleanup": [ diff --git a/src/Particular.LicensingComponent.UnitTests/AuditQuery_Tests.cs b/src/Particular.LicensingComponent.UnitTests/AuditQuery_Tests.cs index 0d7eb361a2..a33e55904d 100644 --- a/src/Particular.LicensingComponent.UnitTests/AuditQuery_Tests.cs +++ b/src/Particular.LicensingComponent.UnitTests/AuditQuery_Tests.cs @@ -123,7 +123,7 @@ public async Task Should_include_the_input_queue_named_after_the_audit_instance( "audit_queue": "audit", "forward_audit_messages": false }, - "persistence": { "persistence_type": "PostgreSQL" }, + "storage": { "storage_type": "PostgreSQL" }, "plugins": {} } """; diff --git a/src/ServiceControl.AcceptanceTests.PostgreSql/AcceptanceTestStorageConfiguration.cs b/src/ServiceControl.AcceptanceTests.PostgreSql/AcceptanceTestStorageConfiguration.cs index 786d9b4cb4..384f1c8a38 100644 --- a/src/ServiceControl.AcceptanceTests.PostgreSql/AcceptanceTestStorageConfiguration.cs +++ b/src/ServiceControl.AcceptanceTests.PostgreSql/AcceptanceTestStorageConfiguration.cs @@ -13,7 +13,7 @@ namespace ServiceControl.AcceptanceTests.PostgreSql; public class AcceptanceTestStorageConfiguration : IAcceptanceTestStorageConfiguration { - public string PersistenceType { get; } = "PostgreSQL"; + public string StorageType { get; } = "PostgreSQL"; public async Task CustomizeSettings(Settings settings, CancellationToken cancellationToken = default) { diff --git a/src/ServiceControl.AcceptanceTests.RavenDB/AcceptanceTestStorageConfiguration.cs b/src/ServiceControl.AcceptanceTests.RavenDB/AcceptanceTestStorageConfiguration.cs index 29ef393e10..59a727951b 100644 --- a/src/ServiceControl.AcceptanceTests.RavenDB/AcceptanceTestStorageConfiguration.cs +++ b/src/ServiceControl.AcceptanceTests.RavenDB/AcceptanceTestStorageConfiguration.cs @@ -12,7 +12,7 @@ public class AcceptanceTestStorageConfiguration : IAcceptanceTestStorageConfiguration { - public string PersistenceType { get; } = "RavenDB"; + public string StorageType { get; } = "RavenDB"; public async Task CustomizeSettings(Settings settings, CancellationToken cancellationToken = default) diff --git a/src/ServiceControl.AcceptanceTests.RavenDB/StartupModeTests.cs b/src/ServiceControl.AcceptanceTests.RavenDB/StartupModeTests.cs index 1cd5328ce9..a5bc7d65fd 100644 --- a/src/ServiceControl.AcceptanceTests.RavenDB/StartupModeTests.cs +++ b/src/ServiceControl.AcceptanceTests.RavenDB/StartupModeTests.cs @@ -28,7 +28,7 @@ public async Task InitializeSettings() transportType: transportIntegration.TypeName, forwardErrorMessages: false, errorRetentionPeriod: TimeSpan.FromDays(1), - persisterType: "RavenDB") + storageType: "RavenDB") { TransportConnectionString = transportIntegration.ConnectionString, AssemblyLoadContextResolver = static _ => AssemblyLoadContext.Default @@ -42,20 +42,14 @@ public async Task InitializeSettings() public async Task Cleanup() => await configuration.Cleanup(); [Test] - public async Task CanRunMaintenanceMode() + public void MaintenanceModeIsRejectedForExternalServer() { - // ideally we'd be using the MaintenanceModeCommand here but that indefinitely blocks due to the RunAsync - // not terminating. + // The acceptance tests run the persister against an external server; only the embedded database supports maintenance mode. var hostBuilder = Host.CreateApplicationBuilder(); - hostBuilder.Services.AddPersistence(settings, maintenanceMode: true); - using var host = hostBuilder.Build(); - await host.StartAsync(); - - // Maintenance mode never calls AddServiceControl, so the persister has to supply the clock itself. - Assert.That(host.Services.GetRequiredService(), Is.Not.Null); + var exception = Assert.Throws(() => hostBuilder.Services.AddPersistence(settings, maintenanceMode: true)); - await host.StopAsync(); + Assert.That(exception.Message, Does.Contain("Maintenance mode is not supported")); } [Test] diff --git a/src/ServiceControl.AcceptanceTests.SqlServer/AcceptanceTestStorageConfiguration.cs b/src/ServiceControl.AcceptanceTests.SqlServer/AcceptanceTestStorageConfiguration.cs index fd453c930a..f51131109e 100644 --- a/src/ServiceControl.AcceptanceTests.SqlServer/AcceptanceTestStorageConfiguration.cs +++ b/src/ServiceControl.AcceptanceTests.SqlServer/AcceptanceTestStorageConfiguration.cs @@ -13,7 +13,7 @@ namespace ServiceControl.AcceptanceTests.SqlServer; public class AcceptanceTestStorageConfiguration : IAcceptanceTestStorageConfiguration { - public string PersistenceType { get; } = "SQLServer"; + public string StorageType { get; } = "SQLServer"; public async Task CustomizeSettings(Settings settings, CancellationToken cancellationToken = default) { diff --git a/src/ServiceControl.AcceptanceTests/ClockRegistrationTests.cs b/src/ServiceControl.AcceptanceTests/ClockRegistrationTests.cs index 7dba9a1c84..2c43b3c83b 100644 --- a/src/ServiceControl.AcceptanceTests/ClockRegistrationTests.cs +++ b/src/ServiceControl.AcceptanceTests/ClockRegistrationTests.cs @@ -20,7 +20,7 @@ public async Task InitializeSettings() { settings = new Settings( transportType: TransportIntegration.TypeName, - persisterType: StorageConfiguration.PersistenceType, + storageType: StorageConfiguration.StorageType, forwardErrorMessages: false, errorRetentionPeriod: TimeSpan.FromDays(1)) { diff --git a/src/ServiceControl.AcceptanceTests/MaintenanceModeTests.cs b/src/ServiceControl.AcceptanceTests/MaintenanceModeTests.cs index 549cd87221..bf3cfeb603 100644 --- a/src/ServiceControl.AcceptanceTests/MaintenanceModeTests.cs +++ b/src/ServiceControl.AcceptanceTests/MaintenanceModeTests.cs @@ -15,7 +15,7 @@ public void Should_refuse_maintenance_mode() { var settings = new Settings( transportType: TransportIntegration.TypeName, - persisterType: StorageConfiguration.PersistenceType, + storageType: StorageConfiguration.StorageType, forwardErrorMessages: false, errorRetentionPeriod: TimeSpan.FromDays(1)) { @@ -25,7 +25,7 @@ public void Should_refuse_maintenance_mode() var exception = Assert.Throws(() => new ServiceCollection().AddPersistence(settings, maintenanceMode: true)); - Assert.That(exception.Message, Does.Contain("Maintenance mode is not supported").And.Contain(StorageConfiguration.PersistenceType)); + Assert.That(exception.Message, Does.Contain("Maintenance mode is not supported").And.Contain(StorageConfiguration.StorageType)); } } } \ No newline at end of file diff --git a/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_a_custom_check_fails.cs b/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_a_custom_check_fails.cs index c2d4161a55..cb215a2b83 100644 --- a/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_a_custom_check_fails.cs +++ b/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_a_custom_check_fails.cs @@ -19,6 +19,7 @@ class When_a_custom_check_fails : AcceptanceTest public async Task Should_publish_notification() { var externalProcessorSubscribed = false; + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomConfiguration = config => config.OnEndpointSubscribed((s, ctx) => { if (s.SubscriberReturnAddress.IndexOf("ExternalProcessor", StringComparison.OrdinalIgnoreCase) >= 0) diff --git a/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_a_custom_check_succeeds.cs b/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_a_custom_check_succeeds.cs index 987acae9b2..6cd4239186 100644 --- a/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_a_custom_check_succeeds.cs +++ b/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_a_custom_check_succeeds.cs @@ -19,6 +19,7 @@ class When_a_custom_check_succeeds : AcceptanceTest public async Task Should_publish_notification() { var externalProcessorSubscribed = false; + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomConfiguration = config => config.OnEndpointSubscribed((s, ctx) => { if (s.SubscriberReturnAddress.IndexOf("ExternalProcessor", StringComparison.OrdinalIgnoreCase) >= 0) diff --git a/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_heartbeat_is_restored.cs b/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_heartbeat_is_restored.cs index 71e7d4d303..85735020ee 100644 --- a/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_heartbeat_is_restored.cs +++ b/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_heartbeat_is_restored.cs @@ -24,6 +24,7 @@ public async Task Should_publish_notification() { var externalProcessorSubscribed = false; + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomConfiguration = config => config.OnEndpointSubscribed((s, ctx) => { if (s.SubscriberReturnAddress.IndexOf("ExternalProcessor", StringComparison.OrdinalIgnoreCase) >= 0) diff --git a/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_heartbeat_loss_is_detected.cs b/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_heartbeat_loss_is_detected.cs index a737e05b0b..a41538e382 100644 --- a/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_heartbeat_loss_is_detected.cs +++ b/src/ServiceControl.AcceptanceTests/Monitoring/ExternalIntegration/When_heartbeat_loss_is_detected.cs @@ -25,6 +25,7 @@ public async Task Should_publish_notification() { var externalProcessorSubscribed = false; + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomConfiguration = config => config.OnEndpointSubscribed((s, ctx) => { if (s.SubscriberReturnAddress.IndexOf("ExternalProcessor", StringComparison.OrdinalIgnoreCase) >= 0) diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_edit_is_resolved_by_retry.cs b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_edit_is_resolved_by_retry.cs index bbe93e6e09..7d886da679 100644 --- a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_edit_is_resolved_by_retry.cs +++ b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_edit_is_resolved_by_retry.cs @@ -18,6 +18,7 @@ class When_a_failed_edit_is_resolved_by_retry : AcceptanceTest [Test] public async Task Should_publish_notification() { + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomConfiguration = config => config.OnEndpointSubscribed((s, ctx) => { ctx.ExternalProcessorSubscribed = s.SubscriberReturnAddress.Contains(nameof(MessageReceiver)); diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_archived.cs b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_archived.cs index 7fd796b0d5..29f0790c23 100644 --- a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_archived.cs +++ b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_archived.cs @@ -16,6 +16,7 @@ class When_a_failed_message_is_archived : ExternalIntegrationAcceptanceTest [Test] public async Task Should_publish_notification() { + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomConfiguration = config => config.OnEndpointSubscribed((s, ctx) => { ctx.ExternalProcessorSubscribed = s.SubscriberReturnAddress.Contains(nameof(ExternalProcessor)); diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_resolved_by_retry.cs b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_resolved_by_retry.cs index cd7e9c6d79..20bc8f4f21 100644 --- a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_resolved_by_retry.cs +++ b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_resolved_by_retry.cs @@ -16,6 +16,7 @@ class When_a_failed_message_is_resolved_by_retry : ExternalIntegrationAcceptance [Test] public async Task Should_publish_notification() { + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomConfiguration = config => config.OnEndpointSubscribed((s, ctx) => { ctx.ExternalProcessorSubscribed = s.SubscriberReturnAddress.Contains(nameof(ExternalProcessor)); diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_resolved_manually.cs b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_resolved_manually.cs index 384bf23ca6..d64072f6be 100644 --- a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_resolved_manually.cs +++ b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_resolved_manually.cs @@ -18,6 +18,7 @@ class When_a_failed_message_is_resolved_manually : ExternalIntegrationAcceptance [Test] public async Task Should_publish_notification() { + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomConfiguration = config => config.OnEndpointSubscribed((s, ctx) => { if (s.SubscriberReturnAddress.IndexOf("ExternalProcessor", StringComparison.OrdinalIgnoreCase) >= 0) diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_unarchived.cs b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_unarchived.cs index ea3998e399..565af2ae9d 100644 --- a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_unarchived.cs +++ b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_message_is_unarchived.cs @@ -18,6 +18,7 @@ class When_a_failed_message_is_unarchived : ExternalIntegrationAcceptanceTest [Test] public async Task Should_publish_notification() { + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomConfiguration = config => config.OnEndpointSubscribed((s, ctx) => { if (s.SubscriberReturnAddress.IndexOf("ExternalProcessor", StringComparison.OrdinalIgnoreCase) >= 0) diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_msg_is_resolved_by_edit.cs b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_msg_is_resolved_by_edit.cs index 68d49c0b68..e47b827493 100644 --- a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_msg_is_resolved_by_edit.cs +++ b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_failed_msg_is_resolved_by_edit.cs @@ -17,6 +17,7 @@ class When_a_failed_msg_is_resolved_by_edit : AcceptanceTest [Test] public async Task Should_publish_notification() { + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomConfiguration = config => config.OnEndpointSubscribed((s, ctx) => { ctx.ExternalProcessorSubscribed = s.SubscriberReturnAddress.Contains(nameof(MessageReceiver)); diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_group_is_archived.cs b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_group_is_archived.cs index 36b3ed3e32..5758c68162 100644 --- a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_group_is_archived.cs +++ b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_group_is_archived.cs @@ -18,6 +18,7 @@ class When_a_group_is_archived : ExternalIntegrationAcceptanceTest [Test] public async Task Should_publish_notification() { + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomConfiguration = config => config.OnEndpointSubscribed((s, ctx) => { if (s.SubscriberReturnAddress.IndexOf("ExternalProcessor", StringComparison.OrdinalIgnoreCase) >= 0) diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_message_has_failed_detected.cs b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_message_has_failed_detected.cs index b07036890c..6d4eeb5cd8 100644 --- a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_message_has_failed_detected.cs +++ b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_message_has_failed_detected.cs @@ -16,6 +16,7 @@ class When_a_message_has_failed_detected : AcceptanceTest [Test] public async Task Should_publish_notification() { + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomConfiguration = config => config.OnEndpointSubscribed((s, ctx) => { if (s.SubscriberReturnAddress.IndexOf("ExternalProcessor", StringComparison.OrdinalIgnoreCase) >= 0) diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_reedit_solves_a_failed_msg.cs b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_reedit_solves_a_failed_msg.cs index d2cad9f0e2..503aee2315 100644 --- a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_reedit_solves_a_failed_msg.cs +++ b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_a_reedit_solves_a_failed_msg.cs @@ -18,6 +18,7 @@ class When_a_reedit_solves_a_failed_msg : AcceptanceTest [Test] public async Task Should_publish_notification() { + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomConfiguration = config => config.OnEndpointSubscribed((s, ctx) => { ctx.ExternalProcessorSubscribed = s.SubscriberReturnAddress.Contains(nameof(MessageReceiver)); diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_encountered_an_error.cs b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_encountered_an_error.cs index f011edcf84..ebbcb03f55 100644 --- a/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_encountered_an_error.cs +++ b/src/ServiceControl.AcceptanceTests/Recoverability/ExternalIntegration/When_encountered_an_error.cs @@ -29,6 +29,7 @@ public async Task Should_restart_dispatch_thread() { var externalProcessorSubscribed = false; + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomizeHostBuilder = builder => builder.Services.AddSingleton(); CustomConfiguration = config => diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_a_failed_message_with_receive_properties_is_edited.cs b/src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_a_failed_message_with_receive_properties_is_edited.cs new file mode 100644 index 0000000000..62be00d2f2 --- /dev/null +++ b/src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_a_failed_message_with_receive_properties_is_edited.cs @@ -0,0 +1,111 @@ +namespace ServiceControl.AcceptanceTests.Recoverability.MessageFailures +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text.Json; + using System.Threading.Tasks; + using AcceptanceTesting; + using AcceptanceTesting.EndpointTemplates; + using Infrastructure; + using NServiceBus; + using NServiceBus.AcceptanceTesting; + using NServiceBus.Settings; + using NServiceBus.Transport; + using NUnit.Framework; + using ServiceControl.MessageFailures; + using ServiceControl.MessageFailures.Api; + + class When_a_failed_message_with_receive_properties_is_edited : AcceptanceTest + { + const string FileCreatedAtHeader = "ServiceControl.ReceiveProperties.LearningTransport.FileCreatedAt"; + + [Test] + public async Task Should_dispatch_edited_receive_properties() + { + //HINT: LearningTransport defines one receive property "LearningTransport.FileCreatedAt" + // and sets the file creation time from the dispatch property with the same name + var editedFileCreatedAt = new DateTimeOffset(2020, 1, 2, 3, 4, 5, TimeSpan.Zero); + + var context = await Define() + .WithEndpoint(e => e + .DoNotFailOnErrorMessages() + .When(c => c.SendLocal(new MyMessage()))) + .Done(async ctx => + { + if (string.IsNullOrWhiteSpace(ctx.UniqueMessageId)) + { + return false; + } + + if (!ctx.EditedMessage) + { + var failedMessage = await this.TryGet($"/api/errors/{ctx.UniqueMessageId}"); + if (!failedMessage.HasResult) + { + return false; + } + + var newHeaders = failedMessage.Item.ProcessingAttempts.Last().Headers.ToDictionary(); + ctx.StoredFileCreatedAt = newHeaders.GetValueOrDefault(FileCreatedAtHeader); + newHeaders[FileCreatedAtHeader] = editedFileCreatedAt.ToString("O"); + + ctx.EditedMessage = true; + await this.Post($"/api/edit/{ctx.UniqueMessageId}", new EditMessageModel + { + MessageBody = JsonSerializer.Serialize(new MyMessage()), + MessageHeaders = newHeaders + }); + return false; + } + + return ctx.EditedMessageHeaders != null; + }) + .Run(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(context.StoredFileCreatedAt, Is.EqualTo(context.FirstAttemptFileCreatedAt), "Receive properties are not stored as headers"); + Assert.That(DateTimeOffset.Parse(context.EditedAttemptFileCreatedAt), Is.EqualTo(editedFileCreatedAt), "Edited receive properties are not dispatched"); + Assert.That(context.EditedMessageHeaders.Keys, Has.None.StartsWith("ServiceControl.ReceiveProperties."), "Receive properties are sent as headers"); + } + } + + public class FailingEndpoint : EndpointConfigurationBuilder + { + public FailingEndpoint() => EndpointSetup(c => c.NoRetries()); + + [Handler] + public class MyMessageHandler(Context testContext, IReadOnlySettings settings) : IHandleMessages + { + public Task Handle(MyMessage message, IMessageHandlerContext context) + { + var fileCreatedAt = context.Extensions.Get().ReceiveProperties["LearningTransport.FileCreatedAt"]; + + if (!testContext.EditedMessage) + { + testContext.FirstAttemptFileCreatedAt = fileCreatedAt; + testContext.UniqueMessageId = DeterministicGuid.MakeId(context.MessageId.Replace(@"\", "-"), settings.EndpointName()).ToString(); + throw new SimulatedException("Simulated Exception"); + } + + testContext.EditedAttemptFileCreatedAt = fileCreatedAt; + testContext.EditedMessageHeaders = context.MessageHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + return Task.CompletedTask; + } + } + } + + public class Context : ScenarioContext + { + public bool EditedMessage { get; set; } + public string UniqueMessageId { get; set; } + public string FirstAttemptFileCreatedAt { get; set; } + public string StoredFileCreatedAt { get; set; } + public string EditedAttemptFileCreatedAt { get; set; } + public Dictionary EditedMessageHeaders { get; set; } + } + + public class MyMessage : ICommand; + } +} diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_a_message_has_failed.cs b/src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_a_message_has_failed.cs index fc8bae05e9..6abcbaa004 100644 --- a/src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_a_message_has_failed.cs +++ b/src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_a_message_has_failed.cs @@ -12,7 +12,6 @@ namespace ServiceControl.AcceptanceTests.Recoverability.MessageFailures using AcceptanceTesting; using AcceptanceTesting.EndpointTemplates; using CompositeViews.Messages; - using EventLog; using Infrastructure; using NServiceBus; using NServiceBus.AcceptanceTesting; @@ -169,30 +168,6 @@ public async Task Should_be_listed_in_the_messages_list(CancellationToken cancel } } - [Test] - public async Task Should_add_an_event_log_item() - { - EventLogItem entry = null; - - var context = await Define() - .WithEndpoint(b => b.When(bus => bus.SendLocal(new MyMessage())).DoNotFailOnErrorMessages()) - .Done(async c => - { - var result = await this.TryGetSingle("/api/eventlogitems/", e => e.RelatedTo.Any(r => r.Contains(c.UniqueMessageId)) && e.EventType == nameof(Contracts.MessageFailures.MessageFailed)); - entry = result; - return result; - }) - .Run(); - - using (Assert.EnterMultipleScope()) - { - Assert.That(entry.Severity, Is.EqualTo(Severity.Error), "Failures should be treated as errors"); - Assert.That(entry.Description, Does.Contain("exception"), "For failed messages, the description should contain the exception information"); - Assert.That(entry.RelatedTo.Any(item => item == "/message/" + context.UniqueMessageId), Is.True, "Should contain the api url to retrieve additional details about the failed message"); - Assert.That(entry.RelatedTo.Any(item => item == "/endpoint/" + context.EndpointNameOfReceivingEndpoint), Is.True, "Should contain the api url to retrieve additional details about the endpoint where the message failed"); - } - } - [Test] public async Task Should_be_able_to_search_queueaddresses() { diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_failed_error_imports_are_imported_again.cs b/src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_failed_error_imports_are_imported_again.cs new file mode 100644 index 0000000000..a80362c9f0 --- /dev/null +++ b/src/ServiceControl.AcceptanceTests/Recoverability/MessageFailures/When_failed_error_imports_are_imported_again.cs @@ -0,0 +1,149 @@ +namespace ServiceControl.AcceptanceTests.Recoverability.MessageFailures +{ + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Linq; + using System.Runtime.Loader; + using System.Threading.Tasks; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Logging; + using NServiceBus; + using NUnit.Framework; + using Particular.ServiceControl.Hosting; + using ServiceBus.Management.Infrastructure.Settings; + using ServiceControl.Hosting.Commands; + using ServiceControl.Infrastructure; + using ServiceControl.Operations; + using ServiceControl.Persistence; + + class When_failed_error_imports_are_imported_again : AcceptanceTest + { + [Test] + public async Task Should_store_the_sending_and_receiving_endpoints() + { + var settings = await CreateSettings(); + + var sendingHostId = Guid.NewGuid(); + var receivingHostId = Guid.NewGuid(); + var nativeMessageId = Guid.NewGuid().ToString(); + var headers = new Dictionary + { + [Headers.MessageId] = nativeMessageId, + [Headers.EnclosedMessageTypes] = "Reimport.SomeCommand, Reimport, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", + [Headers.OriginatingEndpoint] = "Reimport.Sender", + [Headers.OriginatingMachine] = "SenderHost", + [Headers.OriginatingHostId] = sendingHostId.ToString("N"), + [Headers.ProcessingEndpoint] = "Reimport.Receiver", + [Headers.HostDisplayName] = "ReceiverHost", + [Headers.HostId] = receivingHostId.ToString("N"), + ["NServiceBus.FailedQ"] = "Reimport.Receiver@ReceiverHost", + ["NServiceBus.TimeOfFailure"] = DateTimeOffsetHelper.ToWireFormattedString(DateTimeOffset.UtcNow), + ["NServiceBus.ExceptionInfo.ExceptionType"] = "System.InvalidOperationException", + ["NServiceBus.ExceptionInfo.Message"] = "Simulated failure", + ["NServiceBus.ExceptionInfo.StackTrace"] = " at Reimport.Receiver.Handle()" + }; + var failedMessageId = FailedErrorImport.DeriveKey(headers, nativeMessageId).ToString(); + + IHost host = null; + try + { + using (await StorageConfiguration.UseDatabaseLifecycleLock()) + { + await new SetupCommand().Execute(new HostArguments([]), settings); + + host = ImportFailedErrorsCommand.BuildHost(settings); + await host.StartAsync(); + } + + var failedImports = host.Services.GetRequiredService(); + await failedImports.StoreFailedErrorImport(new FailedErrorImport + { + Id = failedMessageId, + Message = new FailedTransportMessage { Id = nativeMessageId, Headers = headers, Body = "{}"u8.ToArray() }, + ExceptionInfo = "Simulated import failure" + }); + + // RavenDB finds failed imports through an index, which may not have caught up with the write yet. + await WaitFor(() => failedImports.QueryContainsFailedImports(), "the failed import to become visible"); + + await host.Services.GetRequiredService().Run(); + + var failedMessage = await host.Services.GetRequiredService() + .GetLatestFailedMessageView(failedMessageId); + + Assert.That(failedMessage, Is.Not.Null, "the failed import was not stored as a failed message"); + using (Assert.EnterMultipleScope()) + { + Assert.That(failedMessage.SendingEndpoint?.Name, Is.EqualTo("Reimport.Sender")); + Assert.That(failedMessage.SendingEndpoint?.Host, Is.EqualTo("SenderHost")); + Assert.That(failedMessage.SendingEndpoint?.HostId, Is.EqualTo(sendingHostId)); + Assert.That(failedMessage.ReceivingEndpoint?.Name, Is.EqualTo("Reimport.Receiver")); + Assert.That(failedMessage.ReceivingEndpoint?.Host, Is.EqualTo("ReceiverHost")); + Assert.That(failedMessage.ReceivingEndpoint?.HostId, Is.EqualTo(receivingHostId)); + } + + var monitoring = host.Services.GetRequiredService(); + + // RavenDB reads known endpoints through an index, which may not have caught up with the import yet. + await WaitFor(async () => + { + var knownEndpointNames = (await monitoring.GetAllKnownEndpoints()).Select(endpoint => endpoint.EndpointDetails.Name).ToArray(); + return knownEndpointNames.Contains("Reimport.Sender") && knownEndpointNames.Contains("Reimport.Receiver"); + }, "Reimport.Sender and Reimport.Receiver to be recorded as known endpoints"); + } + finally + { + if (host != null) + { + try + { + await host.StopAsync(); + } + finally + { + host.Dispose(); + } + } + } + } + + static async Task WaitFor(Func> condition, string description) + { + var timeout = Stopwatch.StartNew(); + + while (timeout.Elapsed < TimeSpan.FromSeconds(30)) + { + if (await condition()) + { + return; + } + + await Task.Delay(TimeSpan.FromMilliseconds(200)); + } + + Assert.Fail($"Timed out waiting for {description}."); + } + + async Task CreateSettings() + { + var logPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + Directory.CreateDirectory(logPath); + + var settings = new Settings(TransportIntegration.TypeName, StorageConfiguration.StorageType, + new LoggingSettings(Settings.SettingsRootNamespace, defaultLevel: LogLevel.Debug, logPath: logPath), + forwardErrorMessages: false, errorRetentionPeriod: TimeSpan.FromDays(10)) + { + InstanceName = $"Reimport.{Guid.NewGuid():n}", + TransportConnectionString = TransportIntegration.ConnectionString, + AssemblyLoadContextResolver = static _ => AssemblyLoadContext.Default + }; + + await StorageConfiguration.CustomizeSettings(settings); + + return settings; + } + } +} diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/When_edited_message_fails_to_process.cs b/src/ServiceControl.AcceptanceTests/Recoverability/When_edited_message_fails_to_process.cs index 8b68a22c8e..22e50a5634 100644 --- a/src/ServiceControl.AcceptanceTests/Recoverability/When_edited_message_fails_to_process.cs +++ b/src/ServiceControl.AcceptanceTests/Recoverability/When_edited_message_fails_to_process.cs @@ -19,6 +19,7 @@ class When_edited_message_fails_to_process : AcceptanceTest [Test] public async Task A_new_message_failure_is_created() { + SetSettings = settings => settings.EnableExternalIntegrationsPublishing = true; CustomConfiguration = config => config.OnEndpointSubscribed((s, ctx) => { ctx.ExternalProcessorSubscribed = s.SubscriberReturnAddress.Contains(nameof(FailingEditedMessageReceiver)); diff --git a/src/ServiceControl.AcceptanceTests/Recoverability/When_hosting_error_ingestion_only.cs b/src/ServiceControl.AcceptanceTests/Recoverability/When_hosting_error_ingestion_only.cs index 58cef8074f..96083be488 100644 --- a/src/ServiceControl.AcceptanceTests/Recoverability/When_hosting_error_ingestion_only.cs +++ b/src/ServiceControl.AcceptanceTests/Recoverability/When_hosting_error_ingestion_only.cs @@ -162,10 +162,6 @@ public async Task Should_ingest_a_failed_message_into_the_shared_database() Assert.That(knownEndpoints.Select(endpoint => endpoint.Name), Does.Contain("IngestOnly.Receiver")); } - await WaitFor(host, async dbContext => await dbContext.EventLogItems.AsNoTracking() - .AnyAsync(item => item.EventType == "MessageFailed" && item.Description == "Simulated failure"), - "an event log entry for the failure"); - using var client = host.GetTestClient(); var liveness = await client.GetAsync("/health"); @@ -302,27 +298,6 @@ await infrastructure.Dispatcher.Dispatch( } } - static async Task WaitFor(IHost host, Func> condition, string description) - { - var scopeFactory = host.Services.GetRequiredService(); - var timeout = Stopwatch.StartNew(); - - while (timeout.Elapsed < TimeSpan.FromSeconds(60)) - { - await using var scope = scopeFactory.CreateAsyncScope(); - var dbContext = scope.ServiceProvider.GetRequiredService(); - - if (await condition(dbContext)) - { - return; - } - - await Task.Delay(TimeSpan.FromMilliseconds(200)); - } - - Assert.Fail($"Timed out waiting for {description}."); - } - static async Task WaitForFailedMessage(IHost host, string messageId) { var scopeFactory = host.Services.GetRequiredService(); @@ -350,7 +325,7 @@ static async Task WaitForFailedMessage(IHost host, string m async Task CreateSettings() { - var settings = new Settings(TransportIntegration.TypeName, StorageConfiguration.PersistenceType, + var settings = new Settings(TransportIntegration.TypeName, StorageConfiguration.StorageType, CreateLoggingSettings(), forwardErrorMessages: false, errorRetentionPeriod: TimeSpan.FromDays(10)) { InstanceName = $"IngestOnly.{Guid.NewGuid():n}", diff --git a/src/ServiceControl.AcceptanceTests/TestSupport/IAcceptanceTestStorageConfiguration.cs b/src/ServiceControl.AcceptanceTests/TestSupport/IAcceptanceTestStorageConfiguration.cs index b79507a129..37b48e8604 100644 --- a/src/ServiceControl.AcceptanceTests/TestSupport/IAcceptanceTestStorageConfiguration.cs +++ b/src/ServiceControl.AcceptanceTests/TestSupport/IAcceptanceTestStorageConfiguration.cs @@ -7,7 +7,7 @@ namespace ServiceControl.AcceptanceTests.TestSupport; public interface IAcceptanceTestStorageConfiguration { - string PersistenceType { get; } + string StorageType { get; } Task CustomizeSettings(Settings settings, CancellationToken cancellationToken = default); diff --git a/src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs b/src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs index f810c9acf0..867316201e 100644 --- a/src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs +++ b/src/ServiceControl.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs @@ -61,7 +61,7 @@ async Task InitializeServiceControlCore(ScenarioContext context) var loggingSettings = new LoggingSettings(Settings.SettingsRootNamespace, defaultLevel: LogLevel.Debug, logPath: logPath); LoggerUtil.ActiveLoggers = Loggers.Test; - var settings = new Settings(transportToUse.TypeName, persistenceToUse.PersistenceType, loggingSettings, forwardErrorMessages: false, errorRetentionPeriod: TimeSpan.FromDays(10)) + var settings = new Settings(transportToUse.TypeName, persistenceToUse.StorageType, loggingSettings, forwardErrorMessages: false, errorRetentionPeriod: TimeSpan.FromDays(10)) { InstanceName = instanceName, AllowMessageEditing = true, diff --git a/src/ServiceControl.AcceptanceTests/WebApi/When_triggering_a_manual_retention_purge.cs b/src/ServiceControl.AcceptanceTests/WebApi/When_triggering_a_manual_retention_purge.cs index 91660ca073..e4239d72c4 100644 --- a/src/ServiceControl.AcceptanceTests/WebApi/When_triggering_a_manual_retention_purge.cs +++ b/src/ServiceControl.AcceptanceTests/WebApi/When_triggering_a_manual_retention_purge.cs @@ -17,7 +17,7 @@ class When_triggering_a_manual_retention_purge : AcceptanceTest [Test] public async Task Should_be_available_on_efcore_persisters() { - if (StorageConfiguration.PersistenceType == "RavenDB") + if (StorageConfiguration.StorageType == "RavenDB") { Assert.Ignore("RavenDB has no sweeper — covered by Should_return_501_on_a_ravendb_backed_instance."); return; @@ -67,7 +67,7 @@ await Define() [Test] public async Task Should_report_background_completion_via_status() { - if (StorageConfiguration.PersistenceType == "RavenDB") + if (StorageConfiguration.StorageType == "RavenDB") { Assert.Ignore("RavenDB has no sweeper — covered by Should_return_501_on_a_ravendb_backed_instance."); return; @@ -101,7 +101,7 @@ await Define() [Test] public async Task Should_return_501_on_a_ravendb_backed_instance() { - if (StorageConfiguration.PersistenceType != "RavenDB") + if (StorageConfiguration.StorageType != "RavenDB") { Assert.Ignore("EFCore persisters support the purge — covered by the efcore tests."); return; diff --git a/src/ServiceControl.Audit.AcceptanceTests.PostgreSql/AcceptanceTestStorageConfiguration.cs b/src/ServiceControl.Audit.AcceptanceTests.PostgreSql/AcceptanceTestStorageConfiguration.cs index 82c9ed933b..c06150463e 100644 --- a/src/ServiceControl.Audit.AcceptanceTests.PostgreSql/AcceptanceTestStorageConfiguration.cs +++ b/src/ServiceControl.Audit.AcceptanceTests.PostgreSql/AcceptanceTestStorageConfiguration.cs @@ -12,7 +12,7 @@ namespace ServiceControl.Audit.AcceptanceTests.PostgreSql; public class AcceptanceTestStorageConfiguration : IAcceptanceTestStorageConfiguration { - public string PersistenceType { get; } = "PostgreSQL"; + public string StorageType { get; } = "PostgreSQL"; public async Task> CustomizeSettings(CancellationToken cancellationToken = default) { diff --git a/src/ServiceControl.Audit.AcceptanceTests.RavenDB/AcceptanceTestStorageConfiguration.cs b/src/ServiceControl.Audit.AcceptanceTests.RavenDB/AcceptanceTestStorageConfiguration.cs index 2a34743384..ae04b428cb 100644 --- a/src/ServiceControl.Audit.AcceptanceTests.RavenDB/AcceptanceTestStorageConfiguration.cs +++ b/src/ServiceControl.Audit.AcceptanceTests.RavenDB/AcceptanceTestStorageConfiguration.cs @@ -13,7 +13,7 @@ public class AcceptanceTestStorageConfiguration : IAcceptanceTestStorageConfiguration { - public string PersistenceType { get; } = "RavenDB"; + public string StorageType { get; } = "RavenDB"; EmbeddedDatabase databaseInstance; string databaseName; diff --git a/src/ServiceControl.Audit.AcceptanceTests.SqlServer/AcceptanceTestStorageConfiguration.cs b/src/ServiceControl.Audit.AcceptanceTests.SqlServer/AcceptanceTestStorageConfiguration.cs index 54c4b0a87d..89a51ffd5e 100644 --- a/src/ServiceControl.Audit.AcceptanceTests.SqlServer/AcceptanceTestStorageConfiguration.cs +++ b/src/ServiceControl.Audit.AcceptanceTests.SqlServer/AcceptanceTestStorageConfiguration.cs @@ -12,7 +12,7 @@ namespace ServiceControl.Audit.AcceptanceTests.SqlServer; public class AcceptanceTestStorageConfiguration : IAcceptanceTestStorageConfiguration { - public string PersistenceType { get; } = "SQLServer"; + public string StorageType { get; } = "SQLServer"; public async Task> CustomizeSettings(CancellationToken cancellationToken = default) { diff --git a/src/ServiceControl.Audit.AcceptanceTests/AcceptanceTest.cs b/src/ServiceControl.Audit.AcceptanceTests/AcceptanceTest.cs index dafe95f451..74fed98307 100644 --- a/src/ServiceControl.Audit.AcceptanceTests/AcceptanceTest.cs +++ b/src/ServiceControl.Audit.AcceptanceTests/AcceptanceTest.cs @@ -47,7 +47,7 @@ public void Setup() StorageConfiguration = new AcceptanceTestStorageConfiguration(); serviceControlRunnerBehavior = new ServiceControlComponentBehavior(TransportIntegration, StorageConfiguration, s => SetSettings(s), s => CustomConfiguration(s), d => SetStorageConfiguration(d), hb => CustomizeHostBuilder(hb)); - TestContext.Out.WriteLine($"Using persistence {StorageConfiguration.PersistenceType}"); + TestContext.Out.WriteLine($"Using storage type {StorageConfiguration.StorageType}"); } [TearDown] diff --git a/src/ServiceControl.Audit.AcceptanceTests/MaintenanceModeTests.cs b/src/ServiceControl.Audit.AcceptanceTests/MaintenanceModeTests.cs index 85e4ea25fd..c01418e8e6 100644 --- a/src/ServiceControl.Audit.AcceptanceTests/MaintenanceModeTests.cs +++ b/src/ServiceControl.Audit.AcceptanceTests/MaintenanceModeTests.cs @@ -13,7 +13,7 @@ class MaintenanceModeTests : AcceptanceTest [Test] public void Should_refuse_unsupported_persister_before_starting_host() { - var settings = new Settings(persisterType: StorageConfiguration.PersistenceType) + var settings = new Settings(storageType: StorageConfiguration.StorageType) { AssemblyLoadContextResolver = static _ => AssemblyLoadContext.Default }; @@ -21,7 +21,7 @@ public void Should_refuse_unsupported_persister_before_starting_host() var exception = Assert.ThrowsAsync(async () => await new MaintenanceModeCommand().Execute(new HostArguments([]), settings)); - Assert.That(exception.Message, Does.Contain("Maintenance mode is not supported").And.Contain(StorageConfiguration.PersistenceType)); + Assert.That(exception.Message, Does.Contain("Maintenance mode is not supported").And.Contain(StorageConfiguration.StorageType)); } } } diff --git a/src/ServiceControl.Audit.AcceptanceTests/TestSupport/IAcceptanceTestStorageConfiguration.cs b/src/ServiceControl.Audit.AcceptanceTests/TestSupport/IAcceptanceTestStorageConfiguration.cs index ad8c43e24b..909defdc76 100644 --- a/src/ServiceControl.Audit.AcceptanceTests/TestSupport/IAcceptanceTestStorageConfiguration.cs +++ b/src/ServiceControl.Audit.AcceptanceTests/TestSupport/IAcceptanceTestStorageConfiguration.cs @@ -7,7 +7,7 @@ namespace ServiceControl.Audit.AcceptanceTests.TestSupport; public interface IAcceptanceTestStorageConfiguration { - string PersistenceType { get; } + string StorageType { get; } Task> CustomizeSettings(CancellationToken cancellationToken = default); diff --git a/src/ServiceControl.Audit.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs b/src/ServiceControl.Audit.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs index 81d73b1386..e85345813a 100644 --- a/src/ServiceControl.Audit.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs +++ b/src/ServiceControl.Audit.AcceptanceTests/TestSupport/ServiceControlComponentRunner.cs @@ -61,7 +61,7 @@ async Task InitializeServiceControlCore(ScenarioContext context) var loggingSettings = new LoggingSettings(Settings.SettingsRootNamespace, defaultLevel: LogLevel.Debug, logPath: logPath); LoggerUtil.ActiveLoggers = Loggers.Test; - settings = new Settings(transportToUse.TypeName, persistenceToUse.PersistenceType, loggingSettings) + settings = new Settings(transportToUse.TypeName, persistenceToUse.StorageType, loggingSettings) { InstanceName = instanceName, TransportConnectionString = transportToUse.ConnectionString, diff --git a/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/20261126045230_AddEndpointTimeSentIndex.Designer.cs b/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/20261126045230_AddEndpointTimeSentIndex.Designer.cs new file mode 100644 index 0000000000..a7e5fb16c2 --- /dev/null +++ b/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/20261126045230_AddEndpointTimeSentIndex.Designer.cs @@ -0,0 +1,257 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using ServiceControl.Audit.Persistence.EFCore.PostgreSql; + +#nullable disable + +namespace ServiceControl.Audit.Persistence.EFCore.PostgreSql.Migrations +{ + [DbContext(typeof(PostgreSqlAuditDbContext))] + [Migration("20261126045230_AddEndpointTimeSentIndex")] + partial class AddEndpointTimeSentIndex + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.15") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("ServiceControl.Audit.Persistence.EFCore.Entities.AuditMessageEntity", b => + { + b.Property("CreatedOn") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_on"); + + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BodyContentType") + .HasColumnType("text") + .HasColumnName("body_content_type"); + + b.Property("BodySize") + .HasColumnType("integer") + .HasColumnName("body_size"); + + b.Property("BodyState") + .HasColumnType("integer") + .HasColumnName("body_state"); + + b.Property("BodyText") + .HasColumnType("text") + .HasColumnName("body_text"); + + b.Property("ConversationId") + .HasMaxLength(450) + .HasColumnType("character varying(450)") + .HasColumnName("conversation_id"); + + b.Property("CriticalTimeTicks") + .HasColumnType("bigint") + .HasColumnName("critical_time_ticks"); + + b.Property("DeliveryTimeTicks") + .HasColumnType("bigint") + .HasColumnName("delivery_time_ticks"); + + b.Property("HeadersJson") + .IsRequired() + .HasColumnType("text") + .HasColumnName("headers_json"); + + b.Property("IsSystemMessage") + .HasColumnType("boolean") + .HasColumnName("is_system_message"); + + b.Property("MessageId") + .HasColumnType("text") + .HasColumnName("message_id"); + + b.Property("MessageType") + .HasColumnType("text") + .HasColumnName("message_type"); + + b.Property("ProcessedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("processed_at"); + + b.Property("ProcessingTimeTicks") + .HasColumnType("bigint") + .HasColumnName("processing_time_ticks"); + + b.Property("ReceivingEndpointHost") + .HasColumnType("text") + .HasColumnName("receiving_endpoint_host"); + + b.Property("ReceivingEndpointHostId") + .HasColumnType("uuid") + .HasColumnName("receiving_endpoint_host_id"); + + b.Property("ReceivingEndpointName") + .HasMaxLength(450) + .HasColumnType("character varying(450)") + .HasColumnName("receiving_endpoint_name"); + + b.Property("SendingEndpointHost") + .HasColumnType("text") + .HasColumnName("sending_endpoint_host"); + + b.Property("SendingEndpointHostId") + .HasColumnType("uuid") + .HasColumnName("sending_endpoint_host_id"); + + b.Property("SendingEndpointName") + .HasColumnType("text") + .HasColumnName("sending_endpoint_name"); + + b.Property("Status") + .HasColumnType("integer") + .HasColumnName("status"); + + b.Property("TimeSent") + .HasColumnType("timestamp with time zone") + .HasColumnName("time_sent"); + + b.Property("UniqueMessageId") + .HasColumnType("uuid") + .HasColumnName("unique_message_id"); + + b.HasKey("CreatedOn", "Id") + .HasName("pk_audit_messages"); + + b.HasIndex("ConversationId") + .HasDatabaseName("ix_audit_messages_conversation_id"); + + b.HasIndex("ProcessedAt") + .HasDatabaseName("ix_audit_messages_processed_at"); + + b.HasIndex("TimeSent") + .HasDatabaseName("ix_audit_messages_time_sent"); + + b.HasIndex("UniqueMessageId") + .HasDatabaseName("ix_audit_messages_unique_message_id"); + + b.HasIndex("ReceivingEndpointName", "CreatedOn") + .HasDatabaseName("ix_audit_messages_receiving_endpoint_name_created_on"); + + b.HasIndex("ReceivingEndpointName", "TimeSent") + .HasDatabaseName("ix_audit_messages_receiving_endpoint_name_time_sent"); + + b.ToTable("audit_messages", (string)null); + }); + + modelBuilder.Entity("ServiceControl.Audit.Persistence.EFCore.Entities.FailedAuditImportEntity", b => + { + b.Property("UniqueMessageId") + .HasColumnType("uuid") + .HasColumnName("unique_message_id"); + + b.Property("Body") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("body"); + + b.Property("ExceptionInfo") + .HasColumnType("text") + .HasColumnName("exception_info"); + + b.Property("FailedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("failed_at"); + + b.Property("HeadersJson") + .IsRequired() + .HasColumnType("text") + .HasColumnName("headers_json"); + + b.Property("MessageId") + .HasColumnType("text") + .HasColumnName("message_id"); + + b.HasKey("UniqueMessageId") + .HasName("pk_failed_audit_imports"); + + b.HasIndex("FailedAt", "UniqueMessageId") + .HasDatabaseName("ix_failed_audit_imports_failed_at_unique_message_id"); + + b.ToTable("failed_audit_imports", (string)null); + }); + + modelBuilder.Entity("ServiceControl.Audit.Persistence.EFCore.Entities.SagaSnapshotEntity", b => + { + b.Property("CreatedOn") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_on"); + + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Endpoint") + .HasColumnType("text") + .HasColumnName("endpoint"); + + b.Property("FinishTime") + .HasColumnType("timestamp with time zone") + .HasColumnName("finish_time"); + + b.Property("InitiatingMessageJson") + .HasColumnType("text") + .HasColumnName("initiating_message_json"); + + b.Property("OutgoingMessagesJson") + .HasColumnType("text") + .HasColumnName("outgoing_messages_json"); + + b.Property("ProcessedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("processed_at"); + + b.Property("SagaId") + .HasColumnType("uuid") + .HasColumnName("saga_id"); + + b.Property("SagaType") + .HasColumnType("text") + .HasColumnName("saga_type"); + + b.Property("StartTime") + .HasColumnType("timestamp with time zone") + .HasColumnName("start_time"); + + b.Property("StateAfterChange") + .HasColumnType("text") + .HasColumnName("state_after_change"); + + b.Property("Status") + .HasColumnType("integer") + .HasColumnName("status"); + + b.HasKey("CreatedOn", "Id") + .HasName("pk_saga_snapshots"); + + b.HasIndex("SagaId", "FinishTime") + .HasDatabaseName("ix_saga_snapshots_saga_id_finish_time"); + + b.ToTable("saga_snapshots", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/20261126045230_AddEndpointTimeSentIndex.cs b/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/20261126045230_AddEndpointTimeSentIndex.cs new file mode 100644 index 0000000000..32eb35fb74 --- /dev/null +++ b/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/20261126045230_AddEndpointTimeSentIndex.cs @@ -0,0 +1,27 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ServiceControl.Audit.Persistence.EFCore.PostgreSql.Migrations +{ + /// + public partial class AddEndpointTimeSentIndex : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateIndex( + name: "ix_audit_messages_receiving_endpoint_name_time_sent", + table: "audit_messages", + columns: new[] { "receiving_endpoint_name", "time_sent" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "ix_audit_messages_receiving_endpoint_name_time_sent", + table: "audit_messages"); + } + } +} diff --git a/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/PostgreSqlAuditDbContextModelSnapshot.cs b/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/PostgreSqlAuditDbContextModelSnapshot.cs index eb646b0c01..657fc1ffe7 100644 --- a/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/PostgreSqlAuditDbContextModelSnapshot.cs +++ b/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/Migrations/PostgreSqlAuditDbContextModelSnapshot.cs @@ -144,6 +144,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasIndex("ReceivingEndpointName", "CreatedOn") .HasDatabaseName("ix_audit_messages_receiving_endpoint_name_created_on"); + b.HasIndex("ReceivingEndpointName", "TimeSent") + .HasDatabaseName("ix_audit_messages_receiving_endpoint_name_time_sent"); + b.ToTable("audit_messages", (string)null); }); diff --git a/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/persistence.manifest b/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/persistence.manifest index 93363f97c6..db5298fb6e 100644 --- a/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/persistence.manifest +++ b/src/ServiceControl.Audit.Persistence.EFCore.PostgreSql/persistence.manifest @@ -78,5 +78,8 @@ "Name": "ServiceControl.Audit/MessageBody/MinCompressionSize", "Mandatory": false } + ], + "SettingsWithPathsToCleanup": [ + "ServiceControl.Audit/MessageBody/FileSystem/StoragePath" ] } diff --git a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/20261126035956_AddEndpointTimeSentIndex.Designer.cs b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/20261126035956_AddEndpointTimeSentIndex.Designer.cs new file mode 100644 index 0000000000..ad1253f967 --- /dev/null +++ b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/20261126035956_AddEndpointTimeSentIndex.Designer.cs @@ -0,0 +1,207 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using ServiceControl.Audit.Persistence.EFCore.SqlServer; + +#nullable disable + +namespace ServiceControl.Audit.Persistence.EFCore.SqlServer.Migrations +{ + [DbContext(typeof(SqlServerAuditDbContext))] + [Migration("20261126035956_AddEndpointTimeSentIndex")] + partial class AddEndpointTimeSentIndex + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.15") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("ServiceControl.Audit.Persistence.EFCore.Entities.AuditMessageEntity", b => + { + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("BodyContentType") + .HasColumnType("nvarchar(max)"); + + b.Property("BodySize") + .HasColumnType("int"); + + b.Property("BodyState") + .HasColumnType("int"); + + b.Property("BodyText") + .HasColumnType("nvarchar(max)"); + + b.Property("ConversationId") + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("CriticalTimeTicks") + .HasColumnType("bigint"); + + b.Property("DeliveryTimeTicks") + .HasColumnType("bigint"); + + b.Property("HeadersJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("IsSystemMessage") + .HasColumnType("bit"); + + b.Property("MessageId") + .HasColumnType("nvarchar(max)"); + + b.Property("MessageType") + .HasColumnType("nvarchar(max)"); + + b.Property("ProcessedAt") + .HasColumnType("datetime2"); + + b.Property("ProcessingTimeTicks") + .HasColumnType("bigint"); + + b.Property("ReceivingEndpointHost") + .HasColumnType("nvarchar(max)"); + + b.Property("ReceivingEndpointHostId") + .HasColumnType("uniqueidentifier"); + + b.Property("ReceivingEndpointName") + .HasMaxLength(450) + .HasColumnType("nvarchar(450)"); + + b.Property("SendingEndpointHost") + .HasColumnType("nvarchar(max)"); + + b.Property("SendingEndpointHostId") + .HasColumnType("uniqueidentifier"); + + b.Property("SendingEndpointName") + .HasColumnType("nvarchar(max)"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("TimeSent") + .HasColumnType("datetime2"); + + b.Property("UniqueMessageId") + .HasColumnType("uniqueidentifier"); + + b.HasKey("CreatedOn", "Id"); + + b.HasIndex("ConversationId"); + + b.HasIndex("Id") + .IsUnique(); + + b.HasIndex("ProcessedAt"); + + b.HasIndex("TimeSent"); + + b.HasIndex("UniqueMessageId"); + + b.HasIndex("ReceivingEndpointName", "CreatedOn"); + + b.HasIndex("ReceivingEndpointName", "TimeSent"); + + b.ToTable("AuditMessages"); + }); + + modelBuilder.Entity("ServiceControl.Audit.Persistence.EFCore.Entities.FailedAuditImportEntity", b => + { + b.Property("UniqueMessageId") + .HasColumnType("uniqueidentifier"); + + b.Property("Body") + .IsRequired() + .HasColumnType("varbinary(max)"); + + b.Property("ExceptionInfo") + .HasColumnType("nvarchar(max)"); + + b.Property("FailedAt") + .HasColumnType("datetime2"); + + b.Property("HeadersJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("MessageId") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UniqueMessageId"); + + b.HasIndex("FailedAt", "UniqueMessageId"); + + b.ToTable("FailedAuditImports"); + }); + + modelBuilder.Entity("ServiceControl.Audit.Persistence.EFCore.Entities.SagaSnapshotEntity", b => + { + b.Property("CreatedOn") + .HasColumnType("datetime2"); + + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Endpoint") + .HasColumnType("nvarchar(max)"); + + b.Property("FinishTime") + .HasColumnType("datetime2"); + + b.Property("InitiatingMessageJson") + .HasColumnType("nvarchar(max)"); + + b.Property("OutgoingMessagesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("ProcessedAt") + .HasColumnType("datetime2"); + + b.Property("SagaId") + .HasColumnType("uniqueidentifier"); + + b.Property("SagaType") + .HasColumnType("nvarchar(max)"); + + b.Property("StartTime") + .HasColumnType("datetime2"); + + b.Property("StateAfterChange") + .HasColumnType("nvarchar(max)"); + + b.Property("Status") + .HasColumnType("int"); + + b.HasKey("CreatedOn", "Id"); + + b.HasIndex("SagaId", "FinishTime"); + + b.ToTable("SagaSnapshots"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/20261126035956_AddEndpointTimeSentIndex.cs b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/20261126035956_AddEndpointTimeSentIndex.cs new file mode 100644 index 0000000000..5e990c310f --- /dev/null +++ b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/20261126035956_AddEndpointTimeSentIndex.cs @@ -0,0 +1,27 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ServiceControl.Audit.Persistence.EFCore.SqlServer.Migrations +{ + /// + public partial class AddEndpointTimeSentIndex : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateIndex( + name: "IX_AuditMessages_ReceivingEndpointName_TimeSent", + table: "AuditMessages", + columns: new[] { "ReceivingEndpointName", "TimeSent" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_AuditMessages_ReceivingEndpointName_TimeSent", + table: "AuditMessages"); + } + } +} diff --git a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/SqlServerAuditDbContextModelSnapshot.cs b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/SqlServerAuditDbContextModelSnapshot.cs index 397af20956..5af000d58c 100644 --- a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/SqlServerAuditDbContextModelSnapshot.cs +++ b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/Migrations/SqlServerAuditDbContextModelSnapshot.cs @@ -117,6 +117,8 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasIndex("ReceivingEndpointName", "CreatedOn"); + b.HasIndex("ReceivingEndpointName", "TimeSent"); + b.ToTable("AuditMessages"); }); diff --git a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/persistence.manifest b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/persistence.manifest index 475fec6814..4f85894da0 100644 --- a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/persistence.manifest +++ b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/persistence.manifest @@ -78,5 +78,8 @@ "Name": "ServiceControl.Audit/MessageBody/MinCompressionSize", "Mandatory": false } + ], + "SettingsWithPathsToCleanup": [ + "ServiceControl.Audit/MessageBody/FileSystem/StoragePath" ] } diff --git a/src/ServiceControl.Audit.Persistence.EFCore/EntityConfigurations/AuditMessageConfiguration.cs b/src/ServiceControl.Audit.Persistence.EFCore/EntityConfigurations/AuditMessageConfiguration.cs index 3d85ce3114..332b34b7ae 100644 --- a/src/ServiceControl.Audit.Persistence.EFCore/EntityConfigurations/AuditMessageConfiguration.cs +++ b/src/ServiceControl.Audit.Persistence.EFCore/EntityConfigurations/AuditMessageConfiguration.cs @@ -25,6 +25,7 @@ public void Configure(EntityTypeBuilder builder) builder.HasIndex(e => e.UniqueMessageId); builder.HasIndex(e => new { e.ReceivingEndpointName, e.CreatedOn }); + builder.HasIndex(e => new { e.ReceivingEndpointName, e.TimeSent }); builder.HasIndex(e => e.ConversationId); builder.HasIndex(e => e.ProcessedAt); builder.HasIndex(e => e.TimeSent); diff --git a/src/ServiceControl.Audit.Persistence.EFCore/Implementation/BodyStorage/AuditFileSystemBodyStorage.cs b/src/ServiceControl.Audit.Persistence.EFCore/Implementation/BodyStorage/AuditFileSystemBodyStorage.cs index 7270626b14..cb89d1224e 100644 --- a/src/ServiceControl.Audit.Persistence.EFCore/Implementation/BodyStorage/AuditFileSystemBodyStorage.cs +++ b/src/ServiceControl.Audit.Persistence.EFCore/Implementation/BodyStorage/AuditFileSystemBodyStorage.cs @@ -19,10 +19,10 @@ public class AuditFileSystemBodyStorage(FileSystemBodyStorageSettings settings) public async Task WriteBody(string bodyId, DateTime createdOn, ReadOnlyMemory body, string contentType, CancellationToken cancellationToken = default) { - Directory.CreateDirectory(HourDirectory(createdOn)); - var filePath = GetBodyFilePath(createdOn, bodyId); + Directory.CreateDirectory(HourDirectory(createdOn)); + if (File.Exists(filePath)) { return; @@ -163,7 +163,15 @@ public async Task DeleteBodiesForDay(DateTime day, CancellationToken cancellatio string HourDirectory(DateTime hour) => Path.Combine(StoragePath, AuditBodyStorageKey.HourPrefix(hour)); - string GetBodyFilePath(DateTime createdOn, string bodyId) => Path.Combine(StoragePath, $"{AuditBodyStorageKey.For(createdOn, bodyId)}.body"); + string GetBodyFilePath(DateTime createdOn, string bodyId) + { + if (!Guid.TryParse(bodyId, out _)) + { + throw new ArgumentException("The body id must be a GUID.", nameof(bodyId)); + } + + return Path.Combine(StoragePath, $"{AuditBodyStorageKey.For(createdOn, bodyId)}.body"); + } static void TryDelete(string filePath) { diff --git a/src/ServiceControl.Audit.Persistence.RavenDB/CustomChecks/CheckRavenDBIndexLag.cs b/src/ServiceControl.Audit.Persistence.RavenDB/CustomChecks/CheckRavenDBIndexLag.cs index 7cd6d76321..9b2f8f618b 100644 --- a/src/ServiceControl.Audit.Persistence.RavenDB/CustomChecks/CheckRavenDBIndexLag.cs +++ b/src/ServiceControl.Audit.Persistence.RavenDB/CustomChecks/CheckRavenDBIndexLag.cs @@ -24,7 +24,7 @@ public override async Task PerformCheck(CancellationToken cancellat if (indexCountWithTooMuchLag > 0) { - return CheckResult.Failed($"At least one index significantly stale. Please run maintenance mode if this custom check persists to ensure index(es) can recover. See log file for more details. Visit https://docs.particular.net/search?q=servicecontrol+troubleshooting for more information."); + return CheckResult.Failed($"At least one index is significantly stale. If this custom check persists, pause ingestion so the index(es) can recover: start the instance in maintenance mode for an embedded database, or stop the instance for an external RavenDB server. See log file for more details. Visit https://docs.particular.net/search?q=servicecontrol+troubleshooting for more information."); } return CheckResult.Pass; @@ -43,12 +43,12 @@ int CheckAndReportIndexesWithTooMuchIndexLag(IndexInformation[] indexes) if (indexLag > IndexLagThresholdError) { indexCountWithTooMuchLag++; - logger.LogError("Index [{IndexStatsName}] IndexingLag {IndexLag} is above error threshold ({IndexLagThresholdError}). Launch in maintenance mode to let indexes catch up", indexStats.Name, indexLag, IndexLagThresholdError); + logger.LogError("Index [{IndexStatsName}] IndexingLag {IndexLag} is above error threshold ({IndexLagThresholdError}). Pause ingestion to let indexes catch up: use maintenance mode for an embedded database, or stop the instance for an external RavenDB server", indexStats.Name, indexLag, IndexLagThresholdError); } else if (indexLag > IndexLagThresholdWarning) { indexCountWithTooMuchLag++; - logger.LogWarning("Index [{IndexStatsName}] IndexingLag {IndexLag} is above warning threshold ({IndexLagThresholdWarning}). Launch in maintenance mode to let indexes catch up", indexStats.Name, indexLag, IndexLagThresholdWarning); + logger.LogWarning("Index [{IndexStatsName}] IndexingLag {IndexLag} is above warning threshold ({IndexLagThresholdWarning}). Pause ingestion to let indexes catch up: use maintenance mode for an embedded database, or stop the instance for an external RavenDB server", indexStats.Name, indexLag, IndexLagThresholdWarning); } } } diff --git a/src/ServiceControl.Audit.Persistence.RavenDB/RavenPersistenceConfiguration.cs b/src/ServiceControl.Audit.Persistence.RavenDB/RavenPersistenceConfiguration.cs index ea6df95fdb..33144adc94 100644 --- a/src/ServiceControl.Audit.Persistence.RavenDB/RavenPersistenceConfiguration.cs +++ b/src/ServiceControl.Audit.Persistence.RavenDB/RavenPersistenceConfiguration.cs @@ -51,6 +51,11 @@ public IPersistence Create(PersistenceSettings settings) { var databaseConfiguration = GetDatabaseConfiguration(settings); + if (settings.MaintenanceMode && !databaseConfiguration.ServerConfiguration.UseEmbeddedServer) + { + throw new InvalidOperationException("Maintenance mode is not supported with an external RavenDB server. Stop the ServiceControl instance and access the database directly."); + } + return new RavenPersistence(databaseConfiguration); } diff --git a/src/ServiceControl.Audit.Persistence.RavenDB/persistence.manifest b/src/ServiceControl.Audit.Persistence.RavenDB/persistence.manifest index 75c8e5c96e..2b7383a4ad 100644 --- a/src/ServiceControl.Audit.Persistence.RavenDB/persistence.manifest +++ b/src/ServiceControl.Audit.Persistence.RavenDB/persistence.manifest @@ -16,6 +16,9 @@ { "Name": "ServiceControl.Audit/DatabaseMaintenancePort", "Mandatory": true + }, + { + "Name": "ServiceControl.Audit/EnableFullTextSearchOnBodies" } ], "SettingsWithPathsToCleanup": [ diff --git a/src/ServiceControl.Audit.Persistence.Tests.PostgreSql/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt b/src/ServiceControl.Audit.Persistence.Tests.PostgreSql/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt index 48a74dddcc..2b0028a333 100644 --- a/src/ServiceControl.Audit.Persistence.Tests.PostgreSql/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt +++ b/src/ServiceControl.Audit.Persistence.Tests.PostgreSql/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt @@ -1,3 +1,5 @@ 20260928032745_AddFullTextSearch Sql CREATE INDEX ix_audit_messages_full_text ON audit_messages USING GIN (to_tsvector('simple', headers_json || ' ' || substring(COALESCE(body_text, ''), 1, 262144) || ' ' || replace(replace(COALESCE(message_type, ''), '.', ' '), '+', ' '))) +20261126045230_AddEndpointTimeSentIndex + CreateIndex ix_audit_messages_receiving_endpoint_name_time_sent on audit_messages (receiving_endpoint_name, time_sent) diff --git a/src/ServiceControl.Audit.Persistence.Tests.RavenDB/ConfigurationValidationTests.cs b/src/ServiceControl.Audit.Persistence.Tests.RavenDB/ConfigurationValidationTests.cs index a450381824..871d223ad3 100644 --- a/src/ServiceControl.Audit.Persistence.Tests.RavenDB/ConfigurationValidationTests.cs +++ b/src/ServiceControl.Audit.Persistence.Tests.RavenDB/ConfigurationValidationTests.cs @@ -155,6 +155,38 @@ public void Should_fall_back_to_default_query_timeout_when_value_exceeds_maximum Assert.That(configuration.QueryTimeout, Is.EqualTo(TimeSpan.FromMinutes(1))); } + [Test] + public void Should_reject_maintenance_mode_with_external_server() + { + var settings = BuildSettings(); + settings.MaintenanceMode = true; + settings.PersisterSpecificSettings[RavenPersistenceConfiguration.ConnectionStringKey] = "http://someserver:44444"; + + var exception = Assert.Throws(() => new RavenPersistenceConfiguration().Create(settings)); + + Assert.That(exception.Message, Does.Contain("Maintenance mode is not supported")); + } + + [Test] + public void Should_allow_maintenance_mode_with_embedded_server() + { + var settings = BuildSettings(); + settings.MaintenanceMode = true; + settings.PersisterSpecificSettings[RavenPersistenceConfiguration.DatabasePathKey] = "c://db-path"; + settings.PersisterSpecificSettings[RavenPersistenceConfiguration.DatabaseMaintenancePortKey] = "11111"; + + Assert.That(new RavenPersistenceConfiguration().Create(settings), Is.Not.Null); + } + + [Test] + public void Should_allow_normal_mode_with_external_server() + { + var settings = BuildSettings(); + settings.PersisterSpecificSettings[RavenPersistenceConfiguration.ConnectionStringKey] = "http://someserver:44444"; + + Assert.That(new RavenPersistenceConfiguration().Create(settings), Is.Not.Null); + } + PersistenceSettings BuildSettings() { return new PersistenceSettings(TimeSpan.FromMinutes(2), true, 100000); diff --git a/src/ServiceControl.Audit.Persistence.Tests.SqlServer/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt b/src/ServiceControl.Audit.Persistence.Tests.SqlServer/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt index 16e598b9a5..01f121d2b4 100644 --- a/src/ServiceControl.Audit.Persistence.Tests.SqlServer/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt +++ b/src/ServiceControl.Audit.Persistence.Tests.SqlServer/ApprovalFiles/SlowMigrationOperationApprovals.Verify_slow_migration_operations_are_unchanged.approved.txt @@ -22,3 +22,5 @@ ON ServiceControlFullTextCatalog WITH (CHANGE_TRACKING AUTO, STOPLIST = OFF)'); END +20261126035956_AddEndpointTimeSentIndex + CreateIndex IX_AuditMessages_ReceivingEndpointName_TimeSent on AuditMessages (ReceivingEndpointName, TimeSent) diff --git a/src/ServiceControl.Audit.Persistence.Tests.SqlServer/EndpointFilterPlanReuseTests.cs b/src/ServiceControl.Audit.Persistence.Tests.SqlServer/EndpointFilterPlanReuseTests.cs new file mode 100644 index 0000000000..40b47b6294 --- /dev/null +++ b/src/ServiceControl.Audit.Persistence.Tests.SqlServer/EndpointFilterPlanReuseTests.cs @@ -0,0 +1,85 @@ +namespace ServiceControl.Audit.Persistence.Tests +{ + using System.Collections.Generic; + using System.Threading.Tasks; + using Microsoft.Data.SqlClient; + using NUnit.Framework; + using ServiceControl.Audit.Infrastructure; + + // SQL Server compiles the endpoint filter for the first endpoint asked for, then reuses that plan for every other endpoint. + class EndpointFilterPlanReuseTests : EFPersistenceTestFixture + { + [TestCase(BusyEndpoint, QuietEndpoint)] + [TestCase(QuietEndpoint, BusyEndpoint)] + public async Task The_page_for_an_endpoint_stays_cheap_on_a_plan_compiled_for_another_endpoint(string compiledFor, string listed) + { + await Seed(); + + await ListFirstPage(compiledFor); + await ListFirstPage(listed); + + var pageReads = await PageQueryReads(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(pageReads, Is.Not.Empty, "The page query was not found in the plan cache."); + Assert.That(pageReads, Has.All.LessThan(MaxReads)); + } + } + + async Task Seed() + { + await using var connection = new SqlConnection(configuration.ConnectionString); + await connection.OpenAsync(TestTimeoutCancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = $$""" + WITH n AS (SELECT TOP (50000) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1 AS i FROM sys.all_objects a CROSS JOIN sys.all_objects b) + INSERT [{{configuration.Schema}}].[AuditMessages] (CreatedOn, UniqueMessageId, TimeSent, ProcessedAt, IsSystemMessage, Status, ReceivingEndpointName, HeadersJson, BodyState, BodySize) + SELECT DATEADD(hour, -(i % 168), @hour), NEWID(), DATEADD(second, i % 3600, DATEADD(hour, -(i % 168), @hour)), DATEADD(hour, -(i % 168), @hour), 0, 1, + CASE WHEN i % 2500 = 0 THEN @quiet WHEN i % 10 < 6 THEN @busy ELSE @other END, '{}', 0, 0 + FROM n; + UPDATE STATISTICS [{{configuration.Schema}}].[AuditMessages] WITH FULLSCAN; + """; + command.Parameters.AddWithValue("@hour", TimeSent); + command.Parameters.AddWithValue("@quiet", QuietEndpoint); + command.Parameters.AddWithValue("@busy", BusyEndpoint); + command.Parameters.AddWithValue("@other", OtherEndpoint); + await command.ExecuteNonQueryAsync(TestTimeoutCancellationToken); + } + + Task ListFirstPage(string endpoint) => + MessagesViewStore.QueryMessagesByReceivingEndpoint(false, endpoint, new PagingInfo(pageSize: 100), new SortInfo("time_sent", "desc"), cancellationToken: TestTimeoutCancellationToken); + + async Task> PageQueryReads() + { + await using var connection = new SqlConnection(configuration.ConnectionString); + await connection.OpenAsync(TestTimeoutCancellationToken); + + await using var command = connection.CreateCommand(); + command.CommandText = """ + SELECT qs.last_logical_reads + FROM sys.dm_exec_query_stats AS qs + CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st + WHERE CHARINDEX(@table, st.text) > 0 AND CHARINDEX('@endpointName', st.text) > 0 AND CHARINDEX('ORDER BY', st.text) > 0 + """; + command.Parameters.AddWithValue("@table", $"[{configuration.Schema}].[AuditMessages]"); + + var reads = new List(); + await using var reader = await command.ExecuteReaderAsync(TestTimeoutCancellationToken); + while (await reader.ReadAsync(TestTimeoutCancellationToken)) + { + reads.Add(reader.GetInt64(0)); + } + + return reads; + } + + const string BusyEndpoint = "Sales"; + const string OtherEndpoint = "Billing"; + const string QuietEndpoint = "Rare"; + + // Without an index that serves both the filter and the sort, each order reads 90,000 or more. + const long MaxReads = 1_000; + } +} diff --git a/src/ServiceControl.Audit.Persistence.Tests/EFCore/AuditFileSystemBodyStorageTests.cs b/src/ServiceControl.Audit.Persistence.Tests/EFCore/AuditFileSystemBodyStorageTests.cs index 7b307b64ab..f0edcb04d7 100644 --- a/src/ServiceControl.Audit.Persistence.Tests/EFCore/AuditFileSystemBodyStorageTests.cs +++ b/src/ServiceControl.Audit.Persistence.Tests/EFCore/AuditFileSystemBodyStorageTests.cs @@ -13,18 +13,30 @@ namespace ServiceControl.Audit.Persistence.Tests.EFCore; [TestFixture] class AuditFileSystemBodyStorageTests { + const string BodyId = "6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10"; + const string BodyA = "a0000000-0000-4000-8000-00000000000a"; + const string BodyB = "b0000000-0000-4000-8000-00000000000b"; + const string BodyC = "c0000000-0000-4000-8000-00000000000c"; + const string BodyD = "d0000000-0000-4000-8000-00000000000d"; + string tempDir; + string outsideDir; AuditFileSystemBodyStorage store; [SetUp] public void SetUp() { tempDir = Directory.CreateTempSubdirectory("sc-body-tests-").FullName; + outsideDir = Directory.CreateTempSubdirectory("sc-body-outside-").FullName; store = new AuditFileSystemBodyStorage(new FileSystemBodyStorageSettings { StoragePath = tempDir, MinCompressionSize = 64 }); } [TearDown] - public void TearDown() => Directory.Delete(tempDir, recursive: true); + public void TearDown() + { + Directory.Delete(tempDir, recursive: true); + Directory.Delete(outsideDir, recursive: true); + } static readonly DateTime Hour10 = new(2026, 10, 20, 10, 0, 0, DateTimeKind.Utc); static readonly DateTime Hour11 = Hour10.AddHours(1); @@ -34,9 +46,9 @@ public void SetUp() public async Task Round_trips_compressed_and_uncompressed_bodies(int bodyLength) { var body = Encoding.UTF8.GetBytes(new string('a', bodyLength)); - await store.WriteBody("body-1", Hour10, body, "application/json"); + await store.WriteBody(BodyId, Hour10, body, "application/json"); - var result = await store.ReadBody("body-1", Hour10); + var result = await store.ReadBody(BodyId, Hour10); Assert.That(result, Is.Not.Null); using (result.Stream) @@ -52,12 +64,12 @@ public async Task Round_trips_compressed_and_uncompressed_bodies(int bodyLength) } [Test] - public async Task Body_is_stored_in_the_directory_of_its_explicit_hour_whatever_the_id() + public async Task Body_is_stored_in_the_directory_of_its_explicit_hour() { - await store.WriteBody("opaque", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); + await store.WriteBody(BodyId, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); - Assert.That(Relative(), Is.EqualTo(new[] { Path.Combine("2026102010", "opaque.body") })); - var result = await store.ReadBody("opaque", Hour10); + Assert.That(Relative(), Is.EqualTo(new[] { Path.Combine("2026102010", $"{BodyId}.body") })); + var result = await store.ReadBody(BodyId, Hour10); Assert.That(result, Is.Not.Null); result.Stream.Dispose(); } @@ -65,11 +77,11 @@ public async Task Body_is_stored_in_the_directory_of_its_explicit_hour_whatever_ [Test] public async Task Bodies_with_the_same_id_in_different_hours_are_distinct() { - await store.WriteBody("same", Hour10, Encoding.UTF8.GetBytes("ten"), "text/plain"); - await store.WriteBody("same", Hour11, Encoding.UTF8.GetBytes("eleven"), "text/plain"); + await store.WriteBody(BodyId, Hour10, Encoding.UTF8.GetBytes("ten"), "text/plain"); + await store.WriteBody(BodyId, Hour11, Encoding.UTF8.GetBytes("eleven"), "text/plain"); - using var ten = (await store.ReadBody("same", Hour10)).Stream; - using var eleven = (await store.ReadBody("same", Hour11)).Stream; + using var ten = (await store.ReadBody(BodyId, Hour10)).Stream; + using var eleven = (await store.ReadBody(BodyId, Hour11)).Stream; Assert.Multiple(() => { @@ -81,18 +93,18 @@ public async Task Bodies_with_the_same_id_in_different_hours_are_distinct() [Test] public async Task Read_for_another_hour_finds_nothing() { - await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); + await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); - Assert.That(await store.ReadBody("a", Hour11), Is.Null); - Assert.That(await store.ReadBody("a", Hour10.AddDays(-1)), Is.Null); + Assert.That(await store.ReadBody(BodyA, Hour11), Is.Null); + Assert.That(await store.ReadBody(BodyA, Hour10.AddDays(-1)), Is.Null); } [Test] public async Task Read_with_an_unspecified_kind_finds_the_body_of_the_same_clock_hour() { - await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); + await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); - var result = await store.ReadBody("a", DateTime.SpecifyKind(Hour10, DateTimeKind.Unspecified)); + var result = await store.ReadBody(BodyA, DateTime.SpecifyKind(Hour10, DateTimeKind.Unspecified)); Assert.That(result, Is.Not.Null); result.Stream.Dispose(); @@ -101,10 +113,10 @@ public async Task Read_with_an_unspecified_kind_finds_the_body_of_the_same_clock [Test] public async Task Rewriting_a_body_keeps_the_first_write() { - await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("original"), "text/plain"); - await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("different"), "text/plain"); + await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("original"), "text/plain"); + await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("different"), "text/plain"); - using var result = (await store.ReadBody("a", Hour10)).Stream; + using var result = (await store.ReadBody(BodyA, Hour10)).Stream; Assert.That(ReadAll(result), Is.EqualTo(Encoding.UTF8.GetBytes("original"))); } @@ -113,9 +125,9 @@ public async Task Rewriting_a_body_keeps_the_first_write() public async Task Delete_for_hour_removes_only_that_hour() { var body = Encoding.UTF8.GetBytes("payload"); - await store.WriteBody("a", Hour10, body, "text/plain"); - await store.WriteBody("b", Hour10, body, "text/plain"); - await store.WriteBody("a", Hour11, body, "text/plain"); + await store.WriteBody(BodyA, Hour10, body, "text/plain"); + await store.WriteBody(BodyB, Hour10, body, "text/plain"); + await store.WriteBody(BodyA, Hour11, body, "text/plain"); var unrelated = Path.Combine(tempDir, "flat.body"); await File.WriteAllTextAsync(unrelated, "keep"); @@ -123,7 +135,7 @@ public async Task Delete_for_hour_removes_only_that_hour() Assert.Multiple(() => { - Assert.That(Relative(), Is.EquivalentTo(new[] { Path.Combine("2026102011", "a.body"), "flat.body" })); + Assert.That(Relative(), Is.EquivalentTo(new[] { Path.Combine("2026102011", $"{BodyA}.body"), "flat.body" })); Assert.That(Directory.Exists(Path.Combine(tempDir, "2026102010")), Is.False); }); } @@ -131,10 +143,10 @@ public async Task Delete_for_hour_removes_only_that_hour() [Test] public async Task Delete_for_hour_also_removes_temp_files_in_that_hour_only() { - await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); - await store.WriteBody("a", Hour11, Encoding.UTF8.GetBytes("payload"), "text/plain"); - await File.WriteAllTextAsync(Path.Combine(tempDir, "2026102010", "a.body.abc.tmp"), "in progress"); - var otherTemp = Path.Combine(tempDir, "2026102011", "a.body.abc.tmp"); + await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); + await store.WriteBody(BodyA, Hour11, Encoding.UTF8.GetBytes("payload"), "text/plain"); + await File.WriteAllTextAsync(Path.Combine(tempDir, "2026102010", $"{BodyA}.body.abc.tmp"), "in progress"); + var otherTemp = Path.Combine(tempDir, "2026102011", $"{BodyA}.body.abc.tmp"); await File.WriteAllTextAsync(otherTemp, "in progress"); var rootFile = Path.Combine(tempDir, "unrelated.txt"); await File.WriteAllTextAsync(rootFile, "keep"); @@ -153,17 +165,17 @@ public async Task Delete_for_hour_also_removes_temp_files_in_that_hour_only() public async Task Delete_for_day_removes_every_hour_of_that_day_and_no_other() { var body = Encoding.UTF8.GetBytes("payload"); - await store.WriteBody("a", Hour10.Date, body, "text/plain"); - await store.WriteBody("b", Hour10.Date.AddHours(23), body, "text/plain"); - await store.WriteBody("c", Hour10.Date.AddDays(1), body, "text/plain"); - await store.WriteBody("d", Hour10.Date.AddHours(-1), body, "text/plain"); + await store.WriteBody(BodyA, Hour10.Date, body, "text/plain"); + await store.WriteBody(BodyB, Hour10.Date.AddHours(23), body, "text/plain"); + await store.WriteBody(BodyC, Hour10.Date.AddDays(1), body, "text/plain"); + await store.WriteBody(BodyD, Hour10.Date.AddHours(-1), body, "text/plain"); Directory.CreateDirectory(Path.Combine(tempDir, "20261020-unrelated")); await store.DeleteBodiesForDay(Hour10); Assert.Multiple(() => { - Assert.That(Relative(), Is.EquivalentTo(new[] { Path.Combine("2026102100", "c.body"), Path.Combine("2026101923", "d.body") })); + Assert.That(Relative(), Is.EquivalentTo(new[] { Path.Combine("2026102100", $"{BodyC}.body"), Path.Combine("2026101923", $"{BodyD}.body") })); Assert.That(Directory.Exists(Path.Combine(tempDir, "20261020-unrelated")), Is.True); }); } @@ -178,7 +190,7 @@ public void Delete_succeeds_when_nothing_is_stored() [Test] public async Task Delete_honors_cancellation() { - await store.WriteBody("a", Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); + await store.WriteBody(BodyA, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain"); using var cts = new CancellationTokenSource(); await cts.CancelAsync(); @@ -187,6 +199,40 @@ public async Task Delete_honors_cancellation() Assert.That(Relative(), Has.Length.EqualTo(1)); } + [TestCase(null)] + [TestCase("")] + [TestCase("body-1")] + [TestCase("../6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("..\\6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("/etc/6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("C:\\temp\\6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("failedimport-6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("outside-relative")] + [TestCase("outside-rooted")] + public async Task Invalid_body_ids_are_rejected_without_touching_the_file_system(string bodyId) + { + var outsideFile = Path.Combine(outsideDir, "target.body"); + await File.WriteAllTextAsync(outsideFile, "keep"); + bodyId = bodyId switch + { + "outside-relative" => Path.GetRelativePath(Path.Combine(tempDir, "2026102010"), Path.Combine(outsideDir, "target")), + "outside-rooted" => Path.Combine(outsideDir, "target"), + _ => bodyId + }; + + var write = Assert.ThrowsAsync(() => store.WriteBody(bodyId, Hour10, Encoding.UTF8.GetBytes("payload"), "text/plain")); + var read = Assert.ThrowsAsync(() => store.ReadBody(bodyId, Hour10)); + + Assert.Multiple(() => + { + Assert.That(write.ParamName, Is.EqualTo("bodyId")); + Assert.That(read.ParamName, Is.EqualTo("bodyId")); + Assert.That(Directory.GetFileSystemEntries(tempDir), Is.Empty); + Assert.That(Directory.GetFileSystemEntries(outsideDir), Is.EqualTo(new[] { outsideFile })); + Assert.That(File.ReadAllText(outsideFile), Is.EqualTo("keep")); + }); + } + string[] Relative() => Directory.GetFiles(tempDir, "*", SearchOption.AllDirectories).Select(f => Path.GetRelativePath(tempDir, f)).ToArray(); static byte[] ReadAll(Stream stream) diff --git a/src/ServiceControl.Audit.Persistence/PersistenceManifest.cs b/src/ServiceControl.Audit.Persistence/PersistenceManifest.cs index 45b5d89572..7aeb0d5801 100644 --- a/src/ServiceControl.Audit.Persistence/PersistenceManifest.cs +++ b/src/ServiceControl.Audit.Persistence/PersistenceManifest.cs @@ -26,10 +26,10 @@ public class PersistenceManifest public string[] Aliases { get; set; } = []; - internal bool IsMatch(string persistenceType) => - string.Equals(TypeName, persistenceType, StringComparison.Ordinal) // Type names are case-sensitive - || string.Equals(Name, persistenceType, StringComparison.OrdinalIgnoreCase) - || Aliases.Contains(persistenceType, StringComparer.Ordinal); + internal bool IsMatch(string storageType) => + string.Equals(TypeName, storageType, StringComparison.Ordinal) // Type names are case-sensitive + || string.Equals(Name, storageType, StringComparison.OrdinalIgnoreCase) + || Aliases.Contains(storageType, StringComparer.Ordinal); } public static class PersistenceManifestLibrary @@ -95,14 +95,14 @@ static string GetAssemblyDirectory() return Path.GetDirectoryName(assemblyLocation); } - public static PersistenceManifest Find(string persistenceType) + public static PersistenceManifest Find(string storageType) { - if (persistenceType == null) + if (storageType == null) { - throw new Exception("No persistenceType has been configured. Either provide a Type or Name in the PersistenceType setting."); + throw new Exception("No storageType has been configured. Either provide a Type or Name in the StorageType setting."); } - var persistenceManifest = PersistenceManifests.FirstOrDefault(w => w.IsMatch(persistenceType)); + var persistenceManifest = PersistenceManifests.FirstOrDefault(w => w.IsMatch(storageType)); return persistenceManifest; } diff --git a/src/ServiceControl.Audit.UnitTests/ApprovalFiles/APIApprovals.PlatformSampleSettings.approved.txt b/src/ServiceControl.Audit.UnitTests/ApprovalFiles/APIApprovals.PlatformSampleSettings.approved.txt index f0948c181f..25643e8f0a 100644 --- a/src/ServiceControl.Audit.UnitTests/ApprovalFiles/APIApprovals.PlatformSampleSettings.approved.txt +++ b/src/ServiceControl.Audit.UnitTests/ApprovalFiles/APIApprovals.PlatformSampleSettings.approved.txt @@ -50,7 +50,7 @@ "Hostname": "localhost", "VirtualDirectory": "", "TransportType": "LearningTransport", - "PersistenceType": "RavenDB", + "StorageType": "RavenDB", "AuditQueue": "audit", "ForwardAuditMessages": false, "IngestAuditMessages": true, diff --git a/src/ServiceControl.Audit.UnitTests/Infrastructure/PersistenceManifestLibraryTests.cs b/src/ServiceControl.Audit.UnitTests/Infrastructure/PersistenceManifestLibraryTests.cs index 19b5559ece..8c23889787 100644 --- a/src/ServiceControl.Audit.UnitTests/Infrastructure/PersistenceManifestLibraryTests.cs +++ b/src/ServiceControl.Audit.UnitTests/Infrastructure/PersistenceManifestLibraryTests.cs @@ -33,8 +33,8 @@ public void Should_find_persistence_manifest_by_type() [Test] public void Should_return_null_for_not_found_persistence_type() { - var fakePersistenceType = "My.fake.persistence, fakeTransportAssembly"; - var persistenceManifest = PersistenceManifestLibrary.Find(fakePersistenceType); + var fakeStorageType = "My.fake.persistence, fakeTransportAssembly"; + var persistenceManifest = PersistenceManifestLibrary.Find(fakeStorageType); Assert.That(persistenceManifest, Is.Null); } diff --git a/src/ServiceControl.Audit.UnitTests/Infrastructure/WebApi/RootControllerConfigurationTests.cs b/src/ServiceControl.Audit.UnitTests/Infrastructure/WebApi/RootControllerConfigurationTests.cs new file mode 100644 index 0000000000..3918724766 --- /dev/null +++ b/src/ServiceControl.Audit.UnitTests/Infrastructure/WebApi/RootControllerConfigurationTests.cs @@ -0,0 +1,27 @@ +namespace ServiceControl.Audit.UnitTests.Infrastructure.WebApi +{ + using System.Text.Json; + using Audit.Infrastructure.WebApi; + using Audit.Infrastructure.Settings; + using NUnit.Framework; + + [TestFixture] + class RootControllerConfigurationTests + { + const string RavenDbAlias = "ServiceControl.Audit.Persistence.RavenDb.RavenDbPersistenceConfiguration, ServiceControl.Audit.Persistence.RavenDb5"; + + [Test] + public void Reports_the_manifest_name_of_the_storage_type_and_no_persistence_section() + { + var controller = new RootController(new Settings(storageType: RavenDbAlias)); + + var json = JsonSerializer.SerializeToNode(controller.Config().Value, SerializerOptions.Default).AsObject(); + + Assert.Multiple(() => + { + Assert.That((string)json["storage"]["storage_type"], Is.EqualTo("RavenDB")); + Assert.That(json.ContainsKey("persistence"), Is.False); + }); + } + } +} diff --git a/src/ServiceControl.Audit/App.config b/src/ServiceControl.Audit/App.config index 18f35bd6c5..e2284f20d8 100644 --- a/src/ServiceControl.Audit/App.config +++ b/src/ServiceControl.Audit/App.config @@ -18,10 +18,10 @@ These settings are only here so that we can debug ServiceControl while developin - - - - + + + + diff --git a/src/ServiceControl.Audit/Container-README.md b/src/ServiceControl.Audit/Container-README.md index 51a56d36fd..e5f1d21996 100644 --- a/src/ServiceControl.Audit/Container-README.md +++ b/src/ServiceControl.Audit/Container-README.md @@ -7,21 +7,40 @@ The `particular/servicecontrol-audit` image is part of the Particular Service Pl | [`particular/servicecontrol`](https://hub.docker.com/r/particular/servicecontrol) | [Instance Documentation](https://docs.particular.net/servicecontrol/servicecontrol-instances/)
[Container Documentation](https://docs.particular.net/servicecontrol/servicecontrol-instances/deployment/containers) | The primary/error instance, which includes error handling and recoverability | | [`particular/servicecontrol-audit`](https://hub.docker.com/r/particular/servicecontrol-audit) | [Instance Documentation](https://docs.particular.net/servicecontrol/audit-instances/)
[Container Documentation](https://docs.particular.net/servicecontrol/audit-instances/deployment/containers) | The audit instance, which stores audit data, and can be scaled out to multiple audit instances | | [`particular/servicecontrol-monitoring`](https://hub.docker.com/r/particular/servicecontrol-monitoring) | [Instance Documentation](https://docs.particular.net/servicecontrol/monitoring-instances/)
[Container Documentation](https://docs.particular.net/servicecontrol/monitoring-instances/deployment/containers) | The monitoring instance, which tracks runtime information like throughput, queue length, and other metrics | -| [`particular/servicecontrol-ravendb`](https://hub.docker.com/r/particular/servicecontrol-ravendb) | [Container Documentation](https://docs.particular.net/servicecontrol/ravendb/containers) | The database used by the error/audit instances | +| [`particular/servicecontrol-ravendb`](https://hub.docker.com/r/particular/servicecontrol-ravendb) | [Container Documentation](https://docs.particular.net/servicecontrol/storage/ravendb/containers) | The database for error/audit instances using RavenDB persistence | | [`particular/servicepulse`](https://hub.docker.com/r/particular/servicepulse) | [App Documentation](https://docs.particular.net/servicepulse/)
[Container Documentation](https://docs.particular.net/servicepulse/containerization/) | The web application that provides a front end for recoverability and monitoring features | ## Usage -The following is the most basic way to create an audit container using [Docker](https://www.docker.com/), assuming a RabbitMQ message broker also hosted in a Docker container using default `guest`/`guest` credentials: +The following minimal example uses `docker run` to host an Audit instance on Azure, with [Azure Service Bus](https://docs.particular.net/servicecontrol/transports.md#azure-service-bus) as the transport, Azure SQL Database for [SQL Server storage](https://docs.particular.net/servicecontrol/storage/sqlserver/), and [Azure Blob Storage](https://docs.particular.net/servicecontrol/storage/external-body/azure-blob.md) for message bodies: ```shell docker run -d --name audit -p 44444:44444 \ - -e TRANSPORTTYPE=RabbitMQ.QuorumConventionalRouting \ - -e CONNECTIONSTRING="host=rabbitmq" \ - -e RAVENDB_CONNECTIONSTRING="http://audit-db:8080" \ - particular/servicecontrol-audit:latest --setup-and-run + -e TRANSPORTTYPE=NetStandardAzureServiceBus \ + -e CONNECTIONSTRING="Endpoint=sb://my-namespace.servicebus.windows.net/;SharedAccessKeyName=...;SharedAccessKey=..." \ + -e STORAGETYPE=SQLServer \ + -e DATABASE_CONNECTIONSTRING="Server=tcp:my-server.database.windows.net,1433;Database=ServiceControl.Audit;User ID=...;Password=...;Encrypt=True" \ + -e MESSAGEBODY_STORAGETYPE=AzureBlob \ + -e MESSAGEBODY_AZURE_CONNECTIONSTRING="DefaultEndpointsProtocol=https;AccountName=mystorageaccount;AccountKey=...;EndpointSuffix=core.windows.net" \ + particular/servicecontrol-audit:latest ``` +Each of these services can also use [managed identity](https://docs.particular.net/servicecontrol/transports.md#azure-service-bus-enabling-managed-identity) instead of the keys and passwords shown; see [SQL Server authentication](https://docs.particular.net/servicecontrol/storage/sqlserver/#authentication) and [Azure Blob Storage authentication](https://docs.particular.net/servicecontrol/storage/external-body/azure-blob.md#authentication). + +### Storage + +`STORAGETYPE` is required. Prepare the storage as the provider's guide describes before running setup. + +| `STORAGETYPE` | Connection string environment variable | Configuration | +|---------------|----------------------------------------|---------------| +| `RavenDB` | `RAVENDB_CONNECTIONSTRING` | [RavenDB container setup](https://docs.particular.net/servicecontrol/storage/ravendb/containers) | +| `SQLServer` | `DATABASE_CONNECTIONSTRING` | [Configure SQL Server storage](https://docs.particular.net/servicecontrol/storage/sqlserver/) | +| `PostgreSQL` | `DATABASE_CONNECTIONSTRING` | [Configure PostgreSQL storage](https://docs.particular.net/servicecontrol/storage/postgresql/) | + +With SQL Server or PostgreSQL, the database keeps only text message bodies up to `MAXBODYSIZETOSTORE` bytes. To keep larger and binary bodies, configure [external message body storage](https://docs.particular.net/servicecontrol/storage/external-body/) with `MESSAGEBODY_STORAGETYPE`. The [storage overview](https://docs.particular.net/servicecontrol/storage/#sharing-a-database) explains how Error and Audit instances can share a database. + +These settings also accept the `SERVICECONTROL_AUDIT_` prefix, for example `SERVICECONTROL_AUDIT_STORAGETYPE` and `SERVICECONTROL_AUDIT_DATABASE_CONNECTIONSTRING`. Use prefixed settings when error and audit containers share environment configuration but need different persistence settings. + For all other usage information see the [official container documentation](https://docs.particular.net/servicecontrol/audit-instances/deployment/containers). ## Image tagging diff --git a/src/ServiceControl.Audit/Dockerfile b/src/ServiceControl.Audit/Dockerfile index 4dee310716..8d1778629b 100644 --- a/src/ServiceControl.Audit/Dockerfile +++ b/src/ServiceControl.Audit/Dockerfile @@ -19,7 +19,7 @@ EXPOSE 44444 COPY --from=build /deploy/Particular.ServiceControl.Audit /app COPY --from=build /healthcheck /healthcheck -ENV PersistenceType=RavenDB \ +ENV StorageType=RavenDB \ AuditRetentionPeriod=7 HEALTHCHECK --start-period=10s CMD ["/healthcheck/healthcheck", "http://localhost:44444/api/configuration"] diff --git a/src/ServiceControl.Audit/HostApplicationBuilderExtensions.cs b/src/ServiceControl.Audit/HostApplicationBuilderExtensions.cs index be2856badd..e0c0c6d527 100644 --- a/src/ServiceControl.Audit/HostApplicationBuilderExtensions.cs +++ b/src/ServiceControl.Audit/HostApplicationBuilderExtensions.cs @@ -136,7 +136,7 @@ static void RecordStartup(Settings settings, EndpointConfiguration endpointConfi Forwarding Audit Messages: {settings.ForwardAuditMessages} ServiceControl Logging Level: {settings.LoggingSettings.LogLevel} Transport Customization: {settings.TransportType}, -Persistence Customization: {settings.PersistenceType}, +Persistence Customization: {settings.StorageType}, Persistence: {persistenceConfiguration.Name} -------------------------------------------------------------"; diff --git a/src/ServiceControl.Audit/Infrastructure/Hosting/Commands/MaintenanceModeCommand.cs b/src/ServiceControl.Audit/Infrastructure/Hosting/Commands/MaintenanceModeCommand.cs index a868a3bfbb..abdf0e78fd 100644 --- a/src/ServiceControl.Audit/Infrastructure/Hosting/Commands/MaintenanceModeCommand.cs +++ b/src/ServiceControl.Audit/Infrastructure/Hosting/Commands/MaintenanceModeCommand.cs @@ -16,7 +16,7 @@ public override async Task Execute(HostArguments args, Settings settings, Cancel var persistenceConfiguration = PersistenceConfigurationFactory.LoadPersistenceConfiguration(settings); if (!persistenceConfiguration.SupportsMaintenanceMode) { - throw new InvalidOperationException($"Maintenance mode is not supported by the {settings.PersistenceType} persister."); + throw new InvalidOperationException($"Maintenance mode is not supported by the {settings.StorageType} storage type."); } var persistenceSettings = persistenceConfiguration.BuildPersistenceSettings(settings); diff --git a/src/ServiceControl.Audit/Infrastructure/Settings/Settings.cs b/src/ServiceControl.Audit/Infrastructure/Settings/Settings.cs index da096a3720..88a1ddd7c9 100644 --- a/src/ServiceControl.Audit/Infrastructure/Settings/Settings.cs +++ b/src/ServiceControl.Audit/Infrastructure/Settings/Settings.cs @@ -14,7 +14,7 @@ public class Settings { - public Settings(string transportType = null, string persisterType = null, LoggingSettings loggingSettings = null) + public Settings(string transportType = null, string storageType = null, LoggingSettings loggingSettings = null) { LoggingSettings = loggingSettings ?? new(SettingsRootNamespace); @@ -31,7 +31,7 @@ public Settings(string transportType = null, string persisterType = null, Loggin TransportType = transportType ?? SettingsReader.Read(SettingsRootNamespace, "TransportType"); - PersistenceType = persisterType ?? SettingsReader.Read(SettingsRootNamespace, "PersistenceType"); + StorageType = storageType ?? SettingsReader.Read(SettingsRootNamespace, "StorageType"); TransportConnectionString = GetConnectionString(); @@ -153,7 +153,7 @@ public string RootUrl public string TransportType { get; private set; } - public string PersistenceType { get; private set; } + public string StorageType { get; private set; } public string AuditQueue { get; set; } diff --git a/src/ServiceControl.Audit/Infrastructure/WebApi/RootController.cs b/src/ServiceControl.Audit/Infrastructure/WebApi/RootController.cs index 6334d612a6..23e23208b1 100644 --- a/src/ServiceControl.Audit/Infrastructure/WebApi/RootController.cs +++ b/src/ServiceControl.Audit/Infrastructure/WebApi/RootController.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Mvc; + using Persistence; using Settings; // the /api endpoint is used for service-to-service communication. This currently needs to be anonymous @@ -74,9 +75,9 @@ public OkObjectResult Config() settings.AuditQueue, settings.ForwardAuditMessages }, - Persistence = new + Storage = new { - settings.PersistenceType + StorageType = PersistenceManifestLibrary.Find(settings.StorageType)?.Name }, Plugins = new { diff --git a/src/ServiceControl.Audit/Persistence/PersistenceConfigurationFactory.cs b/src/ServiceControl.Audit/Persistence/PersistenceConfigurationFactory.cs index d79ee76fe0..8723ea97f1 100644 --- a/src/ServiceControl.Audit/Persistence/PersistenceConfigurationFactory.cs +++ b/src/ServiceControl.Audit/Persistence/PersistenceConfigurationFactory.cs @@ -11,7 +11,7 @@ public static IPersistenceConfiguration LoadPersistenceConfiguration(Settings se { try { - var persistenceManifest = PersistenceManifestLibrary.Find(settings.PersistenceType); + var persistenceManifest = PersistenceManifestLibrary.Find(settings.StorageType); var assemblyPath = Path.Combine(persistenceManifest.Location, $"{persistenceManifest.AssemblyName}.dll"); var loadContext = settings.AssemblyLoadContextResolver(assemblyPath); var customizationType = Type.GetType(persistenceManifest.TypeName, loadContext.LoadFromAssemblyName, null, true); @@ -20,7 +20,7 @@ public static IPersistenceConfiguration LoadPersistenceConfiguration(Settings se } catch (Exception e) { - throw new Exception($"Could not load persistence customization type {settings.PersistenceType}.", e); + throw new Exception($"Could not load persistence customization type {settings.StorageType}.", e); } } diff --git a/src/ServiceControl.Config.Tests/ServiceControlAddScreenLoadedTests.cs b/src/ServiceControl.Config.Tests/ServiceControlAddScreenLoadedTests.cs index cf18a3c496..e4515fb079 100644 --- a/src/ServiceControl.Config.Tests/ServiceControlAddScreenLoadedTests.cs +++ b/src/ServiceControl.Config.Tests/ServiceControlAddScreenLoadedTests.cs @@ -37,6 +37,168 @@ public void Transports_are_populated() } } + [Test] + public void Storage_types_are_offered_with_no_default_selection() + { + var viewModel = new ServiceControlAddViewModel(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(viewModel.StorageTypes.Select(m => m.Name), Is.EquivalentTo(new[] { "PostgreSQL", "RavenDB", "SQLServer" })); + Assert.That(viewModel.SelectedStorageType, Is.Null); + Assert.That(viewModel.ShowStorageTypePicker, Is.True); + Assert.That(viewModel.ErrorSelectedStorageType, Is.Null); + Assert.That(viewModel.ShowErrorStorageConnectionString, Is.False); + Assert.That(viewModel.AuditSelectedStorageType, Is.Null); + Assert.That(viewModel.ShowAuditStorageConnectionString, Is.False); + } + } + + [TestCase("RavenDB")] + [TestCase("SQLServer")] + [TestCase("PostgreSQL")] + public void Selecting_a_storage_type_applies_it_to_both_instances(string storageTypeName) + { + var viewModel = new ServiceControlAddViewModel(); + var raisedPropertyNames = new System.Collections.Generic.HashSet(); + viewModel.PropertyChanged += (_, e) => raisedPropertyNames.Add(e.PropertyName); + + viewModel.SelectedStorageType = viewModel.StorageTypes.Single(m => m.Name == storageTypeName); + + using (Assert.EnterMultipleScope()) + { + Assert.That(viewModel.ErrorSelectedStorageType, Is.SameAs(ServiceControlInstaller.Engine.Instances.ServiceControlPersisters.GetPrimaryPersistence(storageTypeName))); + Assert.That(viewModel.AuditSelectedStorageType, Is.SameAs(ServiceControlInstaller.Engine.Instances.ServiceControlPersisters.GetAuditPersistence(storageTypeName))); + Assert.That(raisedPropertyNames, Does.Contain(nameof(viewModel.SelectedStorageType))); + Assert.That(raisedPropertyNames, Does.Contain(nameof(viewModel.ShowAuditStorageSettings))); + Assert.That(raisedPropertyNames, Does.Contain(nameof(viewModel.ShowAuditStorageConnectionStringEntry))); + Assert.That(raisedPropertyNames, Does.Contain(nameof(viewModel.ShowStorageConnectionString))); + Assert.That(raisedPropertyNames, Does.Contain(nameof(viewModel.ShowStorageSettings))); + } + } + + [Test] + public void Changing_storage_type_notifies_bound_visibility_properties() + { + var viewModel = new ServiceControlAddViewModel(); + var raisedPropertyNames = new System.Collections.Generic.HashSet(); + viewModel.PropertyChanged += (_, e) => raisedPropertyNames.Add(e.PropertyName); + + viewModel.ErrorSelectedStorageType = ServiceControlInstaller.Engine.Instances.ServiceControlPersisters.GetPrimaryPersistence("SQLServer"); + + using (Assert.EnterMultipleScope()) + { + // These are what the XAML's Visibility bindings actually listen to - if WPF never + // hears these changed, the connection string box silently never appears/disappears, + // even though the underlying ErrorSelectedStorageType value is correct. + Assert.That(raisedPropertyNames, Does.Contain(nameof(viewModel.ShowErrorStorageConnectionString))); + Assert.That(raisedPropertyNames, Does.Contain(nameof(viewModel.ShowErrorDatabasePathFields))); + Assert.That(viewModel.ShowErrorStorageConnectionString, Is.True); + } + } + + [TestCase("RavenDB", true)] + [TestCase("SQLServer", false)] + [TestCase("PostgreSQL", false)] + public void Database_maintenance_port_is_shown_only_for_RavenDB(string storageTypeName, bool expected) + { + var viewModel = new ServiceControlAddViewModel + { + ErrorSelectedStorageType = ServiceControlInstaller.Engine.Instances.ServiceControlPersisters.GetPrimaryPersistence(storageTypeName), + AuditSelectedStorageType = ServiceControlInstaller.Engine.Instances.ServiceControlPersisters.GetAuditPersistence(storageTypeName) + }; + + using (Assert.EnterMultipleScope()) + { + Assert.That(viewModel.ShowErrorDatabaseMaintenancePort, Is.EqualTo(expected)); + Assert.That(viewModel.ShowAuditDatabaseMaintenancePort, Is.EqualTo(expected)); + } + } + + [TestCase("RavenDB", true)] + [TestCase("SQLServer", false)] + [TestCase("PostgreSQL", false)] + public void Full_text_search_option_is_shown_only_for_RavenDB(string storageTypeName, bool expected) + { + var viewModel = new ServiceControlAddViewModel + { + ErrorSelectedStorageType = ServiceControlInstaller.Engine.Instances.ServiceControlPersisters.GetPrimaryPersistence(storageTypeName), + AuditSelectedStorageType = ServiceControlInstaller.Engine.Instances.ServiceControlPersisters.GetAuditPersistence(storageTypeName) + }; + + using (Assert.EnterMultipleScope()) + { + Assert.That(viewModel.ShowErrorFullTextSearchOnBodies, Is.EqualTo(expected)); + Assert.That(viewModel.ShowAuditFullTextSearchOnBodies, Is.EqualTo(expected)); + } + } + + [Test] + public void Message_body_path_is_shown_only_for_storage_types_that_support_it() + { + var viewModel = new ServiceControlAddViewModel(); + + viewModel.ErrorSelectedStorageType = ServiceControlInstaller.Engine.Instances.ServiceControlPersisters.GetPrimaryPersistence("RavenDB"); + Assert.That(viewModel.ShowErrorMessageBodyPath, Is.False); + + viewModel.ErrorSelectedStorageType = ServiceControlInstaller.Engine.Instances.ServiceControlPersisters.GetPrimaryPersistence("SQLServer"); + + using (Assert.EnterMultipleScope()) + { + Assert.That(viewModel.ShowErrorMessageBodyPath, Is.True); + Assert.That(viewModel.ErrorMessageBodyPath, Does.StartWith(programDataPath).And.EndWith("MessageBodies")); + } + } + + [Test] + public void Audit_message_body_storage_is_shown_for_SQL_Server_with_its_own_default_path() + { + var viewModel = new ServiceControlAddViewModel + { + AuditSelectedStorageType = ServiceControlInstaller.Engine.Instances.ServiceControlPersisters.GetAuditPersistence("SQLServer") + }; + + using (Assert.EnterMultipleScope()) + { + Assert.That(viewModel.ShowAuditMessageBodyPath, Is.True); + Assert.That(viewModel.AuditMessageBodyPath, Does.StartWith(programDataPath).And.EndWith("MessageBodies")); + Assert.That(viewModel.AuditMessageBodyPath, Is.Not.EqualTo(viewModel.ErrorMessageBodyPath)); + } + } + + [Test] + public void Both_instances_store_message_bodies_on_the_file_system() + { + var viewModel = new ServiceControlAddViewModel + { + SelectedStorageType = ServiceControlInstaller.Engine.Instances.ServiceControlPersisters.GetPrimaryPersistence("SQLServer"), + ErrorMessageBodyPath = @"D:\ErrorBodies", + AuditMessageBodyPath = @"D:\AuditBodies" + }; + + var errorStorage = viewModel.ServiceControl.CreateMessageBodyStorage(); + var auditStorage = viewModel.ServiceControlAudit.CreateMessageBodyStorage(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(errorStorage.StorageType, Is.EqualTo(ServiceControlInstaller.Engine.Instances.MessageBodyStorageType.FileSystem)); + Assert.That(errorStorage.FileSystemStoragePath, Is.EqualTo(@"D:\ErrorBodies")); + Assert.That(auditStorage.StorageType, Is.EqualTo(ServiceControlInstaller.Engine.Instances.MessageBodyStorageType.FileSystem)); + Assert.That(auditStorage.FileSystemStoragePath, Is.EqualTo(@"D:\AuditBodies")); + } + } + + [Test] + public void Message_body_storage_is_not_created_for_RavenDB() + { + var viewModel = new ServiceControlAddViewModel + { + ErrorSelectedStorageType = ServiceControlInstaller.Engine.Instances.ServiceControlPersisters.GetPrimaryPersistence("RavenDB") + }; + + Assert.That(viewModel.ServiceControl.CreateMessageBodyStorage(), Is.Null); + } + [Test] public void Transport_connection_string_is_null() { diff --git a/src/ServiceControl.Config.Tests/Validation/AddAuditInstanceValidationTests.cs b/src/ServiceControl.Config.Tests/Validation/AddAuditInstanceValidationTests.cs index 449208f04a..99896aa476 100644 --- a/src/ServiceControl.Config.Tests/Validation/AddAuditInstanceValidationTests.cs +++ b/src/ServiceControl.Config.Tests/Validation/AddAuditInstanceValidationTests.cs @@ -151,6 +151,135 @@ public void #endregion + #region storagetype + + [Test] + public void Storage_type_cannot_be_empty_when_adding_audit_instance() + { + var viewModel = new ServiceControlAddViewModel + { + InstallAuditInstance = true, + InstallErrorInstance = false, + SubmitAttempted = true, + SelectedStorageType = null + }; + + viewModel.NotifyOfPropertyChange(nameof(viewModel.SelectedStorageType)); + + var notifyErrorInfo = GetNotifyErrorInfo(viewModel); + var errors = notifyErrorInfo.GetErrors(nameof(viewModel.SelectedStorageType)); + + Assert.That(errors, Is.Not.Empty); + } + + [TestCase("SQLServer")] + [TestCase("PostgreSQL")] + public void Storage_connection_string_cannot_be_empty_for_storage_types_that_require_one_when_adding_audit_instance(string storageTypeName) + { + var viewModel = new ServiceControlAddViewModel + { + InstallAuditInstance = true, + InstallErrorInstance = false, + SelectedStorageType = ServiceControlPersisters.GetPrimaryPersistence(storageTypeName), + SubmitAttempted = true, + StorageConnectionString = string.Empty + }; + + var notifyErrorInfo = GetNotifyErrorInfo(viewModel); + var errors = notifyErrorInfo.GetErrors(nameof(viewModel.StorageConnectionString)); + + Assert.That(errors, Is.Not.Empty); + } + + [Test] + public void Storage_connection_string_can_be_empty_for_RavenDB_when_adding_audit_instance() + { + var viewModel = new ServiceControlAddViewModel + { + InstallAuditInstance = true, + SelectedStorageType = ServiceControlPersisters.GetPrimaryPersistence("RavenDB"), + SubmitAttempted = true, + StorageConnectionString = string.Empty + }; + + var notifyErrorInfo = GetNotifyErrorInfo(viewModel); + var errors = notifyErrorInfo.GetErrors(nameof(viewModel.StorageConnectionString)); + + Assert.That(errors, Is.Empty); + } + + [Test] + public void Audit_instance_uses_the_shared_connection_string_by_default_when_adding_both_instances() + { + var viewModel = new ServiceControlAddViewModel + { + InstallErrorInstance = true, + InstallAuditInstance = true, + SelectedStorageType = ServiceControlPersisters.GetPrimaryPersistence("SQLServer"), + SubmitAttempted = true, + StorageConnectionString = "Server=.;Database=ServiceControl", + AuditStorageConnectionString = string.Empty + }; + + var errors = GetNotifyErrorInfo(viewModel).GetErrors(nameof(viewModel.AuditStorageConnectionString)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(viewModel.ShowAuditUseSharedStorageConnectionString, Is.True); + Assert.That(viewModel.ShowAuditStorageConnectionStringEntry, Is.False); + Assert.That(viewModel.AuditStorageConnectionStringToUse, Is.EqualTo("Server=.;Database=ServiceControl")); + Assert.That(errors, Is.Empty); + } + } + + [Test] + public void Audit_connection_string_is_required_when_choosing_a_different_one() + { + var viewModel = new ServiceControlAddViewModel + { + InstallErrorInstance = true, + InstallAuditInstance = true, + SelectedStorageType = ServiceControlPersisters.GetPrimaryPersistence("PostgreSQL"), + SubmitAttempted = true, + StorageConnectionString = "Host=localhost;Database=error", + AuditUseOwnStorageConnectionString = true, + AuditStorageConnectionString = string.Empty + }; + + var errors = GetNotifyErrorInfo(viewModel).GetErrors(nameof(viewModel.AuditStorageConnectionString)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(viewModel.ShowAuditStorageConnectionStringEntry, Is.True); + Assert.That(errors, Is.Not.Empty); + } + + viewModel.AuditStorageConnectionString = "Host=localhost;Database=audit"; + + Assert.That(viewModel.AuditStorageConnectionStringToUse, Is.EqualTo("Host=localhost;Database=audit")); + } + + [Test] + public void Audit_instance_uses_the_shared_connection_string_when_added_alone() + { + var viewModel = new ServiceControlAddViewModel + { + InstallErrorInstance = false, + InstallAuditInstance = true, + SelectedStorageType = ServiceControlPersisters.GetPrimaryPersistence("SQLServer"), + StorageConnectionString = "Server=.;Database=Audit" + }; + + using (Assert.EnterMultipleScope()) + { + Assert.That(viewModel.ShowAuditUseSharedStorageConnectionString, Is.False); + Assert.That(viewModel.ShowAuditStorageConnectionStringEntry, Is.False); + Assert.That(viewModel.AuditStorageConnectionStringToUse, Is.EqualTo("Server=.;Database=Audit")); + } + } + + #endregion + #region auditinstancename [Test] diff --git a/src/ServiceControl.Config.Tests/Validation/AddErrorInstanceValidationTests.cs b/src/ServiceControl.Config.Tests/Validation/AddErrorInstanceValidationTests.cs index d81a07c4bd..1619b865dc 100644 --- a/src/ServiceControl.Config.Tests/Validation/AddErrorInstanceValidationTests.cs +++ b/src/ServiceControl.Config.Tests/Validation/AddErrorInstanceValidationTests.cs @@ -150,6 +150,97 @@ public void Transport_connection_string_cannot_be_null_if_sample_connection_stri } #endregion + #region storagetype + + [Test] + public void Storage_type_cannot_be_empty_when_adding_error_instance() + { + var viewModel = new ServiceControlAddViewModel + { + InstallErrorInstance = true, + SubmitAttempted = true, + SelectedStorageType = null + }; + + viewModel.NotifyOfPropertyChange(nameof(viewModel.SelectedStorageType)); + + var notifyErrorInfo = GetNotifyErrorInfo(viewModel); + var errors = notifyErrorInfo.GetErrors(nameof(viewModel.SelectedStorageType)); + + Assert.That(errors, Is.Not.Empty); + } + + [TestCase("SQLServer")] + [TestCase("PostgreSQL")] + public void Storage_connection_string_cannot_be_empty_for_storage_types_that_require_one_when_adding_error_instance(string storageTypeName) + { + var viewModel = new ServiceControlAddViewModel + { + InstallErrorInstance = true, + ErrorSelectedStorageType = ServiceControlPersisters.GetPrimaryPersistence(storageTypeName), + SubmitAttempted = true, + StorageConnectionString = string.Empty + }; + + var notifyErrorInfo = GetNotifyErrorInfo(viewModel); + var errors = notifyErrorInfo.GetErrors(nameof(viewModel.StorageConnectionString)); + + Assert.That(errors, Is.Not.Empty); + } + + [Test] + public void Message_body_path_cannot_be_empty_for_file_system_storage() + { + var viewModel = new ServiceControlAddViewModel + { + InstallErrorInstance = true, + ErrorSelectedStorageType = ServiceControlPersisters.GetPrimaryPersistence("SQLServer"), + SubmitAttempted = true + }; + viewModel.ErrorMessageBodyPath = string.Empty; + + var errors = GetNotifyErrorInfo(viewModel).GetErrors(nameof(viewModel.ErrorMessageBodyPath)); + + Assert.That(errors, Is.Not.Empty); + } + + [Test] + public void Error_and_audit_message_body_paths_must_differ() + { + var viewModel = new ServiceControlAddViewModel + { + InstallErrorInstance = true, + InstallAuditInstance = true, + ErrorSelectedStorageType = ServiceControlPersisters.GetPrimaryPersistence("SQLServer"), + AuditSelectedStorageType = ServiceControlPersisters.GetAuditPersistence("SQLServer") + }; + viewModel.ErrorMessageBodyPath = @"C:\ProgramData\Particular\ServiceControl\Shared\MessageBodies"; + viewModel.AuditMessageBodyPath = @"C:\ProgramData\Particular\ServiceControl\Shared\MessageBodies"; + + var errors = GetNotifyErrorInfo(viewModel).GetErrors(nameof(viewModel.AuditMessageBodyPath)); + + Assert.That(errors, Is.Not.Empty); + } + + [Test] + public void Storage_connection_string_can_be_empty_for_RavenDB_when_adding_error_instance() + { + var viewModel = new ServiceControlAddViewModel + { + InstallErrorInstance = true, + ErrorSelectedStorageType = ServiceControlPersisters.GetPrimaryPersistence("RavenDB"), + SubmitAttempted = true, + StorageConnectionString = string.Empty + }; + + var notifyErrorInfo = GetNotifyErrorInfo(viewModel); + var errors = notifyErrorInfo.GetErrors(nameof(viewModel.StorageConnectionString)); + + Assert.That(errors, Is.Empty); + } + + #endregion + #region errorinstancename [Test] diff --git a/src/ServiceControl.Config.Tests/Validation/EditAuditInstanceValidationTests.cs b/src/ServiceControl.Config.Tests/Validation/EditAuditInstanceValidationTests.cs index 8a23c110b3..34f07b5705 100644 --- a/src/ServiceControl.Config.Tests/Validation/EditAuditInstanceValidationTests.cs +++ b/src/ServiceControl.Config.Tests/Validation/EditAuditInstanceValidationTests.cs @@ -92,6 +92,42 @@ public void Transport_connection_string_can_be_null_if_sample_connection_string_ #region hostname + [TestCase("SQLServer", false)] + [TestCase("PostgreSQL", false)] + [TestCase("RavenDB", true)] + public void Database_maintenance_port_is_required_only_for_RavenDB_when_editing_audit_instance(string storageTypeName, bool required) + { + var viewModel = new ServiceControlAuditEditViewModel + { + PersistenceManifest = ServiceControlPersisters.GetAuditPersistence(storageTypeName), + SubmitAttempted = true, + DatabaseMaintenancePortNumber = null + }; + + viewModel.NotifyOfPropertyChange(nameof(viewModel.DatabaseMaintenancePortNumber)); + + var errors = GetNotifyErrorInfo(viewModel).GetErrors(nameof(viewModel.DatabaseMaintenancePortNumber)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(viewModel.DatabaseMaintenancePortNumberRequired, Is.EqualTo(required)); + Assert.That(errors, required ? Is.Not.Empty : Is.Empty); + } + } + + [TestCase("SQLServer", false)] + [TestCase("PostgreSQL", false)] + [TestCase("RavenDB", true)] + public void Full_text_search_option_is_shown_only_for_RavenDB_when_editing_audit_instance(string storageTypeName, bool expected) + { + var viewModel = new ServiceControlAuditEditViewModel + { + PersistenceManifest = ServiceControlPersisters.GetAuditPersistence(storageTypeName) + }; + + Assert.That(viewModel.ShowFullTextSearchOnBodies, Is.EqualTo(expected)); + } + [Test] public void Audit_hostname_can_not_be_empty_when_editing_audit_instance() { diff --git a/src/ServiceControl.Config.Tests/Validation/EditErrorInstanceValidationTests.cs b/src/ServiceControl.Config.Tests/Validation/EditErrorInstanceValidationTests.cs index 52b8d82417..122d975f82 100644 --- a/src/ServiceControl.Config.Tests/Validation/EditErrorInstanceValidationTests.cs +++ b/src/ServiceControl.Config.Tests/Validation/EditErrorInstanceValidationTests.cs @@ -244,6 +244,62 @@ public void Error_port_is_not_equal_to_database_port_number_when_editing_error_i #endregion #region DatabaseManintenancePortnumber + [TestCase("SQLServer")] + [TestCase("PostgreSQL")] + public void Database_maintenance_port_is_not_required_when_editing_error_instance_without_one(string storageTypeName) + { + var viewModel = new ServiceControlEditViewModel + { + PersistenceManifest = ServiceControlPersisters.GetPrimaryPersistence(storageTypeName), + SubmitAttempted = true, + DatabaseMaintenancePortNumber = null + }; + + viewModel.NotifyOfPropertyChange(nameof(viewModel.DatabaseMaintenancePortNumber)); + + var errors = GetNotifyErrorInfo(viewModel).GetErrors(nameof(viewModel.DatabaseMaintenancePortNumber)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(viewModel.DatabaseMaintenancePortNumberRequired, Is.False); + Assert.That(errors, Is.Empty); + } + } + + [Test] + public void Database_maintenance_port_is_required_when_editing_RavenDB_error_instance() + { + var viewModel = new ServiceControlEditViewModel + { + PersistenceManifest = ServiceControlPersisters.GetPrimaryPersistence("RavenDB"), + SubmitAttempted = true, + DatabaseMaintenancePortNumber = null + }; + + viewModel.NotifyOfPropertyChange(nameof(viewModel.DatabaseMaintenancePortNumber)); + + var errors = GetNotifyErrorInfo(viewModel).GetErrors(nameof(viewModel.DatabaseMaintenancePortNumber)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(viewModel.DatabaseMaintenancePortNumberRequired, Is.True); + Assert.That(errors, Is.Not.Empty); + } + } + + [TestCase("SQLServer", false)] + [TestCase("PostgreSQL", false)] + [TestCase("RavenDB", true)] + public void Full_text_search_option_is_shown_only_for_RavenDB_when_editing_error_instance(string storageTypeName, bool expected) + { + var viewModel = new ServiceControlEditViewModel + { + PersistenceManifest = ServiceControlPersisters.GetPrimaryPersistence(storageTypeName) + }; + + Assert.That(viewModel.ShowFullTextSearchOnBodies, Is.EqualTo(expected)); + } + [Test] public void Database_maintenance_port_cannot_be_empty_when_editing_error_instance() { diff --git a/src/ServiceControl.Config/Commands/DeleteServiceControlInstanceCommand.cs b/src/ServiceControl.Config/Commands/DeleteServiceControlInstanceCommand.cs index 9ed943fd4e..2497f63478 100644 --- a/src/ServiceControl.Config/Commands/DeleteServiceControlInstanceCommand.cs +++ b/src/ServiceControl.Config/Commands/DeleteServiceControlInstanceCommand.cs @@ -7,6 +7,7 @@ using Framework; using Framework.Commands; using Framework.Modules; + using ServiceControlInstaller.Engine.Instances; using UI.AdvancedOptions; using UI.DeleteInstanceConfirmation; @@ -31,6 +32,9 @@ public override async Task ExecuteAsync(ServiceControlAdvancedViewModel model) var confirmation = deleteInstanceConfirmation(); confirmation.InstanceName = model.Name; + confirmation.HasCleanableStoragePaths = model.ServiceControlInstance.HasCleanableStoragePaths; + confirmation.RemoveDataLabel = model.ServiceControlInstance.UsesEmbeddedDatabase ? "Remove database files and data" : "Remove message body files"; + confirmation.UnmanagedStorageMessage = DescribeUnmanagedStorage(model.ServiceControlInstance); var isConfirmed = await windowManager.ShowDialogAsync(confirmation); if (isConfirmed == true) { @@ -52,6 +56,35 @@ public override async Task ExecuteAsync(ServiceControlAdvancedViewModel model) } } + static string DescribeUnmanagedStorage(ServiceControlBaseService instance) + { + var database = instance.UsesEmbeddedDatabase ? null : $"The {instance.PersistenceManifest.DisplayName} database"; + var bodyLocation = instance.ConfiguredMessageBodyStorageType switch + { + MessageBodyStorageType.AzureBlob => "Azure Blob Storage", + MessageBodyStorageType.S3 => "Amazon S3", + MessageBodyStorageType.FileSystem => null, + null => null, + _ => null + }; + + var subject = (database, bodyLocation) switch + { + (null, null) => null, + (_, null) => $"{database} is", + (null, _) => $"The message bodies in {bodyLocation} are", + _ => $"{database} and the message bodies in {bodyLocation} are" + }; + + if (subject == null) + { + return null; + } + + var pronoun = bodyLocation == null ? "it" : "them"; + return $"{subject} not managed by ServiceControl and will not be removed. Delete {pronoun} manually if you no longer need {pronoun}."; + } + readonly Func deleteInstanceConfirmation; readonly IEventAggregator eventAggregator; readonly ServiceControlInstanceInstaller installer; diff --git a/src/ServiceControl.Config/Commands/UpgradeServiceControlInstanceCommand.cs b/src/ServiceControl.Config/Commands/UpgradeServiceControlInstanceCommand.cs index d8521c00e4..7670a842a2 100644 --- a/src/ServiceControl.Config/Commands/UpgradeServiceControlInstanceCommand.cs +++ b/src/ServiceControl.Config/Commands/UpgradeServiceControlInstanceCommand.cs @@ -63,19 +63,6 @@ public override async Task ExecuteAsync(InstanceDetailsViewModel model) upgradeOptions.OverrideEnableErrorForwarding = !result.Value; } - //Grab old setting if it exists - if (!instance.AppConfig.AppSettingExists(ServiceControlSettings.AuditRetentionPeriod.Name)) - { - if (instance.AppConfig.AppSettingExists(ServiceControlSettings.HoursToKeepMessagesBeforeExpiring.Name)) - { - var i = instance.AppConfig.Read(ServiceControlSettings.HoursToKeepMessagesBeforeExpiring.Name, -1); - if (i != -1) - { - upgradeOptions.AuditRetentionPeriod = TimeSpan.FromHours(i); - } - } - } - if (!instance.AppConfig.AppSettingExists(ServiceControlSettings.ErrorRetentionPeriod.Name)) { var viewModel = new SliderDialogViewModel("INPUT REQUIRED - DATABASE RETENTION", diff --git a/src/ServiceControl.Config/UI/AdvancedOptions/ServiceControlAdvancedViewModel.cs b/src/ServiceControl.Config/UI/AdvancedOptions/ServiceControlAdvancedViewModel.cs index 638fad9e38..b0a921c104 100644 --- a/src/ServiceControl.Config/UI/AdvancedOptions/ServiceControlAdvancedViewModel.cs +++ b/src/ServiceControl.Config/UI/AdvancedOptions/ServiceControlAdvancedViewModel.cs @@ -65,7 +65,10 @@ ForceUpgradeAuditInstanceCommand forceUpgradeAuditCommand public ICommand StartServiceInMaintenanceModeCommand { get; set; } public ICommand StopMaintenanceModeCommand { get; set; } - public bool MaintenanceModeSupported => ServiceControlInstance.Version >= ServiceControlSettings.MaintenanceMode.SupportedFrom; + // Stays visible while an instance is already in maintenance mode so the user can still stop it. + public bool MaintenanceModeSupported => + ServiceControlInstance.Version >= ServiceControlSettings.MaintenanceMode.SupportedFrom + && (ServiceControlInstance.UsesEmbeddedDatabase || ServiceControlInstance.InMaintenanceMode); public ICommand DeleteCommand { get; set; } diff --git a/src/ServiceControl.Config/UI/DeleteInstanceConfirmation/DeleteServiceControlConfirmationView.xaml b/src/ServiceControl.Config/UI/DeleteInstanceConfirmation/DeleteServiceControlConfirmationView.xaml index cd1641f452..907051a862 100644 --- a/src/ServiceControl.Config/UI/DeleteInstanceConfirmation/DeleteServiceControlConfirmationView.xaml +++ b/src/ServiceControl.Config/UI/DeleteInstanceConfirmation/DeleteServiceControlConfirmationView.xaml @@ -6,7 +6,7 @@ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Title="DeleteInstanceConfirmationView" Width="500" - Height="370" + SizeToContent="Height" Background="{StaticResource Gray10Brush}" Foreground="{StaticResource WhiteBrush}" Padding="0" @@ -29,7 +29,7 @@ - + - - - - - - - + + + + + + + + + !string.IsNullOrEmpty(UnmanagedStorageMessage); + public bool RemoveDatabase { get; set; } public bool RemoveLogs { get; set; } diff --git a/src/ServiceControl.Config/UI/InstanceAdd/MessageBodyStorageOptions.cs b/src/ServiceControl.Config/UI/InstanceAdd/MessageBodyStorageOptions.cs new file mode 100644 index 0000000000..63aeb9eab9 --- /dev/null +++ b/src/ServiceControl.Config/UI/InstanceAdd/MessageBodyStorageOptions.cs @@ -0,0 +1,30 @@ +namespace ServiceControl.Config.UI.InstanceAdd; + +using System.Linq; +using System.Windows.Input; +using Commands; +using Extensions; +using ServiceControlInstaller.Engine.Instances; + +// Instances added from the wizard always store message bodies on the file system. +public class MessageBodyStorageOptions +{ + public MessageBodyStorageOptions() => SelectPath = new SelectPathCommand(p => Path = p, isFolderPicker: true, defaultPath: Path); + + public static bool IsSupportedBy(PersistenceManifest manifest) => manifest?.Settings.Any(s => s.Name.EndsWith("/MessageBody/StorageType")) == true; + + public string Path + { + get => path; + set => path = value.SanitizeFilePath(); + } + + public ICommand SelectPath { get; } + + // Returns null for storage types that keep message bodies in the database. + public MessageBodyStorage Create(PersistenceManifest manifest) => IsSupportedBy(manifest) + ? new MessageBodyStorage { StorageType = MessageBodyStorageType.FileSystem, FileSystemStoragePath = Path } + : null; + + string path; +} diff --git a/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddAttachment.cs b/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddAttachment.cs index 8cf5c88352..39e5a2ba76 100644 --- a/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddAttachment.cs +++ b/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddAttachment.cs @@ -53,7 +53,7 @@ async Task Add(CancellationToken cancellationToken) viewModel.InProgress = true; - var serviceControlNewInstance = viewModel.InstallErrorInstance ? ServiceControlNewInstance.CreateWithDefaultPersistence() : null; + var serviceControlNewInstance = viewModel.InstallErrorInstance ? ServiceControlNewInstance.CreateWithPersistence(viewModel.ServiceControl.SelectedStorageType.Name) : null; if (viewModel.InstallErrorInstance) { @@ -61,18 +61,20 @@ async Task Add(CancellationToken cancellationToken) serviceControlNewInstance.Name = viewModel.ServiceControl.InstanceName.Replace(' ', '.'); serviceControlNewInstance.InstanceName = viewModel.ServiceControl.InstanceName.Replace(' ', '.'); serviceControlNewInstance.ServiceDescription = viewModel.ServiceControl.Description; - serviceControlNewInstance.DBPath = viewModel.ServiceControl.DatabasePath; + serviceControlNewInstance.DBPath = viewModel.ServiceControl.ShowDatabasePathFields ? viewModel.ServiceControl.DatabasePath : null; + serviceControlNewInstance.MessageBodyStorage = viewModel.ServiceControl.CreateMessageBodyStorage(); serviceControlNewInstance.LogPath = viewModel.ServiceControl.LogPath; serviceControlNewInstance.InstallPath = viewModel.ServiceControl.DestinationPath; serviceControlNewInstance.HostName = viewModel.ServiceControl.HostName; serviceControlNewInstance.Port = Convert.ToInt32(viewModel.ServiceControl.PortNumber); - serviceControlNewInstance.DatabaseMaintenancePort = Convert.ToInt32(viewModel.ServiceControl.DatabaseMaintenancePortNumber); + serviceControlNewInstance.DatabaseMaintenancePort = viewModel.ShowErrorDatabaseMaintenancePort ? Convert.ToInt32(viewModel.ServiceControl.DatabaseMaintenancePortNumber) : null; serviceControlNewInstance.VirtualDirectory = null; serviceControlNewInstance.ErrorQueue = viewModel.ServiceControl.ErrorQueueName; serviceControlNewInstance.ErrorLogQueue = viewModel.ServiceControl.ErrorForwarding.Value ? viewModel.ServiceControl.ErrorForwardingQueueName : null; serviceControlNewInstance.ForwardErrorMessages = viewModel.ServiceControl.ErrorForwarding.Value; serviceControlNewInstance.TransportPackage = viewModel.SelectedTransport; serviceControlNewInstance.ConnectionString = viewModel.ConnectionString; + serviceControlNewInstance.PersistenceConnectionString = viewModel.ServiceControl.StorageConnectionString; serviceControlNewInstance.ErrorRetentionPeriod = viewModel.ServiceControl.ErrorRetentionPeriod; serviceControlNewInstance.ServiceAccount = viewModel.ServiceControl.ServiceAccount; serviceControlNewInstance.ServiceAccountPwd = viewModel.ServiceControl.Password; @@ -80,24 +82,26 @@ async Task Add(CancellationToken cancellationToken) serviceControlNewInstance.EnableIntegratedServicePulse = viewModel.ServiceControl.EnableIntegratedServicePulse.Value; } - var auditNewInstance = viewModel.InstallAuditInstance ? ServiceControlAuditNewInstance.CreateWithDefaultPersistence() : null; + var auditNewInstance = viewModel.InstallAuditInstance ? ServiceControlAuditNewInstance.CreateWithPersistence(viewModel.ServiceControlAudit.SelectedStorageType.Name) : null; if (viewModel.InstallAuditInstance) { auditNewInstance.DisplayName = viewModel.ServiceControlAudit.InstanceName; auditNewInstance.Name = viewModel.ServiceControlAudit.InstanceName.Replace(' ', '.'); auditNewInstance.InstanceName = viewModel.ServiceControlAudit.InstanceName.Replace(' ', '.'); auditNewInstance.ServiceDescription = viewModel.ServiceControlAudit.Description; - auditNewInstance.DBPath = viewModel.ServiceControlAudit.DatabasePath; + auditNewInstance.DBPath = viewModel.ServiceControlAudit.ShowDatabasePathFields ? viewModel.ServiceControlAudit.DatabasePath : null; + auditNewInstance.MessageBodyStorage = viewModel.ServiceControlAudit.CreateMessageBodyStorage(); auditNewInstance.LogPath = viewModel.ServiceControlAudit.LogPath; auditNewInstance.InstallPath = viewModel.ServiceControlAudit.DestinationPath; auditNewInstance.HostName = viewModel.ServiceControlAudit.HostName; auditNewInstance.Port = Convert.ToInt32(viewModel.ServiceControlAudit.PortNumber); - auditNewInstance.DatabaseMaintenancePort = Convert.ToInt32(viewModel.ServiceControlAudit.DatabaseMaintenancePortNumber); + auditNewInstance.DatabaseMaintenancePort = viewModel.ShowAuditDatabaseMaintenancePort ? Convert.ToInt32(viewModel.ServiceControlAudit.DatabaseMaintenancePortNumber) : null; auditNewInstance.AuditLogQueue = viewModel.ServiceControlAudit.AuditForwarding.Value ? viewModel.ServiceControlAudit.AuditForwardingQueueName : null; auditNewInstance.AuditQueue = viewModel.ServiceControlAudit.AuditQueueName; auditNewInstance.ForwardAuditMessages = viewModel.ServiceControlAudit.AuditForwarding.Value; auditNewInstance.TransportPackage = viewModel.SelectedTransport; auditNewInstance.ConnectionString = viewModel.ConnectionString; + auditNewInstance.PersistenceConnectionString = viewModel.AuditStorageConnectionStringToUse; auditNewInstance.AuditRetentionPeriod = viewModel.ServiceControlAudit.AuditRetentionPeriod; auditNewInstance.ServiceAccount = viewModel.ServiceControlAudit.ServiceAccount; auditNewInstance.ServiceAccountPwd = viewModel.ServiceControlAudit.Password; diff --git a/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddView.xaml b/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddView.xaml index 8b34111dc8..903ee88e24 100644 --- a/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddView.xaml +++ b/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddView.xaml @@ -71,6 +71,29 @@ TextWrapping="Wrap" Visibility="{Binding ShowConnectionString, Converter={StaticResource boolToVis}}" /> + + + + + + + + + + @@ -135,7 +158,9 @@ - + + Text="{Binding ErrorDatabasePath}" + Visibility="{Binding ShowErrorDatabasePathFields, Converter={StaticResource boolToVis}}" /> + + + SelectedValue="{Binding ErrorEnableFullTextSearchOnBodies}" + Visibility="{Binding ShowErrorFullTextSearchOnBodies, Converter={StaticResource boolToVis}}" /> - + + + + + + + + + + + + + + + + + + + Text="{Binding AuditDatabasePath}" + Visibility="{Binding ShowAuditDatabasePathFields, Converter={StaticResource boolToVis}}" /> + + - - - - + + + + + + diff --git a/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddViewModel.cs b/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddViewModel.cs index 02ddc46a89..4eba84d7be 100644 --- a/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddViewModel.cs +++ b/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddViewModel.cs @@ -8,6 +8,7 @@ namespace ServiceControl.Config.UI.InstanceAdd using System.Windows.Input; using PropertyChanged; using ServiceControl.Config.Extensions; + using ServiceControlInstaller.Engine.Configuration.ServiceControl; using ServiceControlInstaller.Engine.Instances; using Validar; using Xaml.Controls; @@ -45,6 +46,9 @@ public ServiceControlAddViewModel(Func getWindowsServiceNames = null) NotifyOfPropertyChange(nameof(ServiceControlQueueAddressOptions)); NotifyOfPropertyChange(nameof(ShowServiceControlQueueAddressSelection)); NotifyOfPropertyChange(nameof(ShowServiceControlQueueAddressEntry)); + NotifyOfPropertyChange(nameof(ShowAuditUseSharedStorageConnectionString)); + NotifyOfPropertyChange(nameof(ShowAuditStorageConnectionStringEntry)); + NotifyOfPropertyChange(nameof(ShowAuditStorageSettings)); } }; } @@ -115,6 +119,31 @@ public override void OnSelectedTransportChanged() NotifyOfPropertyChange(nameof(ConnectionString)); } + // Error and Audit have separate manifests for each storage type, matched by name. + public IEnumerable StorageTypes => ErrorStorageTypes.Where(manifest => AuditStorageTypes.Any(audit => audit.Name == manifest.Name)); + + public PersistenceManifest SelectedStorageType + { + get => ErrorSelectedStorageType; + set + { + ErrorSelectedStorageType = value; + AuditSelectedStorageType = value == null ? null : AuditStorageTypes.Single(audit => audit.Name == value.Name); + } + } + + public bool ShowStorageTypePicker => StorageTypes.Count() > 1; + + public bool ShowStorageSettings => ShowStorageTypePicker || ShowStorageConnectionString; + + public string StorageConnectionString + { + get => ErrorStorageConnectionString; + set => ErrorStorageConnectionString = value; + } + + public bool ShowStorageConnectionString => ShowErrorStorageConnectionString; + public string ErrorInstanceName { get => ServiceControl.InstanceName; @@ -127,6 +156,8 @@ protected void OnErrorInstanceNameChanged() "Particular Software", ErrorInstanceName); ErrorDatabasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Particular", "ServiceControl", ErrorInstanceName, "DB"); + ErrorMessageBodyPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), + "Particular", "ServiceControl", ErrorInstanceName, "MessageBodies"); ErrorLogPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Particular", "ServiceControl", ErrorInstanceName, "Logs"); } @@ -200,6 +231,38 @@ public string ErrorDatabaseMaintenancePortNumber set => ServiceControl.DatabaseMaintenancePortNumber = value; } + public IEnumerable ErrorStorageTypes => ServiceControl.StorageTypes; + + public PersistenceManifest ErrorSelectedStorageType + { + get => ServiceControl.SelectedStorageType; + set => ServiceControl.SelectedStorageType = value; + } + + public string ErrorStorageConnectionString + { + get => ServiceControl.StorageConnectionString; + set => ServiceControl.StorageConnectionString = value; + } + + public bool ShowErrorStorageConnectionString => ErrorSelectedStorageType != null && ErrorSelectedStorageType.Settings.Any(s => s.Mandatory && s.Name.EndsWith("/ConnectionString")); + + public bool ShowErrorDatabasePathFields => ErrorSelectedStorageType == null || ErrorSelectedStorageType.Settings.Any(s => s.Name.EndsWith("/DBPath")); + + public bool ShowErrorDatabaseMaintenancePort => ErrorSelectedStorageType == null || ErrorSelectedStorageType.Settings.Any(s => s.Name == ServiceControlSettings.DatabaseMaintenancePort.Name); + + public bool ShowErrorFullTextSearchOnBodies => ErrorSelectedStorageType == null || ErrorSelectedStorageType.Settings.Any(s => s.Name == ServiceControlSettings.EnableFullTextSearchOnBodies.Name); + + public bool ShowErrorMessageBodyPath => MessageBodyStorageOptions.IsSupportedBy(ErrorSelectedStorageType); + + public ICommand ErrorSelectMessageBodyPath => ServiceControl.MessageBodyStorage.SelectPath; + + public string ErrorMessageBodyPath + { + get => ServiceControl.MessageBodyStorage.Path; + set => ServiceControl.MessageBodyStorage.Path = value.SanitizeFilePath(); + } + public ICommand ErrorSelectDestinationPath => ServiceControl.SelectDestinationPath; public string ErrorDestinationPath @@ -294,6 +357,8 @@ protected void OnAuditInstanceNameChanged() "Particular Software", AuditInstanceName); AuditDatabasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Particular", "ServiceControl", AuditInstanceName, "DB"); + AuditMessageBodyPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), + "Particular", "ServiceControl", AuditInstanceName, "MessageBodies"); AuditLogPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Particular", "ServiceControl", AuditInstanceName, "Logs"); } @@ -367,6 +432,58 @@ public string AuditDatabaseMaintenancePortNumber set => ServiceControlAudit.DatabaseMaintenancePortNumber = value; } + public IEnumerable AuditStorageTypes => ServiceControlAudit.StorageTypes; + + public PersistenceManifest AuditSelectedStorageType + { + get => ServiceControlAudit.SelectedStorageType; + set => ServiceControlAudit.SelectedStorageType = value; + } + + public string AuditStorageConnectionString + { + get => ServiceControlAudit.StorageConnectionString; + set => ServiceControlAudit.StorageConnectionString = value; + } + + public bool ShowAuditStorageSettings => ShowAuditUseSharedStorageConnectionString; + + public bool AuditUseSharedStorageConnectionString { get; set; } = true; + + public bool AuditUseOwnStorageConnectionString + { + get => !AuditUseSharedStorageConnectionString; + set => AuditUseSharedStorageConnectionString = !value; + } + + // An Audit instance added on its own always uses the shared connection string. + public bool ShowAuditUseSharedStorageConnectionString => InstallErrorInstance && ShowAuditStorageConnectionString; + + public bool ShowAuditStorageConnectionStringEntry => ShowAuditUseSharedStorageConnectionString && AuditUseOwnStorageConnectionString; + + public string AuditStorageConnectionStringToUse => + !ShowAuditStorageConnectionString ? null + : ShowAuditStorageConnectionStringEntry ? AuditStorageConnectionString + : StorageConnectionString; + + public bool ShowAuditStorageConnectionString => AuditSelectedStorageType != null && AuditSelectedStorageType.Settings.Any(s => s.Mandatory && s.Name.EndsWith("/ConnectionString")); + + public bool ShowAuditDatabasePathFields => AuditSelectedStorageType == null || AuditSelectedStorageType.Settings.Any(s => s.Name.EndsWith("/DBPath")); + + public bool ShowAuditDatabaseMaintenancePort => AuditSelectedStorageType == null || AuditSelectedStorageType.Settings.Any(s => s.Name == AuditInstanceSettingsList.DatabaseMaintenancePort.Name); + + public bool ShowAuditFullTextSearchOnBodies => AuditSelectedStorageType == null || AuditSelectedStorageType.Settings.Any(s => s.Name == AuditInstanceSettingsList.EnableFullTextSearchOnBodies.Name); + + public bool ShowAuditMessageBodyPath => MessageBodyStorageOptions.IsSupportedBy(AuditSelectedStorageType); + + public ICommand AuditSelectMessageBodyPath => ServiceControlAudit.MessageBodyStorage.SelectPath; + + public string AuditMessageBodyPath + { + get => ServiceControlAudit.MessageBodyStorage.Path; + set => ServiceControlAudit.MessageBodyStorage.Path = value.SanitizeFilePath(); + } + public ICommand AuditSelectDestinationPath => ServiceControlAudit.SelectDestinationPath; public string AuditDestinationPath diff --git a/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddViewModelValidator.cs b/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddViewModelValidator.cs index 50b27017a8..91c32aa82a 100644 --- a/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddViewModelValidator.cs +++ b/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAddViewModelValidator.cs @@ -46,6 +46,22 @@ public ServiceControlAddViewModelValidator() .WithMessage("Error instance name is already in use") .When(viewModel => viewModel.InstallErrorInstance); + RuleFor(x => x.SelectedStorageType) + .NotEmpty() + .When(x => (x.InstallErrorInstance || x.InstallAuditInstance) && x.SubmitAttempted); + + RuleFor(x => x.StorageConnectionString) + .NotEmpty() + .WithMessage(Validation.Validations.MSG_THIS_STORAGE_TYPE_REQUIRES_A_CONNECTION_STRING) + .When(x => (x.InstallErrorInstance || x.InstallAuditInstance) && x.ShowStorageConnectionString && x.SubmitAttempted); + + RuleFor(x => x.ErrorMessageBodyPath) + .NotEmpty() + .ValidPath() + .MustNotBeIn(x => Validations.UsedPaths(x.ErrorInstanceName)) + .WithMessage(string.Format(Validation.Validations.MSG_MUST_BE_UNIQUE, "Message Body Paths")) + .When(x => x.InstallErrorInstance && x.ShowErrorMessageBodyPath); + RuleFor(x => x.ErrorServiceAccount) .NotEmpty() .When(x => x.InstallErrorInstance && x.SubmitAttempted); @@ -85,7 +101,7 @@ public ServiceControlAddViewModelValidator() .WithMessage(string.Format(Validation.Validations.MSG_PORTS_NOT_EQUAL, "Database Maintenance", "Audit")) .NotEqual(x => x.AuditDatabaseMaintenancePortNumber) .WithMessage(string.Format(Validation.Validations.MSG_PORTS_NOT_EQUAL, "Database Maintenance", "Audit Database Maintenance")) - .When(x => x.InstallErrorInstance); + .When(x => x.InstallErrorInstance && x.ShowErrorDatabaseMaintenancePort); RuleFor(x => x.ErrorDestinationPath) .NotEmpty() @@ -157,6 +173,23 @@ public ServiceControlAddViewModelValidator() .WithMessage(string.Format(Validation.Validations.MSG_CANTCONTAINWHITESPACE, "Error instance queue address")) .When(viewModel => viewModel.InstallAuditInstance && !viewModel.InstallErrorInstance); + RuleFor(x => x.AuditStorageConnectionString) + .NotEmpty() + .WithMessage(Validation.Validations.MSG_THIS_STORAGE_TYPE_REQUIRES_A_CONNECTION_STRING) + .When(x => x.InstallAuditInstance && x.ShowAuditStorageConnectionStringEntry && x.SubmitAttempted); + + RuleFor(x => x.AuditMessageBodyPath) + .NotEmpty() + .ValidPath() + .MustNotBeIn(x => Validations.UsedPaths(x.AuditInstanceName)) + .WithMessage(string.Format(Validation.Validations.MSG_MUST_BE_UNIQUE, "Audit Message Body Paths")) + .When(x => x.InstallAuditInstance && x.ShowAuditMessageBodyPath); + + RuleFor(x => x.AuditMessageBodyPath) + .NotEqual(x => x.ErrorMessageBodyPath, System.StringComparer.OrdinalIgnoreCase) + .WithMessage(string.Format(Validation.Validations.MSG_MUST_BE_UNIQUE, "Message Body Paths")) + .When(x => x.InstallAuditInstance && x.ShowAuditMessageBodyPath && x.InstallErrorInstance && x.ShowErrorMessageBodyPath); + RuleFor(x => x.AuditServiceAccount) .NotEmpty() .When(x => x.InstallAuditInstance && x.SubmitAttempted); @@ -196,7 +229,7 @@ public ServiceControlAddViewModelValidator() .WithMessage(string.Format(Validation.Validations.MSG_PORTS_NOT_EQUAL, "Audit Database Maintenance", "ServiceControl")) .NotEqual(x => x.ErrorDatabaseMaintenancePortNumber) .WithMessage(string.Format(Validation.Validations.MSG_PORTS_NOT_EQUAL, "Audit Database Maintenance", "ServiceControl Database Maintenance")) - .When(x => x.InstallAuditInstance); + .When(x => x.InstallAuditInstance && x.ShowAuditDatabaseMaintenancePort); RuleFor(x => x.AuditDestinationPath) .NotEmpty() diff --git a/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAuditInformation.cs b/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAuditInformation.cs index 9a8fc02769..6b219c29d9 100644 --- a/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAuditInformation.cs +++ b/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlAuditInformation.cs @@ -49,10 +49,44 @@ public ServiceControlAuditInformation(ServiceControlEditorViewModel viewModelPar DatabaseMaintenancePortNumber = "44445"; EnableFullTextSearchOnBodies = EnableFullTextSearchOnBodiesOptions.First(p => p.Value); //Default to On. ViewModelParent = viewModelParent; + + // Only auto-select when there's no real choice to make (picker hidden, RavenDB-only); + // otherwise leave it unselected so the combo box shows "Please Select...", like transport. + if (StorageTypes.Count() == 1) + { + SelectedStorageType = StorageTypes.First(); + } } public ServiceControlEditorViewModel ViewModelParent { get; } + public IEnumerable StorageTypes { get; } = ServiceControlPersisters.GetSupportedAuditManifests(); + + // Intentionally not editable after creation - changing storage backend on an existing + // instance has no supported data migration path yet, so this is only ever set at Add time. + public PersistenceManifest SelectedStorageType + { + get => selectedStorageType; + set + { + StorageConnectionString = null; + selectedStorageType = value; + } + } + + public string StorageConnectionString { get; set; } + + public bool ShowStorageTypePicker => StorageTypes.Count() > 1; + + public bool ShowStorageConnectionString => SelectedStorageType != null && SelectedStorageType.Settings.Any(s => s.Mandatory && s.Name.EndsWith("/ConnectionString")); + + public bool ShowDatabasePathFields => SelectedStorageType == null || SelectedStorageType.Settings.Any(s => s.Name.EndsWith("/DBPath")); + + public MessageBodyStorageOptions MessageBodyStorage { get; } = new(); + + // Returns null for storage types that keep message bodies in the database. + public MessageBodyStorage CreateMessageBodyStorage() => MessageBodyStorage.Create(SelectedStorageType); + public int MinimumAuditRetentionPeriod => SettingConstants.AuditRetentionPeriodMinInDays; public int MaximumAuditRetentionPeriod => SettingConstants.AuditRetentionPeriodMaxInDays; @@ -137,4 +171,5 @@ public void UpdateFromInstance(ServiceControlAuditInstance instance) EnableFullTextSearchOnBodies = EnableFullTextSearchOnBodiesOptions.FirstOrDefault(p => p.Value == instance.EnableFullTextSearchOnBodies); } ForwardingOption auditForwarding; + PersistenceManifest selectedStorageType; } \ No newline at end of file diff --git a/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlInformation.cs b/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlInformation.cs index 13e6d1289c..8290777817 100644 --- a/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlInformation.cs +++ b/src/ServiceControl.Config/UI/InstanceAdd/ServiceControlInformation.cs @@ -63,6 +63,13 @@ public ServiceControlInformation(ServiceControlEditorViewModel viewModelParent) EnableFullTextSearchOnBodies = EnableFullTextSearchOnBodiesOptions.First(p => p.Value); //Default to On. EnableIntegratedServicePulse = EnableIntegratedServicePulseOptions.First(p => p.Value); //Default to On. ViewModelParent = viewModelParent; + + // Only auto-select when there's no real choice to make (picker hidden, RavenDB-only); + // otherwise leave it unselected so the combo box shows "Please Select...", like transport. + if (StorageTypes.Count() == 1) + { + SelectedStorageType = StorageTypes.First(); + } } public int MaximumErrorRetentionPeriod => SettingConstants.ErrorRetentionPeriodMaxInDays; @@ -73,6 +80,33 @@ public ServiceControlInformation(ServiceControlEditorViewModel viewModelParent) public ServiceControlEditorViewModel ViewModelParent { get; } + public IEnumerable StorageTypes { get; } = ServiceControlPersisters.GetSupportedPrimaryManifests(); + + // Intentionally not editable after creation - changing storage backend on an existing + // instance has no supported data migration path yet, so this is only ever set at Add time. + public PersistenceManifest SelectedStorageType + { + get => selectedStorageType; + set + { + StorageConnectionString = null; + selectedStorageType = value; + } + } + + public string StorageConnectionString { get; set; } + + public bool ShowStorageTypePicker => StorageTypes.Count() > 1; + + public bool ShowStorageConnectionString => SelectedStorageType != null && SelectedStorageType.Settings.Any(s => s.Mandatory && s.Name.EndsWith("/ConnectionString")); + + public bool ShowDatabasePathFields => SelectedStorageType == null || SelectedStorageType.Settings.Any(s => s.Name.EndsWith("/DBPath")); + + public MessageBodyStorageOptions MessageBodyStorage { get; } = new(); + + // Returns null for storage types that keep message bodies in the database. + public MessageBodyStorage CreateMessageBodyStorage() => MessageBodyStorage.Create(SelectedStorageType); + public double ErrorRetention { get; set; } public TimeSpan ErrorRetentionPeriod => ErrorRetentionUnits == TimeSpanUnits.Days ? TimeSpan.FromDays(ErrorRetention) : TimeSpan.FromHours(ErrorRetention); @@ -144,4 +178,5 @@ public void UpdateFromInstance(ServiceControlInstance instance) } ForwardingOption errorForwarding; + PersistenceManifest selectedStorageType; } \ No newline at end of file diff --git a/src/ServiceControl.Config/UI/InstanceDetails/InstanceDetailsView.xaml b/src/ServiceControl.Config/UI/InstanceDetails/InstanceDetailsView.xaml index 477d4de761..c04b113eed 100644 --- a/src/ServiceControl.Config/UI/InstanceDetails/InstanceDetailsView.xaml +++ b/src/ServiceControl.Config/UI/InstanceDetails/InstanceDetailsView.xaml @@ -273,6 +273,29 @@ + + + + + + + + + + + + + !string.IsNullOrEmpty(DBPath); + public string MessageBodyPath => IsServiceControlInstance ? ServiceControlInstance?.MessageBodyStoragePath : IsServiceControlAudit ? ServiceControlAuditInstance?.MessageBodyStoragePath : null; + + public bool HasBrowsableMessageBodyPath => !string.IsNullOrEmpty(MessageBodyPath); + public string LogPath => ((IServicePaths)ServiceInstance).LogPath; public SemanticVersion Version => ServiceInstance.Version; @@ -370,6 +367,9 @@ public Task HandleAsync(PostRefreshInstances message, CancellationToken cancella NotifyOfPropertyChange("Host"); NotifyOfPropertyChange("InstallPath"); NotifyOfPropertyChange("DBPath"); + NotifyOfPropertyChange(nameof(HasBrowsableDBPath)); + NotifyOfPropertyChange(nameof(MessageBodyPath)); + NotifyOfPropertyChange(nameof(HasBrowsableMessageBodyPath)); NotifyOfPropertyChange("LogPath"); NotifyOfPropertyChange("Version"); NotifyOfPropertyChange("NewVersion"); diff --git a/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlAuditEditView.xaml b/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlAuditEditView.xaml index bff0eec344..6854cb2588 100644 --- a/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlAuditEditView.xaml +++ b/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlAuditEditView.xaml @@ -87,7 +87,8 @@ Warning="{Binding HostNameWarning}" /> + Text="{Binding DatabaseMaintenancePortNumber}" + Visibility="{Binding DatabaseMaintenancePortNumberRequired, Converter={StaticResource boolToVis}}" /> - - - - + + + + + + diff --git a/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlAuditEditViewModel.cs b/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlAuditEditViewModel.cs index 20069e1e87..638cb0b95f 100644 --- a/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlAuditEditViewModel.cs +++ b/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlAuditEditViewModel.cs @@ -2,10 +2,12 @@ namespace ServiceControl.Config.UI.InstanceEdit { using System; using System.Collections.Generic; + using System.Linq; using System.Windows.Input; using Extensions; using InstanceAdd; using PropertyChanged; + using ServiceControlInstaller.Engine.Configuration.ServiceControl; using ServiceControlInstaller.Engine.Instances; using Validar; using Xaml.Controls; @@ -17,6 +19,7 @@ public ServiceControlAuditEditViewModel(ServiceControlAuditInstance instance) { DisplayName = "EDIT SERVICECONTROL AUDIT INSTANCE"; ServiceControlInstance = instance; + PersistenceManifest = instance.PersistenceManifest; ServiceControlAudit.UpdateFromInstance(instance); SelectedTransport = instance.TransportPackage; ConnectionString = instance.ConnectionString; @@ -29,6 +32,12 @@ internal ServiceControlAuditEditViewModel() public ServiceControlAuditInstance ServiceControlInstance { get; set; } + public PersistenceManifest PersistenceManifest { get; set; } + + public bool DatabaseMaintenancePortNumberRequired => PersistenceManifest?.Settings.Any(s => s.Name == AuditInstanceSettingsList.DatabaseMaintenancePort.Name) ?? true; + + public bool ShowFullTextSearchOnBodies => PersistenceManifest?.Settings.Any(s => s.Name == AuditInstanceSettingsList.EnableFullTextSearchOnBodies.Name) ?? true; + public void UpdateInstanceFromViewModel(ServiceControlAuditInstance instance) { instance.HostName = ServiceControlAudit.HostName; @@ -39,7 +48,7 @@ public void UpdateInstanceFromViewModel(ServiceControlAuditInstance instance) instance.AuditRetentionPeriod = ServiceControlAudit.AuditRetentionPeriod; instance.ForwardAuditMessages = ServiceControlAudit.AuditForwarding.Value; instance.ConnectionString = ConnectionString; - instance.DatabaseMaintenancePort = Convert.ToInt32(ServiceControlAudit.DatabaseMaintenancePortNumber); + instance.DatabaseMaintenancePort = string.IsNullOrWhiteSpace(ServiceControlAudit.DatabaseMaintenancePortNumber) ? null : Convert.ToInt32(ServiceControlAudit.DatabaseMaintenancePortNumber); instance.EnableFullTextSearchOnBodies = ServiceControlAudit.EnableFullTextSearchOnBodies.Value; } diff --git a/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlAuditEditViewModelValidator.cs b/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlAuditEditViewModelValidator.cs index 9741d57238..af5ed8f819 100644 --- a/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlAuditEditViewModelValidator.cs +++ b/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlAuditEditViewModelValidator.cs @@ -40,7 +40,7 @@ public ServiceControlAuditEditViewModelValidator() .WithMessage(string.Format(Validation.Validations.MSG_MUST_BE_UNIQUE, "Audit Database Maintenance Port")) .NotEqual(x => x.PortNumber) .WithMessage(string.Format(Validation.Validations.MSG_PORTS_NOT_EQUAL, "Database Maintenance", "Audit")) - .When(x => x.SubmitAttempted); + .When(x => x.SubmitAttempted && x.DatabaseMaintenancePortNumberRequired); RuleFor(x => x.LogPath) .NotEmpty() diff --git a/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlEditView.xaml b/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlEditView.xaml index 7565b9c214..122160effd 100644 --- a/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlEditView.xaml +++ b/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlEditView.xaml @@ -230,7 +230,8 @@ DisplayMemberPath="Name" Header="FULL TEXT SEARCH ON MESSAGE BODIES" ItemsSource="{Binding EnableFullTextSearchOnBodiesOptions}" - SelectedValue="{Binding EnableFullTextSearchOnBodies}" /> + SelectedValue="{Binding EnableFullTextSearchOnBodies}" + Visibility="{Binding ShowFullTextSearchOnBodies, Converter={StaticResource boolToVis}}" /> PersistenceManifest?.Settings.Any(s => s.Name == ServiceControlSettings.DatabaseMaintenancePort.Name) ?? true; + + public bool ShowFullTextSearchOnBodies => PersistenceManifest?.Settings.Any(s => s.Name == ServiceControlSettings.EnableFullTextSearchOnBodies.Name) ?? true; + public void UpdateInstanceFromViewModel(ServiceControlInstance instance) { instance.HostName = ServiceControl.HostName; @@ -40,7 +49,7 @@ public void UpdateInstanceFromViewModel(ServiceControlInstance instance) instance.ErrorRetentionPeriod = ServiceControl.ErrorRetentionPeriod; instance.ForwardErrorMessages = ServiceControl.ErrorForwarding.Value; instance.ConnectionString = ConnectionString; - instance.DatabaseMaintenancePort = Convert.ToInt32(ServiceControl.DatabaseMaintenancePortNumber); + instance.DatabaseMaintenancePort = string.IsNullOrWhiteSpace(ServiceControl.DatabaseMaintenancePortNumber) ? null : Convert.ToInt32(ServiceControl.DatabaseMaintenancePortNumber); instance.EnableFullTextSearchOnBodies = ServiceControl.EnableFullTextSearchOnBodies.Value; instance.EnableIntegratedServicePulse = ServiceControl.EnableIntegratedServicePulse.Value; } diff --git a/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlEditViewModelValidator.cs b/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlEditViewModelValidator.cs index 0e9f6bfe8f..e3e6354065 100644 --- a/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlEditViewModelValidator.cs +++ b/src/ServiceControl.Config/UI/InstanceEdit/ServiceControlEditViewModelValidator.cs @@ -44,7 +44,7 @@ public ServiceControlEditViewModelValidator() .NotEqual(x => x.PortNumber) .WithMessage(string.Format(Validation.Validations.MSG_PORTS_NOT_EQUAL, "Database Maintenance", "ServiceControl")) - .When(x => x.SubmitAttempted); + .When(x => x.SubmitAttempted && x.DatabaseMaintenancePortNumberRequired); RuleFor(x => x.LogPath) .NotEmpty() diff --git a/src/ServiceControl.Config/Validation/Validations.cs b/src/ServiceControl.Config/Validation/Validations.cs index 7fb7ba8373..23e68f6f52 100644 --- a/src/ServiceControl.Config/Validation/Validations.cs +++ b/src/ServiceControl.Config/Validation/Validations.cs @@ -221,6 +221,8 @@ public static IRuleBuilderOptions ValidHostname(this IRuleBuilder< public const string MSG_THIS_TRANSPORT_REQUIRES_A_CONNECTION_STRING = "This transport requires a connection string."; + public const string MSG_THIS_STORAGE_TYPE_REQUIRES_A_CONNECTION_STRING = "This storage type requires a database connection string."; + public const string MSG_CANTCONTAINWHITESPACE = "{0} cannot contain white space."; public const string MSG_SELECTAUDITFORWARDING = "Must select audit forwarding."; diff --git a/src/ServiceControl.Infrastructure.Tests/LoggingConfiguratorTests.cs b/src/ServiceControl.Infrastructure.Tests/LoggingConfiguratorTests.cs index 3e32ba8d39..d0c86f9b01 100644 --- a/src/ServiceControl.Infrastructure.Tests/LoggingConfiguratorTests.cs +++ b/src/ServiceControl.Infrastructure.Tests/LoggingConfiguratorTests.cs @@ -1,6 +1,8 @@ #nullable enable namespace ServiceControl.Infrastructure.Tests; +using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; @@ -17,31 +19,31 @@ namespace ServiceControl.Infrastructure.Tests; [TestFixture] public class LoggingConfiguratorTests { - static readonly string AuditPattern = $"{AuthorizationAuditLog.AuditCategory}*"; - static LoggingConfiguration BuildConfig() => LoggingConfigurator.BuildConfiguration("logfile.txt", Path.GetTempPath(), LogLevel.Info); + static List AuditRules(LoggingConfiguration config) => + [.. config.LoggingRules.Where(r => r.Targets.Any(t => t.Name == "audit-console"))]; + + static NLog.Layouts.Layout LayoutOf(LoggingConfiguration config, string targetName) => + config.AllTargets.OfType().Single(t => t.Name == targetName).Layout; + [Test] public void Audit_target_emits_the_prerendered_event_verbatim() { - var auditTarget = BuildConfig().LoggingRules - .Single(r => r.LoggerNamePattern == AuditPattern) - .Targets.OfType() - .Single(t => t.Name == "audit-console"); - - var rendered = auditTarget.Layout.Render(new LogEventInfo(LogLevel.Info, AuthorizationAuditLog.AuditCategory, "ECS-PAYLOAD")); + var rendered = LayoutOf(BuildConfig(), "audit-console").Render(new LogEventInfo(LogLevel.Info, AuthorizationAuditLog.AuditCategory, "ECS-PAYLOAD")); Assert.That(rendered, Is.EqualTo("ECS-PAYLOAD"), "the audit target must pass the pre-rendered ECS JSON through unwrapped, not double-encode it"); } - [Test] - public void Audit_events_do_not_fall_through_to_the_operational_log() + [TestCase(AuthorizationAuditLog.AuditCategory)] + [TestCase(MessageActionAuditLog.MessageCategory)] + public void Audit_events_do_not_fall_through_to_the_operational_log(string category) { var config = BuildConfig(); - var auditRule = config.LoggingRules.Single(r => r.LoggerNamePattern == AuditPattern); + var auditRule = AuditRules(config).Single(r => r.NameMatches(category)); var operationalConsoleRule = config.LoggingRules.Single(r => r.LoggerNamePattern == "*" && r.Targets.Any(t => t.Name == "console")); Assert.That(auditRule.Final, Is.True, "the audit rule must be final so audit JSON is not duplicated into the plain-text operational log"); @@ -63,7 +65,7 @@ public void Audit_decisions_render_as_valid_structured_json() // ...and capture what it renders, driven through the real audit logger over an isolated NLog factory. var captured = new MemoryTarget("audit-capture") { Layout = auditLayout }; var captureConfig = new LoggingConfiguration(); - captureConfig.AddRule(LogLevel.Info, LogLevel.Fatal, captured, AuditPattern); + captureConfig.AddRule(LogLevel.Info, LogLevel.Fatal, captured, AuthorizationAuditLog.AuditCategory); var logFactory = new LogFactory { Configuration = captureConfig }; using (var loggerFactory = LoggerFactory.Create(b => b.AddNLog(_ => logFactory))) @@ -108,11 +110,53 @@ public void Audit_decisions_render_as_valid_structured_json() [Test] public void Message_action_subcategory_is_captured_by_the_audit_rule() + { + var auditRules = AuditRules(BuildConfig()); + + Assert.That(auditRules.Any(r => r.NameMatches(MessageActionAuditLog.MessageCategory)), Is.True); + Assert.That(auditRules.Any(r => r.NameMatches(MessageActionAuditLog.OperationCategory)), Is.True); + } + + [Test] + public void Audit_instance_loggers_write_to_the_operational_log_with_the_full_layout() { var config = BuildConfig(); - var auditRule = config.LoggingRules.Single(r => r.LoggerNamePattern == AuditPattern); + var operational = new MemoryTarget("operational-capture") { Layout = LayoutOf(config, "console") }; + var audit = new MemoryTarget("audit-capture") { Layout = LayoutOf(config, "audit-console") }; + using var logFactory = new LogFactory { Configuration = RouteToMemory(config, operational, audit) }; + + logFactory.GetLogger("ServiceControl.Audit.Auditing.AuditPersister").Error(new InvalidOperationException("boom"), "Processing of message failed"); + logFactory.Flush(); + + Assert.Multiple(() => + { + Assert.That(operational.Logs, Has.One.EndsWith("|Error|ServiceControl.Audit.Auditing.AuditPersister|Processing of message failed|System.InvalidOperationException: boom"), + "an audit instance logger must keep the level, logger name and exception of the operational layout"); + Assert.That(audit.Logs, Is.Empty, "only the authorization and message action categories belong in the audit trail"); + }); + } + + static LoggingConfiguration RouteToMemory(LoggingConfiguration config, Target operational, Target audit) + { + var routed = new LoggingConfiguration(); + + foreach (var rule in config.LoggingRules) + { + var targets = rule.Targets + .Select(t => t.Name switch + { + "console" => operational, + "audit-console" => audit, + _ => null + }) + .OfType() + .ToList(); + + rule.Targets.Clear(); + targets.ForEach(rule.Targets.Add); + routed.LoggingRules.Add(rule); + } - Assert.That(auditRule.NameMatches(ServiceControl.Infrastructure.Auth.MessageActionAuditLog.MessageCategory), Is.True); - Assert.That(auditRule.NameMatches(ServiceControl.Infrastructure.Auth.MessageActionAuditLog.OperationCategory), Is.True); + return routed; } } diff --git a/src/ServiceControl.Infrastructure/LoggingConfigurator.cs b/src/ServiceControl.Infrastructure/LoggingConfigurator.cs index 5e232163a0..efc766c84b 100644 --- a/src/ServiceControl.Infrastructure/LoggingConfigurator.cs +++ b/src/ServiceControl.Infrastructure/LoggingConfigurator.cs @@ -108,18 +108,24 @@ public static LoggingConfiguration BuildConfiguration(string logFileName, string // Audit events are captured from Info upward (allow = Information, deny = Warning) regardless of the // operational LogLevel — lowering the operational verbosity must never drop entries from the audit trail. - // Final stops audit events from also reaching the catch-all operational rules below, so this rule must + // Final stops audit events from also reaching the catch-all operational rules below, so these rules must // be registered before them. - var auditRule = new LoggingRule + LoggingRule AuditRule(string category) { - LoggerNamePattern = $"{AuthorizationAuditLog.AuditCategory}*", - Final = true - }; - auditRule.SetLoggingLevels(LogLevel.Info, LogLevel.Fatal); - auditRule.Targets.Add(auditConsoleTarget); - if (!AppEnvironment.RunningInContainer) - { - auditRule.Targets.Add(auditFileTarget); + var rule = new LoggingRule + { + // An exact name, not a prefix: the audit instance's own loggers are in the ServiceControl.Audit namespace. + LoggerNamePattern = category, + Final = true + }; + rule.SetLoggingLevels(LogLevel.Info, LogLevel.Fatal); + rule.Targets.Add(auditConsoleTarget); + if (!AppEnvironment.RunningInContainer) + { + rule.Targets.Add(auditFileTarget); + } + + return rule; } nlogConfig.AddTarget(consoleTarget); @@ -128,7 +134,8 @@ public static LoggingConfiguration BuildConfiguration(string logFileName, string nlogConfig.LoggingRules.Add(aspNetCoreRule); nlogConfig.LoggingRules.Add(httpClientRule); nlogConfig.LoggingRules.Add(efCoreRule); - nlogConfig.LoggingRules.Add(auditRule); + nlogConfig.LoggingRules.Add(AuditRule(AuthorizationAuditLog.AuditCategory)); + nlogConfig.LoggingRules.Add(AuditRule(MessageActionAuditLog.MessageCategory)); nlogConfig.LoggingRules.Add(new LoggingRule("*", logLevel, consoleTarget)); diff --git a/src/ServiceControl.Management.PowerShell/Cmdlets/AuditInstances/NewServiceControlAuditInstance.cs b/src/ServiceControl.Management.PowerShell/Cmdlets/AuditInstances/NewServiceControlAuditInstance.cs index 768041419f..71774d4c03 100644 --- a/src/ServiceControl.Management.PowerShell/Cmdlets/AuditInstances/NewServiceControlAuditInstance.cs +++ b/src/ServiceControl.Management.PowerShell/Cmdlets/AuditInstances/NewServiceControlAuditInstance.cs @@ -1,6 +1,7 @@ namespace ServiceControl.Management.PowerShell { using System; + using System.Collections.Generic; using System.Management.Automation; using System.Threading; using System.Threading.Tasks; @@ -23,11 +24,72 @@ public class NewServiceControlAuditInstance : PSCmdlet [ValidatePath] public string InstallPath { get; set; } - [Parameter(Mandatory = true, HelpMessage = "Specify the directory that will contain the RavenDB database for this Audit Instance")] + [Parameter(Mandatory = true, HelpMessage = "Specify the storage type to use")] + [ValidateSet(typeof(AuditStorageTypeValuesGenerator))] + public string StorageType { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the directory that will contain the RavenDB database for this Audit Instance. Required for RavenDB")] [ValidateNotNullOrEmpty] [ValidatePath] public string DBPath { get; set; } + [Parameter(Mandatory = false, HelpMessage = "Specify the database connection string. Required for SQLServer and PostgreSQL")] + [ValidateNotNullOrEmpty] + public string DatabaseConnectionString { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify where message bodies are stored for SQLServer and PostgreSQL. Defaults to FileSystem")] + [ValidateSet("FileSystem", "AzureBlob", "S3")] + public string MessageBodyStorageType { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the directory that will contain message bodies. Required for FileSystem message body storage")] + [ValidateNotNullOrEmpty] + [ValidatePath] + public string MessageBodyPath { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the Azure Blob Storage connection string. Use this or AzureBlobServiceUri")] + [ValidateNotNullOrEmpty] + public string AzureBlobConnectionString { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the Azure Blob Storage service URI to connect with a managed identity. Use this or AzureBlobConnectionString")] + [ValidateNotNullOrEmpty] + public string AzureBlobServiceUri { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the client ID of a user-assigned managed identity")] + [ValidateNotNullOrEmpty] + public string AzureBlobManagedIdentityClientId { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the Microsoft Entra authority host for sovereign clouds")] + [ValidateNotNullOrEmpty] + public string AzureBlobAuthorityHost { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the Azure Blob Storage container name. Defaults to audit-bodies")] + [ValidateNotNullOrEmpty] + public string AzureBlobContainerName { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the S3 bucket name. Required for S3 message body storage")] + [ValidateNotNullOrEmpty] + public string S3BucketName { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the S3 key prefix. Defaults to audit-bodies/")] + [ValidateNotNullOrEmpty] + public string S3KeyPrefix { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the S3 region")] + [ValidateNotNullOrEmpty] + public string S3Region { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the service URL of S3-compatible storage")] + [ValidateNotNullOrEmpty] + public string S3ServiceUrl { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the S3 access key ID. Use with S3SecretAccessKey, or omit both to use the default AWS credentials")] + [ValidateNotNullOrEmpty] + public string S3AccessKeyId { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the S3 secret access key. Use with S3AccessKeyId")] + [ValidateNotNullOrEmpty] + public string S3SecretAccessKey { get; set; } + [Parameter(Mandatory = true, HelpMessage = "Specify the directory to use for this Audit Instance Logs")] [ValidateNotNullOrEmpty] [ValidatePath] @@ -41,9 +103,9 @@ public class NewServiceControlAuditInstance : PSCmdlet [ValidateRange(1, 49151)] public int Port { get; set; } - [Parameter(Mandatory = true, HelpMessage = "Specify the database maintenance port number to listen on")] + [Parameter(Mandatory = false, HelpMessage = "Specify the database maintenance port number to listen on. Required for RavenDB")] [ValidateRange(1, 49151)] - public int DatabaseMaintenancePort { get; set; } + public int? DatabaseMaintenancePort { get; set; } [Parameter(Mandatory = false, HelpMessage = "Specify AuditQueue name to consume messages from. Default is audit")] [ValidateNotNullOrEmpty] @@ -88,7 +150,7 @@ public class NewServiceControlAuditInstance : PSCmdlet [Parameter(Mandatory = false, HelpMessage = "Do not automatically create queues")] public SwitchParameter SkipQueueCreation { get; set; } - [Parameter(Mandatory = false, HelpMessage = "Specify whether to enable full text search on audit messages.")] + [Parameter(Mandatory = false, HelpMessage = "Specify whether to enable full text search on audit message bodies. Only used when StorageType is RavenDB.")] public SwitchParameter EnableFullTextSearchOnBodies { get; set; } = true; [Parameter(Mandatory = false, HelpMessage = "Reuse the specified log, db, and install paths even if they are not empty")] @@ -99,6 +161,24 @@ public class NewServiceControlAuditInstance : PSCmdlet protected override void BeginProcessing() { + persistenceManifest = ServiceControlPersisters.GetAuditPersistence(StorageType); + PersistenceParameters.Validate(persistenceManifest, DBPath, DatabaseMaintenancePort, DatabaseConnectionString, MyInvocation.BoundParameters.ContainsKey(nameof(EnableFullTextSearchOnBodies))); + messageBodyStorage = PersistenceParameters.CreateMessageBodyStorage(persistenceManifest, MessageBodyStorageType, new Dictionary + { + [nameof(MessageBodyPath)] = MessageBodyPath, + [nameof(AzureBlobConnectionString)] = AzureBlobConnectionString, + [nameof(AzureBlobServiceUri)] = AzureBlobServiceUri, + [nameof(AzureBlobManagedIdentityClientId)] = AzureBlobManagedIdentityClientId, + [nameof(AzureBlobAuthorityHost)] = AzureBlobAuthorityHost, + [nameof(AzureBlobContainerName)] = AzureBlobContainerName, + [nameof(S3BucketName)] = S3BucketName, + [nameof(S3KeyPrefix)] = S3KeyPrefix, + [nameof(S3Region)] = S3Region, + [nameof(S3ServiceUrl)] = S3ServiceUrl, + [nameof(S3AccessKeyId)] = S3AccessKeyId, + [nameof(S3SecretAccessKey)] = S3SecretAccessKey + }); + var transport = ServiceControlCoreTransports.Find(Transport); var requiresConnectionString = !string.IsNullOrEmpty(transport.SampleConnectionString); @@ -140,7 +220,7 @@ protected override void BeginProcessing() protected override void ProcessRecord() { - var newAuditInstance = ServiceControlAuditNewInstance.CreateWithDefaultPersistence(); + var newAuditInstance = ServiceControlAuditNewInstance.CreateWithPersistence(persistenceManifest.Name); newAuditInstance.InstallPath = InstallPath; newAuditInstance.LogPath = LogPath; @@ -154,6 +234,8 @@ protected override void ProcessRecord() newAuditInstance.HostName = HostName; newAuditInstance.Port = Port; newAuditInstance.DatabaseMaintenancePort = DatabaseMaintenancePort; + newAuditInstance.PersistenceConnectionString = DatabaseConnectionString; + newAuditInstance.MessageBodyStorage = messageBodyStorage; newAuditInstance.AuditQueue = AuditQueue; newAuditInstance.AuditLogQueue = string.IsNullOrWhiteSpace(AuditLogQueue) ? null : AuditLogQueue; newAuditInstance.ForwardAuditMessages = ForwardAuditMessages.ToBool(); @@ -202,6 +284,9 @@ protected override void ProcessRecord() } } + PersistenceManifest persistenceManifest; + MessageBodyStorage messageBodyStorage; + Task PromptToProceed(PathInfo pathInfo, CancellationToken cancellationToken) { if (!pathInfo.CheckIfEmpty) diff --git a/src/ServiceControl.Management.PowerShell/Cmdlets/AuditInstances/RemoveServiceControlAuditInstance.cs b/src/ServiceControl.Management.PowerShell/Cmdlets/AuditInstances/RemoveServiceControlAuditInstance.cs index 9c2b8fcb05..64b0590a51 100644 --- a/src/ServiceControl.Management.PowerShell/Cmdlets/AuditInstances/RemoveServiceControlAuditInstance.cs +++ b/src/ServiceControl.Management.PowerShell/Cmdlets/AuditInstances/RemoveServiceControlAuditInstance.cs @@ -12,7 +12,7 @@ public class RemoveServiceControlAuditInstance : PSCmdlet [Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, Position = 0, HelpMessage = "Specify the ServiceControl Audit instance name to remove")] public string[] Name { get; set; } - [Parameter(HelpMessage = "Remove the RavenDB database")] + [Parameter(HelpMessage = "Remove the database and message body files that the instance stores locally. A SQL Server or PostgreSQL database, Azure Blob Storage and Amazon S3 are not removed")] public SwitchParameter RemoveDB { get; set; } [Parameter(HelpMessage = "Remove the Logs directory")] diff --git a/src/ServiceControl.Management.PowerShell/Cmdlets/AuditInstances/StartServiceControlAuditMaintenance.cs b/src/ServiceControl.Management.PowerShell/Cmdlets/AuditInstances/StartServiceControlAuditMaintenance.cs new file mode 100644 index 0000000000..7921821a09 --- /dev/null +++ b/src/ServiceControl.Management.PowerShell/Cmdlets/AuditInstances/StartServiceControlAuditMaintenance.cs @@ -0,0 +1,42 @@ +namespace ServiceControl.Management.PowerShell +{ + using System; + using System.Linq; + using System.Management.Automation; + using ServiceControlInstaller.Engine.Instances; + + [Cmdlet(VerbsLifecycle.Start, "ServiceControlAuditMaintenance")] + public class StartServiceControlAuditMaintenance : PSCmdlet + { + [ValidateNotNullOrEmpty] + [Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, Position = 0, HelpMessage = "Specify the ServiceControl Audit instance name")] + public string Name { get; set; } + + protected override void BeginProcessing() + { + Account.TestIfAdmin(); + } + + protected override void ProcessRecord() + { + var instance = InstanceFinder.ServiceControlAuditInstances().FirstOrDefault(i => i.Name.Equals(Name, StringComparison.OrdinalIgnoreCase)); + if (instance == null) + { + WriteWarning($"No action taken. An instance called {Name} was not found"); + return; + } + + if (!instance.TryStopService()) + { + ThrowTerminatingError(new ErrorRecord(new Exception($"Failed to stop {instance.Name}"), "StopFailure", ErrorCategory.InvalidResult, null)); + } + + instance.EnableMaintenanceMode(); + + if (!instance.TryStartService()) + { + ThrowTerminatingError(new ErrorRecord(new Exception($"Failed to start {instance.Name}"), "StartFailure", ErrorCategory.InvalidResult, null)); + } + } + } +} diff --git a/src/ServiceControl.Management.PowerShell/Cmdlets/AuditInstances/StopServiceControlAuditMaintenance.cs b/src/ServiceControl.Management.PowerShell/Cmdlets/AuditInstances/StopServiceControlAuditMaintenance.cs new file mode 100644 index 0000000000..d448fe511b --- /dev/null +++ b/src/ServiceControl.Management.PowerShell/Cmdlets/AuditInstances/StopServiceControlAuditMaintenance.cs @@ -0,0 +1,37 @@ +namespace ServiceControl.Management.PowerShell +{ + using System; + using System.Linq; + using System.Management.Automation; + using ServiceControlInstaller.Engine.Instances; + + [Cmdlet(VerbsLifecycle.Stop, "ServiceControlAuditMaintenance")] + public class StopServiceControlAuditMaintenance : PSCmdlet + { + [ValidateNotNullOrEmpty] + [Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, Position = 0, HelpMessage = "Specify the ServiceControl Audit instance name")] + public string Name { get; set; } + + protected override void BeginProcessing() + { + Account.TestIfAdmin(); + } + + protected override void ProcessRecord() + { + var instance = InstanceFinder.ServiceControlAuditInstances().FirstOrDefault(i => i.Name.Equals(Name, StringComparison.OrdinalIgnoreCase)); + if (instance == null) + { + WriteWarning($"No action taken. An instance called {Name} was not found"); + return; + } + + if (!instance.TryStopService()) + { + ThrowTerminatingError(new ErrorRecord(new Exception($"Failed to stop {instance.Name}"), "StopFailure", ErrorCategory.InvalidResult, null)); + } + + instance.DisableMaintenanceMode(); + } + } +} diff --git a/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/NewServiceControlInstance.cs b/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/NewServiceControlInstance.cs index eb2e792fcf..519ca735e6 100644 --- a/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/NewServiceControlInstance.cs +++ b/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/NewServiceControlInstance.cs @@ -1,6 +1,7 @@ namespace ServiceControl.Management.PowerShell { using System; + using System.Collections.Generic; using System.IO; using System.Linq; using System.Management.Automation; @@ -25,11 +26,72 @@ public class NewServiceControlInstance : PSCmdlet [ValidatePath] public string InstallPath { get; set; } - [Parameter(Mandatory = true, HelpMessage = "Specify the directory that will contain the RavenDB database for this ServiceControl Instance")] + [Parameter(Mandatory = true, HelpMessage = "Specify the storage type to use")] + [ValidateSet(typeof(PrimaryStorageTypeValuesGenerator))] + public string StorageType { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the directory that will contain the RavenDB database for this ServiceControl Instance. Required for RavenDB")] [ValidateNotNullOrEmpty] [ValidatePath] public string DBPath { get; set; } + [Parameter(Mandatory = false, HelpMessage = "Specify the database connection string. Required for SQLServer and PostgreSQL")] + [ValidateNotNullOrEmpty] + public string DatabaseConnectionString { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify where message bodies are stored for SQLServer and PostgreSQL. Defaults to FileSystem")] + [ValidateSet("FileSystem", "AzureBlob", "S3")] + public string MessageBodyStorageType { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the directory that will contain message bodies. Required for FileSystem message body storage")] + [ValidateNotNullOrEmpty] + [ValidatePath] + public string MessageBodyPath { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the Azure Blob Storage connection string. Use this or AzureBlobServiceUri")] + [ValidateNotNullOrEmpty] + public string AzureBlobConnectionString { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the Azure Blob Storage service URI to connect with a managed identity. Use this or AzureBlobConnectionString")] + [ValidateNotNullOrEmpty] + public string AzureBlobServiceUri { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the client ID of a user-assigned managed identity")] + [ValidateNotNullOrEmpty] + public string AzureBlobManagedIdentityClientId { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the Microsoft Entra authority host for sovereign clouds")] + [ValidateNotNullOrEmpty] + public string AzureBlobAuthorityHost { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the Azure Blob Storage container name. Defaults to error-bodies")] + [ValidateNotNullOrEmpty] + public string AzureBlobContainerName { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the S3 bucket name. Required for S3 message body storage")] + [ValidateNotNullOrEmpty] + public string S3BucketName { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the S3 key prefix. Defaults to error-bodies/")] + [ValidateNotNullOrEmpty] + public string S3KeyPrefix { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the S3 region")] + [ValidateNotNullOrEmpty] + public string S3Region { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the service URL of S3-compatible storage")] + [ValidateNotNullOrEmpty] + public string S3ServiceUrl { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the S3 access key ID. Use with S3SecretAccessKey, or omit both to use the default AWS credentials")] + [ValidateNotNullOrEmpty] + public string S3AccessKeyId { get; set; } + + [Parameter(Mandatory = false, HelpMessage = "Specify the S3 secret access key. Use with S3AccessKeyId")] + [ValidateNotNullOrEmpty] + public string S3SecretAccessKey { get; set; } + [Parameter(Mandatory = true, HelpMessage = "Specify the directory to use for this ServiceControl Logs")] [ValidateNotNullOrEmpty] [ValidatePath] @@ -43,9 +105,9 @@ public class NewServiceControlInstance : PSCmdlet [ValidateRange(1, 49151)] public int Port { get; set; } - [Parameter(Mandatory = true, HelpMessage = "Specify the database maintenance port number to listen on. If this is the only ServiceControl instance then 33334 is recommended")] + [Parameter(Mandatory = false, HelpMessage = "Specify the database maintenance port number to listen on. If this is the only ServiceControl instance then 33334 is recommended. Required for RavenDB")] [ValidateRange(1, 49151)] - public int DatabaseMaintenancePort { get; set; } + public int? DatabaseMaintenancePort { get; set; } [Parameter(Mandatory = false, HelpMessage = "Specify ErrorQueue name to consume messages from. Default is error")] [ValidateNotNullOrEmpty] @@ -92,7 +154,7 @@ public class NewServiceControlInstance : PSCmdlet [Parameter(Mandatory = false, HelpMessage = "Do not automatically create queues")] public SwitchParameter SkipQueueCreation { get; set; } - [Parameter(Mandatory = false, HelpMessage = "Specify whether to enable full text search on error messages.")] + [Parameter(Mandatory = false, HelpMessage = "Specify whether to enable full text search on error message bodies. Only used when StorageType is RavenDB.")] public SwitchParameter EnableFullTextSearchOnBodies { get; set; } = true; [Parameter(Mandatory = false, HelpMessage = "Specify whether to enable integrated ServicePulse instance.")] @@ -106,6 +168,24 @@ public class NewServiceControlInstance : PSCmdlet protected override void BeginProcessing() { + persistenceManifest = ServiceControlPersisters.GetPrimaryPersistence(StorageType); + PersistenceParameters.Validate(persistenceManifest, DBPath, DatabaseMaintenancePort, DatabaseConnectionString, MyInvocation.BoundParameters.ContainsKey(nameof(EnableFullTextSearchOnBodies))); + messageBodyStorage = PersistenceParameters.CreateMessageBodyStorage(persistenceManifest, MessageBodyStorageType, new Dictionary + { + [nameof(MessageBodyPath)] = MessageBodyPath, + [nameof(AzureBlobConnectionString)] = AzureBlobConnectionString, + [nameof(AzureBlobServiceUri)] = AzureBlobServiceUri, + [nameof(AzureBlobManagedIdentityClientId)] = AzureBlobManagedIdentityClientId, + [nameof(AzureBlobAuthorityHost)] = AzureBlobAuthorityHost, + [nameof(AzureBlobContainerName)] = AzureBlobContainerName, + [nameof(S3BucketName)] = S3BucketName, + [nameof(S3KeyPrefix)] = S3KeyPrefix, + [nameof(S3Region)] = S3Region, + [nameof(S3ServiceUrl)] = S3ServiceUrl, + [nameof(S3AccessKeyId)] = S3AccessKeyId, + [nameof(S3SecretAccessKey)] = S3SecretAccessKey + }); + var transport = ServiceControlCoreTransports.Find(Transport); var requiresConnectionString = !string.IsNullOrEmpty(transport.SampleConnectionString); @@ -153,7 +233,7 @@ protected override void BeginProcessing() protected override void ProcessRecord() { - var details = ServiceControlNewInstance.CreateWithDefaultPersistence(); + var details = ServiceControlNewInstance.CreateWithPersistence(persistenceManifest.Name); details.InstallPath = InstallPath; details.LogPath = LogPath; @@ -167,6 +247,8 @@ protected override void ProcessRecord() details.HostName = HostName; details.Port = Port; details.DatabaseMaintenancePort = DatabaseMaintenancePort; + details.PersistenceConnectionString = DatabaseConnectionString; + details.MessageBodyStorage = messageBodyStorage; details.VirtualDirectory = VirtualDirectory; details.ErrorQueue = ErrorQueue; details.ErrorLogQueue = string.IsNullOrWhiteSpace(ErrorLogQueue) ? null : ErrorLogQueue; @@ -229,6 +311,9 @@ protected override void ProcessRecord() } } + PersistenceManifest persistenceManifest; + MessageBodyStorage messageBodyStorage; + Task PromptToProceed(PathInfo pathInfo, CancellationToken cancellationToken) { if (!pathInfo.CheckIfEmpty) diff --git a/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/PSServiceControl.cs b/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/PSServiceControl.cs index 11d5977c16..e6fe51006d 100644 --- a/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/PSServiceControl.cs +++ b/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/PSServiceControl.cs @@ -44,8 +44,6 @@ public class PsServiceControl public bool ForwardAuditMessages { get; set; } - public TimeSpan? AuditRetentionPeriod { get; set; } - public string ServiceAccount { get; set; } public SemanticVersion Version { get; set; } @@ -77,7 +75,6 @@ public static PsServiceControl FromInstance(ServiceControlInstance instance) AuditQueue = instance.AuditQueue, AuditLogQueue = instance.ForwardAuditMessages ? instance.AuditLogQueue : null, ForwardAuditMessages = instance.ForwardAuditMessages, - AuditRetentionPeriod = instance.AuditRetentionPeriod, ErrorRetentionPeriod = instance.ErrorRetentionPeriod, EnableFullTextSearchOnBodies = instance.EnableFullTextSearchOnBodies, RemoteInstances = instance.RemoteInstances.Select(i => diff --git a/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/RemoveServiceControlInstance.cs b/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/RemoveServiceControlInstance.cs index 017578f73d..4badc9d5f7 100644 --- a/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/RemoveServiceControlInstance.cs +++ b/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/RemoveServiceControlInstance.cs @@ -13,7 +13,7 @@ public class RemoveServiceControlInstance : PSCmdlet [Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, Position = 0, HelpMessage = "Specify the ServiceControl instance name to remove")] public string[] Name { get; set; } - [Parameter(HelpMessage = "Remove the RavenDB database")] + [Parameter(HelpMessage = "Remove the database and message body files that the instance stores locally. A SQL Server or PostgreSQL database, Azure Blob Storage and Amazon S3 are not removed")] public SwitchParameter RemoveDB { get; set; } [Parameter(HelpMessage = "Remove the Logs directory")] diff --git a/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/StartServiceControlMaintenance.cs b/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/StartServiceControlMaintenance.cs new file mode 100644 index 0000000000..81aee14405 --- /dev/null +++ b/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/StartServiceControlMaintenance.cs @@ -0,0 +1,42 @@ +namespace ServiceControl.Management.PowerShell +{ + using System; + using System.Linq; + using System.Management.Automation; + using ServiceControlInstaller.Engine.Instances; + + [Cmdlet(VerbsLifecycle.Start, "ServiceControlMaintenance")] + public class StartServiceControlMaintenance : PSCmdlet + { + [ValidateNotNullOrEmpty] + [Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, Position = 0, HelpMessage = "Specify the ServiceControl instance name")] + public string Name { get; set; } + + protected override void BeginProcessing() + { + Account.TestIfAdmin(); + } + + protected override void ProcessRecord() + { + var instance = InstanceFinder.ServiceControlInstances().FirstOrDefault(i => i.Name.Equals(Name, StringComparison.OrdinalIgnoreCase)); + if (instance == null) + { + WriteWarning($"No action taken. An instance called {Name} was not found"); + return; + } + + if (!instance.TryStopService()) + { + ThrowTerminatingError(new ErrorRecord(new Exception($"Failed to stop {instance.Name}"), "StopFailure", ErrorCategory.InvalidResult, null)); + } + + instance.EnableMaintenanceMode(); + + if (!instance.TryStartService()) + { + ThrowTerminatingError(new ErrorRecord(new Exception($"Failed to start {instance.Name}"), "StartFailure", ErrorCategory.InvalidResult, null)); + } + } + } +} diff --git a/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/StopServiceControlMaintenance.cs b/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/StopServiceControlMaintenance.cs new file mode 100644 index 0000000000..9ea0bddb7c --- /dev/null +++ b/src/ServiceControl.Management.PowerShell/Cmdlets/ServiceControlInstances/StopServiceControlMaintenance.cs @@ -0,0 +1,37 @@ +namespace ServiceControl.Management.PowerShell +{ + using System; + using System.Linq; + using System.Management.Automation; + using ServiceControlInstaller.Engine.Instances; + + [Cmdlet(VerbsLifecycle.Stop, "ServiceControlMaintenance")] + public class StopServiceControlMaintenance : PSCmdlet + { + [ValidateNotNullOrEmpty] + [Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, Position = 0, HelpMessage = "Specify the ServiceControl instance name")] + public string Name { get; set; } + + protected override void BeginProcessing() + { + Account.TestIfAdmin(); + } + + protected override void ProcessRecord() + { + var instance = InstanceFinder.ServiceControlInstances().FirstOrDefault(i => i.Name.Equals(Name, StringComparison.OrdinalIgnoreCase)); + if (instance == null) + { + WriteWarning($"No action taken. An instance called {Name} was not found"); + return; + } + + if (!instance.TryStopService()) + { + ThrowTerminatingError(new ErrorRecord(new Exception($"Failed to stop {instance.Name}"), "StopFailure", ErrorCategory.InvalidResult, null)); + } + + instance.DisableMaintenanceMode(); + } + } +} diff --git a/src/ServiceControl.Management.PowerShell/Cmdlets/UrlAcls/AddUrlAcl.cs b/src/ServiceControl.Management.PowerShell/Cmdlets/UrlAcls/AddUrlAcl.cs deleted file mode 100644 index 8231789209..0000000000 --- a/src/ServiceControl.Management.PowerShell/Cmdlets/UrlAcls/AddUrlAcl.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace ServiceControl.Management.PowerShell -{ - using System; - using System.Management.Automation; - using Particular.Obsoletes; - - [ObsoleteMetadata(Message = "ServiceControl no longer requires URL reservations, so this command no longer functions", ReplacementTypeOrMember = "netsh http add urlacl", TreatAsErrorFromVersion = "7", RemoveInVersion = "8")] - [Obsolete("ServiceControl no longer requires URL reservations, so this command no longer functions. Use 'netsh http add urlacl' instead. Will be treated as an error from version 7.0.0. Will be removed in version 8.0.0.", false)] - [Cmdlet(VerbsCommon.Add, "UrlAcl")] - public class AddUrlAcl : PSCmdlet - { - [ValidateNotNullOrEmpty] - [Parameter(Mandatory = true, Position = 0, HelpMessage = "The URL to add to the URLACL list. This should always in a trailing /")] - public string Url { get; set; } - - [ValidateNotNullOrEmpty] - [Parameter(Mandatory = true, Position = 1, HelpMessage = "The user or group to assign to this URLACL")] - public string[] Users; - } -} \ No newline at end of file diff --git a/src/ServiceControl.Management.PowerShell/Cmdlets/UrlAcls/GetUrlAcls.cs b/src/ServiceControl.Management.PowerShell/Cmdlets/UrlAcls/GetUrlAcls.cs deleted file mode 100644 index ca1d6c3c9c..0000000000 --- a/src/ServiceControl.Management.PowerShell/Cmdlets/UrlAcls/GetUrlAcls.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ServiceControl.Management.PowerShell -{ - using System; - using System.Management.Automation; - using Particular.Obsoletes; - - [ObsoleteMetadata(Message = "ServiceControl no longer requires URL reservations, so this command no longer functions", ReplacementTypeOrMember = "netsh http show urlacl", TreatAsErrorFromVersion = "7", RemoveInVersion = "8")] - [Obsolete("ServiceControl no longer requires URL reservations, so this command no longer functions. Use 'netsh http show urlacl' instead. Will be treated as an error from version 7.0.0. Will be removed in version 8.0.0.", false)] - [Cmdlet(VerbsCommon.Get, "UrlAcls")] - public class GetUrlAcls : PSCmdlet; -} \ No newline at end of file diff --git a/src/ServiceControl.Management.PowerShell/Cmdlets/UrlAcls/RemoveUrlAcl.cs b/src/ServiceControl.Management.PowerShell/Cmdlets/UrlAcls/RemoveUrlAcl.cs deleted file mode 100644 index 19855324eb..0000000000 --- a/src/ServiceControl.Management.PowerShell/Cmdlets/UrlAcls/RemoveUrlAcl.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace ServiceControl.Management.PowerShell -{ - using System; - using System.Management.Automation; - using Particular.Obsoletes; - - [ObsoleteMetadata(Message = "ServiceControl no longer requires URL reservations, so this command no longer functions", ReplacementTypeOrMember = "netsh http delete urlacl", TreatAsErrorFromVersion = "7", RemoveInVersion = "8")] - [Obsolete("ServiceControl no longer requires URL reservations, so this command no longer functions. Use 'netsh http delete urlacl' instead. Will be treated as an error from version 7.0.0. Will be removed in version 8.0.0.", false)] - [Cmdlet(VerbsCommon.Remove, "UrlAcl")] - public class RemoveUrlAcl : PSCmdlet; -} \ No newline at end of file diff --git a/src/ServiceControl.Management.PowerShell/Cmdlets/UrlAcls/obsoletes-v7.cs b/src/ServiceControl.Management.PowerShell/Cmdlets/UrlAcls/obsoletes-v7.cs new file mode 100644 index 0000000000..261e0a4fae --- /dev/null +++ b/src/ServiceControl.Management.PowerShell/Cmdlets/UrlAcls/obsoletes-v7.cs @@ -0,0 +1,22 @@ +#pragma warning disable CS1591 +namespace ServiceControl.Management.PowerShell +{ + using System; + using System.Management.Automation; + using Particular.Obsoletes; + + [ObsoleteMetadata(Message = "ServiceControl no longer requires URL reservations, so this command no longer functions", ReplacementTypeOrMember = "netsh http show urlacl", TreatAsErrorFromVersion = "7", RemoveInVersion = "8")] + [Obsolete("ServiceControl no longer requires URL reservations, so this command no longer functions. Use 'netsh http show urlacl' instead. Will be removed in version 8.0.0.", true)] + [Cmdlet(VerbsCommon.Get, "UrlAcls")] + public class GetUrlAcls : PSCmdlet; + + [ObsoleteMetadata(Message = "ServiceControl no longer requires URL reservations, so this command no longer functions", ReplacementTypeOrMember = "netsh http add urlacl", TreatAsErrorFromVersion = "7", RemoveInVersion = "8")] + [Obsolete("ServiceControl no longer requires URL reservations, so this command no longer functions. Use 'netsh http add urlacl' instead. Will be removed in version 8.0.0.", true)] + [Cmdlet(VerbsCommon.Add, "UrlAcl")] + public class AddUrlAcl : PSCmdlet; + + [ObsoleteMetadata(Message = "ServiceControl no longer requires URL reservations, so this command no longer functions", ReplacementTypeOrMember = "netsh http delete urlacl", TreatAsErrorFromVersion = "7", RemoveInVersion = "8")] + [Obsolete("ServiceControl no longer requires URL reservations, so this command no longer functions. Use 'netsh http delete urlacl' instead. Will be removed in version 8.0.0.", true)] + [Cmdlet(VerbsCommon.Remove, "UrlAcl")] + public class RemoveUrlAcl : PSCmdlet; +} \ No newline at end of file diff --git a/src/ServiceControl.Management.PowerShell/Particular.ServiceControl.Management.psm1 b/src/ServiceControl.Management.PowerShell/Particular.ServiceControl.Management.psm1 index 5c06c1b9e7..8eee4922ef 100644 --- a/src/ServiceControl.Management.PowerShell/Particular.ServiceControl.Management.psm1 +++ b/src/ServiceControl.Management.PowerShell/Particular.ServiceControl.Management.psm1 @@ -41,6 +41,10 @@ New-Alias -Value Get-ServiceControlManagementCommands -Name sc-help New-Alias -Value Get-ServiceControlRemotes -Name sc-remotes New-Alias -Value Add-ServiceControlRemote -Name sc-addremote New-Alias -Value Remove-ServiceControlRemote -Name sc-deleteremote +New-Alias -Value Start-ServiceControlMaintenance -Name sc-startmaintenance +New-Alias -Value Stop-ServiceControlMaintenance -Name sc-stopmaintenance +New-Alias -Value Start-ServiceControlAuditMaintenance -Name audit-startmaintenance +New-Alias -Value Stop-ServiceControlAuditMaintenance -Name audit-stopmaintenance Export-ModuleMember * -Alias * diff --git a/src/ServiceControl.Management.PowerShell/ServiceControl.Management.PowerShell.csproj b/src/ServiceControl.Management.PowerShell/ServiceControl.Management.PowerShell.csproj index 2c1dc84b79..1d55a586d0 100644 --- a/src/ServiceControl.Management.PowerShell/ServiceControl.Management.PowerShell.csproj +++ b/src/ServiceControl.Management.PowerShell/ServiceControl.Management.PowerShell.csproj @@ -27,7 +27,7 @@ - + diff --git a/src/ServiceControl.Management.PowerShell/ServiceControl.Management.PowerShell.dll-help.xml b/src/ServiceControl.Management.PowerShell/ServiceControl.Management.PowerShell.dll-help.xml index 42ad697714..8e1bca0868 100644 --- a/src/ServiceControl.Management.PowerShell/ServiceControl.Management.PowerShell.dll-help.xml +++ b/src/ServiceControl.Management.PowerShell/ServiceControl.Management.PowerShell.dll-help.xml @@ -190,6 +190,374 @@ + + + + Stop-ServiceControlAuditMaintenance + + Stops a ServiceControl Audit instance and clears maintenance mode. + + + + + Stop + ServiceControlAuditMaintenance + + + + Stops the ServiceControl Audit service and removes the maintenance mode setting from its configuration file. The service stays stopped; start it normally to resume ingesting audit messages. Requires an elevated session. Alias: audit-stopmaintenance + + + + Stop-ServiceControlAuditMaintenance + + Name + + Name of the ServiceControl Audit Service. This corresponds to the Windows Service Name for the service not the Display Name. + + String + + + + + + Name + + Name of the ServiceControl Audit Service. This corresponds to the Windows Service Name for the service not the Display Name. + + String + + String + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -------------------------- Example 1 -------------------------- + + PS C:\> + + Stop-ServiceControlAuditMaintenance -Name Particular.ServiceControl.Audit + + Stops the Particular.ServiceControl.Audit service and clears maintenance mode. + + + + + + + + + + Stop-ServiceControlMaintenance + + Stops a ServiceControl instance and clears maintenance mode. + + + + + Stop + ServiceControlMaintenance + + + + Stops the ServiceControl service and removes the maintenance mode setting from its configuration file. The service stays stopped; start it normally to resume ingesting error messages. Requires an elevated session. Alias: sc-stopmaintenance + + + + Stop-ServiceControlMaintenance + + Name + + Name of the ServiceControl Service. This corresponds to the Windows Service Name for the service not the Display Name. + + String + + + + + + Name + + Name of the ServiceControl Service. This corresponds to the Windows Service Name for the service not the Display Name. + + String + + String + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -------------------------- Example 1 -------------------------- + + PS C:\> + + Stop-ServiceControlMaintenance -Name Particular.ServiceControl + + Stops the Particular.ServiceControl service and clears maintenance mode. + + + + + + + + + + Start-ServiceControlAuditMaintenance + + Starts a ServiceControl Audit instance in maintenance mode. + + + + + Start + ServiceControlAuditMaintenance + + + + Stops the ServiceControl Audit service, writes the maintenance mode setting to its configuration file, and starts the service again. In maintenance mode the instance does not ingest audit messages and its RavenDB database stays available. Run Stop-ServiceControlAuditMaintenance to clear the setting and stop the service. Requires an elevated session. Alias: audit-startmaintenance + + + + Start-ServiceControlAuditMaintenance + + Name + + Name of the ServiceControl Audit Service. This corresponds to the Windows Service Name for the service not the Display Name. + + String + + + + + + Name + + Name of the ServiceControl Audit Service. This corresponds to the Windows Service Name for the service not the Display Name. + + String + + String + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -------------------------- Example 1 -------------------------- + + PS C:\> + + Start-ServiceControlAuditMaintenance -Name Particular.ServiceControl.Audit + + Restarts the Particular.ServiceControl.Audit service in maintenance mode. + + + + + + + + + + Start-ServiceControlMaintenance + + Starts a ServiceControl instance in maintenance mode. + + + + + Start + ServiceControlMaintenance + + + + Stops the ServiceControl service, writes the maintenance mode setting to its configuration file, and starts the service again. In maintenance mode the instance does not ingest error messages and its RavenDB database stays available. Run Stop-ServiceControlMaintenance to clear the setting and stop the service. Requires an elevated session. Alias: sc-startmaintenance + + + + Start-ServiceControlMaintenance + + Name + + Name of the ServiceControl Service. This corresponds to the Windows Service Name for the service not the Display Name. + + String + + + + + + Name + + Name of the ServiceControl Service. This corresponds to the Windows Service Name for the service not the Display Name. + + String + + String + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + -------------------------- Example 1 -------------------------- + + PS C:\> + + Start-ServiceControlMaintenance -Name Particular.ServiceControl + + Restarts the Particular.ServiceControl service in maintenance mode. + + + + + + @@ -1485,16 +1853,6 @@ Invoke-ServiceControlInstanceUpgrade - - AuditRetentionPeriod - - - AuditRetentionPeriod controls how long ServiceControl retains messages ingested from the Audit queue in the database. The value must be a TimeSpan within the range 1 hour to 365 days. - Use the New-TimeSpan cmdlet to generate a TimeSpan value. - - - Nullable`1[TimeSpan] - ErrorRetentionPeriod @@ -1525,32 +1883,17 @@ Name of the ServiceControl Service to upgrade. This corresponds to the Windows Service Name for the service not the Display Name. String[] - - - ForwardErrorMessages - - This parameter is mandatory if the existing instance of ServiceControl does not have an entry in the configuration file for ForwardErrorMessages. When enabled all messages read of the Error queue are forwarded to queue specified ErrorLog queue as part of the import into ServiceControl. This configuration settings did not exist prior to Version of 1.12. - - Nullable`1[Boolean] - - - - - - AuditRetentionPeriod - - - AuditRetentionPeriod controls how long ServiceControl retains messages ingested from the Audit queue in the database. The value must be a TimeSpan within the range 1 hour to 365 days. - Use the New-TimeSpan cmdlet to generate a TimeSpan value. - - - Nullable`1[TimeSpan] - - Nullable`1[TimeSpan] - - - - + + + ForwardErrorMessages + + This parameter is mandatory if the existing instance of ServiceControl does not have an entry in the configuration file for ForwardErrorMessages. When enabled all messages read of the Error queue are forwarded to queue specified ErrorLog queue as part of the import into ServiceControl. This configuration settings did not exist prior to Version of 1.12. + + Nullable`1[Boolean] + + + + ErrorRetentionPeriod @@ -2514,10 +2857,10 @@ String - + DBPath - The directory that will contain the embedded database files for this ServiceControl Instance. This should be unique for each instance of ServiceControl and should not be a subfolder of the InstallPath or LogPath. + The directory that will contain the embedded database files for this ServiceControl Instance. This should be unique for each instance of ServiceControl and should not be a subfolder of the InstallPath or LogPath. Required when StorageType is RavenDB, and not used otherwise. String @@ -2548,13 +2891,118 @@ Int32 - + DatabaseMaintenancePort - + The port the embedded RavenDB database listens on. If this is the only ServiceControl instance then 33334 is recommended. Required when StorageType is RavenDB, and not used otherwise. Int32 + + StorageType + + The storage type to use: RavenDB, SQLServer, or PostgreSQL. + + String + + + DatabaseConnectionString + + The connection string of the database that stores the instance data. Required when StorageType is SQLServer or PostgreSQL, and not used otherwise. + + String + + + MessageBodyStorageType + + Where message bodies are stored when StorageType is SQLServer or PostgreSQL: FileSystem, AzureBlob, or S3. Not used for RavenDB, which stores message bodies in its database. + + String + + + MessageBodyPath + + The directory that will contain message bodies. Required when MessageBodyStorageType is FileSystem. This should be unique for each instance of ServiceControl and should not be a subfolder of the InstallPath or LogPath. + + String + + + AzureBlobConnectionString + + The Azure Blob Storage connection string, using a shared key or SAS token. Specify this or AzureBlobServiceUri when MessageBodyStorageType is AzureBlob. + + String + + + AzureBlobServiceUri + + The Azure Blob Storage service URI, for example https://account.blob.core.windows.net, to connect with a managed identity. Specify this or AzureBlobConnectionString when MessageBodyStorageType is AzureBlob. + + String + + + AzureBlobManagedIdentityClientId + + The client ID of a user-assigned managed identity. Used with AzureBlobServiceUri. Leave empty to use the system-assigned identity. + + String + + + AzureBlobAuthorityHost + + The Microsoft Entra authority host for sovereign clouds. Used with AzureBlobServiceUri. + + String + + + AzureBlobContainerName + + The Azure Blob Storage container that stores message bodies. + + String + + + S3BucketName + + The S3 bucket that stores message bodies. Required when MessageBodyStorageType is S3. + + String + + + S3KeyPrefix + + The prefix for message body object keys in the S3 bucket. + + String + + + S3Region + + The AWS region of the S3 bucket. + + String + + + S3ServiceUrl + + The service URL of S3-compatible storage. Leave empty to use Amazon S3. + + String + + + S3AccessKeyId + + The S3 access key ID. Specify with S3SecretAccessKey, or omit both to use the default AWS credentials, such as an IAM role. + + String + + + S3SecretAccessKey + + The S3 secret access key. Specify with S3AccessKeyId. + + String + ErrorQueue @@ -2696,10 +3144,10 @@ - + DBPath - The directory that will contain the embedded database files for this ServiceControl Instance. This should be unique for each instance of ServiceControl and should not be a subfolder of the InstallPath or LogPath. + The directory that will contain the embedded database files for this ServiceControl Instance. This should be unique for each instance of ServiceControl and should not be a subfolder of the InstallPath or LogPath. Required when StorageType is RavenDB, and not used otherwise. String @@ -2750,10 +3198,10 @@ - + DatabaseMaintenancePort - + The port the embedded RavenDB database listens on. If this is the only ServiceControl instance then 33334 is recommended. Required when StorageType is RavenDB, and not used otherwise. Int32 @@ -2762,6 +3210,186 @@ + + StorageType + + The storage type to use: RavenDB, SQLServer, or PostgreSQL. + + String + + String + + + + + + DatabaseConnectionString + + The connection string of the database that stores the instance data. Required when StorageType is SQLServer or PostgreSQL, and not used otherwise. + + String + + String + + + + + + MessageBodyStorageType + + Where message bodies are stored when StorageType is SQLServer or PostgreSQL: FileSystem, AzureBlob, or S3. Not used for RavenDB, which stores message bodies in its database. + + String + + String + + + FileSystem + + + MessageBodyPath + + The directory that will contain message bodies. Required when MessageBodyStorageType is FileSystem. This should be unique for each instance of ServiceControl and should not be a subfolder of the InstallPath or LogPath. + + String + + String + + + + + + AzureBlobConnectionString + + The Azure Blob Storage connection string, using a shared key or SAS token. Specify this or AzureBlobServiceUri when MessageBodyStorageType is AzureBlob. + + String + + String + + + + + + AzureBlobServiceUri + + The Azure Blob Storage service URI, for example https://account.blob.core.windows.net, to connect with a managed identity. Specify this or AzureBlobConnectionString when MessageBodyStorageType is AzureBlob. + + String + + String + + + + + + AzureBlobManagedIdentityClientId + + The client ID of a user-assigned managed identity. Used with AzureBlobServiceUri. Leave empty to use the system-assigned identity. + + String + + String + + + + + + AzureBlobAuthorityHost + + The Microsoft Entra authority host for sovereign clouds. Used with AzureBlobServiceUri. + + String + + String + + + + + + AzureBlobContainerName + + The Azure Blob Storage container that stores message bodies. + + String + + String + + + error-bodies + + + S3BucketName + + The S3 bucket that stores message bodies. Required when MessageBodyStorageType is S3. + + String + + String + + + + + + S3KeyPrefix + + The prefix for message body object keys in the S3 bucket. + + String + + String + + + error-bodies/ + + + S3Region + + The AWS region of the S3 bucket. + + String + + String + + + + + + S3ServiceUrl + + The service URL of S3-compatible storage. Leave empty to use Amazon S3. + + String + + String + + + + + + S3AccessKeyId + + The S3 access key ID. Specify with S3SecretAccessKey, or omit both to use the default AWS credentials, such as an IAM role. + + String + + String + + + + + + S3SecretAccessKey + + The S3 secret access key. Specify with S3AccessKeyId. + + String + + String + + + + ErrorQueue @@ -2934,21 +3562,6 @@ - - AuditRetentionPeriod - - - AuditRetention Period controls how long ServiceControl retains messages ingested from the Audit queue in the database. The value must be a TimeSpan within the range 1 hour to 365 days. - Use the New-TimeSpan cmdlet to generate a TimeSpan value. - - - timespan - - timespan - - - - EnableIntegratedServicePulse @@ -3003,7 +3616,6 @@ PS C:\> - $AuditRetention = New-TimeSpan -Days 30 $ErrorRetention = New-TimeSpan -Days 30 New-ServiceControlInstance -Name 'ServiceControlTest' ` @@ -3015,7 +3627,6 @@ -ErrorQueue error ` -Transport MSMQ ` -DisplayName 'ServiceControl Test' ` - -AuditRetentionPeriod $AuditRetention ` -ErrorRetentionPeriod $ErrorRetention ` -ForwardErrorMessages:$false ` -EnableIntegratedServicePulse @@ -3087,7 +3698,7 @@ RemoveDB - Remove the contents of the Database folder. + Remove the database and message body files that the instance stores locally. A SQL Server or PostgreSQL database, Azure Blob Storage and Amazon S3 are not removed. SwitchParameter @@ -3116,7 +3727,7 @@ RemoveDB - Remove the contents of the Database folder. + Remove the database and message body files that the instance stores locally. A SQL Server or PostgreSQL database, Azure Blob Storage and Amazon S3 are not removed. SwitchParameter @@ -3308,7 +3919,7 @@ RemoveDB - Remove the contents of the Database folder. + Remove the database and message body files that the instance stores locally. A SQL Server or PostgreSQL database, Azure Blob Storage and Amazon S3 are not removed. SwitchParameter @@ -3337,7 +3948,7 @@ RemoveDB - Remove the contents of the Database folder. + Remove the database and message body files that the instance stores locally. A SQL Server or PostgreSQL database, Azure Blob Storage and Amazon S3 are not removed. SwitchParameter diff --git a/src/ServiceControl.Management.PowerShell/Validation/PersistenceParameters.cs b/src/ServiceControl.Management.PowerShell/Validation/PersistenceParameters.cs new file mode 100644 index 0000000000..a2ed0fd3df --- /dev/null +++ b/src/ServiceControl.Management.PowerShell/Validation/PersistenceParameters.cs @@ -0,0 +1,106 @@ +namespace ServiceControl.Management.PowerShell.Validation +{ + using System; + using System.Collections.Generic; + using System.Linq; + using ServiceControlInstaller.Engine.Instances; + + // Checks that only the parameters the selected storage type uses are given, like the transport connection string check. + static class PersistenceParameters + { + public static void Validate(PersistenceManifest manifest, string dbPath, int? databaseMaintenancePort, string databaseConnectionString, bool enableFullTextSearchOnBodiesSpecified) + { + Check(manifest, "DBPath", manifest.Settings.Any(s => s.Name.EndsWith("/DBPath")), !string.IsNullOrWhiteSpace(dbPath)); + Check(manifest, "DatabaseMaintenancePort", manifest.Settings.Any(s => s.Name.EndsWith("/DatabaseMaintenancePort")), databaseMaintenancePort.HasValue); + Check(manifest, "DatabaseConnectionString", manifest.Settings.Any(s => s.Mandatory && s.Name.EndsWith("/Database/ConnectionString")), !string.IsNullOrWhiteSpace(databaseConnectionString)); + + if (enableFullTextSearchOnBodiesSpecified && !manifest.Settings.Any(s => s.Name.EndsWith("/EnableFullTextSearchOnBodies"))) + { + throw new Exception($"The '{manifest.Name}' storage type does not use EnableFullTextSearchOnBodies."); + } + } + + // Returns null for storage types that keep message bodies in the database. + public static MessageBodyStorage CreateMessageBodyStorage(PersistenceManifest manifest, string storageTypeName, IReadOnlyDictionary parameters) + { + var supportsBodyStorage = manifest.Settings.Any(s => s.Name.EndsWith("/MessageBody/StorageType")); + var specified = parameters.Where(p => !string.IsNullOrWhiteSpace(p.Value)).Select(p => p.Key).ToList(); + + if (!supportsBodyStorage) + { + if (storageTypeName != null) + { + specified.Insert(0, "MessageBodyStorageType"); + } + + if (specified.Count > 0) + { + throw new Exception($"The '{manifest.Name}' storage type does not use {string.Join(", ", specified)}."); + } + + return null; + } + + var storageType = storageTypeName == null ? MessageBodyStorageType.FileSystem : Enum.Parse(storageTypeName); + var parameterPrefix = storageType switch + { + MessageBodyStorageType.FileSystem => "MessageBodyPath", + MessageBodyStorageType.AzureBlob => "AzureBlob", + MessageBodyStorageType.S3 => "S3", + _ => throw new Exception($"Message body storage type '{storageType}' is not supported.") + }; + + var unused = specified.Where(name => !name.StartsWith(parameterPrefix)).ToList(); + if (unused.Count > 0) + { + throw new Exception($"The '{storageType}' message body storage type does not use {string.Join(", ", unused)}."); + } + + string Value(string name) => parameters.TryGetValue(name, out var value) && !string.IsNullOrWhiteSpace(value) ? value : null; + + var requiredParameter = storageType switch + { + MessageBodyStorageType.FileSystem => "MessageBodyPath", + MessageBodyStorageType.S3 => "S3BucketName", + // Azure Blob needs one of two parameters, which the installer checks. + MessageBodyStorageType.AzureBlob => null, + _ => null + }; + + if (requiredParameter != null && Value(requiredParameter) == null) + { + throw new Exception($"{requiredParameter} is mandatory for the '{storageType}' message body storage type."); + } + + return new MessageBodyStorage + { + StorageType = storageType, + FileSystemStoragePath = Value("MessageBodyPath"), + AzureConnectionString = Value("AzureBlobConnectionString"), + AzureServiceUri = Value("AzureBlobServiceUri"), + AzureManagedIdentityClientId = Value("AzureBlobManagedIdentityClientId"), + AzureAuthorityHost = Value("AzureBlobAuthorityHost"), + AzureContainerName = Value("AzureBlobContainerName"), + S3BucketName = Value("S3BucketName"), + S3KeyPrefix = Value("S3KeyPrefix"), + S3Region = Value("S3Region"), + S3ServiceUrl = Value("S3ServiceUrl"), + S3AccessKeyId = Value("S3AccessKeyId"), + S3SecretAccessKey = Value("S3SecretAccessKey") + }; + } + + static void Check(PersistenceManifest manifest, string parameterName, bool isUsed, bool isSpecified) + { + if (isUsed && !isSpecified) + { + throw new Exception($"{parameterName} is mandatory for the '{manifest.Name}' storage type."); + } + + if (!isUsed && isSpecified) + { + throw new Exception($"The '{manifest.Name}' storage type does not use {parameterName}."); + } + } + } +} diff --git a/src/ServiceControl.Management.PowerShell/Validation/StorageTypeValuesGenerator.cs b/src/ServiceControl.Management.PowerShell/Validation/StorageTypeValuesGenerator.cs new file mode 100644 index 0000000000..ae7133a71e --- /dev/null +++ b/src/ServiceControl.Management.PowerShell/Validation/StorageTypeValuesGenerator.cs @@ -0,0 +1,20 @@ +namespace ServiceControl.Management.PowerShell.Validation +{ + using System.Linq; + using System.Management.Automation; + using ServiceControlInstaller.Engine.Instances; + + public class PrimaryStorageTypeValuesGenerator : IValidateSetValuesGenerator + { + public string[] GetValidValues() => ServiceControlPersisters.GetSupportedPrimaryManifests() + .Select(m => m.Name) + .ToArray(); + } + + public class AuditStorageTypeValuesGenerator : IValidateSetValuesGenerator + { + public string[] GetValidValues() => ServiceControlPersisters.GetSupportedAuditManifests() + .Select(m => m.Name) + .ToArray(); + } +} diff --git a/src/ServiceControl.Monitoring/Container-README.md b/src/ServiceControl.Monitoring/Container-README.md index bc3c223f15..00a9e4fd90 100644 --- a/src/ServiceControl.Monitoring/Container-README.md +++ b/src/ServiceControl.Monitoring/Container-README.md @@ -7,7 +7,7 @@ The `particular/servicecontrol-monitoring` image is part of the Particular Servi | [`particular/servicecontrol`](https://hub.docker.com/r/particular/servicecontrol) | [Instance Documentation](https://docs.particular.net/servicecontrol/servicecontrol-instances/)
[Container Documentation](https://docs.particular.net/servicecontrol/servicecontrol-instances/deployment/containers) | The primary/error instance, which includes error handling and recoverability | | [`particular/servicecontrol-audit`](https://hub.docker.com/r/particular/servicecontrol-audit) | [Instance Documentation](https://docs.particular.net/servicecontrol/audit-instances/)
[Container Documentation](https://docs.particular.net/servicecontrol/audit-instances/deployment/containers) | The audit instance, which stores audit data, and can be scaled out to multiple audit instances | | [`particular/servicecontrol-monitoring`](https://hub.docker.com/r/particular/servicecontrol-monitoring) | [Instance Documentation](https://docs.particular.net/servicecontrol/monitoring-instances/)
[Container Documentation](https://docs.particular.net/servicecontrol/monitoring-instances/deployment/containers) | The monitoring instance, which tracks runtime information like throughput, queue length, and other metrics | -| [`particular/servicecontrol-ravendb`](https://hub.docker.com/r/particular/servicecontrol-ravendb) | [Container Documentation](https://docs.particular.net/servicecontrol/ravendb/containers) | The database used by the error/audit instances | +| [`particular/servicecontrol-ravendb`](https://hub.docker.com/r/particular/servicecontrol-ravendb) | [Container Documentation](https://docs.particular.net/servicecontrol/storage/ravendb/containers) | The database for error/audit instances using RavenDB persistence | | [`particular/servicepulse`](https://hub.docker.com/r/particular/servicepulse) | [App Documentation](https://docs.particular.net/servicepulse/)
[Container Documentation](https://docs.particular.net/servicepulse/containerization/) | The web application that provides a front end for recoverability and monitoring features | ## Usage diff --git a/src/ServiceControl.MultiInstance.AcceptanceTests/TestSupport/SharedRavenStorageConfiguration.cs b/src/ServiceControl.MultiInstance.AcceptanceTests/TestSupport/SharedRavenStorageConfiguration.cs index 0b599318fb..b5da9105b1 100644 --- a/src/ServiceControl.MultiInstance.AcceptanceTests/TestSupport/SharedRavenStorageConfiguration.cs +++ b/src/ServiceControl.MultiInstance.AcceptanceTests/TestSupport/SharedRavenStorageConfiguration.cs @@ -18,9 +18,9 @@ namespace ServiceControl.MultiInstance.AcceptanceTests.TestSupport class SharedRavenStorageConfiguration : PrimaryStorageConfiguration, AuditStorageConfiguration { // Both persisters ship a manifest named RavenDB, and only one of them survives the copy into this project's output folder - string PrimaryStorageConfiguration.PersistenceType => TypeNameOf(typeof(RavenPersistenceConfiguration)); + string PrimaryStorageConfiguration.StorageType => TypeNameOf(typeof(RavenPersistenceConfiguration)); - string AuditStorageConfiguration.PersistenceType => TypeNameOf(typeof(AuditRavenPersistenceConfiguration)); + string AuditStorageConfiguration.StorageType => TypeNameOf(typeof(AuditRavenPersistenceConfiguration)); async Task PrimaryStorageConfiguration.CustomizeSettings(PrimaryInstanceSettings settings, CancellationToken cancellationToken) { diff --git a/src/ServiceControl.Persistence.EFCore.PostgreSql/PostgreSqlPersistenceConfiguration.cs b/src/ServiceControl.Persistence.EFCore.PostgreSql/PostgreSqlPersistenceConfiguration.cs index 2418cef18e..d4bc4d2618 100644 --- a/src/ServiceControl.Persistence.EFCore.PostgreSql/PostgreSqlPersistenceConfiguration.cs +++ b/src/ServiceControl.Persistence.EFCore.PostgreSql/PostgreSqlPersistenceConfiguration.cs @@ -1,17 +1,11 @@ namespace ServiceControl.Persistence.EFCore.PostgreSql; -using Microsoft.Extensions.Logging; -using ServiceControl.Infrastructure; using ServiceControl.Persistence.EFCore.Abstractions; class PostgreSqlPersistenceConfiguration : EFPersistenceConfigurationBase { public override IPersistence Create(PersistenceSettings settings) { - // Temporary until the persister is fully implemented - LoggerUtil.CreateStaticLogger() - .LogError("The PostgreSQL persistence is still under development and is not ready for use"); - return new PostgreSqlPersistence((PostgreSqlPersisterSettings)settings); } diff --git a/src/ServiceControl.Persistence.EFCore.PostgreSql/persistence.manifest b/src/ServiceControl.Persistence.EFCore.PostgreSql/persistence.manifest index f021224da5..77a1c26cfa 100644 --- a/src/ServiceControl.Persistence.EFCore.PostgreSql/persistence.manifest +++ b/src/ServiceControl.Persistence.EFCore.PostgreSql/persistence.manifest @@ -19,6 +19,7 @@ }, { "Name": "ServiceControl/MessageBody/StorageType", + "DefaultValue": "FileSystem", "Mandatory": true }, { @@ -77,5 +78,8 @@ "Name": "ServiceControl/MessageBody/MinCompressionSize", "Mandatory": false } + ], + "SettingsWithPathsToCleanup": [ + "ServiceControl/MessageBody/FileSystem/StoragePath" ] } diff --git a/src/ServiceControl.Persistence.EFCore.SqlServer/SqlServerPersistenceConfiguration.cs b/src/ServiceControl.Persistence.EFCore.SqlServer/SqlServerPersistenceConfiguration.cs index 741888b1c8..11fa9e32c5 100644 --- a/src/ServiceControl.Persistence.EFCore.SqlServer/SqlServerPersistenceConfiguration.cs +++ b/src/ServiceControl.Persistence.EFCore.SqlServer/SqlServerPersistenceConfiguration.cs @@ -1,17 +1,11 @@ namespace ServiceControl.Persistence.EFCore.SqlServer; -using Microsoft.Extensions.Logging; -using ServiceControl.Infrastructure; using ServiceControl.Persistence.EFCore.Abstractions; class SqlServerPersistenceConfiguration : EFPersistenceConfigurationBase { public override IPersistence Create(PersistenceSettings settings) { - // Temporary until the persister is fully implemented - LoggerUtil.CreateStaticLogger() - .LogError("The SQL Server persistence is still under development and is not ready for use"); - var sqlSettings = (SqlServerPersisterSettings)settings; return new SqlServerPersistence(sqlSettings); diff --git a/src/ServiceControl.Persistence.EFCore.SqlServer/persistence.manifest b/src/ServiceControl.Persistence.EFCore.SqlServer/persistence.manifest index faa1f24c3e..7853239632 100644 --- a/src/ServiceControl.Persistence.EFCore.SqlServer/persistence.manifest +++ b/src/ServiceControl.Persistence.EFCore.SqlServer/persistence.manifest @@ -19,6 +19,7 @@ }, { "Name": "ServiceControl/MessageBody/StorageType", + "DefaultValue": "FileSystem", "Mandatory": true }, { @@ -77,5 +78,8 @@ "Name": "ServiceControl/MessageBody/MinCompressionSize", "Mandatory": false } + ], + "SettingsWithPathsToCleanup": [ + "ServiceControl/MessageBody/FileSystem/StoragePath" ] } diff --git a/src/ServiceControl.Persistence.EFCore/Implementation/BodyStorage/FileSystemBodyStoragePersistence.cs b/src/ServiceControl.Persistence.EFCore/Implementation/BodyStorage/FileSystemBodyStoragePersistence.cs index ba4a043e2b..f6db572b3e 100644 --- a/src/ServiceControl.Persistence.EFCore/Implementation/BodyStorage/FileSystemBodyStoragePersistence.cs +++ b/src/ServiceControl.Persistence.EFCore/Implementation/BodyStorage/FileSystemBodyStoragePersistence.cs @@ -141,7 +141,20 @@ public Task DeleteBodyIfExists(string bodyId, CancellationToken cancellationToke return Task.CompletedTask; } - string GetBodyFilePath(string bodyId) => Path.Combine(StoragePath, $"{bodyId}.body"); + string GetBodyFilePath(string bodyId) + { + const string FailedImportPrefix = "failedimport-"; + var guidText = bodyId is not null && bodyId.StartsWith(FailedImportPrefix, StringComparison.Ordinal) + ? bodyId[FailedImportPrefix.Length..] + : bodyId; + + if (!Guid.TryParse(guidText, out _)) + { + throw new ArgumentException("The body id must be a GUID, optionally prefixed with 'failedimport-'.", nameof(bodyId)); + } + + return Path.Combine(StoragePath, $"{bodyId}.body"); + } static void TryDelete(string filePath) { diff --git a/src/ServiceControl.Persistence.EFCore/Implementation/FailedMessageLifecycleDataStore.cs b/src/ServiceControl.Persistence.EFCore/Implementation/FailedMessageLifecycleDataStore.cs index bdb0201b1b..fcab5cb00d 100644 --- a/src/ServiceControl.Persistence.EFCore/Implementation/FailedMessageLifecycleDataStore.cs +++ b/src/ServiceControl.Persistence.EFCore/Implementation/FailedMessageLifecycleDataStore.cs @@ -130,13 +130,26 @@ await ExecuteWithDbContext(async (dbContext, token) => } var now = timeProvider.GetUtcNow().UtcDateTime; + var strategy = dbContext.Database.CreateExecutionStrategy(); - await dbContext.FailedMessages - .Where(fm => fm.UniqueMessageId == uniqueMessageId && fm.Status == FailedMessageStatus.RetryIssued) - .ExecuteUpdateAsync(s => s - .SetProperty(fm => fm.Status, FailedMessageStatus.Unresolved) - .SetProperty(fm => fm.StatusChangedAt, now) - .SetProperty(fm => fm.LastModified, now), token); + await strategy.ExecuteAsync(async () => + { + await using var transaction = await dbContext.Database.BeginTransactionAsync(token); + + await dbContext.FailedMessages + .Where(fm => fm.UniqueMessageId == uniqueMessageId && fm.Status == FailedMessageStatus.RetryIssued) + .ExecuteUpdateAsync(s => s + .SetProperty(fm => fm.Status, FailedMessageStatus.Unresolved) + .SetProperty(fm => fm.StatusChangedAt, now) + .SetProperty(fm => fm.LastModified, now), token); + + // The claim would otherwise stop every later retry from staging the message. + await dbContext.FailedMessageRetries + .Where(retry => retry.UniqueMessageId == uniqueMessageId) + .ExecuteDeleteAsync(token); + + await transaction.CommitAsync(token); + }); }, cancellationToken); } } \ No newline at end of file diff --git a/src/ServiceControl.Persistence.EFCore/Implementation/UnitOfWork/EFRecoverabilityIngestionUnitOfWork.cs b/src/ServiceControl.Persistence.EFCore/Implementation/UnitOfWork/EFRecoverabilityIngestionUnitOfWork.cs index 2b9f37cab5..b8ecdd00e1 100644 --- a/src/ServiceControl.Persistence.EFCore/Implementation/UnitOfWork/EFRecoverabilityIngestionUnitOfWork.cs +++ b/src/ServiceControl.Persistence.EFCore/Implementation/UnitOfWork/EFRecoverabilityIngestionUnitOfWork.cs @@ -17,7 +17,8 @@ public Task RecordFailedProcessingAttempt(MessageContext context, List groups, CancellationToken cancellationToken = default) { - var uniqueMessageId = context.Headers.UniqueId(); + var uniqueMessageIdString = context.Headers.UniqueId(); + var uniqueMessageId = Guid.TryParse(uniqueMessageIdString, out var parsed) ? parsed : DeterministicGuid.MakeId(uniqueMessageIdString); var contentType = context.Headers.GetValueOrDefault(Headers.ContentType, "text/plain"); var bodySize = context.Body.Length; var (bodyText, storeExternally) = MessageBodyClassifier.Classify(context.Headers, context.Body, settings.BodyStorage.MaxBodySizeToStore); @@ -25,7 +26,7 @@ public Task RecordFailedProcessingAttempt(MessageContext context, if (storeExternally) { parentUnitOfWork.RecordBodyWrite( - storagePersistence.WriteBody(uniqueMessageId, context.Body, contentType, cancellationToken)); + storagePersistence.WriteBody(uniqueMessageId.ToString(), context.Body, contentType, cancellationToken)); } var sendingEndpoint = GetMetadata(processingAttempt, "SendingEndpoint"); @@ -33,7 +34,7 @@ public Task RecordFailedProcessingAttempt(MessageContext context, parentUnitOfWork.Record(new RecordedFailedProcessingAttempt { - UniqueMessageId = Guid.Parse(uniqueMessageId), + UniqueMessageId = uniqueMessageId, AttemptedAt = processingAttempt.AttemptedAt, TimeOfFailure = processingAttempt.FailureDetails.TimeOfFailure, Groups = groups, diff --git a/src/ServiceControl.Persistence.RavenDB/CustomChecks/CheckRavenDBIndexErrors.cs b/src/ServiceControl.Persistence.RavenDB/CustomChecks/CheckRavenDBIndexErrors.cs index 89ea567a80..25da5fd86c 100644 --- a/src/ServiceControl.Persistence.RavenDB/CustomChecks/CheckRavenDBIndexErrors.cs +++ b/src/ServiceControl.Persistence.RavenDB/CustomChecks/CheckRavenDBIndexErrors.cs @@ -28,7 +28,7 @@ public override async Task PerformCheck(CancellationToken cancellat } var text = new StringBuilder(); - text.AppendLine("Detected RavenDB index errors, please start maintenance mode and resolve the following issues:"); + text.AppendLine("Detected RavenDB index errors. Resolve the following issues in RavenDB Studio, starting the instance in maintenance mode first for an embedded database:"); foreach (var indexError in indexErrors) { diff --git a/src/ServiceControl.Persistence.RavenDB/CustomChecks/CheckRavenDBIndexLag.cs b/src/ServiceControl.Persistence.RavenDB/CustomChecks/CheckRavenDBIndexLag.cs index 6cac66e4ef..97aa4a15d3 100644 --- a/src/ServiceControl.Persistence.RavenDB/CustomChecks/CheckRavenDBIndexLag.cs +++ b/src/ServiceControl.Persistence.RavenDB/CustomChecks/CheckRavenDBIndexLag.cs @@ -25,7 +25,7 @@ public override async Task PerformCheck(CancellationToken cancellat if (indexCountWithTooMuchLag > 0) { - return CheckResult.Failed($"At least one index significantly stale. Please run maintenance mode if this custom check persists to ensure index(es) can recover. See log file for more details. Visit https://docs.particular.net/search?q=servicecontrol+troubleshooting for more information."); + return CheckResult.Failed($"At least one index is significantly stale. If this custom check persists, pause ingestion so the index(es) can recover: start the instance in maintenance mode for an embedded database, or stop the instance for an external RavenDB server. See log file for more details. Visit https://docs.particular.net/search?q=servicecontrol+troubleshooting for more information."); } return CheckResult.Pass; @@ -45,12 +45,12 @@ int CheckAndReportIndexesWithTooMuchIndexLag(IndexInformation[] indexes) if (indexLag > IndexLagThresholdError) { indexCountWithTooMuchLag++; - logger.LogError("Index [{IndexName}] IndexingLag {IndexLag} is above error threshold ({IndexLagThresholdError}). Launch in maintenance mode to let indexes catch up", indexStats.Name, indexLag, IndexLagThresholdError); + logger.LogError("Index [{IndexName}] IndexingLag {IndexLag} is above error threshold ({IndexLagThresholdError}). Pause ingestion to let indexes catch up: use maintenance mode for an embedded database, or stop the instance for an external RavenDB server", indexStats.Name, indexLag, IndexLagThresholdError); } else if (indexLag > IndexLagThresholdWarning) { indexCountWithTooMuchLag++; - logger.LogWarning("Index [{IndexName}] IndexingLag {IndexLag} is above warning threshold ({IndexLagThresholdWarning}). Launch in maintenance mode to let indexes catch up", indexStats.Name, indexLag, IndexLagThresholdWarning); + logger.LogWarning("Index [{IndexName}] IndexingLag {IndexLag} is above warning threshold ({IndexLagThresholdWarning}). Pause ingestion to let indexes catch up: use maintenance mode for an embedded database, or stop the instance for an external RavenDB server", indexStats.Name, indexLag, IndexLagThresholdWarning); } } } diff --git a/src/ServiceControl.Persistence.RavenDB/RavenPersistenceConfiguration.cs b/src/ServiceControl.Persistence.RavenDB/RavenPersistenceConfiguration.cs index 7dfaeb715c..48417c2535 100644 --- a/src/ServiceControl.Persistence.RavenDB/RavenPersistenceConfiguration.cs +++ b/src/ServiceControl.Persistence.RavenDB/RavenPersistenceConfiguration.cs @@ -12,7 +12,6 @@ namespace ServiceControl.Persistence.RavenDB class RavenPersistenceConfiguration : PersistenceConfiguration, IPersistenceConfiguration { public const string DataSpaceRemainingThresholdKey = "DataSpaceRemainingThreshold"; - const string AuditRetentionPeriodKey = "AuditRetentionPeriod"; const string ErrorRetentionPeriodKey = "ErrorRetentionPeriod"; const string ExternalIntegrationsDispatchingBatchSizeKey = "ExternalIntegrationsDispatchingBatchSize"; const string MaintenanceModeKey = "MaintenanceMode"; @@ -38,7 +37,6 @@ public PersistenceSettings CreateSettings(SettingsRootNamespace settingsRootName DataSpaceRemainingThreshold = SettingsReader.Read(settingsRootNamespace, DataSpaceRemainingThresholdKey, CheckFreeDiskSpace.DataSpaceRemainingThresholdDefault), ErrorRetentionPeriod = GetRequiredSetting(settingsRootNamespace, ErrorRetentionPeriodKey), EventsRetentionPeriod = ReadEventsRetentionPeriod(settingsRootNamespace, TimeSpan.FromDays(14)), - AuditRetentionPeriod = SettingsReader.Read(settingsRootNamespace, AuditRetentionPeriodKey, TimeSpan.Zero), ExternalIntegrationsDispatchingBatchSize = ReadExternalIntegrationsDispatchingBatchSize(settingsRootNamespace), QueryTimeout = QueryTimeLimit.Read(settingsRootNamespace, LoggerUtil.CreateStaticLogger()), MaintenanceMode = SettingsReader.Read(settingsRootNamespace, MaintenanceModeKey, false), @@ -87,6 +85,12 @@ static string DefaultLogLocation() public IPersistence Create(PersistenceSettings settings) { var specificSettings = (RavenPersisterSettings)settings; + + if (specificSettings.MaintenanceMode && !specificSettings.UseEmbeddedServer) + { + throw new InvalidOperationException("Maintenance mode is not supported with an external RavenDB server. Stop the ServiceControl instance and access the database directly."); + } + return new RavenPersistence(specificSettings); } } diff --git a/src/ServiceControl.Persistence.RavenDB/RavenPersisterSettings.cs b/src/ServiceControl.Persistence.RavenDB/RavenPersisterSettings.cs index 0f59fd9554..ef286b1bdd 100644 --- a/src/ServiceControl.Persistence.RavenDB/RavenPersisterSettings.cs +++ b/src/ServiceControl.Persistence.RavenDB/RavenPersisterSettings.cs @@ -12,7 +12,6 @@ class RavenPersisterSettings : PersistenceSettings, IRavenClientCertificateInfo public int DataSpaceRemainingThreshold { get; set; } = CheckFreeDiskSpace.DataSpaceRemainingThresholdDefault; public TimeSpan ErrorRetentionPeriod { get; set; } public TimeSpan EventsRetentionPeriod { get; set; } - public TimeSpan? AuditRetentionPeriod { get; set; } public int ExternalIntegrationsDispatchingBatchSize { get; set; } = ExternalIntegrationsDispatchingBatchSizeDefault; /// diff --git a/src/ServiceControl.Persistence.RavenDB/persistence.manifest b/src/ServiceControl.Persistence.RavenDB/persistence.manifest index cc351d645c..9057d349cb 100644 --- a/src/ServiceControl.Persistence.RavenDB/persistence.manifest +++ b/src/ServiceControl.Persistence.RavenDB/persistence.manifest @@ -16,6 +16,9 @@ { "Name": "ServiceControl/DatabaseMaintenancePort", "Mandatory": true + }, + { + "Name": "ServiceControl/EnableFullTextSearchOnBodies" } ], "SettingsWithPathsToCleanup": [ diff --git a/src/ServiceControl.Persistence.Tests.RavenDB/ApprovalFiles/RavenPersistedTypes.Verify.approved.txt b/src/ServiceControl.Persistence.Tests.RavenDB/ApprovalFiles/RavenPersistedTypes.Verify.approved.txt index c0fafba4a7..6eac0fab2d 100644 --- a/src/ServiceControl.Persistence.Tests.RavenDB/ApprovalFiles/RavenPersistedTypes.Verify.approved.txt +++ b/src/ServiceControl.Persistence.Tests.RavenDB/ApprovalFiles/RavenPersistedTypes.Verify.approved.txt @@ -1,14 +1,14 @@ -ServiceControl.Contracts.CustomChecks.CustomCheck, ServiceControl.Persistence.RavenDB, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null -ServiceControl.EventLog.EventLogItem, ServiceControl.Persistence, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null -ServiceControl.MessageFailures.FailedMessage, ServiceControl.Persistence, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null -ServiceControl.MessageFailures.GroupComment, ServiceControl.Persistence, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null -ServiceControl.MessageFailures.QueueAddress, ServiceControl.Persistence, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null -ServiceControl.Operations.FailedErrorImport, ServiceControl.Persistence, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null -ServiceControl.Persistence.KnownEndpoint, ServiceControl.Persistence, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null -ServiceControl.Persistence.MessagesViewIndex+SortAndFilterOptions, ServiceControl.Persistence.RavenDB, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null -ServiceControl.Persistence.RavenDB.FailedMessageRetry, ServiceControl.Persistence.RavenDB, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null -ServiceControl.Persistence.RavenDB.RetryBatch, ServiceControl.Persistence.RavenDB, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null -ServiceControl.Persistence.RavenDB.Throughput.Models.EndpointDocument, ServiceControl.Persistence.RavenDB, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null -ServiceControl.Persistence.RetryBatchGroup, ServiceControl.Persistence, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null -ServiceControl.Recoverability.FailureGroupMessageView, ServiceControl.Persistence, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null -ServiceControl.Recoverability.FailureGroupView, ServiceControl.Persistence, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null \ No newline at end of file +ServiceControl.Contracts.CustomChecks.CustomCheck, ServiceControl.Persistence.RavenDB, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null +ServiceControl.EventLog.EventLogItem, ServiceControl.Persistence, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null +ServiceControl.MessageFailures.FailedMessage, ServiceControl.Persistence, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null +ServiceControl.MessageFailures.GroupComment, ServiceControl.Persistence, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null +ServiceControl.MessageFailures.QueueAddress, ServiceControl.Persistence, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null +ServiceControl.Operations.FailedErrorImport, ServiceControl.Persistence, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null +ServiceControl.Persistence.KnownEndpoint, ServiceControl.Persistence, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null +ServiceControl.Persistence.MessagesViewIndex+SortAndFilterOptions, ServiceControl.Persistence.RavenDB, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null +ServiceControl.Persistence.RavenDB.FailedMessageRetry, ServiceControl.Persistence.RavenDB, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null +ServiceControl.Persistence.RavenDB.RetryBatch, ServiceControl.Persistence.RavenDB, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null +ServiceControl.Persistence.RavenDB.Throughput.Models.EndpointDocument, ServiceControl.Persistence.RavenDB, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null +ServiceControl.Persistence.RetryBatchGroup, ServiceControl.Persistence, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null +ServiceControl.Recoverability.FailureGroupMessageView, ServiceControl.Persistence, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null +ServiceControl.Recoverability.FailureGroupView, ServiceControl.Persistence, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null \ No newline at end of file diff --git a/src/ServiceControl.Persistence.Tests.RavenDB/PersistenceTestsContext.cs b/src/ServiceControl.Persistence.Tests.RavenDB/PersistenceTestsContext.cs index b6610b3ec8..2dcc85ad78 100644 --- a/src/ServiceControl.Persistence.Tests.RavenDB/PersistenceTestsContext.cs +++ b/src/ServiceControl.Persistence.Tests.RavenDB/PersistenceTestsContext.cs @@ -36,7 +36,6 @@ public async Task Setup(IHostApplicationBuilder hostBuilder) PersistenceSettings = new RavenPersisterSettings { - AuditRetentionPeriod = retentionPeriod, ErrorRetentionPeriod = retentionPeriod, EventsRetentionPeriod = retentionPeriod, DatabaseName = databaseName, diff --git a/src/ServiceControl.Persistence.Tests.RavenDB/RavenPersistenceConfigurationTests.cs b/src/ServiceControl.Persistence.Tests.RavenDB/RavenPersistenceConfigurationTests.cs new file mode 100644 index 0000000000..567f30c386 --- /dev/null +++ b/src/ServiceControl.Persistence.Tests.RavenDB/RavenPersistenceConfigurationTests.cs @@ -0,0 +1,40 @@ +namespace ServiceControl.Persistence.Tests; + +using System; +using Microsoft.Extensions.DependencyInjection; +using NUnit.Framework; +using ServiceControl.Persistence.RavenDB; + +[TestFixture] +class RavenPersistenceConfigurationTests +{ + [Test] + public void Should_reject_maintenance_mode_with_external_server() + { + var settings = new RavenPersisterSettings { MaintenanceMode = true, ConnectionString = "http://someserver:44444" }; + + var exception = Assert.Throws(() => new RavenPersistenceConfiguration().Create(settings)); + + Assert.That(exception.Message, Does.Contain("Maintenance mode is not supported")); + } + + [Test] + public void Should_allow_maintenance_mode_with_embedded_server() + { + var settings = new RavenPersisterSettings { MaintenanceMode = true, DatabasePath = "c://db-path" }; + + var services = new ServiceCollection(); + new RavenPersistenceConfiguration().Create(settings).AddPersistence(services); + using var provider = services.BuildServiceProvider(); + + Assert.That(provider.GetRequiredService(), Is.Not.Null); + } + + [Test] + public void Should_allow_normal_mode_with_external_server() + { + var settings = new RavenPersisterSettings { ConnectionString = "http://someserver:44444" }; + + Assert.That(new RavenPersistenceConfiguration().Create(settings), Is.Not.Null); + } +} diff --git a/src/ServiceControl.Persistence.Tests.SqlServer/PersistenceTestsContext.cs b/src/ServiceControl.Persistence.Tests.SqlServer/PersistenceTestsContext.cs index 9ded3182bc..72f7519df9 100644 --- a/src/ServiceControl.Persistence.Tests.SqlServer/PersistenceTestsContext.cs +++ b/src/ServiceControl.Persistence.Tests.SqlServer/PersistenceTestsContext.cs @@ -14,7 +14,7 @@ namespace ServiceControl.Persistence.Tests; using ServiceControl.Persistence.EFCore.Abstractions; using ServiceControl.Persistence.EFCore.Infrastructure; -public partial class PersistenceTestsContext : IPersistenceTestsContext +public partial class PersistenceTestsContext : IPersistenceTestsContext, IAsyncDisposable { IHost host; string connectionString; @@ -62,7 +62,18 @@ public async Task TearDown() { DeleteBodyStorage(); - await TestSchema.Drop(connectionString, schema); + if (!TestSchema.SkipCleanup) + { + await TestSchema.Drop(connectionString, schema); + } + } + + public async ValueTask DisposeAsync() + { + if (TestSchema.SkipCleanup && connectionString != null) + { + await TestSchema.Drop(connectionString, schema); + } } // Drain every insert-only reconciler so that ingested data is visible to the data stores, diff --git a/src/ServiceControl.Persistence.Tests.SqlServer/TestSchema.cs b/src/ServiceControl.Persistence.Tests.SqlServer/TestSchema.cs index 7b8c2d2c7d..57b2745c22 100644 --- a/src/ServiceControl.Persistence.Tests.SqlServer/TestSchema.cs +++ b/src/ServiceControl.Persistence.Tests.SqlServer/TestSchema.cs @@ -7,13 +7,13 @@ namespace ServiceControl.Persistence.Tests; static class TestSchema { - static readonly bool SkipCleanup = string.Equals(Environment.GetEnvironmentVariable("ServiceControl_TESTS_SKIP_SCHEMA_CLEANUP"), "true", StringComparison.OrdinalIgnoreCase); + public static readonly bool SkipCleanup = string.Equals(Environment.GetEnvironmentVariable("ServiceControl_TESTS_SKIP_SCHEMA_CLEANUP"), "true", StringComparison.OrdinalIgnoreCase); static TestSchema() { if (SkipCleanup) { - Console.WriteLine("Schema cleanup is disabled. The workflow must delete the test database after the tests finish."); + Console.WriteLine("Schema cleanup is disabled. Full-text indexes are disabled at teardown; the workflow must delete the test database after the tests finish."); } } @@ -26,7 +26,10 @@ public static Task CreateTable(string connectionString, string schema, string ta // SQL Server has no DROP SCHEMA CASCADE, so the objects have to go first, and the full-text // index has to go before the table it is on. public static Task Drop(string connectionString, string schema, CancellationToken cancellationToken = default) => - SkipCleanup ? Task.CompletedTask : Execute(connectionString, DropSchemaSql, schema, cancellationToken); + Drop(connectionString, schema, SkipCleanup, cancellationToken); + + internal static Task Drop(string connectionString, string schema, bool skipCleanup, CancellationToken cancellationToken = default) => + Execute(connectionString, skipCleanup ? DisableFullTextIndexesSql : DropSchemaSql, schema, cancellationToken); // Tests share one database now, so a schema being set up or torn down contends on the system // catalogs with every other test's CREATE and DROP, and with the transport tests, which CI points @@ -67,6 +70,21 @@ IF SCHEMA_ID(@schema) IS NULL END """; + // Retained schemas must not leave full-text populations competing with later tests. + const string DisableFullTextIndexesSql = """ + SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; + + DECLARE @sql nvarchar(max) = N''; + + SELECT @sql = @sql + N'ALTER FULLTEXT INDEX ON ' + QUOTENAME(s.name) + N'.' + QUOTENAME(t.name) + N' DISABLE;' + FROM sys.fulltext_indexes fi + JOIN sys.tables t ON fi.object_id = t.object_id + JOIN sys.schemas s ON t.schema_id = s.schema_id + WHERE s.name = @schema AND fi.is_enabled = 1; + + EXEC sp_executesql @sql; + """; + const string DropSchemaSql = """ -- Only this test's own schema is read, and no other session creates or drops anything in it, -- so a dirty read cannot be wrong here. It does mean the catalog reads take no shared locks, diff --git a/src/ServiceControl.Persistence.Tests.SqlServer/TestSchemaTests.cs b/src/ServiceControl.Persistence.Tests.SqlServer/TestSchemaTests.cs new file mode 100644 index 0000000000..f9037996ac --- /dev/null +++ b/src/ServiceControl.Persistence.Tests.SqlServer/TestSchemaTests.cs @@ -0,0 +1,162 @@ +namespace ServiceControl.Persistence.Tests; + +using System; +using System.Threading; +using System.Threading.Tasks; +using EFCore.SqlServer; +using Microsoft.Data.SqlClient; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using NUnit.Framework; + +[TestFixture] +class TestSchemaTests +{ + [SetUp] + public async Task SetUp() + { + connectionString = await SqlServerSharedContainer.GetConnectionStringAsync(); + await Execute($"CREATE FULLTEXT CATALOG [{catalog}]"); + } + + [TearDown] + public async Task TearDown() + { + await TestSchema.Drop(connectionString, schema, skipCleanup: false); + await TestSchema.Drop(connectionString, otherSchema, skipCleanup: false); + await Execute($"DROP FULLTEXT CATALOG [{catalog}]"); + } + + [TestCase("")] + [TestCase("]'quoted")] + public async Task Retained_schema_cleanup_disables_only_its_full_text_indexes(string schemaSuffix) + { + schema += schemaSuffix; + await CreateIndexedSchema(schema); + await CreateIndexedSchema(otherSchema); + Assert.That(await ReadSchemaState(schema), Is.EqualTo((1, 2, 2, 2))); + + await TestSchema.Drop(connectionString, schema, skipCleanup: true); + await TestSchema.Drop(connectionString, schema, skipCleanup: true); + + Assert.That(await ReadSchemaState(schema), Is.EqualTo((1, 2, 2, 0))); + Assert.That(await ReadSchemaState(otherSchema), Is.EqualTo((1, 2, 2, 2))); + + await using var connection = new SqlConnection(connectionString); + await connection.OpenAsync(); + await using var command = connection.CreateCommand(); + command.CommandText = $"SELECT Body FROM {Quote(schema)}.Messages WHERE Id = 1"; + Assert.That(await command.ExecuteScalarAsync(), Is.EqualTo("keep this row")); + } + + [Test] + public async Task Normal_cleanup_drops_only_its_schema_and_full_text_indexes() + { + await CreateIndexedSchema(schema); + await CreateIndexedSchema(otherSchema); + + await TestSchema.Drop(connectionString, schema, skipCleanup: false); + + Assert.That(await ReadSchemaState(schema), Is.EqualTo((0, 0, 0, 0))); + Assert.That(await ReadSchemaState(otherSchema), Is.EqualTo((1, 2, 2, 2))); + } + + [Test] + public async Task Retained_schema_cleanup_handles_missing_indexes_and_schemas() + { + await TestSchema.Create(connectionString, schema); + await TestSchema.CreateTable(connectionString, schema, "Messages"); + + await TestSchema.Drop(connectionString, schema, skipCleanup: true); + await TestSchema.Drop(connectionString, schema, skipCleanup: true); + await TestSchema.Drop(connectionString, otherSchema, skipCleanup: true); + + Assert.That(await ReadSchemaState(schema), Is.EqualTo((1, 1, 0, 0))); + Assert.That(await ReadSchemaState(otherSchema), Is.EqualTo((0, 0, 0, 0))); + } + + [Test] + public async Task Primary_persistence_teardown_disables_retained_indexes_after_host_shutdown() + { + var enabledAtShutdown = -1; + string persistenceSchema = null; + var fixture = new PersistenceFixture(async _ => enabledAtShutdown = (await ReadSchemaState(persistenceSchema)).EnabledIndexes); + await fixture.SetUp(); + persistenceSchema = fixture.Settings.Schema; + + await fixture.TearDown(); + + Assert.That(enabledAtShutdown, Is.EqualTo(TestSchema.SkipCleanup ? 1 : 0)); + var state = await ReadSchemaState(persistenceSchema); + Assert.That(state.Schemas, Is.EqualTo(TestSchema.SkipCleanup ? 1 : 0)); + Assert.That(state.Indexes, Is.EqualTo(TestSchema.SkipCleanup ? 1 : 0)); + Assert.That(state.EnabledIndexes, Is.Zero); + } + + sealed class PersistenceFixture : PersistenceTestBase + { + public PersistenceFixture(Func onStop) => + RegisterServices = services => services.AddSingleton(new ShutdownProbe(onStop)); + + public SqlServerPersisterSettings Settings => (SqlServerPersisterSettings)PersistenceSettings; + } + + sealed class ShutdownProbe(Func onStop) : IHostedService + { + public Task StartAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; + + public Task StopAsync(CancellationToken cancellationToken = default) => onStop(cancellationToken); + } + + async Task CreateIndexedSchema(string schemaName) + { + await TestSchema.Create(connectionString, schemaName); + foreach (var table in new[] { "Messages", "OtherMessages" }) + { + await Execute($""" + CREATE TABLE {Quote(schemaName)}.[{table}] ( + Id int NOT NULL CONSTRAINT [PK_{table}] PRIMARY KEY, + Body nvarchar(max) NOT NULL); + CREATE FULLTEXT INDEX ON {Quote(schemaName)}.[{table}] (Body LANGUAGE 0) + KEY INDEX [PK_{table}] ON [{catalog}] WITH CHANGE_TRACKING AUTO; + INSERT INTO {Quote(schemaName)}.[{table}] (Id, Body) VALUES (1, N'keep this row'); + """); + } + } + + async Task<(int Schemas, int Tables, int Indexes, int EnabledIndexes)> ReadSchemaState(string schemaName) + { + await using var connection = new SqlConnection(connectionString); + await connection.OpenAsync(); + await using var command = connection.CreateCommand(); + command.CommandText = """ + SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; + SELECT (SELECT COUNT(*) FROM sys.schemas WHERE name = @schema), + (SELECT COUNT(*) FROM sys.tables WHERE schema_id = SCHEMA_ID(@schema)), + (SELECT COUNT(*) FROM sys.fulltext_indexes fi + JOIN sys.tables t ON fi.object_id = t.object_id WHERE t.schema_id = SCHEMA_ID(@schema)), + (SELECT COUNT(*) FROM sys.fulltext_indexes fi + JOIN sys.tables t ON fi.object_id = t.object_id WHERE t.schema_id = SCHEMA_ID(@schema) AND fi.is_enabled = 1) + """; + command.Parameters.AddWithValue("@schema", schemaName); + await using var reader = await command.ExecuteReaderAsync(); + await reader.ReadAsync(); + return (reader.GetInt32(0), reader.GetInt32(1), reader.GetInt32(2), reader.GetInt32(3)); + } + + async Task Execute(string sql) + { + await using var connection = new SqlConnection(connectionString); + await connection.OpenAsync(); + await using var command = connection.CreateCommand(); + command.CommandText = sql; + await command.ExecuteNonQueryAsync(); + } + + static string Quote(string identifier) => $"[{identifier.Replace("]", "]]")}]"; + + string connectionString; + string schema = $"sc_cleanup_{Guid.NewGuid():N}"; + readonly string otherSchema = $"sc_cleanup_{Guid.NewGuid():N}"; + readonly string catalog = $"sc_cleanup_{Guid.NewGuid():N}"; +} diff --git a/src/ServiceControl.Persistence.Tests/EFCore/EFRecoverabilityIngestionUnitOfWorkTests.cs b/src/ServiceControl.Persistence.Tests/EFCore/EFRecoverabilityIngestionUnitOfWorkTests.cs new file mode 100644 index 0000000000..da12407448 --- /dev/null +++ b/src/ServiceControl.Persistence.Tests/EFCore/EFRecoverabilityIngestionUnitOfWorkTests.cs @@ -0,0 +1,90 @@ +namespace ServiceControl.Persistence.Tests; + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using NServiceBus; +using NServiceBus.Extensibility; +using NServiceBus.Transport; +using NUnit.Framework; +using ServiceControl.MessageFailures; +using ServiceControl.Persistence.EFCore.Abstractions; +using ServiceControl.Persistence.EFCore.Implementation.UnitOfWork; +using ServiceControl.Persistence.Infrastructure; + +// The unit of work is never completed or disposed, so the database, scope and dialect are unused. +[TestFixture] +class EFRecoverabilityIngestionUnitOfWorkTests +{ + const string RetryHeader = "ServiceControl.Retry.UniqueMessageId"; + + InMemoryBodyStoragePersistence storage; + EFRecoverabilityIngestionUnitOfWork unitOfWork; + + [SetUp] + public void SetUp() + { + storage = new InMemoryBodyStoragePersistence(); + var settings = new TestSettings { ConnectionString = "unused", BodyStorage = new FileSystemBodyStorageSettings { StoragePath = "unused" } }; + var parent = new EFIngestionUnitOfWork(null, null, storage, settings, null, TimeProvider.System); + unitOfWork = new EFRecoverabilityIngestionUnitOfWork(parent, storage, settings); + } + + async Task Record(string retryHeaderValue) + { + var headers = new Dictionary + { + [Headers.MessageId] = Guid.NewGuid().ToString(), + [Headers.ProcessingEndpoint] = "Receiver", + [Headers.ContentType] = "application/octet-stream" + }; + if (retryHeaderValue is not null) + { + headers[RetryHeader] = retryHeaderValue; + } + + var context = new MessageContext("native", headers, new byte[] { 1, 2, 3 }, new TransportTransaction(), "receiver", new ContextBag()); + var attempt = new FailedMessage.ProcessingAttempt { Headers = headers }; + + await unitOfWork.RecordFailedProcessingAttempt(context, attempt, []); + + return storage.Written[^1].BodyId; + } + + [TestCase("../traversal")] + [TestCase("not a guid")] + public async Task A_malformed_retry_header_stores_the_body_under_a_deterministic_guid(string value) + { + var first = await Record(value); + var second = await Record(value); + + using (Assert.EnterMultipleScope()) + { + Assert.That(Guid.TryParse(first, out var parsed), Is.True); + Assert.That(parsed, Is.EqualTo(DeterministicGuid.MakeId(value))); + Assert.That(second, Is.EqualTo(first)); + } + } + + [Test] + public async Task A_valid_noncanonical_guid_is_stored_in_canonical_form() + { + var guid = Guid.NewGuid(); + + var bodyId = await Record(guid.ToString("N").ToUpperInvariant()); + + Assert.That(bodyId, Is.EqualTo(guid.ToString())); + } + + [Test] + public async Task A_message_without_a_retry_header_stores_the_body_under_its_derived_guid() + { + var bodyId = await Record(null); + + Assert.That(Guid.TryParse(bodyId, out _), Is.True); + } + + sealed class TestSettings : EFPersisterSettings + { + } +} diff --git a/src/ServiceControl.Persistence.Tests/EFCore/FileSystemBodyStoragePersistenceTests.cs b/src/ServiceControl.Persistence.Tests/EFCore/FileSystemBodyStoragePersistenceTests.cs index 51b7bf5944..40cf1b70e9 100644 --- a/src/ServiceControl.Persistence.Tests/EFCore/FileSystemBodyStoragePersistenceTests.cs +++ b/src/ServiceControl.Persistence.Tests/EFCore/FileSystemBodyStoragePersistenceTests.cs @@ -7,32 +7,42 @@ namespace ServiceControl.Persistence.Tests; using System.Threading.Tasks; using NUnit.Framework; using ServiceControl.Persistence.EFCore.Abstractions; +using ServiceControl.Persistence.EFCore.Entities; using ServiceControl.Persistence.EFCore.Implementation.BodyStorage; [TestFixture] class FileSystemBodyStoragePersistenceTests { + const string BodyId = "6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10"; + const string MissingBodyId = "0b9a1d52-4d7c-4f3e-8a21-5c6e7f8091a2"; + string tempDir; + string outsideDir; FileSystemBodyStoragePersistence store; [SetUp] public void SetUp() { tempDir = Directory.CreateTempSubdirectory("sc-body-tests-").FullName; + outsideDir = Directory.CreateTempSubdirectory("sc-body-outside-").FullName; store = new FileSystemBodyStoragePersistence(new FileSystemBodyStorageSettings { StoragePath = tempDir, MinCompressionSize = 64 }); } [TearDown] - public void TearDown() => Directory.Delete(tempDir, recursive: true); + public void TearDown() + { + Directory.Delete(tempDir, recursive: true); + Directory.Delete(outsideDir, recursive: true); + } [TestCase(11)] [TestCase(100_000)] public async Task Round_trips_compressed_and_uncompressed_bodies(int bodyLength) { var body = Encoding.UTF8.GetBytes(new string('a', bodyLength)); - await store.WriteBody("body-1", body, "application/json"); + await store.WriteBody(BodyId, body, "application/json"); - var result = await store.ReadBody("body-1"); + var result = await store.ReadBody(BodyId); Assert.That(result, Is.Not.Null); using (result.Stream) @@ -50,10 +60,10 @@ public async Task Round_trips_compressed_and_uncompressed_bodies(int bodyLength) [Test] public async Task Rewriting_a_body_keeps_the_first_write() { - await store.WriteBody("body-1", Encoding.UTF8.GetBytes("original"), "text/plain"); - await store.WriteBody("body-1", Encoding.UTF8.GetBytes("different"), "text/plain"); + await store.WriteBody(BodyId, Encoding.UTF8.GetBytes("original"), "text/plain"); + await store.WriteBody(BodyId, Encoding.UTF8.GetBytes("different"), "text/plain"); - var result = await store.ReadBody("body-1"); + var result = await store.ReadBody(BodyId); using (result.Stream) { @@ -64,8 +74,8 @@ public async Task Rewriting_a_body_keeps_the_first_write() [Test] public async Task Missing_body_reads_as_null_and_deletes_quietly() { - Assert.That(await store.ReadBody("missing"), Is.Null); - Assert.DoesNotThrowAsync(() => store.DeleteBodyIfExists("missing")); + Assert.That(await store.ReadBody(MissingBodyId), Is.Null); + Assert.DoesNotThrowAsync(() => store.DeleteBodyIfExists(MissingBodyId)); } [Test] @@ -97,11 +107,71 @@ public async Task Reading_when_the_storage_directory_is_gone_finds_nothing() { Directory.Delete(tempDir, recursive: true); - Assert.That(await store.ReadBody("body-1"), Is.Null); + Assert.That(await store.ReadBody(BodyId), Is.Null); Directory.CreateDirectory(tempDir); } + [Test] + public async Task Failed_import_body_ids_round_trip_and_delete() + { + var bodyId = FailedErrorImportEntity.ExternalBodyId(Guid.Parse(BodyId)); + await store.WriteBody(bodyId, Encoding.UTF8.GetBytes("payload"), "text/plain"); + + Assert.That(File.Exists(Path.Combine(tempDir, $"{bodyId}.body")), Is.True); + var result = await store.ReadBody(bodyId); + Assert.That(result, Is.Not.Null); + using (result.Stream) + { + Assert.That(ReadAll(result.Stream), Is.EqualTo(Encoding.UTF8.GetBytes("payload"))); + } + + await store.DeleteBodyIfExists(bodyId); + + Assert.That(Directory.GetFileSystemEntries(tempDir), Is.Empty); + } + + [TestCase(null)] + [TestCase("")] + [TestCase("body-1")] + [TestCase("../6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("..\\6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("/etc/6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("C:\\temp\\6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("failedimport-")] + [TestCase("failedimport-../x")] + [TestCase("failedimport-..\\x")] + [TestCase("failedimport-6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10/x")] + [TestCase("FAILEDIMPORT-6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("failedimport-failedimport-6f0e5a47-6c9b-4a5c-9d86-3b2d1c8a7e10")] + [TestCase("outside-relative")] + [TestCase("outside-rooted")] + public async Task Invalid_body_ids_are_rejected_without_touching_the_file_system(string bodyId) + { + var outsideFile = Path.Combine(outsideDir, "target.body"); + await File.WriteAllTextAsync(outsideFile, "keep"); + bodyId = bodyId switch + { + "outside-relative" => Path.GetRelativePath(tempDir, Path.Combine(outsideDir, "target")), + "outside-rooted" => Path.Combine(outsideDir, "target"), + _ => bodyId + }; + + var write = Assert.ThrowsAsync(() => store.WriteBody(bodyId, Encoding.UTF8.GetBytes("payload"), "text/plain")); + var read = Assert.ThrowsAsync(() => store.ReadBody(bodyId)); + var delete = Assert.ThrowsAsync(() => store.DeleteBodyIfExists(bodyId)); + + Assert.Multiple(() => + { + Assert.That(write.ParamName, Is.EqualTo("bodyId")); + Assert.That(read.ParamName, Is.EqualTo("bodyId")); + Assert.That(delete.ParamName, Is.EqualTo("bodyId")); + Assert.That(Directory.GetFileSystemEntries(tempDir), Is.Empty); + Assert.That(Directory.GetFileSystemEntries(outsideDir), Is.EqualTo(new[] { outsideFile })); + Assert.That(File.ReadAllText(outsideFile), Is.EqualTo("keep")); + }); + } + static byte[] ReadAll(Stream stream) { using var buffer = new MemoryStream(); diff --git a/src/ServiceControl.Persistence.Tests/EFCore/RetentionSweepTests.cs b/src/ServiceControl.Persistence.Tests/EFCore/RetentionSweepTests.cs index 41d435247c..4319cff284 100644 --- a/src/ServiceControl.Persistence.Tests/EFCore/RetentionSweepTests.cs +++ b/src/ServiceControl.Persistence.Tests/EFCore/RetentionSweepTests.cs @@ -619,37 +619,15 @@ public async Task Scheduled_sweep_with_a_failing_pass_reports_failed() [Test] public async Task A_cancelled_sweep_keeps_the_errors_of_passes_that_failed_first() { + // Subtracting this from the clock cannot be represented, so the failed messages pass fails before the first delete. + // The interceptor cancels the sweep at that delete, so the failure is recorded before the cancellation. EFSettings.ErrorRetentionPeriod = TimeSpan.FromDays(1_000_000); using var cancellation = new CancellationTokenSource(); - var sweeper = GetSweeper(); - - // The failed messages pass throws before any database call, so by the time the start returns - // the event log pass is waiting on the database and the cancellation lands there. - sweeper.TryStartManualSweep(null, null, cancellation.Token); - await cancellation.CancelAsync(); - - await WaitForManualSweepToFinish(); - - var status = sweeper.GetStatus(); - - using (Assert.EnterMultipleScope()) - { - Assert.That(status.LastOutcome, Is.EqualTo(RetentionSweepOutcome.Cancelled)); - Assert.That(status.LastError, Does.Contain(nameof(RetentionEntity.FailedMessages))); - } - } + cancelAfterBatchDelete.Cancellation = cancellation; - [Test] - public async Task Manual_sweep_cancelled_part_way_reports_cancelled() - { - using var cancellation = new CancellationTokenSource(); var sweeper = GetSweeper(); - - // The background sweep runs on this thread until its first database call, so it is still - // running when the token is cancelled. sweeper.TryStartManualSweep(null, null, cancellation.Token); - await cancellation.CancelAsync(); await WaitForManualSweepToFinish(); @@ -658,8 +636,7 @@ public async Task Manual_sweep_cancelled_part_way_reports_cancelled() using (Assert.EnterMultipleScope()) { Assert.That(status.LastOutcome, Is.EqualTo(RetentionSweepOutcome.Cancelled)); - Assert.That(status.LastError, Is.Null); - Assert.That(status.LastFinishedAt, Is.Not.Null); + Assert.That(status.LastError, Does.Contain(nameof(RetentionEntity.FailedMessages))); } } @@ -758,11 +735,15 @@ public async Task An_event_log_pass_cancelled_between_batches_is_recorded_as_can await WaitForManualSweepToFinish(); + var status = sweeper.GetStatus(); + using (Assert.EnterMultipleScope()) { Assert.That(recorded.Cycles(RetentionEntity.EventLog).Select(cycle => cycle.Result), Is.EqualTo(new[] { "cancelled" })); Assert.That(recorded.Cycles(RetentionEntity.GroupComments), Is.Empty, "the sweep must stop at the pass that was cut short"); - Assert.That(sweeper.GetStatus().LastOutcome, Is.EqualTo(RetentionSweepOutcome.Cancelled)); + Assert.That(status.LastOutcome, Is.EqualTo(RetentionSweepOutcome.Cancelled)); + Assert.That(status.LastError, Is.Null, "a cancelled pass is not an error"); + Assert.That(status.LastFinishedAt, Is.Not.Null); Assert.That(await Query(dbContext => dbContext.EventLogItems.CountAsync()), Is.EqualTo(500), "exactly one batch is deleted before the cancellation"); } } diff --git a/src/ServiceControl.Persistence.Tests/PersistenceTestBase.cs b/src/ServiceControl.Persistence.Tests/PersistenceTestBase.cs index f065c190f6..7d6f9b97ab 100644 --- a/src/ServiceControl.Persistence.Tests/PersistenceTestBase.cs +++ b/src/ServiceControl.Persistence.Tests/PersistenceTestBase.cs @@ -60,10 +60,14 @@ public async Task SetUp() [TearDown] public async Task TearDown() { - // Needs to go first or database will be disposed - await PersistenceTestsContext.TearDown(); - await host.StopAsync(); - host.Dispose(); + // SQL Server retires retained full-text indexes only after the host releases the database. + await using var cleanup = PersistenceTestsContext as IAsyncDisposable; + using (host) + { + // Needs to go first or database will be disposed + await PersistenceTestsContext.TearDown(); + await host.StopAsync(); + } } protected PersistenceTestsContext PersistenceTestsContext { get; private set; } diff --git a/src/ServiceControl.Persistence.Tests/Recoverability/RetryStagingStoreTests.cs b/src/ServiceControl.Persistence.Tests/Recoverability/RetryStagingStoreTests.cs index ea576afa94..5f3861c2f9 100644 --- a/src/ServiceControl.Persistence.Tests/Recoverability/RetryStagingStoreTests.cs +++ b/src/ServiceControl.Persistence.Tests/Recoverability/RetryStagingStoreTests.cs @@ -225,6 +225,25 @@ public async Task Removing_a_message_from_the_batch_leaves_it_out_of_staging() Assert.That(messages.Single().UniqueMessageId, Is.EqualTo(kept)); } + [Test] + public async Task The_next_retry_stages_a_message_whose_send_failed_but_not_one_that_was_sent() + { + var failedToSend = await Insert(new IngestedFailure()); + var sent = await Insert(new IngestedFailure()); + + var firstBatch = await StageBatch(failedToSend, sent); + await RetryStagingStore.MarkBatchAsForwarding(firstBatch, "staging-1", [failedToSend, sent]); + await FailedMessageLifecycleStore.RevertRetry(failedToSend); + await RetryStagingStore.CompleteForwarding(firstBatch); + await CompleteDatabaseOperation(); + + var secondBatch = await StageBatch(failedToSend, sent); + + var messages = await RetryStagingStore.GetMessagesToStage(secondBatch); + + Assert.That(messages.Select(message => message.UniqueMessageId), Is.EquivalentTo(new[] { failedToSend })); + } + async Task Insert(IngestedFailure failure) { var message = failure.ToFailedMessage(); diff --git a/src/ServiceControl.Persistence/PersistenceManifest.cs b/src/ServiceControl.Persistence/PersistenceManifest.cs index 7f5f0a1d67..905d557e43 100644 --- a/src/ServiceControl.Persistence/PersistenceManifest.cs +++ b/src/ServiceControl.Persistence/PersistenceManifest.cs @@ -27,19 +27,19 @@ public class PersistenceManifest public string[] Aliases { get; set; } = []; - internal bool IsMatch(string persistenceType) => - string.Equals(Name, persistenceType, StringComparison.OrdinalIgnoreCase) - || Aliases.Contains(persistenceType, StringComparer.Ordinal) - || IsTypeMatch(persistenceType); + internal bool IsMatch(string storageType) => + string.Equals(Name, storageType, StringComparison.OrdinalIgnoreCase) + || Aliases.Contains(storageType, StringComparer.Ordinal) + || IsTypeMatch(storageType); - bool IsTypeMatch(string persistenceType) + bool IsTypeMatch(string storageType) { - if (string.Equals(TypeName, persistenceType, StringComparison.Ordinal)) // Type names are case-sensitive + if (string.Equals(TypeName, storageType, StringComparison.Ordinal)) // Type names are case-sensitive { return true; } - var type = Type.GetType(persistenceType); + var type = Type.GetType(storageType); if (type == null) { return false; @@ -115,14 +115,14 @@ static string GetAssemblyDirectory() ?? throw new InvalidOperationException("The persistence assembly has no containing directory."); } - public static PersistenceManifest? Find(string persistenceType) + public static PersistenceManifest? Find(string storageType) { - if (persistenceType == null) + if (storageType == null) { - throw new Exception("No persistenceType has been configured. Either provide a Type or Name in the PersistenceType setting."); + throw new Exception("No storageType has been configured. Either provide a Type or Name in the StorageType setting."); } - var persistenceManifest = PersistenceManifests.FirstOrDefault(w => w.IsMatch(persistenceType)); + var persistenceManifest = PersistenceManifests.FirstOrDefault(w => w.IsMatch(storageType)); return persistenceManifest; } diff --git a/src/ServiceControl.RavenDB/Container-README.md b/src/ServiceControl.RavenDB/Container-README.md index 0c7b42a517..06d223e27a 100644 --- a/src/ServiceControl.RavenDB/Container-README.md +++ b/src/ServiceControl.RavenDB/Container-README.md @@ -7,10 +7,10 @@ The `particular/servicecontrol-ravendb` image is part of the Particular Service | [`particular/servicecontrol`](https://hub.docker.com/r/particular/servicecontrol) | [Instance Documentation](https://docs.particular.net/servicecontrol/servicecontrol-instances/)
[Container Documentation](https://docs.particular.net/servicecontrol/servicecontrol-instances/deployment/containers) | The primary/error instance, which includes error handling and recoverability | | [`particular/servicecontrol-audit`](https://hub.docker.com/r/particular/servicecontrol-audit) | [Instance Documentation](https://docs.particular.net/servicecontrol/audit-instances/)
[Container Documentation](https://docs.particular.net/servicecontrol/audit-instances/deployment/containers) | The audit instance, which stores audit data, and can be scaled out to multiple audit instances | | [`particular/servicecontrol-monitoring`](https://hub.docker.com/r/particular/servicecontrol-monitoring) | [Instance Documentation](https://docs.particular.net/servicecontrol/monitoring-instances/)
[Container Documentation](https://docs.particular.net/servicecontrol/monitoring-instances/deployment/containers) | The monitoring instance, which tracks runtime information like throughput, queue length, and other metrics | -| [`particular/servicecontrol-ravendb`](https://hub.docker.com/r/particular/servicecontrol-ravendb) | [Container Documentation](https://docs.particular.net/servicecontrol/ravendb/containers) | The database used by the error/audit instances | +| [`particular/servicecontrol-ravendb`](https://hub.docker.com/r/particular/servicecontrol-ravendb) | [Container Documentation](https://docs.particular.net/servicecontrol/storage/ravendb/containers) | The database for error/audit instances using RavenDB persistence | | [`particular/servicepulse`](https://hub.docker.com/r/particular/servicepulse) | [App Documentation](https://docs.particular.net/servicepulse/)
[Container Documentation](https://docs.particular.net/servicepulse/containerization/) | The web application that provides a front end for recoverability and monitoring features | -This image is the database used by the [`particular/servicecontrol`](https://hub.docker.com/r/particular/servicecontrol) and [`particular/servicecontrol-audit`](https://hub.docker.com/r/particular/servicecontrol-audit) images, based on the official [RavenDB image](https://hub.docker.com/r/ravendb/ravendb). +This image provides the database for the [`particular/servicecontrol`](https://hub.docker.com/r/particular/servicecontrol) and [`particular/servicecontrol-audit`](https://hub.docker.com/r/particular/servicecontrol-audit) images when `STORAGETYPE=RavenDB`. It is based on the official [RavenDB image](https://hub.docker.com/r/ravendb/ravendb). Instances using [other storage providers](https://docs.particular.net/servicecontrol/storage/) do not need this image. The purpose of this image is to provide version parity between ServiceControl and database containers. Users can be sure that a given version of the `servicecontrol` and `servicecontrol-audit` container images have been tested with and are known to work with the matching version of `servicecontrol-ravendb`. @@ -25,7 +25,7 @@ docker run -d --name servicecontrol-db \ particular/servicecontrol-ravendb:latest ``` -For all other usage information see the [official container documentation](https://docs.particular.net/servicecontrol/ravendb/containers). +For all other usage information see the [official container documentation](https://docs.particular.net/servicecontrol/storage/ravendb/containers). _**IMPORTANT:** A single database container should not be shared between multiple ServiceControl instances in production scenarios._ diff --git a/src/ServiceControl.Transports.ASBS.Tests/FindNamespaceTests.cs b/src/ServiceControl.Transports.ASBS.Tests/FindNamespaceTests.cs new file mode 100644 index 0000000000..088ff6e66c --- /dev/null +++ b/src/ServiceControl.Transports.ASBS.Tests/FindNamespaceTests.cs @@ -0,0 +1,118 @@ +namespace ServiceControl.Transport.Tests; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Azure; +using Azure.ResourceManager.ServiceBus; +using Azure.ResourceManager.ServiceBus.Models; +using NUnit.Framework; +using Transports.ASBS; + +[TestFixture] +class FindNamespaceTests +{ + [TestCase("contoso")] + [TestCase("CONTOSO")] + public async Task Matches_a_namespace_by_name_without_reading_aliases(string name) + { + var contoso = Namespace("contoso", NotToBeRead); + + var found = await AzureQuery.FindNamespace(Listed(Namespace("fabrikam", NotToBeRead), contoso), name); + + Assert.That(found, Is.SameAs(contoso)); + } + + [Test] + public async Task Resolves_a_geo_recovery_alias_to_its_primary_namespace() + { + var primary = Namespace("contoso-west", Alias("contoso", ServiceBusDisasterRecoveryRole.Primary)); + + var found = await AzureQuery.FindNamespace(Listed(Namespace("contoso-east", Alias("contoso", ServiceBusDisasterRecoveryRole.Secondary)), primary), "CONTOSO"); + + Assert.That(found, Is.SameAs(primary)); + } + + [Test] + public async Task Resolves_a_geo_recovery_alias_after_failover() + { + var newPrimary = Namespace("contoso-east", Alias("contoso", ServiceBusDisasterRecoveryRole.PrimaryNotReplicating)); + + var found = await AzureQuery.FindNamespace(Listed(Namespace("contoso-west"), newPrimary), "contoso"); + + Assert.That(found, Is.SameAs(newPrimary)); + } + + [Test] + public async Task Skips_namespaces_whose_aliases_cannot_be_read() + { + var primary = Namespace("contoso-west", Alias("contoso", ServiceBusDisasterRecoveryRole.Primary)); + + var found = await AzureQuery.FindNamespace(Listed(Namespace("fabrikam", Forbidden), primary), "contoso"); + + Assert.That(found, Is.SameAs(primary)); + } + + [Test] + public void Does_not_resolve_an_alias_to_its_secondary_namespace() + { + var exception = Assert.ThrowsAsync(() => + AzureQuery.FindNamespace(Listed(Namespace("contoso-east", Alias("contoso", ServiceBusDisasterRecoveryRole.Secondary))), "contoso")); + + Assert.That(exception.Message, Is.EqualTo("Could not find an Azure Service Bus namespace or Geo-Recovery alias named \"contoso\"")); + } + + [Test] + public void Names_the_missing_permission_when_aliases_cannot_be_read() + { + var exception = Assert.ThrowsAsync(() => AzureQuery.FindNamespace(Listed(Namespace("contoso-west", Forbidden)), "contoso")); + + Assert.That(exception.Message, Is.EqualTo("Could not find an Azure Service Bus namespace named \"contoso\". If \"contoso\" is a Geo-Recovery alias, resolving it requires the Microsoft.ServiceBus/namespaces/disasterRecoveryConfigs/read permission.")); + } + + static IAsyncEnumerable Listed(params ServiceBusNamespaceResource[] namespaces) => namespaces.ToAsyncEnumerable(); + + static ServiceBusNamespaceResource Namespace(string name, params ServiceBusDisasterRecoveryData[] aliases) => + new FakeNamespace(name, () => aliases); + + static ServiceBusNamespaceResource Namespace(string name, Func> aliases) => + new FakeNamespace(name, aliases); + + static ServiceBusDisasterRecoveryData Alias(string name, ServiceBusDisasterRecoveryRole role) => + ArmServiceBusModelFactory.ServiceBusDisasterRecoveryData(name: name, role: role); + + static readonly Func> NotToBeRead = + () => throw new AssertionException("Aliases were read although a namespace matched by name"); + + static readonly Func> Forbidden = + () => throw new RequestFailedException(403, "The client does not have authorization to perform action 'Microsoft.ServiceBus/namespaces/disasterRecoveryConfigs/read'"); + + class FakeNamespace(string name, Func> aliases) : ServiceBusNamespaceResource + { + public override bool HasData => true; + + public override ServiceBusNamespaceData Data { get; } = ArmServiceBusModelFactory.ServiceBusNamespaceData(name: name, geoDataReplication: null); + + public override ServiceBusDisasterRecoveryCollection GetServiceBusDisasterRecoveries() => new FakeAliases(aliases); + } + + class FakeAliases(Func> aliases) : ServiceBusDisasterRecoveryCollection + { + public override AsyncPageable GetAllAsync(CancellationToken cancellationToken = default) => + AsyncPageable.FromPages(Pages()); + + IEnumerable> Pages() + { + yield return Page.FromValues([.. aliases().Select(data => new FakeAlias(data))], null, null); + } + } + + class FakeAlias(ServiceBusDisasterRecoveryData data) : ServiceBusDisasterRecoveryResource + { + public override bool HasData => true; + + public override ServiceBusDisasterRecoveryData Data => data; + } +} diff --git a/src/ServiceControl.Transports.ASBS/AzureQuery.cs b/src/ServiceControl.Transports.ASBS/AzureQuery.cs index fa1430251a..a51571e0ba 100644 --- a/src/ServiceControl.Transports.ASBS/AzureQuery.cs +++ b/src/ServiceControl.Transports.ASBS/AzureQuery.cs @@ -9,6 +9,7 @@ namespace ServiceControl.Transports.ASBS; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; +using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.Identity; @@ -17,9 +18,8 @@ namespace ServiceControl.Transports.ASBS; using Azure.ResourceManager.Monitor.Models; using Azure.ResourceManager.Resources; using Azure.ResourceManager.ServiceBus; +using Azure.ResourceManager.ServiceBus.Models; using BrokerThroughput; -using DnsClient; -using DnsClient.Protocol; using Microsoft.Extensions.Logging; public class AzureQuery(ILogger logger, TimeProvider timeProvider, TransportSettings transportSettings) @@ -36,7 +36,6 @@ public class AzureQuery(ILogger logger, TimeProvider timeProvider, T ArmClient? armClient; TokenCredential? credential; ResourceIdentifier? resourceId; - ArmEnvironment armEnvironment; protected override void InitializeCore(ReadOnlyDictionary settings) { @@ -109,7 +108,7 @@ protected override void InitializeCore(ReadOnlyDictionary settin Diagnostics.AppendLine("Client secret set"); } - armEnvironment = GetEnvironment(); + ArmEnvironment armEnvironment = GetEnvironment(); if (managementUrl == null) { @@ -274,64 +273,55 @@ async Task> GetMetrics(string queueName, DateO public override async IAsyncEnumerable GetQueueNames( [EnumeratorCancellation] CancellationToken cancellationToken = default) { - var validNamespaces = await GetValidNamespaceNames(cancellationToken); + SubscriptionResource subscription = await armClient!.GetDefaultSubscriptionAsync(cancellationToken); + ServiceBusNamespaceResource serviceBusNamespace = + await FindNamespace(subscription.GetServiceBusNamespacesAsync(cancellationToken), serviceBusName, cancellationToken); - SubscriptionResource? subscription = await armClient!.GetDefaultSubscriptionAsync(cancellationToken); - var namespaces = subscription.GetServiceBusNamespacesAsync(cancellationToken); + resourceId = serviceBusNamespace.Id; - await foreach (var serviceBusNamespaceResource in namespaces) + await foreach (var queue in serviceBusNamespace.GetServiceBusQueues().WithCancellation(cancellationToken)) { - if (!validNamespaces.Contains(serviceBusNamespaceResource.Data.Name)) - { - continue; - } - - resourceId = serviceBusNamespaceResource.Id; - - await foreach (var queue in serviceBusNamespaceResource.GetServiceBusQueues() - .WithCancellation(cancellationToken)) - { - yield return new DefaultBrokerQueue(queue.Data.Name); - } - - yield break; + yield return new DefaultBrokerQueue(queue.Data.Name); } - - throw new Exception($"Could not find a Azure Service Bus namespace named \"{serviceBusName}\""); } - // ArmEnvironment Audience Values: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/resourcemanager/Azure.ResourceManager/src/ArmEnvironment.cs - // Service Bus Domains: https://learn.microsoft.com/en-us/rest/api/servicebus/ - static readonly Dictionary ServiceBusDomains = new() - { - { ArmEnvironment.AzurePublicCloud, "servicebus.windows.net" }, - { ArmEnvironment.AzureGovernment, "servicebus.usgovcloudapi.net" }, - { ArmEnvironment.AzureGermany, "servicebus.cloudapi.de" }, - { ArmEnvironment.AzureChina, "servicebus.chinacloudapi.cn" }, - }; - - async Task> GetValidNamespaceNames(CancellationToken cancellationToken) + internal static async Task FindNamespace( + IAsyncEnumerable namespaces, string name, CancellationToken cancellationToken = default) { - var validNamespaces = new HashSet(StringComparer.OrdinalIgnoreCase) { serviceBusName }; - - var serviceBusCloudDomain = ServiceBusDomains.GetValueOrDefault(armEnvironment, "servicebus.windows.net"); + var otherNamespaces = new List(); + await foreach (var serviceBusNamespace in namespaces.WithCancellation(cancellationToken)) + { + if (string.Equals(serviceBusNamespace.Data.Name, name, StringComparison.OrdinalIgnoreCase)) + { + return serviceBusNamespace; + } - // Worst case: the DNS lookup finds nothing additional to match - var queryDomain = $"{serviceBusName}.{serviceBusCloudDomain}"; - var validDomainTail = $".{serviceBusCloudDomain}."; + otherNamespaces.Add(serviceBusNamespace); + } - var dnsLookup = new LookupClient(); - var dnsResult = await dnsLookup.QueryAsync(queryDomain, QueryType.CNAME, cancellationToken: cancellationToken); - var domain = (dnsResult.Answers.FirstOrDefault() as CNameRecord)?.CanonicalName.Value; - if (domain is not null && domain.EndsWith(validDomainTail)) + var aliasesForbidden = false; + foreach (var serviceBusNamespace in otherNamespaces) { - // In some cases, like private networking access, result might be something like `namespacename.private` with a dot in the middle - // which is not a big deal because that will not actually match a namespace name in metrics - var otherName = domain[..^validDomainTail.Length]; - validNamespaces.Add(otherName); + try + { + await foreach (var alias in serviceBusNamespace.GetServiceBusDisasterRecoveries().GetAllAsync(cancellationToken)) + { + if (string.Equals(alias.Data.Name, name, StringComparison.OrdinalIgnoreCase) && + alias.Data.Role is ServiceBusDisasterRecoveryRole.Primary or ServiceBusDisasterRecoveryRole.PrimaryNotReplicating) + { + return serviceBusNamespace; + } + } + } + catch (RequestFailedException e) when (e.Status == 403) + { + aliasesForbidden = true; + } } - return validNamespaces; + throw new Exception(aliasesForbidden + ? $"Could not find an Azure Service Bus namespace named \"{name}\". If \"{name}\" is a Geo-Recovery alias, resolving it requires the Microsoft.ServiceBus/namespaces/disasterRecoveryConfigs/read permission." + : $"Could not find an Azure Service Bus namespace or Geo-Recovery alias named \"{name}\""); } public override string SanitizedEndpointNameCleanser(string endpointName) => endpointName.ToLower(); diff --git a/src/ServiceControl.Transports.ASBS/ServiceControl.Transports.ASBS.csproj b/src/ServiceControl.Transports.ASBS/ServiceControl.Transports.ASBS.csproj index bd61cf9af1..ddd818a257 100644 --- a/src/ServiceControl.Transports.ASBS/ServiceControl.Transports.ASBS.csproj +++ b/src/ServiceControl.Transports.ASBS/ServiceControl.Transports.ASBS.csproj @@ -14,7 +14,6 @@ - @@ -23,6 +22,10 @@ + + + + diff --git a/src/ServiceControl.UnitTests/API/APIApprovals.cs b/src/ServiceControl.UnitTests/API/APIApprovals.cs index dee1ef8c12..29134fdcde 100644 --- a/src/ServiceControl.UnitTests/API/APIApprovals.cs +++ b/src/ServiceControl.UnitTests/API/APIApprovals.cs @@ -192,7 +192,7 @@ string RemoveDataStoreSettings(string json) var result = string.Empty; - var dataStoreSettings = new[] { nameof(Settings.PersistenceType) }; + var dataStoreSettings = new[] { nameof(Settings.StorageType) }; foreach (var settingLine in settingsLines) { diff --git a/src/ServiceControl.UnitTests/ApprovalFiles/APIApprovals.PlatformSampleSettings.approved.txt b/src/ServiceControl.UnitTests/ApprovalFiles/APIApprovals.PlatformSampleSettings.approved.txt index b7303ff3a8..516da53707 100644 --- a/src/ServiceControl.UnitTests/ApprovalFiles/APIApprovals.PlatformSampleSettings.approved.txt +++ b/src/ServiceControl.UnitTests/ApprovalFiles/APIApprovals.PlatformSampleSettings.approved.txt @@ -49,7 +49,7 @@ "EmailDropFolder": null, "ValidateConfiguration": true, "ExternalIntegrationsDispatchingBatchSize": 100, - "DisableExternalIntegrationsPublishing": false, + "EnableExternalIntegrationsPublishing": false, "RunCleanupBundle": false, "RootUrl": "http://localhost:8888/", "ApiUrl": "http://localhost:8888/api", @@ -69,7 +69,6 @@ "IngestErrorMessages": true, "RunRetryProcessor": true, "ErrorIngestionOnly": false, - "AuditRetentionPeriod": null, "ErrorRetentionPeriod": "10.00:00:00", "EventsRetentionPeriod": "14.00:00:00", "InstanceName": "Particular.ServiceControl", diff --git a/src/ServiceControl.UnitTests/Infrastructure/Settings/ExternalIntegrationsPublishingSettingsTests.cs b/src/ServiceControl.UnitTests/Infrastructure/Settings/ExternalIntegrationsPublishingSettingsTests.cs new file mode 100644 index 0000000000..ae03bda38c --- /dev/null +++ b/src/ServiceControl.UnitTests/Infrastructure/Settings/ExternalIntegrationsPublishingSettingsTests.cs @@ -0,0 +1,58 @@ +namespace ServiceControl.UnitTests.Infrastructure.Settings; + +using System; +using NUnit.Framework; +using ServiceBus.Management.Infrastructure.Settings; + +[TestFixture] +[NonParallelizable] +class ExternalIntegrationsPublishingSettingsTests +{ + const string Variable = "SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING"; + const string LegacyVariable = "SERVICECONTROL_DISABLEEXTERNALINTEGRATIONSPUBLISHING"; + + string originalValue; + string originalLegacyValue; + + [SetUp] + public void SetUp() + { + originalValue = Environment.GetEnvironmentVariable(Variable); + originalLegacyValue = Environment.GetEnvironmentVariable(LegacyVariable); + Environment.SetEnvironmentVariable(Variable, null); + Environment.SetEnvironmentVariable(LegacyVariable, null); + } + + [TearDown] + public void TearDown() + { + Environment.SetEnvironmentVariable(Variable, originalValue); + Environment.SetEnvironmentVariable(LegacyVariable, originalLegacyValue); + } + + [Test] + public void Is_disabled_when_neither_setting_is_configured() => + Assert.That(new Settings().EnableExternalIntegrationsPublishing, Is.False); + + [TestCase("true", true)] + [TestCase("false", false)] + public void Reads_the_enable_setting(string value, bool expected) + { + Environment.SetEnvironmentVariable(Variable, value); + + Assert.That(new Settings().EnableExternalIntegrationsPublishing, Is.EqualTo(expected)); + } + + [TestCase(null)] + [TestCase("true")] + [TestCase("false")] + public void Rejects_the_legacy_setting(string enableValue) + { + Environment.SetEnvironmentVariable(Variable, enableValue); + Environment.SetEnvironmentVariable(LegacyVariable, "true"); + + var ex = Assert.Throws(() => _ = new Settings()); + + Assert.That(ex.Message, Does.Contain("no longer supported")); + } +} diff --git a/src/ServiceControl.UnitTests/Licensing/ServiceControlErrorInstanceEnvironmentDataProviderTests.cs b/src/ServiceControl.UnitTests/Licensing/ServiceControlErrorInstanceEnvironmentDataProviderTests.cs index dd52a9fd60..d49e88665c 100644 --- a/src/ServiceControl.UnitTests/Licensing/ServiceControlErrorInstanceEnvironmentDataProviderTests.cs +++ b/src/ServiceControl.UnitTests/Licensing/ServiceControlErrorInstanceEnvironmentDataProviderTests.cs @@ -93,6 +93,27 @@ public async Task Should_report_feature_switches_from_configuration() } } + [TestCase("SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING", "true", "Enabled")] + [TestCase("SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING", "false", "Disabled")] + public async Task Should_report_external_integrations_publishing(string variable, string value, string expected) + { + Environment.SetEnvironmentVariable(variable, value); + + var data = await GetData(); + + Assert.That(data["Features.ExternalIntegrationsPublishing"], Is.EqualTo(expected)); + } + + [Test] + public async Task Should_reject_the_legacy_external_integrations_publishing_setting() + { + Environment.SetEnvironmentVariable("SERVICECONTROL_DISABLEEXTERNALINTEGRATIONSPUBLISHING", "false"); + + var ex = Assert.ThrowsAsync(() => GetData()); + + Assert.That(ex.Message, Does.Contain("no longer supported")); + } + [Test] public async Task Should_report_otlp_metrics_export_without_the_endpoint() { @@ -158,6 +179,8 @@ public Task SaveSettings(NotificationsSettings settings, CancellationToken cance "DEFAULT_ROUTE", "SHOW_PENDING_RETRY", "SERVICECONTROL_INGESTERRORMESSAGES", - "SERVICECONTROL_VIRTUALDIRECTORY" + "SERVICECONTROL_VIRTUALDIRECTORY", + "SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING", + "SERVICECONTROL_DISABLEEXTERNALINTEGRATIONSPUBLISHING" ]; } diff --git a/src/ServiceControl/App.config b/src/ServiceControl/App.config index 8afc7351d0..8bc0d1f457 100644 --- a/src/ServiceControl/App.config +++ b/src/ServiceControl/App.config @@ -23,9 +23,9 @@ These settings are only here so that we can debug ServiceControl while developin - - - + + + diff --git a/src/ServiceControl/Container-README.md b/src/ServiceControl/Container-README.md index 806df8c49c..d9c6bb98da 100644 --- a/src/ServiceControl/Container-README.md +++ b/src/ServiceControl/Container-README.md @@ -7,23 +7,43 @@ The `particular/servicecontrol` image is part of the Particular Service Platform | [`particular/servicecontrol`](https://hub.docker.com/r/particular/servicecontrol) | [Instance Documentation](https://docs.particular.net/servicecontrol/servicecontrol-instances/)
[Container Documentation](https://docs.particular.net/servicecontrol/servicecontrol-instances/deployment/containers) | The primary/error instance, which includes error handling and recoverability | | [`particular/servicecontrol-audit`](https://hub.docker.com/r/particular/servicecontrol-audit) | [Instance Documentation](https://docs.particular.net/servicecontrol/audit-instances/)
[Container Documentation](https://docs.particular.net/servicecontrol/audit-instances/deployment/containers) | The audit instance, which stores audit data, and can be scaled out to multiple audit instances | | [`particular/servicecontrol-monitoring`](https://hub.docker.com/r/particular/servicecontrol-monitoring) | [Instance Documentation](https://docs.particular.net/servicecontrol/monitoring-instances/)
[Container Documentation](https://docs.particular.net/servicecontrol/monitoring-instances/deployment/containers) | The monitoring instance, which tracks runtime information like throughput, queue length, and other metrics | -| [`particular/servicecontrol-ravendb`](https://hub.docker.com/r/particular/servicecontrol-ravendb) | [Container Documentation](https://docs.particular.net/servicecontrol/ravendb/containers) | The database used by the error/audit instances | +| [`particular/servicecontrol-ravendb`](https://hub.docker.com/r/particular/servicecontrol-ravendb) | [Container Documentation](https://docs.particular.net/servicecontrol/storage/ravendb/containers) | The database for error/audit instances using RavenDB persistence | | [`particular/servicepulse`](https://hub.docker.com/r/particular/servicepulse) | [App Documentation](https://docs.particular.net/servicepulse/)
[Container Documentation](https://docs.particular.net/servicepulse/containerization/) | The web application that provides a front end for recoverability and monitoring features | ## Usage -The following is the most basic way to create ServiceControl containers using [Docker](https://www.docker.com/), assuming a RabbitMQ message broker also hosted in a Docker container using default `guest`/`guest` credentials: +The following minimal example uses `docker run` to host an Error instance on AWS, with [Amazon SQS](https://docs.particular.net/servicecontrol/transports.md#amazon-sqs) as the transport, Amazon Aurora PostgreSQL for [PostgreSQL storage](https://docs.particular.net/servicecontrol/storage/postgresql/), and [Amazon S3](https://docs.particular.net/servicecontrol/storage/external-body/amazon-s3.md) for message bodies: ```shell docker run -d --name servicecontrol -p 33333:33333 \ - -e TRANSPORTTYPE=RabbitMQ.QuorumConventionalRouting \ - -e CONNECTIONSTRING="host=rabbitmq" \ - -e RAVENDB_CONNECTIONSTRING="http://servicecontrol-db:8080" \ + -e AWS_REGION=us-east-1 \ + -e TRANSPORTTYPE=AmazonSQS \ + -e CONNECTIONSTRING="Region=us-east-1" \ + -e STORAGETYPE=PostgreSQL \ + -e DATABASE_CONNECTIONSTRING="Host=my-cluster.cluster-xxxxxxxxxxxx.us-east-1.rds.amazonaws.com;Database=ServiceControl;Username=servicecontrol;Token Authentication=AwsRdsIam;SSL Mode=Require" \ + -e MESSAGEBODY_STORAGETYPE=S3 \ + -e MESSAGEBODY_S3_BUCKETNAME=my-servicecontrol-bodies \ -e REMOTEINSTANCES='[{"api_uri":"http://audit:44444/api"}]' \ -e ENABLEINTEGRATEDSERVICEPULSE="true" \ - particular/servicecontrol:latest --setup-and-run + particular/servicecontrol:latest ``` +The example contains no AWS keys or database password. SQS, S3, and the [IAM database login](https://docs.particular.net/servicecontrol/storage/postgresql/#authentication-token-authentication) use the AWS SDK default credential chain, such as an IAM role attached to the host or task, and the region set in `AWS_REGION`. + +### Storage + +`STORAGETYPE` is required. Prepare the storage as the provider's guide describes before running setup. + +| `STORAGETYPE` | Connection string environment variable | Configuration | +|---------------|----------------------------------------|---------------| +| `RavenDB` | `RAVENDB_CONNECTIONSTRING` | [RavenDB container setup](https://docs.particular.net/servicecontrol/storage/ravendb/containers) | +| `SQLServer` | `DATABASE_CONNECTIONSTRING` | [Configure SQL Server storage](https://docs.particular.net/servicecontrol/storage/sqlserver/) | +| `PostgreSQL` | `DATABASE_CONNECTIONSTRING` | [Configure PostgreSQL storage](https://docs.particular.net/servicecontrol/storage/postgresql/) | + +SQL Server and PostgreSQL also require [external message body storage](https://docs.particular.net/servicecontrol/storage/external-body/), selected with `MESSAGEBODY_STORAGETYPE`. The [storage overview](https://docs.particular.net/servicecontrol/storage/#sharing-a-database) explains how Error and Audit instances can share a database. + +These settings also accept the `SERVICECONTROL_` prefix, for example `SERVICECONTROL_STORAGETYPE` and `SERVICECONTROL_DATABASE_CONNECTIONSTRING`. + For all other usage information see the [official container documentation](https://docs.particular.net/servicecontrol/servicecontrol-instances/deployment/containers). ## Image tagging diff --git a/src/ServiceControl/CustomChecks/CustomChecksComponent.cs b/src/ServiceControl/CustomChecks/CustomChecksComponent.cs index 5e4b20e731..b5693b02fc 100644 --- a/src/ServiceControl/CustomChecks/CustomChecksComponent.cs +++ b/src/ServiceControl/CustomChecks/CustomChecksComponent.cs @@ -14,7 +14,7 @@ class CustomChecksComponent : ServiceControlComponent public override void Setup(Settings settings, IComponentInstallationContext context, IHostApplicationBuilder hostBuilder) { // Integration Events - if (!settings.DisableExternalIntegrationsPublishing) + if (settings.EnableExternalIntegrationsPublishing) { context.AddEventPublished(); context.AddEventPublished(); diff --git a/src/ServiceControl/Dockerfile b/src/ServiceControl/Dockerfile index 777bbc4224..28a5af6006 100644 --- a/src/ServiceControl/Dockerfile +++ b/src/ServiceControl/Dockerfile @@ -19,7 +19,7 @@ EXPOSE 33333 COPY --from=build /deploy/Particular.ServiceControl /app COPY --from=build /healthcheck /healthcheck -ENV PersistenceType=RavenDB \ +ENV StorageType=RavenDB \ ForwardErrorMessages=false \ ErrorRetentionPeriod=15 diff --git a/src/ServiceControl/ExternalIntegrations/ExternalIntegrationsComponent.cs b/src/ServiceControl/ExternalIntegrations/ExternalIntegrationsComponent.cs index 6d86407288..9919d0c7ef 100644 --- a/src/ServiceControl/ExternalIntegrations/ExternalIntegrationsComponent.cs +++ b/src/ServiceControl/ExternalIntegrations/ExternalIntegrationsComponent.cs @@ -14,7 +14,7 @@ public override void Configure(Settings settings, ITransportCustomization transp var services = hostBuilder.Services; services.AddEventLogMapping(); - if (!settings.DisableExternalIntegrationsPublishing) + if (settings.EnableExternalIntegrationsPublishing) { services.AddDomainEventHandler(); diff --git a/src/ServiceControl/HostApplicationBuilderExtensions.cs b/src/ServiceControl/HostApplicationBuilderExtensions.cs index c294001cf3..0de363bedc 100644 --- a/src/ServiceControl/HostApplicationBuilderExtensions.cs +++ b/src/ServiceControl/HostApplicationBuilderExtensions.cs @@ -206,7 +206,6 @@ static void RecordStartup(Settings settings, EndpointConfiguration endpointConfi var startupMessage = $@" ------------------------------------------------------------- ServiceControl Version: {version} -Audit Retention Period (optional): {settings.AuditRetentionPeriod} Error Retention Period: {settings.ErrorRetentionPeriod} Ingest Error Messages: {settings.IngestErrorMessages} Error Ingestion Only: {settings.ErrorIngestionOnly} @@ -214,6 +213,7 @@ Audit Retention Period (optional): {settings.AuditRetentionPeriod} ServiceControl Logging Level: {settings.LoggingSettings.LogLevel} Selected Transport Customization: {settings.TransportType} Integrated ServicePulse: {(settings.EnableIntegratedServicePulse ? "Enabled" : "Disabled")} +External Integrations Publishing: {(settings.EnableExternalIntegrationsPublishing ? "Enabled" : "Disabled")} -------------------------------------------------------------"; var logger = LoggerUtil.CreateStaticLogger(typeof(HostApplicationBuilderExtensions), settings.LoggingSettings.LogLevel); diff --git a/src/ServiceControl/Hosting/Commands/ErrorIngestionOnlyCommand.cs b/src/ServiceControl/Hosting/Commands/ErrorIngestionOnlyCommand.cs index 00d38bb0b3..c9081c954e 100644 --- a/src/ServiceControl/Hosting/Commands/ErrorIngestionOnlyCommand.cs +++ b/src/ServiceControl/Hosting/Commands/ErrorIngestionOnlyCommand.cs @@ -58,12 +58,12 @@ internal static WebApplication BuildHost(Settings settings, Action(); + hostBuilder.Services.AddErrorMessageEnricher(); + return hostBuilder.Build(); } } diff --git a/src/ServiceControl/Infrastructure/Api/ConfigurationApi.cs b/src/ServiceControl/Infrastructure/Api/ConfigurationApi.cs index 21eeaa37e7..b4fde43d03 100644 --- a/src/ServiceControl/Infrastructure/Api/ConfigurationApi.cs +++ b/src/ServiceControl/Infrastructure/Api/ConfigurationApi.cs @@ -69,7 +69,6 @@ public Task GetConfig(CancellationToken cancellationToken = default) }, DataRetention = new { - settings.AuditRetentionPeriod, settings.ErrorRetentionPeriod }, PerformanceTunning = new @@ -79,7 +78,7 @@ public Task GetConfig(CancellationToken cancellationToken = default) PersistenceSettings = settings.PersisterSpecificSettings, Storage = new { - StorageType = PersistenceManifestLibrary.Find(settings.PersistenceType)?.Name + StorageType = PersistenceManifestLibrary.Find(settings.StorageType)?.Name }, Transport = new { diff --git a/src/ServiceControl/Infrastructure/NServiceBusFactory.cs b/src/ServiceControl/Infrastructure/NServiceBusFactory.cs index fce530c4d8..21db83ad63 100644 --- a/src/ServiceControl/Infrastructure/NServiceBusFactory.cs +++ b/src/ServiceControl/Infrastructure/NServiceBusFactory.cs @@ -41,7 +41,7 @@ public static void Configure(Settings.Settings settings, ITransportCustomization configuration.GetSettings().Set(settings.LoggingSettings); configuration.SetDiagnosticsPath(settings.LoggingSettings.LogPath); - if (!settings.DisableExternalIntegrationsPublishing) + if (settings.EnableExternalIntegrationsPublishing) { configuration.EnableFeature(); } diff --git a/src/ServiceControl/Infrastructure/Settings/Settings.cs b/src/ServiceControl/Infrastructure/Settings/Settings.cs index c601c07b57..7a4c47b3dd 100644 --- a/src/ServiceControl/Infrastructure/Settings/Settings.cs +++ b/src/ServiceControl/Infrastructure/Settings/Settings.cs @@ -24,7 +24,7 @@ public class Settings { public Settings( string transportType = null, - string persisterType = null, + string storageType = null, LoggingSettings loggingSettings = null, bool? forwardErrorMessages = default, TimeSpan? errorRetentionPeriod = default @@ -47,8 +47,7 @@ public Settings( TransportConnectionString = GetConnectionString(); TransportType = transportType ?? SettingsReader.Read(SettingsRootNamespace, "TransportType"); - PersistenceType = persisterType ?? SettingsReader.Read(SettingsRootNamespace, "PersistenceType"); - AuditRetentionPeriod = GetAuditRetentionPeriod(); + StorageType = storageType ?? SettingsReader.Read(SettingsRootNamespace, "StorageType"); ForwardErrorMessages = forwardErrorMessages ?? GetForwardErrorMessages(); ErrorRetentionPeriod = errorRetentionPeriod ?? GetErrorRetentionPeriod(); EventsRetentionPeriod = GetEventRetentionPeriod(); @@ -84,7 +83,7 @@ public Settings( ErrorIngestionBatchSize = IngestionSettingsReader.ReadBatchSize(SettingsRootNamespace, nameof(ErrorIngestionBatchSize), ValidateConfiguration); ErrorIngestionMaxParallelWriters = IngestionSettingsReader.ReadMaxParallelWriters(SettingsRootNamespace, nameof(ErrorIngestionMaxParallelWriters), ValidateConfiguration); ErrorIngestionBatchTimeout = IngestionSettingsReader.ReadBatchTimeout(SettingsRootNamespace, nameof(ErrorIngestionBatchTimeout), ValidateConfiguration); - DisableExternalIntegrationsPublishing = SettingsReader.Read(SettingsRootNamespace, "DisableExternalIntegrationsPublishing", false); + EnableExternalIntegrationsPublishing = ReadEnableExternalIntegrationsPublishing(); TrackInstancesInitialValue = SettingsReader.Read(SettingsRootNamespace, "TrackInstancesInitialValue", true); ShutdownTimeout = SettingsReader.Read(SettingsRootNamespace, ShutdownTimeoutKey, ShutdownTimeout); AssemblyLoadContextResolver = static assemblyPath => new PluginAssemblyLoadContext(assemblyPath); @@ -132,7 +131,7 @@ public Settings( public int ExternalIntegrationsDispatchingBatchSize => SettingsReader.Read(SettingsRootNamespace, ExternalIntegrationsDispatchingBatchSizeKey, 100); - public bool DisableExternalIntegrationsPublishing { get; set; } + public bool EnableExternalIntegrationsPublishing { get; set; } public bool RunCleanupBundle { get; set; } @@ -184,7 +183,7 @@ public string InstanceId public TimeSpan HeartbeatGracePeriod { get; set; } public string TransportType { get; set; } - public string PersistenceType { get; private set; } + public string StorageType { get; private set; } public string ErrorLogQueue { get; set; } public string ErrorQueue { get; set; } @@ -196,8 +195,6 @@ public string InstanceId // Set by the --error-ingestion-only command, never read from configuration. public bool ErrorIngestionOnly { get; set; } - public TimeSpan? AuditRetentionPeriod { get; set; } - public TimeSpan ErrorRetentionPeriod { get; } public TimeSpan EventsRetentionPeriod { get; } @@ -305,6 +302,18 @@ TimeSpan GetEventRetentionPeriod() return SettingsReader.Read(SettingsRootNamespace, "EventsRetentionPeriod", TimeSpan.FromDays(14)); } + bool ReadEnableExternalIntegrationsPublishing() + { + if (SettingsReader.TryRead(SettingsRootNamespace, "DisableExternalIntegrationsPublishing", out _)) + { + const string message = "The DisableExternalIntegrationsPublishing setting is no longer supported, please remove it and use EnableExternalIntegrationsPublishing instead"; + logger.LogCritical(message); + throw new Exception(message); + } + + return SettingsReader.Read(SettingsRootNamespace, "EnableExternalIntegrationsPublishing", false); + } + TimeSpan GetErrorRetentionPeriod() { string message; @@ -342,41 +351,6 @@ TimeSpan GetErrorRetentionPeriod() return result; } - TimeSpan? GetAuditRetentionPeriod() - { - string message; - var valueRead = SettingsReader.Read(SettingsRootNamespace, "AuditRetentionPeriod"); - if (valueRead == null) - { - return null; - } - - if (TimeSpan.TryParse(valueRead, out var result)) - { - if (ValidateConfiguration && result < TimeSpan.FromHours(1)) - { - message = "AuditRetentionPeriod settings is invalid, value should be minimum 1 hour."; - InternalLogger.Fatal(message); - throw new Exception(message); - } - - if (ValidateConfiguration && result > TimeSpan.FromDays(365)) - { - message = "AuditRetentionPeriod settings is invalid, value should be maximum 365 days."; - InternalLogger.Fatal(message); - throw new Exception(message); - } - } - else - { - message = "AuditRetentionPeriod settings is invalid, please make sure it is a TimeSpan."; - InternalLogger.Fatal(message); - throw new Exception(message); - } - - return result; - } - TimeSpan GetHeartbeatGracePeriod() { try diff --git a/src/ServiceControl/Monitoring/HeartbeatMonitoringComponent.cs b/src/ServiceControl/Monitoring/HeartbeatMonitoringComponent.cs index 542901eed0..d60e816204 100644 --- a/src/ServiceControl/Monitoring/HeartbeatMonitoringComponent.cs +++ b/src/ServiceControl/Monitoring/HeartbeatMonitoringComponent.cs @@ -20,7 +20,7 @@ class HeartbeatMonitoringComponent : ServiceControlComponent public override void Setup(Settings settings, IComponentInstallationContext context, IHostApplicationBuilder hostBuilder) { // Integration Events - if (!settings.DisableExternalIntegrationsPublishing) + if (settings.EnableExternalIntegrationsPublishing) { context.AddEventPublished(); context.AddEventPublished(); diff --git a/src/ServiceControl/Persistence/PersistenceFactory.cs b/src/ServiceControl/Persistence/PersistenceFactory.cs index 892920cf18..01134e3f48 100644 --- a/src/ServiceControl/Persistence/PersistenceFactory.cs +++ b/src/ServiceControl/Persistence/PersistenceFactory.cs @@ -12,7 +12,7 @@ public static IPersistence Create(Settings settings, bool maintenanceMode = fals if (maintenanceMode && !persistenceConfiguration.SupportsMaintenanceMode) { - throw new Exception($"Maintenance mode is not supported by the {settings.PersistenceType} persister. It is only available on RavenDB, where it starts the embedded database so RavenDB Studio can be used."); + throw new Exception($"Maintenance mode is not supported by the {settings.StorageType} storage type. It is only available on RavenDB, where it starts the embedded database so RavenDB Studio can be used."); } //HINT: This is false when executed from acceptance tests @@ -28,7 +28,7 @@ static IPersistenceConfiguration CreatePersistenceConfiguration(Settings setting { try { - var persistenceManifest = PersistenceManifestLibrary.Find(settings.PersistenceType); + var persistenceManifest = PersistenceManifestLibrary.Find(settings.StorageType); var assemblyPath = Path.Combine(persistenceManifest.Location, $"{persistenceManifest.AssemblyName}.dll"); var loadContext = settings.AssemblyLoadContextResolver(assemblyPath); var customizationType = Type.GetType(persistenceManifest.TypeName, loadContext.LoadFromAssemblyName, null, true); @@ -37,7 +37,7 @@ static IPersistenceConfiguration CreatePersistenceConfiguration(Settings setting } catch (Exception e) { - throw new Exception($"Could not load persistence customization type {settings.PersistenceType}.", e); + throw new Exception($"Could not load persistence customization type {settings.StorageType}.", e); } } } diff --git a/src/ServiceControl/Recoverability/Editing/EditHandler.cs b/src/ServiceControl/Recoverability/Editing/EditHandler.cs index 19a8827afb..111551e492 100644 --- a/src/ServiceControl/Recoverability/Editing/EditHandler.cs +++ b/src/ServiceControl/Recoverability/Editing/EditHandler.cs @@ -105,12 +105,21 @@ Task DispatchEditedMessage(OutgoingMessage editedMessage, string address, IMessa AddressTag destination = new UnicastAddressTag(address); var transportTransaction = context.Extensions.GetOrCreate(); + var dispatchProperties = new DispatchProperties(); + foreach (var header in editedMessage.Headers.Keys.Where(k => k.StartsWith(ReceivePropertiesHeaderPrefix, StringComparison.Ordinal)).ToList()) + { + dispatchProperties[header[ReceivePropertiesHeaderPrefix.Length..]] = editedMessage.Headers[header]; + editedMessage.Headers.Remove(header); + } + return dispatcher.Dispatch( - new TransportOperations(new TransportOperation(editedMessage, destination)), + new TransportOperations(new TransportOperation(editedMessage, destination, dispatchProperties)), transportTransaction, context.CancellationToken); } + const string ReceivePropertiesHeaderPrefix = "ServiceControl.ReceiveProperties."; + readonly CorruptedReplyToHeaderStrategy corruptedReplyToHeaderStrategy = new(RuntimeEnvironment.MachineName, logger); } } \ No newline at end of file diff --git a/src/ServiceControl/Recoverability/EventLog/MessageFailedDefinition.cs b/src/ServiceControl/Recoverability/EventLog/MessageFailedDefinition.cs deleted file mode 100644 index 8a81ddfd88..0000000000 --- a/src/ServiceControl/Recoverability/EventLog/MessageFailedDefinition.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace ServiceControl.Recoverability.EventLog -{ - using Contracts.MessageFailures; - using ServiceControl.EventLog; - - class MessageFailedDefinition : EventLogMappingDefinition - { - public MessageFailedDefinition() - { - TreatAsError(); - - Description(m => m.FailureDetails.Exception.Message); - - RelatesToMessage(m => m.FailedMessageId); - RelatesToEndpoint(m => m.EndpointId); - - RaisedAt(m => m.FailureDetails.TimeOfFailure); - } - } -} \ No newline at end of file diff --git a/src/ServiceControl/Recoverability/RecoverabilityComponent.cs b/src/ServiceControl/Recoverability/RecoverabilityComponent.cs index ab17793427..5f58f61314 100644 --- a/src/ServiceControl/Recoverability/RecoverabilityComponent.cs +++ b/src/ServiceControl/Recoverability/RecoverabilityComponent.cs @@ -42,7 +42,7 @@ public override void Setup(Settings settings, IComponentInstallationContext cont } // Integration Events - if (!settings.DisableExternalIntegrationsPublishing) + if (settings.EnableExternalIntegrationsPublishing) { context.AddEventPublished(); context.AddEventPublished(); @@ -125,7 +125,6 @@ public override void Configure(Settings settings, ITransportCustomization transp services.AddEventLogMapping(); services.AddEventLogMapping(); services.AddEventLogMapping(); - services.AddEventLogMapping(); services.AddEventLogMapping(); services.AddEventLogMapping(); services.AddEventLogMapping(); diff --git a/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSenderDequeuer.cs b/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSenderDequeuer.cs index 2c4d975e6a..61ff7acb51 100644 --- a/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSenderDequeuer.cs +++ b/src/ServiceControl/Recoverability/Retrying/Infrastructure/ReturnToSenderDequeuer.cs @@ -1,6 +1,7 @@ namespace ServiceControl.Recoverability; using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Infrastructure.DomainEvents; @@ -222,7 +223,7 @@ await domainEvents.Raise(new MessagesSubmittedForRetryFailed catch (Exception ex) { // If something goes wrong here we just ignore, not the end of the world! - logger.LogError(ex, "A failure occurred when trying to handle a retry failure"); + logger.LogError(ex, "A failure occurred when trying to handle a retry failure of message '{UniqueMessageId}'", errorContext.Headers.GetValueOrDefault("ServiceControl.Retry.UniqueMessageId")); } finally { diff --git a/src/ServiceControl/ServiceControlErrorInstanceEnvironmentDataProvider.cs b/src/ServiceControl/ServiceControlErrorInstanceEnvironmentDataProvider.cs index 6fa63c0606..76ed3597cf 100644 --- a/src/ServiceControl/ServiceControlErrorInstanceEnvironmentDataProvider.cs +++ b/src/ServiceControl/ServiceControlErrorInstanceEnvironmentDataProvider.cs @@ -19,7 +19,7 @@ public IEnumerable GetData() => [ Value("Features.IntegratedServicePulse", () => Toggle(settings.EnableIntegratedServicePulse)), Value("Features.MessageEditing", () => Toggle(settings.AllowMessageEditing)), - Value("Features.ExternalIntegrationsPublishing", () => Toggle(!settings.DisableExternalIntegrationsPublishing)), + Value("Features.ExternalIntegrationsPublishing", () => Toggle(settings.EnableExternalIntegrationsPublishing)), Value("Features.ForwardErrorMessages", () => Toggle(settings.ForwardErrorMessages)), Value("Features.ErrorIngestion", () => Toggle(settings.IngestErrorMessages)), Value("Features.ConfigurationValidation", () => Toggle(settings.ValidateConfiguration)), diff --git a/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/AuditInstanceTests.Should_update_existing_persister.approved.txt b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/AuditInstanceTests.Should_update_existing_persister.approved.txt deleted file mode 100644 index c43ed4e591..0000000000 --- a/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/AuditInstanceTests.Should_update_existing_persister.approved.txt +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.Audit_install_should_write_expected_config_file.PostgreSQL.approved.txt b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.Audit_install_should_write_expected_config_file.PostgreSQL.approved.txt new file mode 100644 index 0000000000..279819d735 --- /dev/null +++ b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.Audit_install_should_write_expected_config_file.PostgreSQL.approved.txt @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.Audit_install_should_write_expected_config_file.RavenDB.approved.txt b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.Audit_install_should_write_expected_config_file.RavenDB.approved.txt index 5050490958..db48111a86 100644 --- a/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.Audit_install_should_write_expected_config_file.RavenDB.approved.txt +++ b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.Audit_install_should_write_expected_config_file.RavenDB.approved.txt @@ -6,7 +6,7 @@ - + diff --git a/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.Audit_install_should_write_expected_config_file.SQLServer.approved.txt b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.Audit_install_should_write_expected_config_file.SQLServer.approved.txt new file mode 100644 index 0000000000..067fd524e4 --- /dev/null +++ b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.Audit_install_should_write_expected_config_file.SQLServer.approved.txt @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.ServiceControl_install_should_write_expected_config_file.PostgreSQL.approved.txt b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.ServiceControl_install_should_write_expected_config_file.PostgreSQL.approved.txt new file mode 100644 index 0000000000..a949e28ed1 --- /dev/null +++ b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.ServiceControl_install_should_write_expected_config_file.PostgreSQL.approved.txt @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.ServiceControl_install_should_write_expected_config_file.RavenDB.approved.txt b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.ServiceControl_install_should_write_expected_config_file.RavenDB.approved.txt new file mode 100644 index 0000000000..0534cc2169 --- /dev/null +++ b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.ServiceControl_install_should_write_expected_config_file.RavenDB.approved.txt @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.ServiceControl_install_should_write_expected_config_file.SQLServer.approved.txt b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.ServiceControl_install_should_write_expected_config_file.SQLServer.approved.txt new file mode 100644 index 0000000000..f13dc8a779 --- /dev/null +++ b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/InstallationTests.ServiceControl_install_should_write_expected_config_file.SQLServer.approved.txt @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/NewAuditInstanceTests.Should_install_modern_raven_for_new_instances.approved.txt b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/NewAuditInstanceTests.Should_install_modern_raven_for_new_instances.approved.txt index 5050490958..db48111a86 100644 --- a/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/NewAuditInstanceTests.Should_install_modern_raven_for_new_instances.approved.txt +++ b/src/ServiceControlInstaller.Engine.UnitTests/ApprovalFiles/NewAuditInstanceTests.Should_install_modern_raven_for_new_instances.approved.txt @@ -6,7 +6,7 @@ - + diff --git a/src/ServiceControlInstaller.Engine.UnitTests/Configuration/AuditInstanceTests.cs b/src/ServiceControlInstaller.Engine.UnitTests/Configuration/AuditInstanceTests.cs index c143ceb24c..376bcccb86 100644 --- a/src/ServiceControlInstaller.Engine.UnitTests/Configuration/AuditInstanceTests.cs +++ b/src/ServiceControlInstaller.Engine.UnitTests/Configuration/AuditInstanceTests.cs @@ -67,6 +67,70 @@ public void Should_remove_log_and_db_folders_on_uninstall() Assert.That(Directory.Exists(DbPath), Is.False); } + [Test] + public void Should_remove_only_message_body_folder_on_uninstall_for_SQL_Server() + { + var messageBodyPath = Path.Combine(Path.GetDirectoryName(DbPath), "bodies"); + var newInstance = CreateSqlServerInstance(new MessageBodyStorage + { + StorageType = MessageBodyStorageType.FileSystem, + FileSystemStoragePath = messageBodyPath + }); + + newInstance.CopyFiles(zipResourceName); + newInstance.WriteConfigurationFile(); + + var instance = new ServiceControlAuditInstance(new FakeWindowsServiceController(Path.Combine(InstallPath, "ServiceControl.Audit.exe"))); + + instance.Reload(); + + Assert.That(Directory.Exists(DbPath), Is.False, "SQL Server instances have no local database folder"); + Assert.That(Directory.Exists(messageBodyPath), Is.True); + Assert.That(instance.HasCleanableStoragePaths, Is.True); + Assert.That(instance.UsesEmbeddedDatabase, Is.False); + Assert.That(instance.ConfiguredMessageBodyStorageType, Is.EqualTo(MessageBodyStorageType.FileSystem)); + Assert.That(instance.MessageBodyStoragePath, Is.EqualTo(messageBodyPath)); + + instance.RemoveDataBaseFolder(); + + Assert.That(Directory.Exists(messageBodyPath), Is.False); + } + + [Test] + public void Should_not_attempt_local_cleanup_on_uninstall_for_external_body_storage() + { + var newInstance = CreateSqlServerInstance(new MessageBodyStorage + { + StorageType = MessageBodyStorageType.AzureBlob, + AzureConnectionString = "UseDevelopmentStorage=true" + }); + + newInstance.CopyFiles(zipResourceName); + newInstance.WriteConfigurationFile(); + + var instance = new ServiceControlAuditInstance(new FakeWindowsServiceController(Path.Combine(InstallPath, "ServiceControl.Audit.exe"))); + + instance.Reload(); + + Assert.That(instance.HasCleanableStoragePaths, Is.False); + Assert.That(instance.ConfiguredMessageBodyStorageType, Is.EqualTo(MessageBodyStorageType.AzureBlob)); + Assert.That(instance.AppConfig.Read("ServiceControl.Audit/MessageBody/Azure/ConnectionString", null), Is.EqualTo("UseDevelopmentStorage=true")); + } + + ServiceControlAuditNewInstance CreateSqlServerInstance(MessageBodyStorage messageBodyStorage) + { + var newInstance = ServiceControlAuditNewInstance.CreateWithPersistence("SQLServer"); + + newInstance.InstallPath = InstallPath; + newInstance.TransportPackage = ServiceControlCoreTransports.Find("LearningTransport"); + newInstance.LogPath = LogPath; + newInstance.HostName = "localhost"; + newInstance.PersistenceConnectionString = "placeholder-connection-string"; + newInstance.MessageBodyStorage = messageBodyStorage; + + return newInstance; + } + class FakeWindowsServiceController : IWindowsServiceController { public FakeWindowsServiceController(string exePath) diff --git a/src/ServiceControlInstaller.Engine.UnitTests/Configuration/InstanceTests.cs b/src/ServiceControlInstaller.Engine.UnitTests/Configuration/InstanceTests.cs new file mode 100644 index 0000000000..4ebac06112 --- /dev/null +++ b/src/ServiceControlInstaller.Engine.UnitTests/Configuration/InstanceTests.cs @@ -0,0 +1,171 @@ +namespace ServiceControlInstaller.Engine.UnitTests.Configuration +{ + using System; + using System.IO; + using System.ServiceProcess; + using NUnit.Framework; + using ServiceControlInstaller.Engine.Configuration.ServiceControl; + using ServiceControlInstaller.Engine.Instances; + using ServiceControlInstaller.Engine.Services; + + [TestFixture] + class InstanceTests : InstallationFixture + { + const string zipResourceName = "Particular.ServiceControl.zip"; + + [Test] + public void Should_remove_db_folder_on_uninstall_for_RavenDB() + { + var newInstance = ServiceControlNewInstance.CreateWithPersistence("RavenDB"); + + newInstance.InstallPath = InstallPath; + newInstance.TransportPackage = ServiceControlCoreTransports.Find("LearningTransport"); + newInstance.DBPath = DbPath; + newInstance.LogPath = LogPath; + newInstance.HostName = "localhost"; + newInstance.DatabaseMaintenancePort = 33333; + + newInstance.CopyFiles(zipResourceName); + newInstance.WriteConfigurationFile(); + + var instance = new ServiceControlInstance(new FakeWindowsServiceController(Path.Combine(InstallPath, "ServiceControl.exe"))); + + instance.Reload(); + + Assert.That(instance.HasCleanableStoragePaths, Is.True); + Assert.That(instance.UsesEmbeddedDatabase, Is.True); + + instance.RemoveLogsFolder(); + instance.RemoveDataBaseFolder(); + + Assert.That(Directory.Exists(LogPath), Is.False); + Assert.That(Directory.Exists(DbPath), Is.False); + } + + [Test] + public void Should_remove_only_message_body_folder_on_uninstall_for_SQL_Server() + { + var messageBodyPath = Path.Combine(Path.GetDirectoryName(DbPath), "bodies"); + var newInstance = CreateSqlServerInstance(new MessageBodyStorage + { + StorageType = MessageBodyStorageType.FileSystem, + FileSystemStoragePath = messageBodyPath + }); + + newInstance.CopyFiles(zipResourceName); + newInstance.WriteConfigurationFile(); + + var instance = new ServiceControlInstance(new FakeWindowsServiceController(Path.Combine(InstallPath, "ServiceControl.exe"))); + + instance.Reload(); + + Assert.That(Directory.Exists(DbPath), Is.False, "SQL Server instances have no local database folder"); + Assert.That(Directory.Exists(messageBodyPath), Is.True); + Assert.That(instance.HasCleanableStoragePaths, Is.True); + Assert.That(instance.UsesEmbeddedDatabase, Is.False); + Assert.That(instance.ConfiguredMessageBodyStorageType, Is.EqualTo(MessageBodyStorageType.FileSystem)); + Assert.That(instance.MessageBodyStoragePath, Is.EqualTo(messageBodyPath)); + + instance.RemoveLogsFolder(); + instance.RemoveDataBaseFolder(); + + Assert.That(Directory.Exists(LogPath), Is.False); + Assert.That(Directory.Exists(messageBodyPath), Is.False); + } + + [Test] + public void Should_not_attempt_local_cleanup_on_uninstall_for_external_storage() + { + var newInstance = CreateSqlServerInstance(new MessageBodyStorage + { + StorageType = MessageBodyStorageType.S3, + S3BucketName = "bodies" + }); + + newInstance.CopyFiles(zipResourceName); + newInstance.WriteConfigurationFile(); + + var instance = new ServiceControlInstance(new FakeWindowsServiceController(Path.Combine(InstallPath, "ServiceControl.exe"))); + + instance.Reload(); + + Assert.That(instance.HasCleanableStoragePaths, Is.False); + Assert.That(instance.ConfiguredMessageBodyStorageType, Is.EqualTo(MessageBodyStorageType.S3)); + Assert.That(instance.MessageBodyStoragePath, Is.Null); + Assert.That(instance.AppConfig.Read(ServiceControlSettings.MessageBodyFileSystemStoragePath, null), Is.Null, "Only the selected body storage type's settings are written"); + } + + ServiceControlNewInstance CreateSqlServerInstance(MessageBodyStorage messageBodyStorage) + { + var newInstance = ServiceControlNewInstance.CreateWithPersistence("SQLServer"); + + newInstance.InstallPath = InstallPath; + newInstance.TransportPackage = ServiceControlCoreTransports.Find("LearningTransport"); + newInstance.LogPath = LogPath; + newInstance.HostName = "localhost"; + newInstance.PersistenceConnectionString = "placeholder-connection-string"; + newInstance.MessageBodyStorage = messageBodyStorage; + + return newInstance; + } + + [Test] + public void Should_treat_external_RavenDB_as_unmanaged_storage() + { + var newInstance = ServiceControlNewInstance.CreateWithPersistence("RavenDB"); + + newInstance.InstallPath = InstallPath; + newInstance.TransportPackage = ServiceControlCoreTransports.Find("LearningTransport"); + newInstance.DBPath = DbPath; + newInstance.LogPath = LogPath; + newInstance.HostName = "localhost"; + newInstance.DatabaseMaintenancePort = 33333; + + newInstance.CopyFiles(zipResourceName); + newInstance.WriteConfigurationFile(); + + var instance = new ServiceControlInstance(new FakeWindowsServiceController(Path.Combine(InstallPath, "ServiceControl.exe"))); + instance.AppConfig.Config.AppSettings.Settings.Add(ServiceControlSettings.RavenDBConnectionString.Name, "http://ravendb.example:8080"); + instance.AppConfig.Config.Save(); + + instance.Reload(); + + Assert.That(instance.UsesEmbeddedDatabase, Is.False); + Assert.That(instance.HasCleanableStoragePaths, Is.False); + + instance.RemoveDataBaseFolder(); + + Assert.That(Directory.Exists(DbPath), Is.True); + } + + class FakeWindowsServiceController : IWindowsServiceController + { + public FakeWindowsServiceController(string exePath) + { + ExePath = exePath; + } + public string ServiceName => "ServiceControl"; + + public bool Exists() => true; + + public string ExePath { get; } + + public string Description { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + + public ServiceControllerStatus Status => throw new NotImplementedException(); + + public string Account => "system"; + + public string DisplayName => throw new NotImplementedException(); + + public void ChangeAccountDetails(string accountName, string serviceAccountPwd) => throw new NotImplementedException(); + public void Delete() => throw new NotImplementedException(); + public void Refresh() + { } + public void SetStartupMode(string v) => throw new NotImplementedException(); + public void Start() => throw new NotImplementedException(); + public void Stop() => throw new NotImplementedException(); + public void WaitForStatus(ServiceControllerStatus stopped, TimeSpan timeSpan) => throw new NotImplementedException(); + } + } +} diff --git a/src/ServiceControlInstaller.Engine.UnitTests/Configuration/PersistenceManifestTests.cs b/src/ServiceControlInstaller.Engine.UnitTests/Configuration/PersistenceManifestTests.cs index fe91cd2449..e7b0112f56 100644 --- a/src/ServiceControlInstaller.Engine.UnitTests/Configuration/PersistenceManifestTests.cs +++ b/src/ServiceControlInstaller.Engine.UnitTests/Configuration/PersistenceManifestTests.cs @@ -56,6 +56,16 @@ public void Raven35IsDefault() Assert.That(manifests.All(m => m.Name == "RavenDB35")); } + [Test] + public void SupportedManifestsExcludeLegacyRavenDB35() + { + Assert.Multiple(() => + { + Assert.That(ServiceControlPersisters.GetSupportedPrimaryManifests().Select(m => m.Name), Is.EquivalentTo(new[] { "PostgreSQL", "RavenDB", "SQLServer" })); + Assert.That(ServiceControlPersisters.GetSupportedAuditManifests().Select(m => m.Name), Is.EquivalentTo(new[] { "PostgreSQL", "RavenDB", "SQLServer" })); + }); + } + [Test] public void UnknownPersister() { diff --git a/src/ServiceControlInstaller.Engine.UnitTests/InstallationTests.cs b/src/ServiceControlInstaller.Engine.UnitTests/InstallationTests.cs index b6516ac3a2..85ca9ac07b 100644 --- a/src/ServiceControlInstaller.Engine.UnitTests/InstallationTests.cs +++ b/src/ServiceControlInstaller.Engine.UnitTests/InstallationTests.cs @@ -19,6 +19,7 @@ public void Audit_install_should_write_expected_config_file(string manifestPath) var installPath = Path.Combine(Path.GetTempPath(), TestContext.CurrentContext.Test.ID, "install"); var dbPath = Path.Combine(Path.GetTempPath(), TestContext.CurrentContext.Test.ID, "db"); var logPath = Path.Combine(Path.GetTempPath(), TestContext.CurrentContext.Test.ID, "log"); + var messageBodyPath = Path.Combine(Path.GetTempPath(), TestContext.CurrentContext.Test.ID, "bodies"); try { @@ -55,13 +56,23 @@ public void Audit_install_should_write_expected_config_file(string manifestPath) newInstance.LogPath = logPath; newInstance.HostName = "localhost"; newInstance.DatabaseMaintenancePort = 33333; + newInstance.PersistenceConnectionString = "placeholder-connection-string"; + + if (persistenceManifest.Settings.Any(setting => setting.Name == AuditInstanceSettingsList.MessageBodyStorageType.Name)) + { + newInstance.MessageBodyStorage = new MessageBodyStorage + { + StorageType = MessageBodyStorageType.FileSystem, + FileSystemStoragePath = messageBodyPath + }; + } newInstance.WriteConfigurationFile(); var configFile = File.ReadAllText(Path.Combine(installPath, "ServiceControl.Audit.exe.config")); var scenario = Path.GetFileName(Path.GetDirectoryName(manifestPath)); - Approver.Verify(configFile, input => input.Replace(dbPath, "value-not-asserted").Replace(logPath, "value-not-asserted"), scenario); + Approver.Verify(configFile, input => input.Replace(dbPath, "value-not-asserted").Replace(logPath, "value-not-asserted").Replace(messageBodyPath, "value-not-asserted"), scenario); } finally { @@ -75,7 +86,9 @@ public void Audit_install_should_write_expected_config_file(string manifestPath) [ AuditInstanceSettingsList.DBPath.Name, AuditInstanceSettingsList.DatabaseMaintenancePort.Name, - AuditInstanceSettingsList.LogPath.Name + AuditInstanceSettingsList.LogPath.Name, + AuditInstanceSettingsList.DatabaseConnectionString.Name, + AuditInstanceSettingsList.MessageBodyStorageType.Name ]; public static IEnumerable GetAuditPersistenceManifestPaths() @@ -85,4 +98,93 @@ public static IEnumerable GetAuditPersistenceManifestPaths() return Directory.GetFiles(persistersPath, "persistence.manifest", SearchOption.AllDirectories); } } + + class ServiceControlInstallationTests + { + const string ConnectionStringPlaceholder = "placeholder-connection-string"; + + [Test] + [TestCaseSource(nameof(GetPrimaryPersistenceManifestPaths))] + public void ServiceControl_install_should_write_expected_config_file(string manifestPath) + { + var installPath = Path.Combine(Path.GetTempPath(), TestContext.CurrentContext.Test.ID, "install"); + var dbPath = Path.Combine(Path.GetTempPath(), TestContext.CurrentContext.Test.ID, "db"); + var logPath = Path.Combine(Path.GetTempPath(), TestContext.CurrentContext.Test.ID, "log"); + var messageBodyPath = Path.Combine(Path.GetTempPath(), TestContext.CurrentContext.Test.ID, "bodies"); + + try + { + PersistenceManifest persistenceManifest; + + using (var reader = new StreamReader(manifestPath)) + { + var manifestContent = reader.ReadToEnd(); + persistenceManifest = JsonSerializer.Deserialize(manifestContent); + } + + if (!persistenceManifest.IsSupported) + { + Assert.Ignore("Don't care about config for unsupported persistence types."); + } + + if (persistenceManifest.Settings.Any(setting => setting.Mandatory && setting.DefaultValue == null && !InstallerSuppliedSettings.Contains(setting.Name))) + { + Assert.Ignore("The installer cannot create an instance on this persister yet: it has no value for one of its mandatory settings."); + } + + var newInstance = new ServiceControlNewInstance(persistenceManifest); + + if (Directory.Exists(installPath)) + { + Directory.Delete(installPath, true); + } + + newInstance.InstallPath = installPath; + newInstance.TransportPackage = ServiceControlCoreTransports.Find("LearningTransport"); + + newInstance.DBPath = dbPath; + newInstance.LogPath = logPath; + newInstance.HostName = "localhost"; + newInstance.DatabaseMaintenancePort = 33333; + newInstance.PersistenceConnectionString = ConnectionStringPlaceholder; + + if (persistenceManifest.Settings.Any(setting => setting.Name == ServiceControlSettings.MessageBodyStorageType.Name)) + { + newInstance.MessageBodyStorage = new MessageBodyStorage + { + StorageType = MessageBodyStorageType.FileSystem, + FileSystemStoragePath = messageBodyPath + }; + } + + newInstance.WriteConfigurationFile(); + + var configFile = File.ReadAllText(Path.Combine(installPath, "ServiceControl.exe.config")); + var scenario = Path.GetFileName(Path.GetDirectoryName(manifestPath)); + + Approver.Verify(configFile, input => input.Replace(dbPath, "value-not-asserted").Replace(logPath, "value-not-asserted").Replace(messageBodyPath, "value-not-asserted"), scenario); + } + finally + { + FileUtils.DeleteDirectory(installPath, true, false); + FileUtils.DeleteDirectory(dbPath, true, false); + FileUtils.DeleteDirectory(logPath, true, false); + } + } + + static readonly string[] InstallerSuppliedSettings = + [ + ServiceControlSettings.DBPath.Name, + ServiceControlSettings.DatabaseMaintenancePort.Name, + ServiceControlSettings.HostName.Name, + ServiceControlSettings.DatabaseConnectionString.Name + ]; + + public static IEnumerable GetPrimaryPersistenceManifestPaths() + { + var deployPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, "..", "..", "..", "..", "..", "deploy")); + var persistersPath = Path.Combine(deployPath, "Particular.ServiceControl", "Persisters"); + return Directory.GetFiles(persistersPath, "persistence.manifest", SearchOption.AllDirectories); + } + } } diff --git a/src/ServiceControlInstaller.Engine.UnitTests/RunEngineTasksExplicitly.cs b/src/ServiceControlInstaller.Engine.UnitTests/RunEngineTasksExplicitly.cs index d45f8f1866..c1c71c16b6 100644 --- a/src/ServiceControlInstaller.Engine.UnitTests/RunEngineTasksExplicitly.cs +++ b/src/ServiceControlInstaller.Engine.UnitTests/RunEngineTasksExplicitly.cs @@ -34,7 +34,6 @@ public void UpgradeInstance() { installer.Upgrade(instance, new ServiceControlUpgradeOptions { - AuditRetentionPeriod = TimeSpan.FromDays(30), ErrorRetentionPeriod = TimeSpan.FromDays(15), OverrideEnableErrorForwarding = true }); @@ -63,7 +62,6 @@ public async Task CreateInstanceMSMQ() details.AuditQueue = "audittest"; details.ForwardAuditMessages = false; details.ForwardErrorMessages = false; - details.AuditRetentionPeriod = TimeSpan.FromDays(SettingConstants.AuditRetentionPeriodDefaultInDaysForUI); details.ErrorRetentionPeriod = TimeSpan.FromDays(SettingConstants.ErrorRetentionPeriodDefaultInDaysForUI); details.ErrorQueue = "testerror"; details.TransportPackage = ServiceControlCoreTransports.Find("MSMQ"); diff --git a/src/ServiceControlInstaller.Engine.UnitTests/Validation/MessageBodyStorageValidationTests.cs b/src/ServiceControlInstaller.Engine.UnitTests/Validation/MessageBodyStorageValidationTests.cs new file mode 100644 index 0000000000..d16bbd82f0 --- /dev/null +++ b/src/ServiceControlInstaller.Engine.UnitTests/Validation/MessageBodyStorageValidationTests.cs @@ -0,0 +1,109 @@ +namespace ServiceControlInstaller.Engine.UnitTests.Validation +{ + using Engine.Validation; + using Instances; + using NUnit.Framework; + + [TestFixture] + public class MessageBodyStorageValidationTests + { + static PersistenceManifest SqlServer => ServiceControlPersisters.GetPrimaryPersistence("SQLServer"); + static PersistenceManifest RavenDB => ServiceControlPersisters.GetPrimaryPersistence("RavenDB"); + + [Test] + public void Should_require_body_storage_for_SQL_Server_audit() => + Assert.Throws(() => MessageBodyStorageValidator.Validate(ServiceControlPersisters.GetAuditPersistence("SQLServer"), null)); + + [Test] + public void Should_accept_body_storage_for_SQL_Server_audit() + { + var storage = new MessageBodyStorage { StorageType = MessageBodyStorageType.S3, S3BucketName = "audit-bodies" }; + + Assert.DoesNotThrow(() => MessageBodyStorageValidator.Validate(ServiceControlPersisters.GetAuditPersistence("SQLServer"), storage)); + } + + [Test] + public void Should_reject_body_storage_for_RavenDB_audit() + { + var storage = new MessageBodyStorage { StorageType = MessageBodyStorageType.FileSystem, FileSystemStoragePath = @"C:\bodies" }; + + Assert.Throws(() => MessageBodyStorageValidator.Validate(ServiceControlPersisters.GetAuditPersistence("RavenDB"), storage)); + } + + [Test] + public void Should_reject_body_storage_for_RavenDB() + { + var storage = new MessageBodyStorage { StorageType = MessageBodyStorageType.FileSystem, FileSystemStoragePath = @"C:\bodies" }; + + Assert.Throws(() => MessageBodyStorageValidator.Validate(RavenDB, storage)); + } + + [Test] + public void Should_allow_no_body_storage_for_RavenDB() => + Assert.DoesNotThrow(() => MessageBodyStorageValidator.Validate(RavenDB, null)); + + [Test] + public void Should_require_body_storage_for_SQL_Server() => + Assert.Throws(() => MessageBodyStorageValidator.Validate(SqlServer, null)); + + [Test] + public void Should_require_path_for_file_system() + { + var storage = new MessageBodyStorage { StorageType = MessageBodyStorageType.FileSystem }; + + Assert.Throws(() => MessageBodyStorageValidator.Validate(SqlServer, storage)); + } + + [TestCase(null, null)] + [TestCase("UseDevelopmentStorage=true", "https://account.blob.core.windows.net")] + public void Should_require_exactly_one_Azure_authentication_method(string connectionString, string serviceUri) + { + var storage = new MessageBodyStorage { StorageType = MessageBodyStorageType.AzureBlob, AzureConnectionString = connectionString, AzureServiceUri = serviceUri }; + + Assert.Throws(() => MessageBodyStorageValidator.Validate(SqlServer, storage)); + } + + [Test] + public void Should_reject_relative_Azure_service_uri() + { + var storage = new MessageBodyStorage { StorageType = MessageBodyStorageType.AzureBlob, AzureServiceUri = "account.blob.core.windows.net" }; + + Assert.Throws(() => MessageBodyStorageValidator.Validate(SqlServer, storage)); + } + + [TestCase("UseDevelopmentStorage=true", null)] + [TestCase(null, "https://account.blob.core.windows.net")] + public void Should_accept_one_Azure_authentication_method(string connectionString, string serviceUri) + { + var storage = new MessageBodyStorage { StorageType = MessageBodyStorageType.AzureBlob, AzureConnectionString = connectionString, AzureServiceUri = serviceUri }; + + Assert.DoesNotThrow(() => MessageBodyStorageValidator.Validate(SqlServer, storage)); + } + + [Test] + public void Should_require_S3_bucket() + { + var storage = new MessageBodyStorage { StorageType = MessageBodyStorageType.S3 }; + + Assert.Throws(() => MessageBodyStorageValidator.Validate(SqlServer, storage)); + } + + [TestCase("key", null)] + [TestCase(null, "secret")] + public void Should_require_both_S3_keys_or_neither(string accessKeyId, string secretAccessKey) + { + var storage = new MessageBodyStorage { StorageType = MessageBodyStorageType.S3, S3BucketName = "bodies", S3AccessKeyId = accessKeyId, S3SecretAccessKey = secretAccessKey }; + + Assert.Throws(() => MessageBodyStorageValidator.Validate(SqlServer, storage)); + } + + [TestCase(null, null)] + [TestCase("key", "secret")] + public void Should_accept_S3_with_both_keys_or_neither(string accessKeyId, string secretAccessKey) + { + var storage = new MessageBodyStorage { StorageType = MessageBodyStorageType.S3, S3BucketName = "bodies", S3AccessKeyId = accessKeyId, S3SecretAccessKey = secretAccessKey }; + + Assert.DoesNotThrow(() => MessageBodyStorageValidator.Validate(SqlServer, storage)); + } + } +} diff --git a/src/ServiceControlInstaller.Engine.UnitTests/Validation/QueueValidationTests.cs b/src/ServiceControlInstaller.Engine.UnitTests/Validation/QueueValidationTests.cs index aaf6fdf138..daff43c1b4 100644 --- a/src/ServiceControlInstaller.Engine.UnitTests/Validation/QueueValidationTests.cs +++ b/src/ServiceControlInstaller.Engine.UnitTests/Validation/QueueValidationTests.cs @@ -25,10 +25,10 @@ class FakeServiceControlInstance : IServiceControlInstance public TimeSpan ErrorRetentionPeriod { get; set; } - public TimeSpan? AuditRetentionPeriod { get; set; } - public List RemoteInstances { get; set; } + public MessageBodyStorage MessageBodyStorage { get; set; } + public bool EnableFullTextSearchOnBodies { get; set; } public int Port { get; set; } @@ -61,6 +61,8 @@ class FakeServiceControlInstance : IServiceControlInstance public PersistenceManifest PersistenceManifest { get; set; } + public string PersistenceConnectionString { get; set; } + public string ConnectionString { get; set; } public string Url { get; set; } @@ -82,8 +84,12 @@ class FakeServiceControlAuditInstance : IServiceControlAuditInstance public string ServiceControlQueueAddress { get; set; } + public MessageBodyStorage MessageBodyStorage { get; set; } + public PersistenceManifest PersistenceManifest { get; set; } + public string PersistenceConnectionString { get; set; } + public bool EnableFullTextSearchOnBodies { get; set; } public int Port { get; set; } diff --git a/src/ServiceControlInstaller.Engine.UnitTests/Validation/StorageEngineUpgradeTests.cs b/src/ServiceControlInstaller.Engine.UnitTests/Validation/StorageEngineUpgradeTests.cs index 54a1268282..fbb52668a1 100644 --- a/src/ServiceControlInstaller.Engine.UnitTests/Validation/StorageEngineUpgradeTests.cs +++ b/src/ServiceControlInstaller.Engine.UnitTests/Validation/StorageEngineUpgradeTests.cs @@ -32,7 +32,7 @@ public void Every_shipped_primary_storage_engine_gets_its_decided_upgrade_answer public void Every_shipped_audit_storage_engine_gets_its_decided_upgrade_answer() => AssertDecidedAnswers(ServiceControlPersisters.GetAllAuditManifests(), AuditUpgradableInPlace); - // A null persistence type is how a version 4 config with no PersistenceType setting resolves, which is RavenDB 3.5. + // A null storage type is how a version 4 config with no legacy PersistenceType setting resolves, which is RavenDB 3.5. [TestCase(null, ExpectedResult = false)] [TestCase("NotAKnownPersister", ExpectedResult = false)] public bool Whether_an_unlisted_primary_persistence_type_can_be_upgraded_in_place(string persistenceType) => diff --git a/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/AuditInstanceSettingsList.cs b/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/AuditInstanceSettingsList.cs index d557bf4bcf..16c441d8e7 100644 --- a/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/AuditInstanceSettingsList.cs +++ b/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/AuditInstanceSettingsList.cs @@ -21,9 +21,21 @@ public static class AuditInstanceSettingsList public static readonly SettingInfo HostName = new() { Name = "ServiceControl.Audit/HostName" }; public static readonly SettingInfo LogPath = new() { Name = "ServiceControl.Audit/LogPath" }; public static readonly SettingInfo DBPath = new() { Name = "ServiceControl.Audit/DBPath" }; + public static readonly SettingInfo DatabaseConnectionString = new() { Name = "ServiceControl.Audit/Database/ConnectionString" }; + public static readonly SettingInfo RavenDBConnectionString = new() { Name = "ServiceControl.Audit/RavenDB/ConnectionString" }; + public static readonly SettingInfo MessageBodyStorageType = new() { Name = "ServiceControl.Audit/MessageBody/StorageType" }; + public static readonly SettingInfo MessageBodyFileSystemStoragePath = new() { Name = "ServiceControl.Audit/MessageBody/FileSystem/StoragePath" }; public static readonly SettingInfo ForwardAuditMessages = new() { Name = "ServiceControl.Audit/ForwardAuditMessages" }; public static readonly SettingInfo TransportType = new() { Name = "ServiceControl.Audit/TransportType" }; - public static readonly SettingInfo PersistenceType = new() { Name = "ServiceControl.Audit/PersistenceType" }; + + public static readonly SettingInfo StorageType = new() { Name = "ServiceControl.Audit/StorageType" }; + + // Legacy name of StorageType. Not version gated for writes: a 6.x runtime ignores the unknown StorageType key, and RemoveIfRetired drops this key once the instance runs 7.0.0 + public static readonly SettingInfo PersistenceType = new() + { + Name = "ServiceControl.Audit/PersistenceType", + RemovedFrom = new(7, 0, 0) + }; public static readonly SettingInfo AuditQueue = new() { Name = "ServiceBus/AuditQueue" }; public static readonly SettingInfo AuditLogQueue = new() { Name = "ServiceBus/AuditLogQueue" }; public static readonly SettingInfo AuditRetentionPeriod = new() { Name = "ServiceControl.Audit/AuditRetentionPeriod" }; diff --git a/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/ServiceControlAppConfig.cs b/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/ServiceControlAppConfig.cs index 3f2ef78627..c9535ee043 100644 --- a/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/ServiceControlAppConfig.cs +++ b/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/ServiceControlAppConfig.cs @@ -4,6 +4,7 @@ using System.Configuration; using System.Data.Common; using System.IO; + using System.Linq; using Instances; using NuGet.Versioning; @@ -25,21 +26,67 @@ protected override void UpdateSettings() settings.Set(ServiceControlSettings.InstanceName, details.InstanceName, version); settings.Set(ServiceControlSettings.VirtualDirectory, details.VirtualDirectory); settings.Set(ServiceControlSettings.Port, details.Port.ToString()); - settings.Set(ServiceControlSettings.DatabaseMaintenancePort, details.DatabaseMaintenancePort.ToString(), version); settings.Set(ServiceControlSettings.HostName, details.HostName); settings.Set(ServiceControlSettings.LogPath, details.LogPath); - settings.Set(ServiceControlSettings.DBPath, details.DBPath); settings.Set(ServiceControlSettings.ForwardErrorMessages, details.ForwardErrorMessages.ToString(), version); settings.Set(ServiceControlSettings.TransportType, details.TransportPackage.Name, version); - settings.Set(ServiceControlSettings.PersistenceType, details.PersistenceManifest.Name); // TODO: Why is it set here AND at ServiceControlInstance.ApplySettingsChanges 🤬 + settings.Set(ServiceControlSettings.StorageType, details.PersistenceManifest.Name); // TODO: Why is it set here AND at ServiceControlInstance.ApplySettingsChanges 🤬 settings.Set(ServiceControlSettings.ErrorQueue, details.ErrorQueue); settings.Set(ServiceControlSettings.ErrorLogQueue, details.ForwardErrorMessages ? details.ErrorLogQueue : null); - settings.Set(ServiceControlSettings.AuditRetentionPeriod, details.AuditRetentionPeriod.ToString(), version); settings.Set(ServiceControlSettings.ErrorRetentionPeriod, details.ErrorRetentionPeriod.ToString(), version); - settings.Set(ServiceControlSettings.EnableFullTextSearchOnBodies, details.EnableFullTextSearchOnBodies.ToString(), version); + settings.Set(ServiceControlSettings.EnableFullTextSearchOnBodies, details.PersistenceManifest.Settings.Any(s => s.Name == ServiceControlSettings.EnableFullTextSearchOnBodies.Name) ? details.EnableFullTextSearchOnBodies.ToString() : null, version); settings.Set(ServiceControlSettings.RemoteInstances, RemoteInstanceConverter.ToJson(details.RemoteInstances), version); settings.Set(ServiceControlSettings.EnableIntegratedServicePulse, details.EnableIntegratedServicePulse.ToString(), version); + if (details.MessageBodyStorage != null) + { + foreach (var (setting, value) in details.MessageBodyStorage.GetSettings("ServiceControl")) + { + settings.Set(setting, value); + } + } + + foreach (var manifestSetting in details.PersistenceManifest.Settings) + { + if (!settings.AllKeys.Contains(manifestSetting.Name)) + { + var value = manifestSetting.DefaultValue; + + if (manifestSetting.Name == ServiceControlSettings.DBPath.Name) + { + value = details.DBPath; + } + + if (manifestSetting.Name == ServiceControlSettings.DatabaseMaintenancePort.Name) + { + value = details.DatabaseMaintenancePort.ToString(); + } + + if (manifestSetting.Name == ServiceControlSettings.DatabaseConnectionString.Name) + { + value = details.PersistenceConnectionString; + } + + if (!string.IsNullOrEmpty(value)) + { + settings.Add(manifestSetting.Name, value); + } + } + + if (manifestSetting.Mandatory) + { + if (!settings.AllKeys.Contains(manifestSetting.Name)) + { + throw new Exception($"Mandatory setting {manifestSetting.Name} was not configured"); + } + + if (string.IsNullOrEmpty(settings[manifestSetting.Name].Value)) + { + throw new Exception($"Mandatory setting {manifestSetting.Name} can not be null or empty"); + } + } + } + // Windows services allow a maximum of 125 seconds when stopping a service. // When shutting down or restarting the OS we have no control over the // shutdown timeout. This is by the installer engine that is run _only_ on @@ -47,10 +94,12 @@ protected override void UpdateSettings() settings.Set(ServiceControlSettings.ShutdownTimeout, "00:02:00", version); // Retired settings + settings.RemoveIfRetired(ServiceControlSettings.AuditRetentionPeriod, version); settings.RemoveIfRetired(ServiceControlSettings.AuditQueue, version); settings.RemoveIfRetired(ServiceControlSettings.AuditLogQueue, version); settings.RemoveIfRetired(ServiceControlSettings.ForwardAuditMessages, version); settings.RemoveIfRetired(ServiceControlSettings.InternalQueueName, version); + settings.RemoveIfRetired(ServiceControlSettings.PersistenceType, version); settings.RemoveIfRetired(ServiceControlSettings.LicensingComponentRabbitMqManagementApiUrl, version); settings.RemoveIfRetired(ServiceControlSettings.LicensingComponentRabbitMqManagementApiUsername, version); settings.RemoveIfRetired(ServiceControlSettings.LicensingComponentRabbitMqManagementApiPassword, version); diff --git a/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/ServiceControlAuditAppConfig.cs b/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/ServiceControlAuditAppConfig.cs index 81386283eb..bbbe533e32 100644 --- a/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/ServiceControlAuditAppConfig.cs +++ b/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/ServiceControlAuditAppConfig.cs @@ -23,12 +23,12 @@ protected override void UpdateSettings() settings.Set(AuditInstanceSettingsList.LogPath, instance.LogPath); settings.Set(AuditInstanceSettingsList.ForwardAuditMessages, instance.ForwardAuditMessages.ToString().ToLowerInvariant()); settings.Set(AuditInstanceSettingsList.TransportType, instance.TransportPackage.Name, version); - settings.Set(AuditInstanceSettingsList.PersistenceType, instance.PersistenceManifest.Name); // TODO: Why is it set here AND at ServiceControlAuditInstance.ApplySettingsChanges 🤬 + settings.Set(AuditInstanceSettingsList.StorageType, instance.PersistenceManifest.Name); // TODO: Why is it set here AND at ServiceControlAuditInstance.ApplySettingsChanges 🤬 settings.Set(AuditInstanceSettingsList.AuditQueue, instance.AuditQueue); settings.Set(AuditInstanceSettingsList.AuditLogQueue, instance.ForwardAuditMessages ? instance.AuditLogQueue : null); settings.Set(AuditInstanceSettingsList.AuditRetentionPeriod, instance.AuditRetentionPeriod.ToString(), version); settings.Set(AuditInstanceSettingsList.ServiceControlQueueAddress, instance.ServiceControlQueueAddress); - settings.Set(AuditInstanceSettingsList.EnableFullTextSearchOnBodies, instance.EnableFullTextSearchOnBodies.ToString().ToLowerInvariant(), version); + settings.Set(AuditInstanceSettingsList.EnableFullTextSearchOnBodies, instance.PersistenceManifest.Settings.Any(s => s.Name == AuditInstanceSettingsList.EnableFullTextSearchOnBodies.Name) ? instance.EnableFullTextSearchOnBodies.ToString().ToLowerInvariant() : null, version); // Windows services allow a maximum of 125 seconds when stopping a service. // When shutting down or restarting the OS we have no control over the @@ -36,6 +36,14 @@ protected override void UpdateSettings() // Windows via SCMU or PowerShell settings.Set(AuditInstanceSettingsList.ShutdownTimeout, "00:02:00", version); + if (instance.MessageBodyStorage != null) + { + foreach (var (setting, value) in instance.MessageBodyStorage.GetSettings("ServiceControl.Audit")) + { + settings.Set(setting, value); + } + } + foreach (var manifestSetting in instance.PersistenceManifest.Settings) { if (!settings.AllKeys.Contains(manifestSetting.Name)) @@ -52,6 +60,11 @@ protected override void UpdateSettings() value = instance.DatabaseMaintenancePort.ToString(); } + if (manifestSetting.Name == AuditInstanceSettingsList.DatabaseConnectionString.Name) + { + value = instance.PersistenceConnectionString; + } + if (!string.IsNullOrEmpty(value)) { settings.Add(manifestSetting.Name, value); @@ -74,6 +87,7 @@ protected override void UpdateSettings() // Retired setting settings.RemoveIfRetired(AuditInstanceSettingsList.InternalQueueName, version); + settings.RemoveIfRetired(AuditInstanceSettingsList.PersistenceType, version); RemoveRavenDB35Settings(settings, version); } diff --git a/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/SettingsList.cs b/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/SettingsList.cs index e209253c27..759a2a97b9 100644 --- a/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/SettingsList.cs +++ b/src/ServiceControlInstaller.Engine/Configuration/ServiceControl/SettingsList.cs @@ -27,6 +27,10 @@ public static class ServiceControlSettings public static readonly SettingInfo HostName = new() { Name = "ServiceControl/HostName" }; public static readonly SettingInfo LogPath = new() { Name = "ServiceControl/LogPath" }; public static readonly SettingInfo DBPath = new() { Name = "ServiceControl/DBPath" }; + public static readonly SettingInfo DatabaseConnectionString = new() { Name = "ServiceControl/Database/ConnectionString" }; + public static readonly SettingInfo RavenDBConnectionString = new() { Name = "ServiceControl/RavenDB/ConnectionString" }; + public static readonly SettingInfo MessageBodyStorageType = new() { Name = "ServiceControl/MessageBody/StorageType" }; + public static readonly SettingInfo MessageBodyFileSystemStoragePath = new() { Name = "ServiceControl/MessageBody/FileSystem/StoragePath" }; public static readonly SettingInfo ForwardAuditMessages = new() { Name = "ServiceControl/ForwardAuditMessages", @@ -40,7 +44,15 @@ public static class ServiceControlSettings }; public static readonly SettingInfo TransportType = new() { Name = "ServiceControl/TransportType" }; - public static readonly SettingInfo PersistenceType = new() { Name = "ServiceControl/PersistenceType" }; + + public static readonly SettingInfo StorageType = new() { Name = "ServiceControl/StorageType" }; + + // Legacy name of StorageType. Not version gated for writes: a 6.x runtime ignores the unknown StorageType key, and RemoveIfRetired drops this key once the instance runs 7.0.0 + public static readonly SettingInfo PersistenceType = new() + { + Name = "ServiceControl/PersistenceType", + RemovedFrom = new(7, 0, 0) + }; public static readonly SettingInfo AuditQueue = new() { Name = "ServiceBus/AuditQueue", @@ -57,7 +69,8 @@ public static class ServiceControlSettings public static SettingInfo AuditRetentionPeriod = new() { Name = "ServiceControl/AuditRetentionPeriod", - SupportedFrom = new SemanticVersion(1, 12, 1) + SupportedFrom = new SemanticVersion(1, 12, 1), + RemovedFrom = new SemanticVersion(7, 0, 0) }; public static SettingInfo ErrorRetentionPeriod = new() diff --git a/src/ServiceControlInstaller.Engine/Instances/MessageBodyStorage.cs b/src/ServiceControlInstaller.Engine/Instances/MessageBodyStorage.cs new file mode 100644 index 0000000000..5e867e54fc --- /dev/null +++ b/src/ServiceControlInstaller.Engine/Instances/MessageBodyStorage.cs @@ -0,0 +1,74 @@ +namespace ServiceControlInstaller.Engine.Instances +{ + using System.Collections.Generic; + using Configuration; + + // Names match ServiceControl's BodyStorageType so they are written to the config file as-is. + public enum MessageBodyStorageType + { + FileSystem, + AzureBlob, + S3 + } + + public class MessageBodyStorage + { + public MessageBodyStorageType StorageType { get; set; } + + public string FileSystemStoragePath { get; set; } + + public string AzureConnectionString { get; set; } + + public string AzureServiceUri { get; set; } + + public string AzureManagedIdentityClientId { get; set; } + + public string AzureAuthorityHost { get; set; } + + public string AzureContainerName { get; set; } + + public string S3BucketName { get; set; } + + public string S3KeyPrefix { get; set; } + + public string S3Region { get; set; } + + public string S3ServiceUrl { get; set; } + + public string S3AccessKeyId { get; set; } + + public string S3SecretAccessKey { get; set; } + + // settingsRoot is the instance's setting prefix, such as ServiceControl or ServiceControl.Audit. + internal IEnumerable<(SettingInfo Setting, string Value)> GetSettings(string settingsRoot) + { + (SettingInfo, string) Setting(string name, string value) => (new SettingInfo { Name = $"{settingsRoot}/MessageBody/{name}" }, value); + + yield return Setting("StorageType", StorageType.ToString()); + + switch (StorageType) + { + case MessageBodyStorageType.FileSystem: + yield return Setting("FileSystem/StoragePath", FileSystemStoragePath); + break; + case MessageBodyStorageType.AzureBlob: + yield return Setting("Azure/ConnectionString", AzureConnectionString); + yield return Setting("Azure/ServiceUri", AzureServiceUri); + yield return Setting("Azure/ManagedIdentityClientId", AzureManagedIdentityClientId); + yield return Setting("Azure/AuthorityHost", AzureAuthorityHost); + yield return Setting("Azure/ContainerName", AzureContainerName); + break; + case MessageBodyStorageType.S3: + yield return Setting("S3/BucketName", S3BucketName); + yield return Setting("S3/KeyPrefix", S3KeyPrefix); + yield return Setting("S3/Region", S3Region); + yield return Setting("S3/ServiceUrl", S3ServiceUrl); + yield return Setting("S3/AccessKeyId", S3AccessKeyId); + yield return Setting("S3/SecretAccessKey", S3SecretAccessKey); + break; + default: + break; + } + } + } +} diff --git a/src/ServiceControlInstaller.Engine/Instances/PersistenceManifest.cs b/src/ServiceControlInstaller.Engine/Instances/PersistenceManifest.cs index 12c1b36478..8b01ab3181 100644 --- a/src/ServiceControlInstaller.Engine/Instances/PersistenceManifest.cs +++ b/src/ServiceControlInstaller.Engine/Instances/PersistenceManifest.cs @@ -21,10 +21,10 @@ public class PersistenceManifest public string[] Aliases { get; set; } = []; - internal bool IsMatch(string persistenceType) => - string.Equals(TypeName, persistenceType, StringComparison.Ordinal) // Type names are case-sensitive - || string.Equals(Name, persistenceType, StringComparison.OrdinalIgnoreCase) - || Aliases.Contains(persistenceType, StringComparer.Ordinal); + internal bool IsMatch(string storageType) => + string.Equals(TypeName, storageType, StringComparison.Ordinal) // Type names are case-sensitive + || string.Equals(Name, storageType, StringComparison.OrdinalIgnoreCase) + || Aliases.Contains(storageType, StringComparer.Ordinal); public class Setting { diff --git a/src/ServiceControlInstaller.Engine/Instances/ServiceControlAuditInstance.cs b/src/ServiceControlInstaller.Engine/Instances/ServiceControlAuditInstance.cs index e280cfaba9..9b89a67257 100644 --- a/src/ServiceControlInstaller.Engine/Instances/ServiceControlAuditInstance.cs +++ b/src/ServiceControlInstaller.Engine/Instances/ServiceControlAuditInstance.cs @@ -46,7 +46,7 @@ public ServiceControlAuditInstance(IWindowsServiceController service) : base(ser public string ServiceControlQueueAddress { get; set; } - public PersistenceManifest PersistenceManifest { get; set; } + public string PersistenceConnectionString { get; set; } protected override void ApplySettingsChanges(KeyValueConfigurationCollection settings) { @@ -68,8 +68,16 @@ protected override void ApplySettingsChanges(KeyValueConfigurationCollection set settings.Set(AuditInstanceSettingsList.AuditRetentionPeriod, AuditRetentionPeriod.ToString(), Version); settings.Set(AuditInstanceSettingsList.AuditQueue, AuditQueue, Version); settings.Set(AuditInstanceSettingsList.AuditLogQueue, AuditLogQueue, Version); - settings.Set(AuditInstanceSettingsList.EnableFullTextSearchOnBodies, EnableFullTextSearchOnBodies.ToString().ToLowerInvariant(), Version); - settings.Set(AuditInstanceSettingsList.PersistenceType, PersistenceManifest.Name); + + var enableFullTextSearchOnBodiesValue = PersistenceManifest.Settings.Any(s => s.Name == AuditInstanceSettingsList.EnableFullTextSearchOnBodies.Name) + ? EnableFullTextSearchOnBodies.ToString().ToLowerInvariant() + : null; + + settings.Set(AuditInstanceSettingsList.EnableFullTextSearchOnBodies, enableFullTextSearchOnBodiesValue, Version); + settings.Set(AuditInstanceSettingsList.StorageType, PersistenceManifest.Name); + + // Retired settings + settings.RemoveIfRetired(AuditInstanceSettingsList.PersistenceType, Version); } protected override AppConfig CreateAppConfig() @@ -89,6 +97,14 @@ protected override TransportInfo DetermineTransportPackage() protected override string BaseServiceName => "ServiceControl.Audit"; + protected override SettingInfo DatabaseMaintenancePortSetting => AuditInstanceSettingsList.DatabaseMaintenancePort; + + protected override SettingInfo RavenDBConnectionStringSetting => AuditInstanceSettingsList.RavenDBConnectionString; + + protected override SettingInfo MessageBodyStorageTypeSetting => AuditInstanceSettingsList.MessageBodyStorageType; + + protected override SettingInfo MessageBodyStoragePathSetting => AuditInstanceSettingsList.MessageBodyFileSystemStoragePath; + public override void Reload() { Service.Refresh(); @@ -114,8 +130,14 @@ public override void Reload() InMaintenanceMode = AppConfig.Read(AuditInstanceSettingsList.MaintenanceMode, false); ServiceControlQueueAddress = AppConfig.Read(AuditInstanceSettingsList.ServiceControlQueueAddress, null); - var persistenceType = AppConfig.Read(AuditInstanceSettingsList.PersistenceType, null); - PersistenceManifest = ServiceControlPersisters.GetAuditPersistence(persistenceType); + var storageType = AppConfig.Read(AuditInstanceSettingsList.StorageType, null); + if (string.IsNullOrWhiteSpace(storageType)) + { + // A pre-7.0.0 config carries the setting under its legacy name; a config rewrite migrates it to StorageType + storageType = AppConfig.Read(AuditInstanceSettingsList.PersistenceType, null); + } + + PersistenceManifest = ServiceControlPersisters.GetAuditPersistence(storageType); TransportPackage = DetermineTransportPackage(); ConnectionString = ReadConnectionString(); @@ -144,22 +166,6 @@ protected override void Prepare(string zipResourceName, string destDir) FileUtils.UnzipToSubdirectory("RavenDBServer.zip", Path.Combine(destDir, "Persisters", "RavenDB", "RavenDBServer")); } - protected override IEnumerable GetPersistencePathsToCleanUp() - { - var settings = AppConfig.Config.AppSettings.Settings; - foreach (var key in PersistenceManifest.SettingsWithPathsToCleanup) - { - if (!settings.AllKeys.Contains(key, StringComparer.OrdinalIgnoreCase)) - { - continue; - } - - var folderPath = settings[key].Value; - yield return folderPath.StartsWith("~") //Raven uses ~ to indicate path is relative to bin folder e.g. ~/Data/Logs - ? Path.Combine(InstallPath, folderPath.Remove(0, 1)) - : folderPath; - } - } protected override void ValidateConnectionString() { diff --git a/src/ServiceControlInstaller.Engine/Instances/ServiceControlAuditNewInstance.cs b/src/ServiceControlInstaller.Engine/Instances/ServiceControlAuditNewInstance.cs index ff192d4cca..bfea58eb4d 100644 --- a/src/ServiceControlInstaller.Engine/Instances/ServiceControlAuditNewInstance.cs +++ b/src/ServiceControlInstaller.Engine/Instances/ServiceControlAuditNewInstance.cs @@ -2,6 +2,7 @@ { using System; using System.IO; + using System.Linq; using System.Xml.Serialization; using Configuration.ServiceControl; using Setup; @@ -64,7 +65,10 @@ protected override void RunSetup() protected override void ValidateMaintenancePort() { - DatabaseMaintenancePortValidator.Validate(this); + if (PersistenceManifest.Settings.Any(s => s.Name == AuditInstanceSettingsList.DatabaseMaintenancePort.Name)) + { + DatabaseMaintenancePortValidator.Validate(this); + } } protected override void ValidateQueueNames() @@ -81,5 +85,10 @@ protected override void ValidateConnectionString() { ConnectionStringValidator.Validate(this); } + + protected override void ValidatePersistence() + { + MessageBodyStorageValidator.Validate(PersistenceManifest, MessageBodyStorage); + } } } \ No newline at end of file diff --git a/src/ServiceControlInstaller.Engine/Instances/ServiceControlBaseService.cs b/src/ServiceControlInstaller.Engine/Instances/ServiceControlBaseService.cs index e2983cb02e..5a86735663 100644 --- a/src/ServiceControlInstaller.Engine/Instances/ServiceControlBaseService.cs +++ b/src/ServiceControlInstaller.Engine/Instances/ServiceControlBaseService.cs @@ -40,6 +40,39 @@ protected ServiceControlBaseService(IWindowsServiceController service) public bool InMaintenanceMode { get; set; } public ReportCard ReportCard { get; set; } + public PersistenceManifest PersistenceManifest { get; set; } + + // False when all data lives somewhere ServiceControl doesn't manage, such as a SQL Server database or an S3 bucket. + public bool HasCleanableStoragePaths => AppConfig?.Config != null && !UsesExternalRavenDB && GetPersistencePathsToCleanUp().Any(); + + // Only persisters that run an embedded database server declare a maintenance port. + public bool UsesEmbeddedDatabase => + PersistenceManifest?.Settings.Any(setting => setting.Name == DatabaseMaintenancePortSetting.Name) == true + && !UsesExternalRavenDB; + + bool UsesExternalRavenDB => !string.IsNullOrWhiteSpace(AppConfig?.Read(RavenDBConnectionStringSetting, null)); + + protected abstract SettingInfo DatabaseMaintenancePortSetting { get; } + + protected abstract SettingInfo RavenDBConnectionStringSetting { get; } + + protected abstract SettingInfo MessageBodyStorageTypeSetting { get; } + + protected abstract SettingInfo MessageBodyStoragePathSetting { get; } + + public MessageBodyStorage MessageBodyStorage => null; + + // Null for storage types that keep message bodies in the database itself. + public MessageBodyStorageType? ConfiguredMessageBodyStorageType => + Enum.TryParse(AppConfig?.Read(MessageBodyStorageTypeSetting, null), ignoreCase: true, out var storageType) + ? storageType + : null; + + // Null unless message bodies are stored on the file system. + public string MessageBodyStoragePath => + ConfiguredMessageBodyStorageType == MessageBodyStorageType.FileSystem + ? AppConfig.Read(MessageBodyStoragePathSetting, null) + : null; /// /// Raven management URL @@ -211,6 +244,11 @@ public void RemoveLogsFolder() public void RemoveDataBaseFolder() { + if (!HasCleanableStoragePaths) + { + return; + } + //Order by length descending in case they are nested paths var folders = GetPersistencePathsToCleanUp().ToList(); @@ -292,9 +330,27 @@ public virtual void DisableMaintenanceMode() InMaintenanceMode = false; } - protected virtual IEnumerable GetPersistencePathsToCleanUp() + IEnumerable GetPersistencePathsToCleanUp() { - return []; + var settings = AppConfig.Config.AppSettings.Settings; + foreach (var key in PersistenceManifest.SettingsWithPathsToCleanup) + { + if (!settings.AllKeys.Contains(key, StringComparer.OrdinalIgnoreCase)) + { + continue; + } + + if (string.Equals(key, MessageBodyStoragePathSetting.Name, StringComparison.OrdinalIgnoreCase) + && ConfiguredMessageBodyStorageType != MessageBodyStorageType.FileSystem) + { + continue; + } + + var folderPath = settings[key].Value; + yield return folderPath.StartsWith("~") //Raven uses ~ to indicate path is relative to bin folder e.g. ~/Data/Logs + ? Path.Combine(InstallPath, folderPath.Remove(0, 1)) + : folderPath; + } } protected virtual void ValidateConnectionString() diff --git a/src/ServiceControlInstaller.Engine/Instances/ServiceControlInstallableBase.cs b/src/ServiceControlInstaller.Engine/Instances/ServiceControlInstallableBase.cs index d66df319ee..2a64351689 100644 --- a/src/ServiceControlInstaller.Engine/Instances/ServiceControlInstallableBase.cs +++ b/src/ServiceControlInstaller.Engine/Instances/ServiceControlInstallableBase.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.IO; + using System.Linq; using System.Security.AccessControl; using System.Security.Principal; using System.Threading; @@ -52,20 +53,26 @@ public string AclMaintenanceUrl } } - string[] FlagFiles + IEnumerable FlagFiles { get { const string flagFileName = ".notconfigured"; - return - [ - Path.Combine(InstallPath, flagFileName), - Path.Combine(DBPath, flagFileName), - Path.Combine(LogPath, flagFileName) - ]; + return new[] { InstallPath, LogPath } + .Concat(DataPaths) + .Where(path => !string.IsNullOrWhiteSpace(path)) + .Select(path => Path.Combine(path, flagFileName)); } } + // Directories the service writes data to. Each is created with modify access for the service account. + protected virtual IEnumerable DataPaths => [DBPath, MessageBodyStoragePath]; + + // Only populated for storage types that keep message bodies outside the database. + public MessageBodyStorage MessageBodyStorage { get; set; } + + string MessageBodyStoragePath => MessageBodyStorage?.StorageType == MessageBodyStorageType.FileSystem ? MessageBodyStorage.FileSystemStoragePath : null; + public string LogPath { get; set; } public string DBPath { get; set; } @@ -98,6 +105,8 @@ string[] FlagFiles public string ConnectionString { get; set; } + public string PersistenceConnectionString { get; set; } + public string Name { get; set; } public string InstanceName { get; set; } @@ -148,9 +157,9 @@ public virtual void CopyFiles(string zipResourceName) FileUtils.CreateDirectoryAndSetAcl(LogPath, modifyAccessRule); } - if (!string.IsNullOrWhiteSpace(DBPath)) + foreach (var dataPath in DataPaths.Where(path => !string.IsNullOrWhiteSpace(path))) { - FileUtils.CreateDirectoryAndSetAcl(DBPath, modifyAccessRule); + FileUtils.CreateDirectoryAndSetAcl(dataPath, modifyAccessRule); } // Mark these directories with a flag @@ -238,6 +247,7 @@ public async Task Validate(Func> promptT RunValidation(ValidateQueueNames); RunValidation(ValidateServiceAccount); RunValidation(ValidateConnectionString); + RunValidation(ValidatePersistence); } public void RunValidation(Action action) @@ -260,6 +270,10 @@ protected virtual void ValidateConnectionString() { } + protected virtual void ValidatePersistence() + { + } + protected virtual void ValidateServiceAccount() { } @@ -270,9 +284,19 @@ protected virtual void ValidateQueueNames() protected virtual Task ValidatePaths(Func> promptToProceed, CancellationToken cancellationToken = default) { - return new PathsValidator(this).RunValidation(true, promptToProceed, cancellationToken); + return new PathsValidator(this, AdditionalPaths).RunValidation(true, promptToProceed, cancellationToken); } + protected virtual IEnumerable AdditionalPaths => + [ + new PathInfo + { + Name = "message body path", + Path = MessageBodyStoragePath, + CheckIfEmpty = true + } + ]; + protected virtual void ValidateMaintenancePort() { } diff --git a/src/ServiceControlInstaller.Engine/Instances/ServiceControlInstance.cs b/src/ServiceControlInstaller.Engine/Instances/ServiceControlInstance.cs index 34328ebe5d..a216eb2063 100644 --- a/src/ServiceControlInstaller.Engine/Instances/ServiceControlInstance.cs +++ b/src/ServiceControlInstaller.Engine/Instances/ServiceControlInstance.cs @@ -48,11 +48,17 @@ public ServiceControlInstance(IWindowsServiceController service) : base(service) protected override string BaseServiceName => "ServiceControl"; - public TimeSpan? AuditRetentionPeriod { get; set; } + protected override SettingInfo DatabaseMaintenancePortSetting => ServiceControlSettings.DatabaseMaintenancePort; + + protected override SettingInfo RavenDBConnectionStringSetting => ServiceControlSettings.RavenDBConnectionString; + + protected override SettingInfo MessageBodyStorageTypeSetting => ServiceControlSettings.MessageBodyStorageType; + + protected override SettingInfo MessageBodyStoragePathSetting => ServiceControlSettings.MessageBodyFileSystemStoragePath; public List RemoteInstances { get; set; } = []; - public PersistenceManifest PersistenceManifest { get; set; } + public string PersistenceConnectionString { get; set; } public void AddRemoteInstance(string apiUri) { @@ -150,8 +156,14 @@ public override void Reload() Description = GetDescription(); ServiceAccount = Service.Account; - var persistenceType = AppConfig.Read(ServiceControlSettings.PersistenceType, null); - PersistenceManifest = ServiceControlPersisters.GetPrimaryPersistence(persistenceType); + var storageType = AppConfig.Read(ServiceControlSettings.StorageType, null); + if (string.IsNullOrWhiteSpace(storageType)) + { + // A pre-7.0.0 config carries the setting under its legacy name; a config rewrite migrates it to StorageType + storageType = AppConfig.Read(ServiceControlSettings.PersistenceType, null); + } + + PersistenceManifest = ServiceControlPersisters.GetPrimaryPersistence(storageType); ForwardErrorMessages = AppConfig.Read(ServiceControlSettings.ForwardErrorMessages, false); if (ForwardErrorMessages) @@ -173,11 +185,6 @@ public override void Reload() ErrorRetentionPeriod = errorRetentionPeriod; } - if (TimeSpan.TryParse(AppConfig.Read(ServiceControlSettings.AuditRetentionPeriod, (string)null), out var auditRetentionPeriod)) - { - AuditRetentionPeriod = auditRetentionPeriod; - } - var remoteInstancesString = AppConfig.Read(ServiceControlSettings.RemoteInstances, default(string)); if (!string.IsNullOrWhiteSpace(remoteInstancesString)) { @@ -205,15 +212,20 @@ protected override void ApplySettingsChanges(KeyValueConfigurationCollection set settings.Set(ServiceControlSettings.LogPath, LogPath); settings.Set(ServiceControlSettings.ForwardAuditMessages, ForwardAuditMessages.ToString(), Version); settings.Set(ServiceControlSettings.ForwardErrorMessages, ForwardErrorMessages.ToString(), Version); - settings.Set(ServiceControlSettings.AuditRetentionPeriod, AuditRetentionPeriod.ToString(), Version); settings.Set(ServiceControlSettings.ErrorRetentionPeriod, ErrorRetentionPeriod.ToString(), Version); settings.RemoveIfRetired(ServiceControlSettings.HoursToKeepMessagesBeforeExpiring, Version); + settings.RemoveIfRetired(ServiceControlSettings.AuditRetentionPeriod, Version); settings.Set(ServiceControlSettings.AuditQueue, AuditQueue, Version); settings.Set(ServiceControlSettings.ErrorQueue, ErrorQueue); settings.Set(ServiceControlSettings.AuditLogQueue, AuditLogQueue, Version); settings.Set(ServiceControlSettings.ErrorLogQueue, ErrorLogQueue, Version); - settings.Set(ServiceControlSettings.EnableFullTextSearchOnBodies, EnableFullTextSearchOnBodies.ToString(), Version); - settings.Set(ServiceControlSettings.PersistenceType, PersistenceManifest.Name); + + var enableFullTextSearchOnBodiesValue = PersistenceManifest.Settings.Any(s => s.Name == ServiceControlSettings.EnableFullTextSearchOnBodies.Name) + ? EnableFullTextSearchOnBodies.ToString().ToLowerInvariant() + : null; + + settings.Set(ServiceControlSettings.EnableFullTextSearchOnBodies, enableFullTextSearchOnBodiesValue, Version); + settings.Set(ServiceControlSettings.StorageType, PersistenceManifest.Name); settings.Set(ServiceControlSettings.EnableIntegratedServicePulse, EnableIntegratedServicePulse.ToString(), Version); if (RemoteInstances != null) @@ -228,6 +240,9 @@ protected override void ApplySettingsChanges(KeyValueConfigurationCollection set settings.Set(ServiceControlSettings.RemoteInstances, RemoteInstanceConverter.ToJson(RemoteInstances), Version); } + + // Retired settings + settings.RemoveIfRetired(ServiceControlSettings.PersistenceType, Version); } protected override void Prepare(string zipFilePath, string destDir) @@ -238,29 +253,5 @@ protected override void Prepare(string zipFilePath, string destDir) FileUtils.UnzipToSubdirectory("RavenDBServer.zip", Path.Combine(destDir, "Persisters", "RavenDB", "RavenDBServer")); } - protected override IEnumerable GetPersistencePathsToCleanUp() - { - string[] keys = - [ - "Raven/IndexStoragePath", - "Raven/CompiledIndexCacheDirectory", - "Raven/Esent/LogsPath", - ServiceControlSettings.DBPath.Name - ]; - - var settings = AppConfig.Config.AppSettings.Settings; - foreach (var key in keys) - { - if (!settings.AllKeys.Contains(key, StringComparer.OrdinalIgnoreCase)) - { - continue; - } - - var folderpath = settings[key].Value; - yield return folderpath.StartsWith("~") //Raven uses ~ to indicate path is relative to bin folder e.g. ~/Data/Logs - ? Path.Combine(InstallPath, folderpath.Remove(0, 1)) - : folderpath; - } - } } } \ No newline at end of file diff --git a/src/ServiceControlInstaller.Engine/Instances/ServiceControlNewInstance.cs b/src/ServiceControlInstaller.Engine/Instances/ServiceControlNewInstance.cs index 62fded61dd..fda52df856 100644 --- a/src/ServiceControlInstaller.Engine/Instances/ServiceControlNewInstance.cs +++ b/src/ServiceControlInstaller.Engine/Instances/ServiceControlNewInstance.cs @@ -66,9 +66,6 @@ public void AddRemoteInstance(string apiUri) } } - [XmlElement(typeof(XmlNullableTimeSpan))] - public TimeSpan? AuditRetentionPeriod { get; set; } - [XmlElement(typeof(XmlTimeSpan))] public TimeSpan ErrorRetentionPeriod { get; set; } @@ -92,7 +89,10 @@ protected override void RunSetup() protected override void ValidateMaintenancePort() { - DatabaseMaintenancePortValidator.Validate(this); + if (PersistenceManifest.Settings.Any(s => s.Name == ServiceControlSettings.DatabaseMaintenancePort.Name)) + { + DatabaseMaintenancePortValidator.Validate(this); + } } protected override void ValidateQueueNames() @@ -110,6 +110,11 @@ protected override void ValidateConnectionString() ConnectionStringValidator.Validate(this); } + protected override void ValidatePersistence() + { + MessageBodyStorageValidator.Validate(PersistenceManifest, MessageBodyStorage); + } + public static ServiceControlNewInstance Load(string path) { ServiceControlNewInstance instanceData; @@ -126,11 +131,6 @@ public static ServiceControlNewInstance Load(string path) throw new InvalidDataException("The supplied file is using an old format. Which is no longer supported."); } - if (doc.SelectSingleNode("/ServiceControlInstanceMetadata/AuditRetentionPeriod") == null) - { - throw new InvalidDataException("The supplied file is using an old format. Which is no longer supported."); - } - if (doc.SelectSingleNode("/ServiceControlInstanceMetadata/ErrorRetentionPeriod") == null) { throw new InvalidDataException("The supplied file is using an old format. Which is no longer supported."); diff --git a/src/ServiceControlInstaller.Engine/Instances/ServiceControlPersisters.cs b/src/ServiceControlInstaller.Engine/Instances/ServiceControlPersisters.cs index 85edb819f0..a9d6fe8492 100644 --- a/src/ServiceControlInstaller.Engine/Instances/ServiceControlPersisters.cs +++ b/src/ServiceControlInstaller.Engine/Instances/ServiceControlPersisters.cs @@ -35,6 +35,9 @@ static ServiceControlPersisters() public static PersistenceManifest GetPrimaryPersistence(string name) => GetPersistenceManifest(primaryPersistenceManifests, name); public static PersistenceManifest GetAuditPersistence(string name) => GetPersistenceManifest(auditPersistenceManifests, name); + public static PersistenceManifest[] GetSupportedPrimaryManifests() => primaryPersistenceManifests.Where(m => m.IsSupported).ToArray(); + public static PersistenceManifest[] GetSupportedAuditManifests() => auditPersistenceManifests.Where(m => m.IsSupported).ToArray(); + static PersistenceManifest GetPersistenceManifest(PersistenceManifest[] manifestCollection, string name) { if (string.IsNullOrEmpty(name)) diff --git a/src/ServiceControlInstaller.Engine/Instances/ServiceControlUpgradeOptions.cs b/src/ServiceControlInstaller.Engine/Instances/ServiceControlUpgradeOptions.cs index 74e2ed9cfe..bd6e5c62f7 100644 --- a/src/ServiceControlInstaller.Engine/Instances/ServiceControlUpgradeOptions.cs +++ b/src/ServiceControlInstaller.Engine/Instances/ServiceControlUpgradeOptions.cs @@ -6,7 +6,6 @@ public class ServiceControlUpgradeOptions { public bool? OverrideEnableErrorForwarding { get; set; } public TimeSpan? ErrorRetentionPeriod { get; set; } - public TimeSpan? AuditRetentionPeriod { get; set; } public int? MaintenancePort { get; set; } public bool SkipQueueCreation { get; set; } public string RemoteUrl { get; set; } @@ -38,11 +37,6 @@ void ApplyChangesTo(ServiceControlInstance instance) instance.ErrorRetentionPeriod = ErrorRetentionPeriod.Value; } - if (AuditRetentionPeriod.HasValue) - { - instance.AuditRetentionPeriod = AuditRetentionPeriod.Value; - } - if (MaintenancePort.HasValue) { instance.DatabaseMaintenancePort = MaintenancePort; diff --git a/src/ServiceControlInstaller.Engine/Interfaces.cs b/src/ServiceControlInstaller.Engine/Interfaces.cs index 5d5968b7a5..ee67ae6290 100644 --- a/src/ServiceControlInstaller.Engine/Interfaces.cs +++ b/src/ServiceControlInstaller.Engine/Interfaces.cs @@ -22,6 +22,10 @@ public interface ITransportConfig public interface IPersistenceConfig { PersistenceManifest PersistenceManifest { get; } + + // Only populated when creating a new instance; existing instances read their + // connection string back from the already-written config file instead. + string PersistenceConnectionString { get; set; } } public interface IHttpInstance @@ -91,6 +95,9 @@ public interface IServiceControlBaseInstance : IHttpInstance, IPersistenceConfig { bool EnableFullTextSearchOnBodies { get; } + + // Only populated when creating a new instance, like PersistenceConnectionString. + MessageBodyStorage MessageBodyStorage { get; } } public interface IServiceControlAuditInstance : IServiceControlBaseInstance @@ -111,7 +118,6 @@ public interface IServiceControlInstance : IServiceControlBaseInstance, IURLInfo bool ForwardErrorMessages { get; } bool EnableIntegratedServicePulse { get; } TimeSpan ErrorRetentionPeriod { get; } - TimeSpan? AuditRetentionPeriod { get; set; } List RemoteInstances { get; } } } \ No newline at end of file diff --git a/src/ServiceControlInstaller.Engine/Validation/MessageBodyStorageValidator.cs b/src/ServiceControlInstaller.Engine/Validation/MessageBodyStorageValidator.cs new file mode 100644 index 0000000000..79352b9246 --- /dev/null +++ b/src/ServiceControlInstaller.Engine/Validation/MessageBodyStorageValidator.cs @@ -0,0 +1,78 @@ +namespace ServiceControlInstaller.Engine.Validation +{ + using System; + using System.Linq; + using Instances; + + // Mirrors the checks ServiceControl runs at startup, so a bad combination fails at install time instead. + static class MessageBodyStorageValidator + { + public static void Validate(PersistenceManifest manifest, MessageBodyStorage storage) + { + var supportsBodyStorage = manifest.Settings.Any(s => s.Name.EndsWith("/MessageBody/StorageType")); + + if (!supportsBodyStorage) + { + if (storage != null) + { + throw new EngineValidationException($"The {manifest.DisplayName} storage type does not support configuring message body storage."); + } + + return; + } + + if (storage == null) + { + throw new EngineValidationException($"Message body storage must be configured for the {manifest.DisplayName} storage type."); + } + + switch (storage.StorageType) + { + case MessageBodyStorageType.FileSystem: + if (IsEmpty(storage.FileSystemStoragePath)) + { + throw new EngineValidationException("A message body path is required when message bodies are stored on the file system."); + } + + break; + case MessageBodyStorageType.AzureBlob: + var hasConnectionString = !IsEmpty(storage.AzureConnectionString); + var hasServiceUri = !IsEmpty(storage.AzureServiceUri); + + if (hasConnectionString == hasServiceUri) + { + throw new EngineValidationException("Azure Blob Storage requires either a connection string or a service URI for managed identity, but not both."); + } + + CheckAbsoluteUri(storage.AzureServiceUri, "Azure Blob Storage service URI"); + CheckAbsoluteUri(storage.AzureAuthorityHost, "Azure authority host"); + break; + case MessageBodyStorageType.S3: + if (IsEmpty(storage.S3BucketName)) + { + throw new EngineValidationException("An S3 bucket name is required when message bodies are stored in Amazon S3."); + } + + if (IsEmpty(storage.S3AccessKeyId) != IsEmpty(storage.S3SecretAccessKey)) + { + throw new EngineValidationException("Specify both the S3 access key ID and secret access key, or neither to use the default AWS credentials."); + } + + CheckAbsoluteUri(storage.S3ServiceUrl, "S3 service URL"); + break; + default: + throw new EngineValidationException($"Message body storage type '{storage.StorageType}' is not supported."); + } + } + + static void CheckAbsoluteUri(string value, string name) + { + if (!IsEmpty(value) && !Uri.TryCreate(value, UriKind.Absolute, out _)) + { + throw new EngineValidationException($"The {name} '{value}' is not a valid absolute URI."); + } + } + + static bool IsEmpty(string value) => string.IsNullOrWhiteSpace(value); + } +} diff --git a/src/ServiceControlInstaller.Engine/Validation/PathsValidator.cs b/src/ServiceControlInstaller.Engine/Validation/PathsValidator.cs index edfa7a5c5f..e041dfcea9 100644 --- a/src/ServiceControlInstaller.Engine/Validation/PathsValidator.cs +++ b/src/ServiceControlInstaller.Engine/Validation/PathsValidator.cs @@ -28,7 +28,11 @@ public PathsValidator(IServicePaths instance) paths = pathList.Where(p => !string.IsNullOrWhiteSpace(p.Path)).ToList(); } - public PathsValidator(IServiceControlPaths instance) + public PathsValidator(IServiceControlPaths instance) : this(instance, []) + { + } + + public PathsValidator(IServiceControlPaths instance, IEnumerable additionalPaths) { var pathList = new List { @@ -50,6 +54,12 @@ public PathsValidator(IServiceControlPaths instance) CheckIfEmpty = true } }; + pathList.AddRange(additionalPaths.Select(p => new PathInfo + { + Name = p.Name, + Path = Environment.ExpandEnvironmentVariables(p.Path ?? string.Empty), + CheckIfEmpty = p.CheckIfEmpty + })); paths = pathList.Where(p => !string.IsNullOrWhiteSpace(p.Path)).ToList(); } diff --git a/tools/testing-tool/README.md b/tools/testing-tool/README.md index 45b0992af1..28f8336b0b 100644 --- a/tools/testing-tool/README.md +++ b/tools/testing-tool/README.md @@ -1,8 +1,6 @@ # ServiceControl Testing Tool -A stateless, horizontally-scalable .NET 10 service that generates error load and real-world failure -scenarios against a test ServiceControl instance to validate its error-ingestion performance, with -OpenTelemetry observability and a simple web UI for manual scenario control. +A horizontally scalable .NET 10 service that generates failure scenarios, verifies smoke checks, and measures error-ingestion performance against a test ServiceControl instance. It includes OpenTelemetry observability and a web UI. The tool drives both ingestion paths: failed messages into the primary ServiceControl instance, and audited messages and saga snapshots into a ServiceControl.Audit instance. @@ -21,7 +19,7 @@ puts each failure shape in its own group, and immediate retries are disabled so | `poison-message` | Poison | 15% deterministic always-fail messages — retry storm | | `deserialization-failure` | Deserialization | 100% fail with `SerializationException` (bad deployment) | | `background-noise` | Noise | ~3% always-on baseline — rotates through four exception types (four small groups) | -| `large-messages` | Body | Starts at 3 msg/s (rate is configurable), each body about 256 KiB of JSON text (the wire envelope is slightly larger), above the 100 KB external body storage threshold. 20% deterministic failures with `InvalidDataException`; the other 80% succeed and are audited | +| `large-messages` | Body | Starts at 3 msg/s (rate is configurable), with about 150 KiB of JSON text per body and about 190 KiB after message serialization. Exceeds the 100 KB external body storage threshold and leaves room for headers on Azure Service Bus Standard. 20% deterministic failures with `InvalidDataException`; the other 80% succeed and are audited | Scenarios are controlled from the web UI, or via: - `GET /api/scenarios` — list scenarios with live status (category, rate, error counts) @@ -92,7 +90,7 @@ A share of claims instead emit a whole **saga episode**: the three messages that `sagaSnapshotRatio` is saga snapshots per processed message; the default `0.2` emits two saga snapshots for every ten processed messages. `0` disables saga episodes. -Audit ingestion needs a ServiceControl.Audit instance on SQL Server or PostgreSQL, so pair `--audit-instances` with `--persistence:PostgreSql` or `--persistence:SqlServer`. Under `--persistence:RavenDb` the audit instance runs on RavenDB and the EF path is not exercised. +Audit ingestion needs a ServiceControl.Audit instance on SQL Server or PostgreSQL, so pair `--audit-instances` with `--storage:PostgreSql` or `--storage:SqlServer`. Under `--storage:RavenDb` the audit instance runs on RavenDB and the EF path is not exercised. The testing tool's own endpoint also audits its successfully handled load messages to the same queue, which is what makes its installers create the queue before the writer first sends into it. @@ -103,6 +101,50 @@ release-test scenarios can be kicked off manually by name: - `GET /api/release-tests` — list all presets - `POST /api/release-tests/{name}/start` — start a preset (e.g. `retry-message-group`, `ingestion-load`) +### Smoke tests + +The **Smoke tests** tab runs an API-verified version of the functionality checklist in [docs/testing-scenarios.md](/docs/testing-scenarios.md). **Run all** executes the automated checks one after another, **Stop** cancels the run, and each row shows pending, running, passed, failed, canceled or manual with the observed detail. The run state lives in the tool, so reloading the page shows the current or last run. + +Every check sends its own messages with a run identifier (`smoke-<8 hex digits>`) and reads the effect back through the ServiceControl APIs. A check matches only what it created: a custom check id, an endpoint name, a message id, a conversation id, a saga id or a failure group that contains the run identifier. Background load and leftovers from earlier runs cannot satisfy a check. An HTTP 202 alone never passes a check, and a transport error or an unexpected status fails the check with the reason. When ServiceControl reports incomplete cross-instance results (`X-Particular-Incomplete-Results`), the check keeps polling and names the missing instances in the timeout detail; data that matches the run identifier still passes. Checks run in order, and a failed check does not stop later checks. Each check attempts cleanup after completion, cancellation, or shutdown. + +| Check | What it does | What it verifies | +|---|---|---| +| `custom-check-fail-then-pass` | Reports a failed, then a passed custom check with id `Smoke.` to the primary input queue | `GET /api/customchecks?status=fail` lists it with the failure reason, then `?status=pass` lists it and `?status=fail` does not | +| `heartbeat-beating-then-dead` | Starts a real in-process endpoint `TestingTool.Smoke.` with the NServiceBus.Heartbeat plugin, then stops its host | `GET /api/endpoints` shows `heartbeat_information.reported_status` `beating`, then `dead` (about 45 seconds after the host stops with the default 40 second grace period; the check waits up to 100 seconds) | +| `audit-ingestion-fulltext` | Handles a message with a run-specific word in the body | `GET /api/messages/search?q=` finds it with status `successful`, and `GET /api/messages/{id}/body` contains the word | +| `fanout-conversation` | Handles a message that sends two children per level for two levels, with a run-specific conversation id | `GET /api/conversations/{id}` returns the seven messages, and every `NServiceBus.RelatedTo` header points at a parent in the conversation | +| `saga-audit` | Runs a real saga (start, step, finish) with saga auditing to the audit queue | `GET /api/messages/search` finds the start message with its saga id, and `GET /api/sagas/{id}` lists `new`, `updated`, `completed` | +| `monitoring-data` | Starts a real endpoint `TestingTool.Smoke.` with the NServiceBus.Metrics.ServiceControl plugin (2 second interval, as the load endpoint) and handles three messages that each take 100 ms | `GET /monitored-endpoints` on the monitoring instance lists the endpoint with a `processingTime` average above zero. Cleanup deletes the instance ids that monitoring reports for it | +| `integration-event` | Subscribes the tool endpoint to `ServiceControl.Contracts.MessageFailed` and fails one message | The published event arrives with the run header and the failed message id that `GET /api/recoverability/groups/{id}/errors` returns | +| `retry-single` | Fails two messages in a group unique to the run, then retries one with `POST /api/errors/{id}/retry` | The tool handled and `GET /api/errors/{id}` reports `resolved` for that message, and its sibling is unresolved and unhandled | +| `retry-group` | Fails three messages in a unique group, then retries the group with `POST /api/recoverability/groups/{id}/errors/retry` | Every message was handled and is `resolved` | +| `edit-and-retry` | Fails a message, then edits it with `POST /api/edit/{id}` (snake_case body, every original header, `Fail` cleared) | The edited message arrives with `ServiceControl.EditOf` set to the failed message id and the edited text | +| `retry-through-redirect` | Starts real endpoints `TestingTool.Smoke..Source` and `.Target`, fails a message in Source, creates a redirect from the Source input address to the Target input address with `POST /api/redirects`, retries it | The failed message has the Source address as its queue, the redirect is listed, the message is handled by Target (a retry that Source handles fails the check) and is `resolved`, and the redirect is gone after `DELETE /api/redirects/{id}`. It runs last because a redirect changes retry routing while it exists | + +Failures come from the real message handler, not from the load scenarios. A smoke message fails when its `Fail` flag is set and its marker was not released, so a retry succeeds when the check releases the marker and an edit succeeds when it clears the flag. The handler throws a `SmokeFailureException` and the tool rewrites the fault headers so ServiceControl groups it under the exception type `TestingTool.Smoke.Failure__`, which makes the group unique to one check. At the end of a check, unresolved failed messages of that check are archived. The redirect check removes only the redirect it created. + +Prerequisites on the instance under test: + +- The primary needs a remote audit instance for the audit, conversation and saga checks. With the Aspire AppHost, pass `--audit-instances 1`. The checks fail with that hint when `GET /api/configuration/remotes` is empty or a remote is not online. +- Integration events need `SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING=true` on the instances that ingest errors. The AppHost sets it on the primary and on the error-ingestion scale units. +- Message editing needs `SERVICECONTROL_ALLOWMESSAGEEDITING=true`. The AppHost sets it. +- The monitoring check needs `TestingTool__MonitoringApiUrl` to point at the monitoring instance. The AppHost sets it. +- Stop the retry, archive and retention-sweep jobs first: they act on every failed message group, so a start is refused while one runs. Scenarios and bypass writers may keep running. + +Run it against a test instance only. Cleanup stops the run-scoped endpoint hosts, removes custom checks, endpoint and monitoring records, and redirects, and archives unresolved failures. Audited messages and resolved or archived failures remain subject to ServiceControl retention. If cleanup fails, the row reports the error and warns that data may remain. + +Limits of the automation: + +- The heartbeat, monitoring and redirect checks start real NServiceBus endpoints, each in its own host in the tool process, next to `TestingTool.Load`. They use the same transport, topology and serializer as the load endpoint, send failures to the same error queue, and handle only smoke messages. Their input addresses come from the transport (`ReceiveAddresses.MainReceiveAddress`), so SQL Server schema and catalog are included. Stopping a host, which a check does explicitly for the heartbeat and always at the end (before any API cleanup, so an unreachable ServiceControl cannot delay it), stops that endpoint and its plugins; it does not stop the tool or the load endpoint. It also does not delete the queues or tables the endpoint created: those run-scoped transport entities stay until the broker or database is torn down. The check exercises the NServiceBus.Heartbeat and NServiceBus.Metrics.ServiceControl plugins. +- The saga is a real saga in the tool endpoint with the NServiceBus.SagaAudit plugin and learning persistence in the temp folder, not a snapshot written by hand. +- Rows marked manual are not automated: instance installation and upgrade, how ServicePulse renders custom checks, heartbeats, recoverability screens, search, the sequence diagram, the saga view and the monitoring graphs, the public integration events sample, chaos testing, and performance, load and stability testing. The API data behind the rendered views is verified by the automated rows above. + +API: + +- `GET /api/smoke` — the current or last run, or the idle checklist +- `POST /api/smoke/start` — start a run; 400 when one is running or a conflicting job is running +- `POST /api/smoke/stop` — cancel the current run + ## Layout ``` @@ -111,9 +153,11 @@ tools/testing-tool/ Dockerfile # multi-stage container build (build context = repo root) TestingTool/ # ASP.NET Core host — API endpoints, web UI, NServiceBus endpoint, # scenario runner, bypass writer, recoverability/search jobs, + # smoke test runner and checks (Smoke/), # OTel setup, ServiceControl REST client TestingTool.Scenarios/ # IScenario contract + the six scenario implementations TestingTool.Contracts/ # shared DTOs (scenarios, status, jobs, bypass) + TestingTool.Tests/ # Unit tests for the tool itself TestingTool.AppHost/ # Aspire AppHost — orchestrates platform, tool, and observability stack obs/ # observability config: OTel Collector, Prometheus, Grafana provisioning # + prebuilt dashboard @@ -151,7 +195,7 @@ builds the solution and the container image on every change under `tools/testing ## Run with Aspire The Aspire AppHost orchestrates the testing tool together with the full Particular platform -(ServiceControl + RabbitMQ or SQL Server transport + RavenDB/SQL Server/PostgreSQL persistence + ServicePulse) and a complete observability +(ServiceControl + RabbitMQ or SQL Server transport + RavenDB/SQL Server/PostgreSQL storage + ServicePulse) and a complete observability stack (OTel Collector, Jaeger, Prometheus, Grafana), so a single command brings up the whole system locally: @@ -165,17 +209,17 @@ To test a specific ServiceControl image tag (e.g. a PR-based prerelease tag): aspire run tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj -- --tag pr-1234 ``` -To select a persistence backend for the ServiceControl error instance (`RavenDb`, +To select a storage backend for the ServiceControl error instance (`RavenDb`, `SqlServer`, or `PostgreSql`; defaults to `RavenDb`): ```bash -aspire run tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj -- --persistence:RavenDb +aspire run tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj -- --storage:RavenDb ``` -`--persistence RavenDb` (space separator) is accepted too. Both flags may be combined: +`--storage RavenDb` (space separator) is accepted too. Both flags may be combined: ```bash -aspire run tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj -- --tag pr-1234 --persistence:SqlServer +aspire run tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj -- --tag pr-1234 --storage:SqlServer ``` ### AppHost CLI options @@ -185,13 +229,13 @@ separator) or `--name:value` (colon separator): | Flag | Default | Values | Description | |---|---|---|---| -| `--persistence` | `RavenDb` | `RavenDb`, `SqlServer`, `PostgreSql` | Persistence backend for the ServiceControl error instance and for the audit instances | -| `--transport` | `RabbitMq` | `RabbitMq`, `SqlServer` | Transport shared by ServiceControl and the testing tool. `SqlServer` reuses the persistence SQL Server container with a separate `Transport` database | +| `--storage` | `RavenDb` | `RavenDb`, `SqlServer`, `PostgreSql` | Storage backend for the ServiceControl error instance and for the audit instances | +| `--transport` | `RabbitMq` | `RabbitMq`, `SqlServer` | Transport shared by ServiceControl and the testing tool. `SqlServer` reuses the storage SQL Server container with a separate `Transport` database | | `--tag` | *(none — uses the current build's image)* | any image tag, e.g. `pr-1234` or `6.3.1` | Override the ServiceControl container image tag (useful for testing PR-based prereleases) | | `--error-ingestion-scale-unit` | `0` | non-negative integer | Number of additional error-ingestion-only scale-out instances to spin up alongside the primary error instance (each runs with `--error-ingestion-only`) | -| `--audit-instances` | `1` | non-negative integer | Number of ServiceControl.Audit instances to add. They take the same `--persistence` backend, report custom checks to the primary and export OTel to the collector | -| `--azure-blob-body-storage` | *(none — uses file-system body storage)* | `""` | Store message bodies in Azure Blob Storage instead of the container file system. Applies only with `--persistence:SqlServer` or `--persistence:PostgreSql`. Quote the value because connection strings contain semicolons. The error instance and its scale-out units share the `error-bodies` container, and each audit instance gets its own `audit-bodies-` container | -| `--s3-body-storage` | *(none — uses file-system body storage)* | `` | Store message bodies in an S3 bucket instead of the container file system. Applies only with `--persistence:SqlServer` or `--persistence:PostgreSql`, and cannot be combined with `--azure-blob-body-storage`. Setup creates the bucket if it is missing and the credentials permit it. The error instance and its scale-out units share the `error-bodies/` key prefix, and each audit instance gets its own `audit-bodies-/` prefix | +| `--audit-instances` | `0` | non-negative integer | Number of ServiceControl.Audit instances to add. They take the same `--storage` backend, report custom checks to the primary and export OTel to the collector | +| `--azure-blob-body-storage` | *(none — uses file-system body storage)* | `""` | Store message bodies in Azure Blob Storage instead of the container file system. Applies only with `--storage:SqlServer` or `--storage:PostgreSql`. Quote the value because connection strings contain semicolons. The error instance and its scale-out units share the `error-bodies` container, and each audit instance gets its own `audit-bodies-` container | +| `--s3-body-storage` | *(none — uses file-system body storage)* | `` | Store message bodies in an S3 bucket instead of the container file system. Applies only with `--storage:SqlServer` or `--storage:PostgreSql`, and cannot be combined with `--azure-blob-body-storage`. Setup creates the bucket if it is missing and the credentials permit it. The error instance and its scale-out units share the `error-bodies/` key prefix, and each audit instance gets its own `audit-bodies-/` prefix | | `--s3-region` | SDK default | region name, e.g. `eu-west-1` | Region for `--s3-body-storage`. Requires `--s3-body-storage` | | `--s3-service-url` | AWS | absolute `http` or `https` URL | S3-compatible endpoint, e.g. MinIO or LocalStack. The ServiceControl containers connect to it, so it must be reachable from inside a container. Requires `--s3-body-storage` | | `--s3-access-key-id`, `--s3-secret-access-key` | *(none — default AWS credential chain)* | key pair | Static credentials for `--s3-body-storage`. Set both or neither. Without them, the AWS default credential chain runs inside each container; the host's credentials are not forwarded. Static keys appear in the container environment | @@ -200,7 +244,7 @@ Pass static credentials explicitly, or omit both key options when the containers ```bash aspire run tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj -- \ - --persistence PostgreSql --s3-body-storage my-bodies --s3-region eu-west-1 \ + --storage PostgreSql --s3-body-storage my-bodies --s3-region eu-west-1 \ --s3-access-key-id "$AWS_ACCESS_KEY_ID" --s3-secret-access-key "$AWS_SECRET_ACCESS_KEY" ``` @@ -208,7 +252,7 @@ For MinIO or LocalStack, use an endpoint reachable from the containers. This exa ```bash aspire run tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj -- \ - --persistence SqlServer --s3-body-storage bodies --s3-region us-east-1 \ + --storage SqlServer --s3-body-storage bodies --s3-region us-east-1 \ --s3-service-url http://host.docker.internal:9000 \ --s3-access-key-id minioadmin --s3-secret-access-key minioadmin ``` @@ -240,9 +284,7 @@ and cumulative), ingestion duration p95, and ingestion outcome by result. ## Horizontal scaling -The tool is **stateless** — all state is in-memory per replica. Run a single instance via -`dotnet run` or the Aspire AppHost; for multi-replica deployments, bring your own orchestration -and give each replica a distinct shard id so deterministic failure decisions don't overlap: +Load counters, job controls, and smoke-run results are in-memory per replica. The smoke saga uses learning persistence in a local temporary directory. Run a single instance with `dotnet run` or the Aspire AppHost. For multiple replicas, provide orchestration and a distinct shard id for each replica so deterministic failure decisions do not overlap: | Shard id source | When | |---|---| @@ -263,11 +305,14 @@ on its own, set it to the broker your ServiceControl instance uses: | Connection string | Transport | |---|---| | starts with `amqp:` or `amqps:` (e.g. `amqp://guest:guest@localhost:5672`) | RabbitMQ — quorum queues, conventional routing topology | +| contains an `Endpoint=sb://...` entry (e.g. `Endpoint=sb://my-namespace.servicebus.windows.net/;SharedAccessKeyName=...;SharedAccessKey=...`) | Azure Service Bus — default topic topology. The direct error and audit writers send through the same endpoint, so they use it too | | SQL Server connection string with `Initial Catalog` or `Database` (e.g. `Server=localhost;Database=Transport;...`) | SQL Server | | not set or empty | Learning transport (local standalone runs only — ServiceControl won't see the messages) | | anything else | startup fails with an error naming `ConnectionStrings__transport` | -The selected transport is logged at startup (`Using RabbitMQ transport` etc.). +The selected transport is logged at startup (`Using RabbitMQ transport` etc.). The smoke tests start their own run-scoped endpoints with the same selection, so they need the same `ConnectionStrings__transport`. + +The Standard Service Bus tier limits a message to 256 KiB including headers. The `large-messages` scenario serializes to about 190 KiB, so it leaves room for headers on Standard and still exceeds the 100 KB external body storage threshold. ## Configuration @@ -292,6 +337,10 @@ All configuration is via environment variables (no files, no database). Settings | `TestingTool__AuditQueueName` | `audit` | NServiceBus audit queue the ServiceControl.Audit instance drains | | `TestingTool__AuditSagaSnapshotRatio` | `0.2` | Default saga snapshots per processed message for the audit-queue writer | | `TestingTool__MonitoringQueueName` | `Particular.Monitoring` | ServiceControl monitoring instance queue that endpoint metrics are sent to | +| `TestingTool__MonitoringApiUrl` | `http://localhost:33633` | ServiceControl.Monitoring API base URL, used by the smoke tests | +| `TestingTool__SmokePollInterval` | `00:00:01` | Interval between polls while a smoke check waits for an effect | +| `TestingTool__SmokePollTimeout` | `00:01:00` | How long a smoke check waits for one effect before it fails | +| `TestingTool__SmokeCheckTimeout` | `00:03:00` | How long one smoke check may take in total | | `TestingTool__ErrorQueueName` | `error` | NServiceBus error queue (ServiceControl monitors this) | | `TestingTool__AutoStartBackgroundNoise` | `false` | Auto-start the background-noise scenario on startup | | `SHARD_ID` (env) | *(auto: hostname ordinal or machine name)* | Shard id for disjoint scenario slices when scaled | diff --git a/tools/testing-tool/TestingTool.AppHost/AppHost.cs b/tools/testing-tool/TestingTool.AppHost/AppHost.cs index eb2c3c0225..0d9c950666 100644 --- a/tools/testing-tool/TestingTool.AppHost/AppHost.cs +++ b/tools/testing-tool/TestingTool.AppHost/AppHost.cs @@ -2,7 +2,7 @@ using TestingTool.AppHost; var options = CliOptions.Parse(args); -var persistenceType = options.GetValue("persistence", PersistenceType.RavenDb); +var storageType = options.GetValue("storage", StorageType.RavenDb); var imageTag = options.GetValueOrDefault("tag"); var azureBlobBodyStorage = options.GetValueOrDefault("azure-blob-body-storage"); if (azureBlobBodyStorage is not null && string.IsNullOrWhiteSpace(azureBlobBodyStorage)) @@ -10,7 +10,7 @@ throw new ArgumentException("--azure-blob-body-storage requires a non-blank Azure Storage connection string."); } var s3BodyStorage = S3BodyStorageOptions.Parse(options, azureBlobBodyStorage is not null); -Console.WriteLine($"Using persistence type: {persistenceType}"); +Console.WriteLine($"Using storage type: {storageType}"); var builder = DistributedApplication.CreateBuilder(args); @@ -32,9 +32,9 @@ .WithEnvironment("SERVICECONTROL_ERRORINGESTIONMAXPARALLELWRITERS", "4") .WithEnvironment("SERVICECONTROL_ERRORINGESTIONBATCHTIMEOUT", "00:00:00.100") .WithEnvironment("SERVICECONTROL_ALLOWMESSAGEEDITING", "true") - .WithEnvironment("SERVICECONTROL_DISABLEEXTERNALINTEGRATIONSPUBLISHING", "true") + .WithEnvironment("SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING", "true") .WithEnvironment("OTEL_EXPORTER_OTLP_ENDPOINT", observability.Collector.GetEndpoint("otlp-grpc")) - .WithPersistenceType(persistenceType, azureBlobBodyStorage, s3BodyStorage) + .WithStorageType(storageType, azureBlobBodyStorage, s3BodyStorage) .WithRunMode(PlatformRunMode.SetupAndRun); for (int i = 0; i < options.GetValue("error-ingestion-scale-unit", 0); i++) { @@ -42,8 +42,8 @@ .AddServiceControlErrorInstance("error-scale-" + i, raven) .WithArgs("--error-ingestion-only") .WithEnvironment("SERVICECONTROL_INSTANCENAME", "Error-scale-" + i) + .WithEnvironment("SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING", "true") .WithEnvironment("OTEL_EXPORTER_OTLP_ENDPOINT", observability.Collector.GetEndpoint("otlp-grpc")) - .WithEnvironment("SERVICECONTROL_DISABLEEXTERNALINTEGRATIONSPUBLISHING", "true") //scale settings .WithEnvironment("SERVICECONTROL_MAXIMUMCONCURRENCYLEVEL", "100") @@ -52,15 +52,16 @@ .WithEnvironment("SERVICECONTROL_ERRORINGESTIONBATCHTIMEOUT", "00:00:00.100") //.WaitFor(primaryErrorInstance) - .WithPersistenceType(persistenceType, azureBlobBodyStorage, s3BodyStorage) + .WithStorageType(storageType, azureBlobBodyStorage, s3BodyStorage) .WithRunMode(PlatformRunMode.Run); } -platform.AddServicePulse("pulse", primaryErrorInstance, platform.AddServiceControlMonitoringInstance("monitoring")); +var monitoringInstance = platform.AddServiceControlMonitoringInstance("monitoring"); +platform.AddServicePulse("pulse", primaryErrorInstance, monitoringInstance); // EF persistence lives in the audit instance itself, so audit load needs a real audit container. // The platform persistence argument stays RavenDB because the Aspire package only knows about -// platform persistences; the SQL wiring is layered on with WithPersistenceType. +// platform persistences; the SQL wiring is layered on with WithStorageType. var auditInstanceCount = options.GetValue("audit-instances", 0); for (int i = 0; i < auditInstanceCount; i++) @@ -76,13 +77,14 @@ .WithAuditQueueName(i == 0 ? "audit" : "audit" + i) .WithRunMode(PlatformRunMode.SetupAndRun) .WithIngestionTuning() - .WithPersistenceType(persistenceType, azureBlobBodyStorage, s3BodyStorage); + .WithStorageType(storageType, azureBlobBodyStorage, s3BodyStorage); } // --- Testing tool --- builder.AddProject("testing-tool") .WithParticularPlatform(platform) .WithEnvironment("TestingTool__ServiceControlApiUrl", primaryErrorInstance.GetEndpoint("http")) + .WithEnvironment("TestingTool__MonitoringApiUrl", monitoringInstance.GetEndpoint("http")) .WithEnvironment("TestingTool__AutoStartBackgroundNoise", "true") .WithEnvironment("OTEL_EXPORTER_OTLP_ENDPOINT", observability.Collector.GetEndpoint("otlp-grpc")) // this should wait for the platform but cannot because error scale out leaves nodes unhealthy diff --git a/tools/testing-tool/TestingTool.AppHost/HostBuilderExtensions.cs b/tools/testing-tool/TestingTool.AppHost/HostBuilderExtensions.cs index 973bc47eb8..e5a43bbb73 100644 --- a/tools/testing-tool/TestingTool.AppHost/HostBuilderExtensions.cs +++ b/tools/testing-tool/TestingTool.AppHost/HostBuilderExtensions.cs @@ -43,10 +43,10 @@ public static IResourceBuilder AddPostgresPersist return postgres.AddDatabase(databaseResource, databaseName); } - public static IResourceBuilder WithPersistenceType( - this IResourceBuilder error, PersistenceType type, string? azureBlobConnectionString = null, S3BodyStorageOptions? s3 = null) + public static IResourceBuilder WithStorageType( + this IResourceBuilder error, StorageType type, string? azureBlobConnectionString = null, S3BodyStorageOptions? s3 = null) { - if (type == PersistenceType.RavenDb) + if (type == StorageType.RavenDb) { //ravenDB is currently set up explicitly even if you aren't using it return error; @@ -54,8 +54,8 @@ public static IResourceBuilder WithPersiste var db = type switch { - PersistenceType.SqlServer => error.ApplicationBuilder.AddSqlServerPersistence("ServiceControl"), - PersistenceType.PostgreSql => error.ApplicationBuilder.AddPostgresPersistence("servicecontrol"), + StorageType.SqlServer => error.ApplicationBuilder.AddSqlServerPersistence("ServiceControl"), + StorageType.PostgreSql => error.ApplicationBuilder.AddPostgresPersistence("servicecontrol"), _ => throw new ArgumentOutOfRangeException(nameof(type), type, null) }; @@ -74,7 +74,7 @@ public static IResourceBuilder WithPersiste return error .WaitFor(db) - .WithEnvironment("SERVICECONTROL_PERSISTENCETYPE", PersistenceTypeName(type)) + .WithEnvironment("SERVICECONTROL_STORAGETYPE", StorageTypeName(type)) .WithEnvironment("SERVICECONTROL_DATABASE_CONNECTIONSTRING", db); } @@ -87,21 +87,21 @@ public static IResourceBuilder WithPersiste /// The setting root namespace is "ServiceControl.Audit", and the settings reader rewrites both /// the dot and the slash to an underscore, so ServiceControl.Audit/Database/ConnectionString is /// SERVICECONTROL_AUDIT_DATABASE_CONNECTIONSTRING. The unprefixed names the audit container's - /// Dockerfile bakes in (PersistenceType, AuditRetentionPeriod) are later in the lookup order, + /// Dockerfile bakes in (StorageType, AuditRetentionPeriod) are later in the lookup order, /// so the namespaced form wins. /// - public static IResourceBuilder WithPersistenceType( - this IResourceBuilder audit, PersistenceType type, string? azureBlobConnectionString = null, S3BodyStorageOptions? s3 = null) + public static IResourceBuilder WithStorageType( + this IResourceBuilder audit, StorageType type, string? azureBlobConnectionString = null, S3BodyStorageOptions? s3 = null) { - if (type == PersistenceType.RavenDb) + if (type == StorageType.RavenDb) { return audit; } var db = type switch { - PersistenceType.SqlServer => audit.ApplicationBuilder.AddSqlServerPersistence("ServiceControl"), - PersistenceType.PostgreSql => audit.ApplicationBuilder.AddPostgresPersistence("servicecontrol"), + StorageType.SqlServer => audit.ApplicationBuilder.AddSqlServerPersistence("ServiceControl"), + StorageType.PostgreSql => audit.ApplicationBuilder.AddPostgresPersistence("servicecontrol"), _ => throw new ArgumentOutOfRangeException(nameof(type), type, null) }; @@ -122,7 +122,7 @@ public static IResourceBuilder WithPersiste return audit .WaitFor(db) - .WithEnvironment("SERVICECONTROL_AUDIT_PERSISTENCETYPE", PersistenceTypeName(type)) + .WithEnvironment("SERVICECONTROL_AUDIT_STORAGETYPE", StorageTypeName(type)) .WithEnvironment("SERVICECONTROL_AUDIT_DATABASE_CONNECTIONSTRING", db); } @@ -190,10 +190,10 @@ static IResourceBuilder WithS3Environment(this IResourceBuilder builder return builder; } - static string PersistenceTypeName(PersistenceType persistence) => persistence switch + static string StorageTypeName(StorageType storage) => storage switch { - PersistenceType.SqlServer => "SQLServer", - PersistenceType.PostgreSql => "PostgreSQL", - _ => throw new ArgumentOutOfRangeException(nameof(persistence)) + StorageType.SqlServer => "SQLServer", + StorageType.PostgreSql => "PostgreSQL", + _ => throw new ArgumentOutOfRangeException(nameof(storage)) }; } \ No newline at end of file diff --git a/tools/testing-tool/TestingTool.AppHost/PersistenceType.cs b/tools/testing-tool/TestingTool.AppHost/StorageType.cs similarity index 72% rename from tools/testing-tool/TestingTool.AppHost/PersistenceType.cs rename to tools/testing-tool/TestingTool.AppHost/StorageType.cs index aa10ff9f68..c2caa2e626 100644 --- a/tools/testing-tool/TestingTool.AppHost/PersistenceType.cs +++ b/tools/testing-tool/TestingTool.AppHost/StorageType.cs @@ -1,8 +1,8 @@ namespace TestingTool.AppHost; -public enum PersistenceType +public enum StorageType { RavenDb, SqlServer, PostgreSql -} \ No newline at end of file +} diff --git a/tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj b/tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj index 2ff8b63c7e..06bdef0e54 100644 --- a/tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj +++ b/tools/testing-tool/TestingTool.AppHost/TestingTool.AppHost.csproj @@ -12,7 +12,7 @@ - + diff --git a/tools/testing-tool/TestingTool.Contracts/SmokeRunInfo.cs b/tools/testing-tool/TestingTool.Contracts/SmokeRunInfo.cs new file mode 100644 index 0000000000..321a0dce12 --- /dev/null +++ b/tools/testing-tool/TestingTool.Contracts/SmokeRunInfo.cs @@ -0,0 +1,50 @@ +using System.Text.Json.Serialization; + +namespace TestingTool.Contracts; + +/// +/// State of the smoke-test checklist returned by GET /api/smoke: the current run, or the last +/// finished one, or the idle checklist before the first run. +/// +public sealed class SmokeRunInfo +{ + /// The identifier that scopes every message, custom check and endpoint of the run. Null before the first run. + public string? RunId { get; init; } + + public bool Running { get; init; } + + public string? StartedAt { get; init; } + + public string? FinishedAt { get; init; } + + public required IReadOnlyList Checks { get; init; } +} + +public sealed class SmokeCheckInfo +{ + public required string Id { get; init; } + + public required string Title { get; init; } + + /// What the check does and which ServiceControl API effect it verifies, or for a manual row what a person must verify. + public required string Description { get; init; } + + public SmokeCheckStatus Status { get; init; } + + /// What the check observed. For a failed check, the reason and the last observed state. + public string? Detail { get; init; } + + public double? DurationSeconds { get; init; } +} + +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum SmokeCheckStatus +{ + Pending, + Running, + Passed, + Failed, + /// The check is not automated. A person verifies it. + Manual, + Canceled +} diff --git a/tools/testing-tool/TestingTool.Scenarios/LargeMessagesScenario.cs b/tools/testing-tool/TestingTool.Scenarios/LargeMessagesScenario.cs index 3e42797b5c..8293beaf8d 100644 --- a/tools/testing-tool/TestingTool.Scenarios/LargeMessagesScenario.cs +++ b/tools/testing-tool/TestingTool.Scenarios/LargeMessagesScenario.cs @@ -3,17 +3,16 @@ namespace TestingTool.Scenarios; /// -/// Large message scenario: every body is about 256 KiB, above the default 100 KB external body storage -/// threshold. A deterministic subset of messages (by hash) fails, so both the Audit and Error ingestion -/// paths store large bodies. +/// Exercises external body storage on the Audit and Error paths. +/// JSON string escaping expands the generated body; leave room for headers under Service Bus Standard's 256 KiB limit. /// public sealed class LargeMessagesScenario(string shardId) : ScenarioBase(shardId) { public override string Name => "large-messages"; - public override string Description => "Publishes about 256 KiB message bodies and fails 20% of them. Exercises external body storage on the Audit and Error paths."; + public override string Description => "Publishes about 190 KiB serialized message bodies and fails 20% of them. Exercises external body storage on the Audit and Error paths."; public override string Category => "Body"; public override double DefaultRate => 3; - public override int? BodySizeBytes => 256 * 1024; + public override int? BodySizeBytes => 150 * 1024; private const double FailureRatio = 0.20; diff --git a/tools/testing-tool/TestingTool.Tests/LargeMessagesScenarioTests.cs b/tools/testing-tool/TestingTool.Tests/LargeMessagesScenarioTests.cs new file mode 100644 index 0000000000..a1946b9a50 --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/LargeMessagesScenarioTests.cs @@ -0,0 +1,25 @@ +using System.Text; +using System.Text.Json; +using NUnit.Framework; +using TestingTool.Scenarios; + +namespace TestingTool.Tests; + +public class LargeMessagesScenarioTests +{ + const int ExternalBodyStorageThresholdBytes = 100 * 1024; + const int AzureServiceBusStandardLimitBytes = 256 * 1024; + const int MinimumHeaderHeadroomBytes = 56 * 1024; + + [Test] + public void Serialized_body_exceeds_external_storage_threshold_and_leaves_header_headroom() + { + var scenario = new LargeMessagesScenario("test"); + var message = new LoadMessage { Sequence = 1, TextBody = MessageTextGenerator.GenerateBody(1, scenario.BodySizeBytes) }; + + var serializedBytes = Encoding.UTF8.GetByteCount(JsonSerializer.Serialize(message)); + + Assert.That(serializedBytes, Is.GreaterThan(ExternalBodyStorageThresholdBytes)); + Assert.That(serializedBytes, Is.LessThanOrEqualTo(AzureServiceBusStandardLimitBytes - MinimumHeaderHeadroomBytes)); + } +} diff --git a/tools/testing-tool/TestingTool.Tests/Smoke/Fakes.cs b/tools/testing-tool/TestingTool.Tests/Smoke/Fakes.cs new file mode 100644 index 0000000000..9d23f181cc --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/Smoke/Fakes.cs @@ -0,0 +1,53 @@ +using System.Net; +using System.Text; +using NServiceBus; + +namespace TestingTool.Tests.Smoke; + +sealed class FakeMessageSession : IMessageSession +{ + public List<(object Message, SendOptions Options)> Sent { get; } = []; + public List Subscribed { get; } = []; + public List Unsubscribed { get; } = []; + + public Task Send(object message, SendOptions sendOptions, CancellationToken cancellationToken = default) + { + Sent.Add((message, sendOptions)); + return Task.CompletedTask; + } + + public Task Subscribe(Type eventType, SubscribeOptions subscribeOptions, CancellationToken cancellationToken = default) + { + Subscribed.Add(eventType); + return Task.CompletedTask; + } + + public Task Unsubscribe(Type eventType, UnsubscribeOptions unsubscribeOptions, CancellationToken cancellationToken = default) + { + Unsubscribed.Add(eventType); + return Task.CompletedTask; + } + + public Task Send(Action messageConstructor, SendOptions sendOptions, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task Publish(object message, PublishOptions publishOptions, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task Publish(Action messageConstructor, PublishOptions publishOptions, CancellationToken cancellationToken = default) => throw new NotSupportedException(); +} + +sealed class FakeHttpHandler(Func respond) : HttpMessageHandler +{ + public List<(HttpMethod Method, string PathAndQuery, string Body)> Requests { get; } = []; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var body = request.Content is null ? "" : await request.Content.ReadAsStringAsync(cancellationToken); + Requests.Add((request.Method, request.RequestUri!.PathAndQuery, body)); + return respond(request); + } + + public static HttpResponseMessage Json(string json, HttpStatusCode status = HttpStatusCode.OK) => + new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + + public static HttpResponseMessage Status(HttpStatusCode status) => new(status); +} diff --git a/tools/testing-tool/TestingTool.Tests/Smoke/SmokeApiClientTests.cs b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeApiClientTests.cs new file mode 100644 index 0000000000..792a70dbe5 --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeApiClientTests.cs @@ -0,0 +1,149 @@ +using System.Net; +using NUnit.Framework; +using TestingTool.Smoke; + +namespace TestingTool.Tests.Smoke; + +public class SmokeApiClientTests +{ + static (SmokeApiClient Client, FakeHttpHandler Handler) Create(Func respond) + { + var handler = new FakeHttpHandler(respond); + return (new SmokeApiClient(new HttpClient(handler) { BaseAddress = new Uri("http://sc.test") }), handler); + } + + [Test] + public void An_unexpected_status_fails_with_the_status_and_body() + { + var (client, _) = Create(_ => FakeHttpHandler.Json("""{"error":"nope"}""", HttpStatusCode.InternalServerError)); + + var ex = Assert.ThrowsAsync(() => client.GetEndpoints(CancellationToken.None)); + + Assert.That(ex!.Message, Does.Contain("GET /api/endpoints returned 500").And.Contain("nope")); + } + + [Test] + public void A_transport_error_fails_the_check_instead_of_returning_an_empty_list() + { + var (client, _) = Create(_ => throw new HttpRequestException("connection refused")); + + var ex = Assert.ThrowsAsync(() => client.GetGroups(CancellationToken.None)); + + Assert.That(ex!.Message, Does.Contain("could not reach http://sc.test/").And.Contain("connection refused")); + } + + [Test] + public async Task A_missing_failed_message_is_null_until_it_is_ingested() + { + var (client, _) = Create(r => r.RequestUri!.AbsolutePath.EndsWith("/missing") + ? FakeHttpHandler.Status(HttpStatusCode.NotFound) + : FakeHttpHandler.Json("""{"status":"retryIssued","processing_attempts":[{"headers":{"NServiceBus.MessageId":"m1"}}]}""")); + + Assert.That(await client.FindFailedMessage("missing", CancellationToken.None), Is.Null); + var found = await client.FindFailedMessage("known", CancellationToken.None); + Assert.That(found!.Status, Is.EqualTo("retryIssued")); + Assert.That(found.ProcessingAttempts[^1].Headers["NServiceBus.MessageId"], Is.EqualTo("m1")); + } + + [Test] + public async Task Edit_sends_snake_case_names_and_reports_an_ignored_edit() + { + var (client, handler) = Create(_ => FakeHttpHandler.Json("""{"edit_ignored":true}""")); + + var accepted = await client.EditMessage("id1", "{}", new Dictionary { ["NServiceBus.MessageId"] = "m1" }, CancellationToken.None); + + Assert.That(accepted, Is.False); + Assert.That(handler.Requests[0].Body, Is.EqualTo("""{"message_body":"{}","message_headers":{"NServiceBus.MessageId":"m1"}}""")); + } + + [Test] + public async Task Redirect_request_uses_the_lowercase_names_of_the_api() + { + var (client, handler) = Create(_ => FakeHttpHandler.Status(HttpStatusCode.Created)); + + await client.CreateRedirect("from-queue", "to-queue", CancellationToken.None); + + Assert.That(handler.Requests[0].Body, Is.EqualTo("""{"fromphysicaladdress":"from-queue","tophysicaladdress":"to-queue","retryexisting":false}""")); + } + + [Test] + public async Task Search_exposes_the_instances_that_did_not_answer() + { + var (client, _) = Create(_ => + { + var response = FakeHttpHandler.Json("[]"); + response.Headers.Add("X-Particular-Incomplete-Results", "audit1:unavailable"); + return response; + }); + + var result = await client.SearchMessages("token", CancellationToken.None); + + Assert.That(result.Incomplete, Is.EqualTo("audit1:unavailable")); + } + + [Test] + public async Task Saga_is_null_while_the_primary_answers_no_content() + { + var (client, _) = Create(_ => FakeHttpHandler.Status(HttpStatusCode.NoContent)); + + Assert.That((await client.GetSaga(Guid.NewGuid(), CancellationToken.None)).Value, Is.Null); + } + + [Test] + public async Task Paged_lists_are_read_until_a_short_page() + { + var (client, handler) = Create(r => + { + var page = int.Parse(System.Web.HttpUtility.ParseQueryString(r.RequestUri!.Query)["page"]!); + var count = page == 1 ? 100 : 3; + var items = string.Join(",", Enumerable.Range(0, count).Select(i => $$"""{"id":"{{page}}-{{i}}","custom_check_id":"c","status":"fail","reported_at":"2026-01-01T00:00:00Z"}""")); + return FakeHttpHandler.Json($"[{items}]"); + }); + + var checks = await client.GetCustomChecks("fail", CancellationToken.None); + + Assert.That(checks, Has.Count.EqualTo(103)); + Assert.That(handler.Requests.Select(r => r.PathAndQuery), Is.EqualTo(["/api/customchecks?status=fail&page=1&per_page=100", "/api/customchecks?status=fail&page=2&per_page=100"])); + } + + [Test] + public async Task Message_body_follows_the_relative_body_url_of_the_audit_instance() + { + var (client, handler) = Create(_ => FakeHttpHandler.Json("body text")); + var message = new SmokeApiClient.AuditedMessage("row-id", "m1", "T", "successful", null, "/messages/body-1/body?instance_id=audit-1", null, null); + + await client.GetMessageBody(message, CancellationToken.None); + + Assert.That(handler.Requests[0].PathAndQuery, Is.EqualTo("/api/messages/body-1/body?instance_id=audit-1")); + } + + [Test] + public void Message_body_without_a_body_url_fails_clearly() + { + var (client, _) = Create(_ => FakeHttpHandler.Json("")); + var message = new SmokeApiClient.AuditedMessage("row-id", "m1", "T", "successful", null, null, null, null); + + var ex = Assert.ThrowsAsync(() => client.GetMessageBody(message, CancellationToken.None)); + + Assert.That(ex!.Message, Does.Contain("no body_url")); + } + + [TestCase("0f8fad5b-d9cb-469f-a165-70867728950e")] + [TestCase("CustomChecks/0f8fad5b-d9cb-469f-a165-70867728950e")] + public async Task Custom_check_delete_uses_only_the_guid(string id) + { + var (client, handler) = Create(_ => FakeHttpHandler.Status(HttpStatusCode.Accepted)); + + await client.DeleteCustomCheck(id, CancellationToken.None); + + Assert.That(handler.Requests[0].PathAndQuery, Is.EqualTo("/api/customchecks/0f8fad5b-d9cb-469f-a165-70867728950e")); + } + + [TestCase("retry", true)] + [TestCase("ARCHIVE", true)] + [TestCase("Retention-Sweep", true)] + [TestCase("search", false)] + [TestCase("custom-check-failures", false)] + public void Only_jobs_that_act_on_every_failure_group_conflict_with_a_smoke_run(string job, bool conflicts) => + Assert.That(SmokeJobConflicts.Conflicts(job), Is.EqualTo(conflicts)); +} diff --git a/tools/testing-tool/TestingTool.Tests/Smoke/SmokeChecksTests.cs b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeChecksTests.cs new file mode 100644 index 0000000000..e9686d816b --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeChecksTests.cs @@ -0,0 +1,247 @@ +using System.Net; +using System.Text.Json; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Options; +using NServiceBus; +using NUnit.Framework; +using ServiceControl.Plugin.CustomChecks.Messages; +using TestingTool.Smoke; + +namespace TestingTool.Tests.Smoke; + +public class SmokeChecksTests +{ + const string RunId = "smoke-test0001"; + + FakeMessageSession session = null!; + SmokeObservations observations = null!; + + [SetUp] + public void SetUp() + { + session = new FakeMessageSession(); + observations = new SmokeObservations(); + } + + SmokeChecks CreateChecks(Func serviceControl) => + new(new SmokeApiClient(new HttpClient(new FakeHttpHandler(serviceControl)) { BaseAddress = new Uri("http://sc.test") }), + new SmokeMonitoringClient(new HttpClient(new FakeHttpHandler(_ => FakeHttpHandler.Json("[]"))) { BaseAddress = new Uri("http://monitoring.test") }), + session, + observations, + Options.Create(new TestingToolOptions()), + new ConfigurationBuilder().Build()); + + static SmokeContext Context() => new(RunId, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(100)); + + static async Task Run(SmokeChecks checks, string id, SmokeContext context) + { + try + { + await checks.Create().Single(c => c.Id == id).Run!(context, CancellationToken.None); + } + finally + { + foreach (var cleanup in context.Cleanups.Reverse()) + { + await cleanup(CancellationToken.None); + } + } + } + + IEnumerable Reports => session.Sent.Select(s => s.Message).OfType(); + + [Test] + public async Task Custom_check_passes_when_the_api_shows_this_runs_check_fail_then_pass() + { + var checks = CreateChecks(r => + { + var failed = r.RequestUri!.Query.Contains("status=fail"); + var own = Reports.LastOrDefault(); + var ownIsListed = own is not null && own.HasFailed == failed; + var entry = ownIsListed ? $$"""{"id":"u1","custom_check_id":"{{own!.CustomCheckId}}","status":"{{(failed ? "fail" : "pass")}}","failure_reason":{{JsonSerializer.Serialize(own.FailureReason)}},"reported_at":"2026-01-01T00:00:00Z"}""" : ""; + return r.Method == HttpMethod.Delete ? FakeHttpHandler.Status(HttpStatusCode.Accepted) : FakeHttpHandler.Json($"[{entry}]"); + }); + + await Run(checks, "custom-check-fail-then-pass", Context()); + + Assert.That(Reports.Select(r => r.HasFailed).ToArray(), Is.EqualTo(new[] { true, false })); + Assert.That(Reports.Select(r => r.CustomCheckId).Distinct().Single(), Is.EqualTo($"Smoke.{RunId}")); + } + + [Test] + public void Custom_check_ignores_a_failed_check_from_another_run() + { + var checks = CreateChecks(r => FakeHttpHandler.Json("""[{"id":"u0","custom_check_id":"Smoke.smoke-older","status":"fail","failure_reason":"x","reported_at":"2026-01-01T00:00:00Z"}]""")); + + var ex = Assert.ThrowsAsync(() => Run(checks, "custom-check-fail-then-pass", Context())); + + Assert.That(ex!.Message, Does.Contain($"no failed check with id Smoke.{RunId}")); + } + + [Test] + public void Audit_check_fails_without_a_remote_audit_instance() + { + var checks = CreateChecks(_ => FakeHttpHandler.Json("[]")); + + var ex = Assert.ThrowsAsync(() => Run(checks, "audit-ingestion-fulltext", Context())); + + Assert.That(ex!.Message, Does.Contain("no remote audit instance")); + } + + [Test] + public void Audit_check_ignores_search_hits_for_other_messages() + { + var checks = CreateChecks(r => r.RequestUri!.AbsolutePath.EndsWith("/remotes") + ? FakeHttpHandler.Json("""[{"api_uri":"http://audit","status":"online"}]""") + : FakeHttpHandler.Json("""[{"id":"a1","message_id":"someone-elses","message_type":"X","status":"successful"}]""")); + + var ex = Assert.ThrowsAsync(() => Run(checks, "audit-ingestion-fulltext", Context())); + + Assert.That(ex!.Message, Does.Contain("none with message id")); + } + + [Test] + public async Task Retry_single_retries_only_the_chosen_message_in_a_group_unique_to_the_run() + { + var server = new FailureServer(session, observations); + var checks = CreateChecks(server.Handle); + + await Run(checks, "retry-single", Context()); + + var failing = session.Sent.Select(s => (Message: (SmokeMessage)s.Message, Headers: s.Options.GetHeaders())).ToList(); + Assert.That(failing, Has.Count.EqualTo(2)); + Assert.That(failing.Select(f => f.Message.FailureType).Distinct().Single(), Is.EqualTo($"TestingTool.Smoke.Failure_{RunId.Replace('-', '_')}_retry_single")); + Assert.That(failing.All(f => f.Message.Fail && f.Headers[SmokeHeaders.RunId] == RunId), Is.True); + Assert.That(server.Retried, Has.Count.EqualTo(1)); + } + + [Test] + public void Retry_single_fails_when_the_retry_also_resolves_the_sibling() + { + var server = new FailureServer(session, observations) { RetryResolvesEverything = true }; + var checks = CreateChecks(server.Handle); + + var ex = Assert.ThrowsAsync(() => Run(checks, "retry-single", Context())); + + Assert.That(ex!.Message, Does.Contain("also acted on its sibling")); + } + + [Test] + public void Retry_group_fails_when_a_message_is_not_handled_even_though_the_api_accepted_the_retry() + { + var server = new FailureServer(session, observations) { HandlesRetries = false }; + var checks = CreateChecks(server.Handle); + + var ex = Assert.ThrowsAsync(() => Run(checks, "retry-group", Context())); + + Assert.That(ex!.Message, Does.Contain("handled by the endpoint: False")); + } + + [Test] + public async Task Failed_messages_left_unresolved_are_archived_when_the_check_ends() + { + var server = new FailureServer(session, observations); + var checks = CreateChecks(server.Handle); + + await Run(checks, "retry-single", Context()); + + Assert.That(server.Archived, Has.Count.EqualTo(1)); + Assert.That(server.Archived.Single(), Is.Not.EqualTo(server.Retried.Single())); + } + + [Test] + public async Task Endpoint_record_cleanup_deletes_only_the_named_run_endpoints() + { + var deleted = new List(); + var checks = CreateChecks(r => + { + if (r.Method == HttpMethod.Delete) + { + deleted.Add(r.RequestUri!.AbsolutePath); + return FakeHttpHandler.Status(HttpStatusCode.NoContent); + } + + return FakeHttpHandler.Json(""" + [{"id":"00000000-0000-0000-0000-000000000001","name":"TestingTool.Smoke.smoke-test0001.Source","monitor_heartbeat":false}, + {"id":"00000000-0000-0000-0000-000000000002","name":"TestingTool.Smoke.smoke-test0001.Target","monitor_heartbeat":false}, + {"id":"00000000-0000-0000-0000-000000000003","name":"TestingTool.Smoke.smoke-other.Source","monitor_heartbeat":false}, + {"id":"00000000-0000-0000-0000-000000000004","name":"Sales","monitor_heartbeat":true}] + """); + }); + var context = Context(); + + checks.DeleteEndpointRecords(context, $"TestingTool.Smoke.{RunId}.Source", $"TestingTool.Smoke.{RunId}.Target"); + foreach (var cleanup in context.Cleanups) + { + await cleanup(CancellationToken.None); + } + + Assert.That(deleted, Is.EqualTo(["/api/endpoints/00000000-0000-0000-0000-000000000001", "/api/endpoints/00000000-0000-0000-0000-000000000002"])); + } + + /// Answers the failed-message API calls for the messages the checks sent through the fake session. + sealed class FailureServer(FakeMessageSession session, SmokeObservations observations) + { + readonly Dictionary status = []; + + public bool RetryResolvesEverything { get; init; } + public bool HandlesRetries { get; init; } = true; + public List Retried { get; } = []; + public List Archived { get; } = []; + + IEnumerable<(string MessageId, SmokeMessage Message, string ExceptionType)> Failing => session.Sent + .Where(s => s.Message is SmokeMessage) + .Select(s => (s.Options.GetMessageId()!, (SmokeMessage)s.Message, ((SmokeMessage)s.Message).FailureType)); + + string StatusOf(string messageId) => status.GetValueOrDefault(messageId, "unresolved"); + + public HttpResponseMessage Handle(HttpRequestMessage request) + { + var path = request.RequestUri!.AbsolutePath; + var failing = Failing.ToList(); + if (path == "/api/recoverability/groups") + { + return FakeHttpHandler.Json($$"""[{"id":"g1","title":"{{failing[0].ExceptionType}}: SmokeMessageHandler.Fail()","count":{{failing.Count}}}]"""); + } + + if (path == "/api/recoverability/groups/g1/errors") + { + return FakeHttpHandler.Json("[" + string.Join(",", failing.Select(f => $$"""{"id":"{{f.MessageId}}","message_id":"{{f.MessageId}}","status":"{{StatusOf(f.MessageId)}}","queue_address":"TestingTool.Load"}""")) + "]"); + } + + if (path == "/api/recoverability/groups/g1/errors/retry") + { + failing.ForEach(f => Resolve(f.MessageId, f.Message)); + return FakeHttpHandler.Status(HttpStatusCode.Accepted); + } + + if (path == "/api/errors/archive") + { + var ids = JsonSerializer.Deserialize(request.Content!.ReadAsStringAsync().Result)!; + Archived.AddRange(ids); + return FakeHttpHandler.Status(HttpStatusCode.Accepted); + } + + var id = path.Split('/')[3]; + if (path.EndsWith("/retry")) + { + Retried.Add(id); + failing.Where(f => RetryResolvesEverything || f.MessageId == id).ToList().ForEach(f => Resolve(f.MessageId, f.Message)); + return FakeHttpHandler.Status(HttpStatusCode.Accepted); + } + + return FakeHttpHandler.Json($$$"""{"status":"{{{StatusOf(id)}}}","processing_attempts":[{"headers":{}}]}"""); + } + + void Resolve(string messageId, SmokeMessage message) + { + if (HandlesRetries) + { + observations.Release(message.Marker); + SmokeMessageHandler.Process(observations, message, null, "Endpoint"); + } + + status[messageId] = "resolved"; + } + } +} diff --git a/tools/testing-tool/TestingTool.Tests/Smoke/SmokeEndpointLifecycleTests.cs b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeEndpointLifecycleTests.cs new file mode 100644 index 0000000000..6ab908db1a --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeEndpointLifecycleTests.cs @@ -0,0 +1,250 @@ +using System.Text.Json; +using NServiceBus; +using NServiceBus.Features; +using Microsoft.Extensions.Logging.Abstractions; +using NUnit.Framework; +using TestingTool.Smoke; + +namespace TestingTool.Tests.Smoke; + +/// Runs real in-process endpoints on the Learning transport in a temporary folder. No broker is needed. +[NonParallelizable] +public class SmokeEndpointLifecycleTests +{ + string storage = null!; + SmokeObservations observations = null!; + + [SetUp] + public void SetUp() + { + storage = Path.Combine(Path.GetTempPath(), "smoke-lifecycle-" + Guid.NewGuid().ToString("N")); + observations = new SmokeObservations(); + } + + [TearDown] + public void TearDown() + { + if (Directory.Exists(storage)) + { + Directory.Delete(storage, recursive: true); + } + } + + Task Start(string name, Action? configure = null, CancellationToken ct = default) => + SmokeEndpoint.Start(name, config => config.UseTransport(new LearningTransport { StorageDirectory = storage }), configure, observations, "error", ct); + + static Dictionary Headers(string metadataFile) => + JsonSerializer.Deserialize>(File.ReadAllText(metadataFile))!; + + IEnumerable> QueueHeaders(string queue) => + Directory.Exists(Path.Combine(storage, queue)) ? Directory.GetFiles(Path.Combine(storage, queue), "*.metadata.txt").Select(Headers) : []; + + static async Task WaitUntil(Func condition) + { + var deadline = DateTime.UtcNow.AddSeconds(15); + while (!condition()) + { + Assert.That(DateTime.UtcNow, Is.LessThan(deadline), "Timed out waiting for the condition"); + await Task.Delay(50); + } + } + + [Test] + public async Task Two_endpoints_handle_messages_with_their_own_identity_and_can_be_recreated() + { + await using var source = await Start("Smoke.Source"); + await using var target = await Start("Smoke.Target"); + Assert.That(source.MainAddress, Is.Not.EqualTo(target.MainAddress)); + + var send = new SendOptions(); + send.SetDestination(target.MainAddress); + await source.Session.Send(new SmokeMessage { Marker = "to-target" }, send); + await WaitUntil(() => observations.FindHandled("to-target") is not null); + Assert.That(observations.FindHandled("to-target")!.Endpoint, Is.EqualTo("Smoke.Target")); + + await target.StopAsync(CancellationToken.None); + await target.StopAsync(CancellationToken.None); + + await using var recreated = await Start("Smoke.Target"); + var again = new SendOptions(); + again.SetDestination(recreated.MainAddress); + await source.Session.Send(new SmokeMessage { Marker = "to-recreated" }, again); + await WaitUntil(() => observations.FindHandled("to-recreated") is not null); + Assert.That(recreated.MainAddress, Is.EqualTo(target.MainAddress)); + } + + [Test] + public async Task A_failing_message_reaches_the_error_queue_from_the_endpoint_that_failed_it() + { + await using var source = await Start("Smoke.Source"); + var send = new SendOptions(); + send.SetDestination(source.MainAddress); + await source.Session.Send(new SmokeMessage { Marker = "fails", Fail = true, FailureType = "TestingTool.Smoke.Failure_run_check" }, send); + + await WaitUntil(() => QueueHeaders("error").Any()); + var headers = QueueHeaders("error").Single(); + Assert.That(headers["NServiceBus.FailedQ"], Is.EqualTo(source.MainAddress)); + Assert.That(headers["NServiceBus.ExceptionInfo.ExceptionType"], Is.EqualTo("TestingTool.Smoke.Failure_run_check")); + Assert.That(observations.FindHandled("fails"), Is.Null); + } + + [Test] + public async Task The_heartbeat_plugin_sends_heartbeats_to_the_service_control_queue() + { + Directory.CreateDirectory(Path.Combine(storage, "Particular.ServiceControl")); + + await using var endpoint = await Start("Smoke.Heartbeat", config => config.SendHeartbeatTo("Particular.ServiceControl", TimeSpan.FromSeconds(1))); + + await WaitUntil(() => QueueHeaders("Particular.ServiceControl").Any(h => h["NServiceBus.EnclosedMessageTypes"] == "ServiceControl.Plugin.Heartbeat.Messages.EndpointHeartbeat")); + } + + [Test] + public async Task The_metrics_plugin_reports_processing_time_of_handled_messages_with_scanning_disabled() + { + Directory.CreateDirectory(Path.Combine(storage, "Particular.Monitoring")); + + await using var endpoint = await Start("Smoke.Metrics", config => config.EnableMetrics().SendMetricDataToServiceControl("Particular.Monitoring", TimeSpan.FromSeconds(1))); + var send = new SendOptions(); + send.SetDestination(endpoint.MainAddress); + for (var i = 0; i < 3; i++) + { + await endpoint.Session.Send(new SmokeMessage { Marker = $"metrics-{i}", DelayMilliseconds = 100 }, send); + } + + await WaitUntil(() => Enumerable.Range(0, 3).All(i => observations.FindHandled($"metrics-{i}")?.Endpoint == endpoint.Name)); + await WaitUntil(() => QueueHeaders("Particular.Monitoring").Any(h => h.GetValueOrDefault("NServiceBus.Metric.Type") == "ProcessingTime")); + } + + [Test] + public async Task A_host_that_fails_to_start_is_disposed_and_a_later_start_works() + { + var blockedStorage = Path.Combine(Path.GetTempPath(), "smoke-blocked-" + Guid.NewGuid().ToString("N")); + await File.WriteAllTextAsync(blockedStorage, "a file where the storage folder should be"); + try + { + var ex = Assert.ThrowsAsync(() => SmokeEndpoint.Start( + "Smoke.Broken", config => config.UseTransport(new LearningTransport { StorageDirectory = blockedStorage }), null, observations, "error", CancellationToken.None)); + Assert.That(ex!.Message, Does.Contain("Smoke.Broken could not start")); + } + finally + { + File.Delete(blockedStorage); + } + + await using var working = await Start("Smoke.Broken"); + Assert.That(working.MainAddress, Is.Not.Empty); + } + + [Test] + public async Task Canceling_while_the_host_is_starting_keeps_the_cancellation_and_stops_the_services_that_started() + { + var probe = new StartupProbe(); + using var cancel = new CancellationTokenSource(); + var start = Start("Smoke.Cancelled", config => + { + EarlierFeature.Probe = probe; + config.EnableFeature(); + config.EnableFeature(); + }, cancel.Token); + + await WaitUntil(() => probe.Blocking); + cancel.Cancel(); + + Assert.CatchAsync(async () => await start); + Assert.That(probe.EarlierStarted && probe.EarlierStopped, Is.True, "the service that had started was stopped when the start was canceled"); + } + + [Test] + public void A_pre_cancelled_start_throws_cancellation() + { + using var cancelled = new CancellationTokenSource(); + cancelled.Cancel(); + + Assert.CatchAsync(() => Start("Smoke.PreCancelled", ct: cancelled.Token)); + } + + [Test] + public async Task The_runner_stops_endpoint_hosts_before_http_cleanup_that_never_finishes_and_disposes_them() + { + var checkEndpoint = default(SmokeEndpoint); + var stopped = false; + var cleanupSawStoppedHost = false; + var check = new SmokeCheck("a", "a", "a", async (ctx, ct) => + { + checkEndpoint = await Start("Smoke.Runner"); + ctx.OnCleanup(async token => + { + // Like an API call that blocks until its time limit, registered before the host stop. + cleanupSawStoppedHost = stopped; + await Task.Delay(Timeout.Infinite, token); + }); + ctx.OnEndpointStop(async token => + { + await checkEndpoint.StopAsync(token); + stopped = true; + }); + }); + var runner = new SmokeRunner([check], () => null, TimeSpan.FromSeconds(30), TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(50), NullLogger.Instance); + + Assert.That(runner.TryStart(out _), Is.True); + await runner.WaitForCompletionAsync(); + + Assert.That(cleanupSawStoppedHost, Is.True); + var send = new SendOptions(); + send.SetDestination(checkEndpoint!.MainAddress); + await using var other = await Start("Smoke.Other"); + await other.Session.Send(new SmokeMessage { Marker = "after-stop" }, send); + await Task.Delay(500); + Assert.That(observations.FindHandled("after-stop"), Is.Null, "the stopped host no longer receives messages"); + } + + sealed class StartupProbe + { + public volatile bool EarlierStarted; + public volatile bool EarlierStopped; + public volatile bool Blocking; + } + + /// Starts and completes first, so a later cancellation leaves a started service behind. + sealed class EarlierFeature : Feature + { + public static StartupProbe Probe { get; set; } = new(); + + protected override void Setup(FeatureConfigurationContext context) => + context.RegisterStartupTask(new EarlierTask(Probe)); + + sealed class EarlierTask(StartupProbe probe) : FeatureStartupTask + { + protected override Task OnStart(IMessageSession session, CancellationToken cancellationToken = default) + { + probe.EarlierStarted = true; + return Task.CompletedTask; + } + + protected override Task OnStop(IMessageSession session, CancellationToken cancellationToken = default) + { + probe.EarlierStopped = true; + return Task.CompletedTask; + } + } + } + + sealed class BlockingFeature : Feature + { + public BlockingFeature() => DependsOn(); + + protected override void Setup(FeatureConfigurationContext context) => + context.RegisterStartupTask(new BlockingTask(EarlierFeature.Probe)); + + sealed class BlockingTask(StartupProbe probe) : FeatureStartupTask + { + protected override async Task OnStart(IMessageSession session, CancellationToken cancellationToken = default) + { + probe.Blocking = true; + await Task.Delay(Timeout.Infinite, cancellationToken); + } + + protected override Task OnStop(IMessageSession session, CancellationToken cancellationToken = default) => Task.CompletedTask; + } + } +} diff --git a/tools/testing-tool/TestingTool.Tests/Smoke/SmokeHandlerTests.cs b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeHandlerTests.cs new file mode 100644 index 0000000000..635d06c426 --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeHandlerTests.cs @@ -0,0 +1,75 @@ +using NUnit.Framework; +using TestingTool.Smoke; + +namespace TestingTool.Tests.Smoke; + +public class SmokeHandlerTests +{ + [Test] + public void Failure_headers_group_by_the_check() + { + var message = new SmokeMessage { Marker = "m1", Fail = true, FailureType = "TestingTool.Smoke.Failure_run_check" }; + var thrown = Assert.Throws(() => SmokeMessageHandler.Process(new SmokeObservations(), message, null, "Endpoint")); + var faultHeaders = new Dictionary + { + ["NServiceBus.FailedQ"] = "Source@dbo", + ["NServiceBus.ExceptionInfo.ExceptionType"] = "TestingTool.Smoke.SmokeFailureException", + ["NServiceBus.ExceptionInfo.Message"] = thrown!.Message + }; + + SmokeHeaders.CustomizeFailure(faultHeaders); + + Assert.That(faultHeaders["NServiceBus.ExceptionInfo.ExceptionType"], Is.EqualTo("TestingTool.Smoke.Failure_run_check")); + Assert.That(faultHeaders["NServiceBus.FailedQ"], Is.EqualTo("Source@dbo")); + } + + [Test] + public void Failure_headers_leave_other_messages_untouched() + { + var faultHeaders = new Dictionary + { + ["NServiceBus.FailedQ"] = "TestingTool.Load", + ["NServiceBus.ExceptionInfo.ExceptionType"] = "System.Exception", + ["NServiceBus.ExceptionInfo.Message"] = "Something|else" + }; + + SmokeHeaders.CustomizeFailure(faultHeaders); + + Assert.That(faultHeaders, Has.Count.EqualTo(3)); + Assert.That(faultHeaders["NServiceBus.ExceptionInfo.ExceptionType"], Is.EqualTo("System.Exception")); + } + + [Test] + public void Redirect_check_passes_only_when_the_target_handled_the_retry() + { + Assert.DoesNotThrow(() => SmokeChecks.RequireHandledBy(new SmokeObservations.HandledMessage(null, "", "Target"), "Target", "Source")); + var bySource = Assert.Throws(() => SmokeChecks.RequireHandledBy(new SmokeObservations.HandledMessage(null, "", "Source"), "Target", "Source")); + Assert.That(bySource!.Message, Does.Contain("handled by 'Source'")); + Assert.Throws(() => SmokeChecks.RequireHandledBy(null, "Target", "Source")); + } + + [Test] + public void A_failing_smoke_message_throws_until_its_marker_is_released() + { + var observations = new SmokeObservations(); + var message = new SmokeMessage { Marker = "m1", Fail = true }; + + Assert.Throws(() => SmokeMessageHandler.Process(observations, message, null, "Endpoint")); + Assert.That(observations.FindHandled("m1"), Is.Null); + + observations.Release("m1"); + SmokeMessageHandler.Process(observations, message, "failed-1", "Endpoint-A"); + + Assert.That(observations.FindHandled("m1")!.EditOf, Is.EqualTo("failed-1")); + Assert.That(observations.FindHandled("m1")!.Endpoint, Is.EqualTo("Endpoint-A")); + } + + [Test] + public void Releasing_one_marker_does_not_release_another() + { + var observations = new SmokeObservations(); + observations.Release("m1"); + + Assert.Throws(() => SmokeMessageHandler.Process(observations, new SmokeMessage { Marker = "m2", Fail = true }, null, "Endpoint")); + } +} diff --git a/tools/testing-tool/TestingTool.Tests/Smoke/SmokeRunnerTests.cs b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeRunnerTests.cs new file mode 100644 index 0000000000..3777c51146 --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeRunnerTests.cs @@ -0,0 +1,220 @@ +using Microsoft.Extensions.Logging.Abstractions; +using NUnit.Framework; +using TestingTool.Contracts; +using TestingTool.Smoke; + +namespace TestingTool.Tests.Smoke; + +public class SmokeRunnerTests +{ + static SmokeRunner Create(IReadOnlyList checks, Func? conflict = null, TimeSpan? checkTimeout = null, TimeSpan? cleanupTimeout = null) => + new(checks, conflict ?? (() => null), checkTimeout ?? TimeSpan.FromSeconds(5), cleanupTimeout ?? TimeSpan.FromSeconds(60), TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(50), NullLogger.Instance); + + static SmokeCheck Check(string id, Func run, TimeSpan? timeout = null) => new(id, id, id, run, timeout); + + static async Task RunToEnd(SmokeRunner runner) + { + Assert.That(runner.TryStart(out var error), Is.True, error); + await runner.WaitForCompletionAsync(); + return runner.GetSnapshot(); + } + + [Test] + public async Task Runs_checks_in_order_and_continues_after_a_failure() + { + var order = new List(); + var runner = Create([ + Check("a", (_, _) => { order.Add("a"); return Task.CompletedTask; }), + Check("b", (_, _) => { order.Add("b"); throw new SmokeCheckFailedException("expected effect missing"); }), + SmokeCheck.Manual("m", "manual", "a person checks this"), + Check("c", (ctx, _) => { order.Add("c"); ctx.Detail = "ok"; return Task.CompletedTask; })]); + + var run = await RunToEnd(runner); + + Assert.That(order, Is.EqualTo(["a", "b", "c"])); + Assert.That(run.Checks.Select(c => c.Status), Is.EqualTo([SmokeCheckStatus.Passed, SmokeCheckStatus.Failed, SmokeCheckStatus.Manual, SmokeCheckStatus.Passed])); + Assert.That(run.Checks[1].Detail, Is.EqualTo("expected effect missing")); + Assert.That(run.Checks[3].Detail, Is.EqualTo("ok")); + Assert.That(run.Running, Is.False); + Assert.That(run.FinishedAt, Is.Not.Null); + } + + [Test] + public async Task Unexpected_errors_fail_the_check_with_the_error_type() + { + var runner = Create([Check("a", (_, _) => throw new HttpRequestException("connection refused"))]); + + var run = await RunToEnd(runner); + + Assert.That(run.Checks[0].Status, Is.EqualTo(SmokeCheckStatus.Failed)); + Assert.That(run.Checks[0].Detail, Is.EqualTo("HttpRequestException: connection refused")); + } + + [Test] + public async Task Manual_rows_are_listed_before_and_after_a_run_without_executing() + { + var runner = Create([SmokeCheck.Manual("m", "manual", "desc")]); + Assert.That(runner.GetSnapshot().Checks[0].Status, Is.EqualTo(SmokeCheckStatus.Manual)); + + var run = await RunToEnd(runner); + + Assert.That(run.Checks[0].Status, Is.EqualTo(SmokeCheckStatus.Manual)); + Assert.That(run.Checks[0].DurationSeconds, Is.Null); + } + + [Test] + public async Task Rejects_a_second_start_while_running_and_accepts_one_after() + { + var release = new TaskCompletionSource(); + var runner = Create([Check("a", async (_, _) => await release.Task)]); + Assert.That(runner.TryStart(out _), Is.True); + + Assert.That(runner.TryStart(out var error), Is.False); + Assert.That(error, Does.Contain("already in progress")); + Assert.That(runner.GetSnapshot().Running, Is.True); + + release.SetResult(); + await runner.WaitForCompletionAsync(); + Assert.That(runner.TryStart(out _), Is.True); + await runner.WaitForCompletionAsync(); + } + + [Test] + public void Refuses_to_start_when_a_conflicting_job_is_running() + { + var runner = Create([Check("a", (_, _) => Task.CompletedTask)], () => "Stop the 'retry' job first."); + + Assert.That(runner.TryStart(out var error), Is.False); + Assert.That(error, Is.EqualTo("Stop the 'retry' job first.")); + Assert.That(runner.GetSnapshot().RunId, Is.Null); + } + + [Test] + public async Task Stop_cancels_the_running_check_and_the_pending_ones_and_still_cleans_up() + { + var started = new TaskCompletionSource(); + var cleaned = false; + var secondRan = false; + var runner = Create([ + Check("a", async (ctx, ct) => + { + ctx.OnCleanup(_ => { cleaned = true; return Task.CompletedTask; }); + started.SetResult(); + await Task.Delay(Timeout.Infinite, ct); + }), + Check("b", (_, _) => { secondRan = true; return Task.CompletedTask; })]); + runner.TryStart(out _); + await started.Task; + + runner.Stop(); + await runner.WaitForCompletionAsync(); + + var run = runner.GetSnapshot(); + Assert.That(run.Checks.Select(c => c.Status), Is.EqualTo([SmokeCheckStatus.Canceled, SmokeCheckStatus.Canceled])); + Assert.That(cleaned, Is.True); + Assert.That(secondRan, Is.False); + } + + [Test] + public async Task A_check_that_exceeds_its_timeout_fails_and_the_next_check_runs() + { + var runner = Create([ + Check("slow", (_, ct) => Task.Delay(Timeout.Infinite, ct), TimeSpan.FromMilliseconds(30)), + Check("next", (_, _) => Task.CompletedTask)]); + + var run = await RunToEnd(runner); + + Assert.That(run.Checks[0].Status, Is.EqualTo(SmokeCheckStatus.Failed)); + Assert.That(run.Checks[0].Detail, Does.Contain("did not finish within")); + Assert.That(run.Checks[1].Status, Is.EqualTo(SmokeCheckStatus.Passed)); + } + + [Test] + public async Task Cleanups_run_in_reverse_order_after_a_failure_and_a_cleanup_error_is_reported() + { + var order = new List(); + var runner = Create([Check("a", (ctx, _) => + { + ctx.OnCleanup(_ => { order.Add("first"); return Task.CompletedTask; }); + ctx.OnCleanup(_ => throw new InvalidOperationException("could not delete")); + throw new SmokeCheckFailedException("boom"); + })]); + + var run = await RunToEnd(runner); + + Assert.That(order, Is.EqualTo(["first"])); + Assert.That(run.Checks[0].Status, Is.EqualTo(SmokeCheckStatus.Failed)); + Assert.That(run.Checks[0].Detail, Does.StartWith("boom").And.Contain("could not delete")); + } + + [Test] + public async Task WaitFor_reports_the_last_observation_when_it_times_out() + { + var runner = Create([Check("a", async (ctx, ct) => + await ctx.WaitFor("the effect", _ => Task.FromResult(PollResult.Waiting("saw 2 of 3")), ct))]); + + var run = await RunToEnd(runner); + + Assert.That(run.Checks[0].Detail, Does.Contain("waiting for the effect").And.Contain("Last observed: saw 2 of 3")); + } + + [Test] + public async Task Each_run_gets_its_own_run_id_and_the_last_run_stays_visible() + { + var ids = new List(); + var runner = Create([Check("a", (ctx, _) => { ids.Add(ctx.RunId); return Task.CompletedTask; })]); + + var first = await RunToEnd(runner); + var second = await RunToEnd(runner); + + Assert.That(ids, Has.Count.EqualTo(2)); + Assert.That(ids[0], Is.Not.EqualTo(ids[1])); + Assert.That(first.RunId, Is.EqualTo(ids[0])); + Assert.That(second.RunId, Is.EqualTo(ids[1])); + Assert.That(runner.GetSnapshot().Checks[0].Status, Is.EqualTo(SmokeCheckStatus.Passed)); + } + + [Test] + public async Task A_cleanup_that_outlives_its_time_limit_is_cancelled_and_awaited_not_abandoned() + { + var observedCancellation = false; + var finished = false; + var runner = Create([Check("a", (ctx, _) => + { + ctx.OnCleanup(async token => + { + try { await Task.Delay(Timeout.Infinite, token); } + catch (OperationCanceledException) { observedCancellation = true; throw; } + finally { finished = true; } + }); + return Task.CompletedTask; + })], cleanupTimeout: TimeSpan.FromMilliseconds(50)); + + var run = await RunToEnd(runner); + + Assert.That(observedCancellation && finished, Is.True); + Assert.That(run.Checks[0].Detail, Does.Contain("timed out")); + } + + [Test] + public async Task Endpoint_stops_run_before_cleanups_even_when_a_stop_fails_and_a_cleanup_blocks() + { + var order = new List(); + var runner = Create([Check("a", (ctx, _) => + { + ctx.OnCleanup(async token => + { + order.Add("blocking cleanup"); + await Task.Delay(Timeout.Infinite, token); + }); + ctx.OnEndpointStop(_ => { order.Add("stop first"); return Task.CompletedTask; }); + ctx.OnEndpointStop(_ => { order.Add("stop second"); throw new InvalidOperationException("stop failed"); }); + return Task.CompletedTask; + })], cleanupTimeout: TimeSpan.FromMilliseconds(50)); + + var run = await RunToEnd(runner); + + Assert.That(order, Is.EqualTo(["stop second", "stop first", "blocking cleanup"])); + Assert.That(run.Checks[0].Detail, Does.Contain("stop failed").And.Contain("timed out")); + } +} diff --git a/tools/testing-tool/TestingTool.Tests/TestingTool.Tests.csproj b/tools/testing-tool/TestingTool.Tests/TestingTool.Tests.csproj new file mode 100644 index 0000000000..12249a6e1d --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/TestingTool.Tests.csproj @@ -0,0 +1,19 @@ + + + + net10.0 + false + + + + + + + + + + + + + + diff --git a/tools/testing-tool/TestingTool.Tests/TransportSelectionTests.cs b/tools/testing-tool/TestingTool.Tests/TransportSelectionTests.cs new file mode 100644 index 0000000000..23167a885a --- /dev/null +++ b/tools/testing-tool/TestingTool.Tests/TransportSelectionTests.cs @@ -0,0 +1,34 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using NUnit.Framework; + +namespace TestingTool.Tests; + +public class TransportSelectionTests +{ + const string ServiceBusConnectionString = + "Endpoint=sb://example.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=ZmFrZQ=="; + + [TestCase(ServiceBusConnectionString, "AzureServiceBus")] + [TestCase("endpoint=SB://example.servicebus.windows.net/;SharedAccessKeyName=k;SharedAccessKey=ZmFrZQ==", "AzureServiceBus")] + [TestCase("amqp://guest:guest@localhost:5672", "RabbitMQ")] + [TestCase("Server=localhost;Database=Transport;User Id=sa;Password=x;TrustServerCertificate=true", "SqlServer")] + [TestCase("", "Learning")] + public void Selects_transport_from_connection_string(string connectionString, string expected) => + Assert.That(Select(connectionString).Name, Is.EqualTo(expected)); + + [TestCase("Endpoint=https://example.servicebus.windows.net/;SharedAccessKey=ZmFrZQ==")] + [TestCase("not a connection string")] + public void Rejects_unrecognised_connection_string(string connectionString) => + Assert.Throws(() => Select(connectionString)); + + static SelectedTransport Select(string connectionString) + { + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary { ["ConnectionStrings:transport"] = connectionString }) + .Build(); + var services = new ServiceCollection(); + services.AddTestingToolEndpoint(new TestingToolOptions(), configuration); + return services.BuildServiceProvider().GetRequiredService(); + } +} diff --git a/tools/testing-tool/TestingTool.slnx b/tools/testing-tool/TestingTool.slnx index a8dbbdfe57..a1e67750a1 100644 --- a/tools/testing-tool/TestingTool.slnx +++ b/tools/testing-tool/TestingTool.slnx @@ -3,4 +3,5 @@ + \ No newline at end of file diff --git a/tools/testing-tool/TestingTool/CustomChecks/ReportCustomCheckResult.cs b/tools/testing-tool/TestingTool/CustomChecks/ReportCustomCheckResult.cs index 09f6da9f2e..71c85a6462 100644 --- a/tools/testing-tool/TestingTool/CustomChecks/ReportCustomCheckResult.cs +++ b/tools/testing-tool/TestingTool/CustomChecks/ReportCustomCheckResult.cs @@ -17,7 +17,7 @@ namespace ServiceControl.Plugin.CustomChecks.Messages; /// pass/fail reports that ServiceControl ingests as if a real endpoint (or ServiceControl /// itself) had produced them. /// -sealed class ReportCustomCheckResult : ICommand +public sealed class ReportCustomCheckResult : ICommand { /// Stable id of the host that ran the check. ServiceControl groups custom checks /// by HostId + CustomCheckId + Category, so a stable value per check gives coherent state diff --git a/tools/testing-tool/TestingTool/NServiceBusSetup.cs b/tools/testing-tool/TestingTool/NServiceBusSetup.cs index f118655085..05baee80d5 100644 --- a/tools/testing-tool/TestingTool/NServiceBusSetup.cs +++ b/tools/testing-tool/TestingTool/NServiceBusSetup.cs @@ -1,7 +1,10 @@ +using System.Data.Common; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Options; using NServiceBus; +using NServiceBus.Features; using TestingTool.Auditing; +using TestingTool.Smoke; namespace TestingTool; @@ -18,6 +21,7 @@ public static class NServiceBusEndpointExtensions /// Aspire AppHost to match the ServiceControl platform transport): /// /// starts with amqp: or amqps: — RabbitMQ, quorum queues with conventional routing + /// a connection string with an Endpoint=sb:// entry — Azure Service Bus, default topic topology /// a SQL Server connection string naming a database (Initial Catalog/Database) — SQL Server /// not set or empty — Learning transport, for local standalone runs /// @@ -28,37 +32,11 @@ public static class NServiceBusEndpointExtensions /// public static IServiceCollection AddTestingToolEndpoint(this IServiceCollection services, TestingToolOptions options, IConfiguration configuration) { - var config = new EndpointConfiguration("TestingTool.Load"); + var config = new EndpointConfiguration(LoadEndpointName); - var transportConnectionString = configuration.GetConnectionString("transport"); - string transportName; - if (string.IsNullOrWhiteSpace(transportConnectionString)) - { - transportName = "Learning"; - config.UseTransport(); - } - else if (transportConnectionString.StartsWith("amqp:", StringComparison.OrdinalIgnoreCase) - || transportConnectionString.StartsWith("amqps:", StringComparison.OrdinalIgnoreCase)) - { - transportName = "RabbitMQ"; - var transport = config.UseTransport(); - transport.UseConventionalRoutingTopology(QueueType.Quorum); - transport.ConnectionString(transportConnectionString); - } - else if (IsSqlServerConnectionString(transportConnectionString)) - { - transportName = "SqlServer"; - config.UseTransport(new SqlServerTransport(transportConnectionString)); - } - else - { - throw new InvalidOperationException( - "Unrecognised 'transport' connection string (ConnectionStrings__transport). Expected an " + - "amqp:// or amqps:// URI for RabbitMQ, or a SQL Server connection string with " + - "Initial Catalog/Database for SQL Server. Leave it unset to use the Learning transport."); - } - - services.AddSingleton(new SelectedTransport(transportName)); + var selectedTransport = ConfigureTransport(config, configuration); + services.AddSingleton(selectedTransport); + services.AddSingleton(new SmokeEndpointIdentity(LoadEndpointName)); // Route failures to the ServiceControl error queue. config.SendFailedMessagesTo(options.ErrorQueueName); @@ -68,7 +46,7 @@ public static IServiceCollection AddTestingToolEndpoint(this IServiceCollection // the only stage late enough to control NServiceBus.EnclosedMessageTypes and the timestamps. config.Pipeline.Register(new RawAuditPayloadBehavior(), "Applies raw audit envelopes from the direct audit-queue writer"); config.SendHeartbeatTo(options.ServiceControlInputQueue); - + // enable metrics var metrics = config.EnableMetrics(); metrics.SendMetricDataToServiceControl( @@ -85,12 +63,80 @@ public static IServiceCollection AddTestingToolEndpoint(this IServiceCollection recoverability.Immediate(im => im.NumberOfRetries(0)); recoverability.Delayed(d => d.NumberOfRetries(0)); + // Smoke checks: a saga with saga auditing, SmokeMessage failures grouped per check, and the + // ServiceControl integration events, subscribed explicitly while a smoke check needs them. + config.UsePersistence().SagaStorageDirectory(Path.Combine(Path.GetTempPath(), "TestingTool.Sagas")); + config.AuditSagaStateChanges(options.AuditQueueName); + recoverability.Failed(failed => failed.HeaderCustomization(SmokeHeaders.CustomizeFailure)); + config.DisableFeature(); + config.Conventions().DefiningEventsAs(type => + typeof(IEvent).IsAssignableFrom(type) || type.Namespace?.StartsWith("ServiceControl.Contracts", StringComparison.Ordinal) == true); + config.EnableInstallers(); services.AddNServiceBusEndpoint(config); return services; } + public const string LoadEndpointName = "TestingTool.Load"; + + /// + /// Selects the transport from the transport connection string, as documented on + /// . The smoke tests call it for their own endpoints too, so they + /// share the transport and topology of the load endpoint. + /// + public static SelectedTransport ConfigureTransport(EndpointConfiguration config, IConfiguration configuration) + { + var transportConnectionString = configuration.GetConnectionString("transport"); + string transportName; + if (string.IsNullOrWhiteSpace(transportConnectionString)) + { + transportName = "Learning"; + config.UseTransport(); + } + else if (transportConnectionString.StartsWith("amqp:", StringComparison.OrdinalIgnoreCase) + || transportConnectionString.StartsWith("amqps:", StringComparison.OrdinalIgnoreCase)) + { + transportName = "RabbitMQ"; + var transport = config.UseTransport(); + transport.UseConventionalRoutingTopology(QueueType.Quorum); + transport.ConnectionString(transportConnectionString); + } + else if (IsAzureServiceBusConnectionString(transportConnectionString)) + { + transportName = "AzureServiceBus"; + config.UseTransport(new AzureServiceBusTransport(transportConnectionString, TopicTopology.Default)); + } + else if (IsSqlServerConnectionString(transportConnectionString)) + { + transportName = "SqlServer"; + config.UseTransport(new SqlServerTransport(transportConnectionString)); + } + else + { + throw new InvalidOperationException( + "Unrecognised 'transport' connection string (ConnectionStrings__transport). Expected an " + + "amqp:// or amqps:// URI for RabbitMQ, an Endpoint=sb://... connection string for Azure Service Bus, or a SQL Server connection string with " + + "Initial Catalog/Database for SQL Server. Leave it unset to use the Learning transport."); + } + + return new SelectedTransport(transportName); + } + + static bool IsAzureServiceBusConnectionString(string connectionString) + { + try + { + var builder = new DbConnectionStringBuilder { ConnectionString = connectionString }; + return builder.TryGetValue("Endpoint", out var endpoint) + && endpoint.ToString()!.StartsWith("sb://", StringComparison.OrdinalIgnoreCase); + } + catch (ArgumentException) + { + return false; + } + } + static bool IsSqlServerConnectionString(string connectionString) { try diff --git a/tools/testing-tool/TestingTool/Program.cs b/tools/testing-tool/TestingTool/Program.cs index 6ea727445d..8183d9128b 100644 --- a/tools/testing-tool/TestingTool/Program.cs +++ b/tools/testing-tool/TestingTool/Program.cs @@ -4,6 +4,7 @@ using TestingTool.Contracts; using TestingTool.Jobs; using TestingTool.Scenarios; +using TestingTool.Smoke; // --- Configuration --- @@ -59,6 +60,39 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); +// --- Smoke tests --- +// An API-verified checklist run from the "Smoke tests" tab. See SmokeChecks for what each check verifies. + +builder.Services.AddHttpClient((sp, client) => +{ + client.BaseAddress = new Uri(sp.GetRequiredService>().Value.ServiceControlApiUrl); + client.Timeout = TimeSpan.FromSeconds(30); +}); +builder.Services.AddHttpClient((sp, client) => +{ + client.BaseAddress = new Uri(sp.GetRequiredService>().Value.MonitoringApiUrl); + client.Timeout = TimeSpan.FromSeconds(30); +}); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(sp => +{ + var opts = sp.GetRequiredService>().Value; + var jobs = sp.GetRequiredService(); + return new SmokeRunner( + sp.GetRequiredService().Create(), + () => jobs.All.FirstOrDefault(j => j.IsRunning && SmokeJobConflicts.Conflicts(j.Name)) is { } job + ? $"Stop the '{job.Name}' job first. It acts on every failed message group, not only the groups of the smoke run." + : null, + opts.SmokeCheckTimeout, + TimeSpan.FromSeconds(60), + opts.SmokePollInterval, + opts.SmokePollTimeout, + sp.GetRequiredService>()); +}); +// Registered after the NServiceBus endpoint so it stops first and the run can still clean up through the endpoint. +builder.Services.AddHostedService(); + // --- Application pipeline --- var app = builder.Build(); @@ -70,6 +104,7 @@ var scClient = app.Services.GetRequiredService(); var jobRunner = app.Services.GetRequiredService(); var startedAt = DateTimeOffset.UtcNow; +var smokeStartGate = new Lock(); // Auto-start background noise after the endpoint is ready. app.Lifetime.ApplicationStarted.Register(() => @@ -160,14 +195,21 @@ app.MapGet("/api/jobs", () => Results.Ok(jobRunner.GetSnapshot())); -app.MapPost("/api/jobs/{name}/start", (string name, StartJobRequest? request) => +app.MapPost("/api/jobs/{name}/start", (string name, StartJobRequest? request, SmokeRunner smokeRunner) => { var interval = request?.IntervalSeconds is { } secs and > 0 ? TimeSpan.FromSeconds(secs) : (TimeSpan?)null; - if (!jobRunner.TryStart(name, interval, request, out var error)) - return Results.BadRequest(new { error }); + // The same lock guards smoke start, so a conflicting job and a smoke run cannot both pass their check. + lock (smokeStartGate) + { + if (SmokeJobConflicts.Conflicts(name) && smokeRunner.GetSnapshot().Running) + return Results.BadRequest(new { error = $"Job '{name}' acts on every failed message group, so it cannot start while a smoke run is in progress." }); + + if (!jobRunner.TryStart(name, interval, request, out var error)) + return Results.BadRequest(new { error }); + } var snapshot = jobRunner.GetSnapshot() .First(j => j.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); @@ -275,6 +317,24 @@ return Results.Ok(new { started = preset.Name, scenario = preset.ScenarioName, rate = preset.Rate }); }); +// --- Smoke test endpoints --- + +app.MapGet("/api/smoke", (SmokeRunner runner) => Results.Ok(runner.GetSnapshot())); + +app.MapPost("/api/smoke/start", (SmokeRunner runner) => +{ + lock (smokeStartGate) + { + return runner.TryStart(out var error) ? Results.Ok(runner.GetSnapshot()) : Results.BadRequest(new { error }); + } +}); + +app.MapPost("/api/smoke/stop", (SmokeRunner runner) => +{ + runner.Stop(); + return Results.Ok(runner.GetSnapshot()); +}); + app.MapFallbackToFile("index.html"); app.Run(); \ No newline at end of file diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeApiClient.cs b/tools/testing-tool/TestingTool/Smoke/SmokeApiClient.cs new file mode 100644 index 0000000000..76bc92aa02 --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeApiClient.cs @@ -0,0 +1,248 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace TestingTool.Smoke; + +/// +/// Strict ServiceControl primary API client for the smoke checks. Unlike +/// every transport error, timeout and unexpected status throws , +/// so a check never reads an empty result as "nothing found". +/// +public sealed class SmokeApiClient(HttpClient http) +{ + // ServiceControl's JSON contract is snake_case with camelCase string enums. + static readonly JsonSerializerOptions ServiceControlJson = new(JsonSerializerDefaults.Web) + { + PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + const string IncompleteResultsHeader = "X-Particular-Incomplete-Results"; + const int PageSize = 100; + const int MaxPages = 50; + + public static string UriEscape(string value) => Uri.EscapeDataString(value); + + public async Task> GetRemotes(CancellationToken ct) => + await Get>("/api/configuration/remotes", ct) ?? []; + + public Task> GetCustomChecks(string status, CancellationToken ct) => + GetAllPages($"/api/customchecks?status={status}", ct); + + /// The RavenDB persister returns ids as CustomChecks/{guid}, but the delete route takes the guid. + public Task DeleteCustomCheck(string id, CancellationToken ct) => + Run(HttpMethod.Delete, $"/api/customchecks/{id[(id.LastIndexOf('/') + 1)..]}", null, ct, HttpStatusCode.Accepted); + + public async Task> GetEndpoints(CancellationToken ct) => + await Get>("/api/endpoints", ct) ?? []; + + public Task DeleteEndpoint(Guid id, CancellationToken ct) => Run(HttpMethod.Delete, $"/api/endpoints/{id}", null, ct, HttpStatusCode.NoContent); + + public async Task> GetGroups(CancellationToken ct) => + await Get>("/api/recoverability/groups", ct) ?? []; + + public Task> GetGroupErrors(string groupId, CancellationToken ct) => + GetAllPages($"/api/recoverability/groups/{UriEscape(groupId)}/errors", ct); + + /// Returns null while ServiceControl answers 404, that is before the failure is ingested. + public async Task FindFailedMessage(string id, CancellationToken ct) + { + using var response = await Send(HttpMethod.Get, $"/api/errors/{UriEscape(id)}", null, ct, HttpStatusCode.OK, HttpStatusCode.NotFound); + return response.StatusCode == HttpStatusCode.NotFound ? null : await Read(response, ct); + } + + public Task RetryMessage(string id, CancellationToken ct) => Run(HttpMethod.Post, $"/api/errors/{UriEscape(id)}/retry", null, ct, HttpStatusCode.Accepted); + + public Task RetryGroup(string groupId, CancellationToken ct) => + Run(HttpMethod.Post, $"/api/recoverability/groups/{UriEscape(groupId)}/errors/retry", null, ct, HttpStatusCode.Accepted); + + public Task ArchiveMessages(IReadOnlyList ids, CancellationToken ct) => Run(HttpMethod.Patch, "/api/errors/archive", ids, ct, HttpStatusCode.Accepted); + + public async Task EditMessage(string id, string body, Dictionary headers, CancellationToken ct) + { + using var response = await Send(HttpMethod.Post, $"/api/edit/{UriEscape(id)}", new EditRequest(body, headers), ct, HttpStatusCode.Accepted, HttpStatusCode.OK); + return response.StatusCode == HttpStatusCode.Accepted; + } + + public Task> GetRedirects(CancellationToken ct) => GetAllPages("/api/redirects", ct); + + public Task CreateRedirect(string from, string to, CancellationToken ct) => + Run(HttpMethod.Post, "/api/redirects", new RedirectRequest(from, to, false), ct, HttpStatusCode.Created); + + public Task DeleteRedirect(Guid id, CancellationToken ct) => Run(HttpMethod.Delete, $"/api/redirects/{id}", null, ct, HttpStatusCode.NoContent); + + public Task>> SearchMessages(string query, CancellationToken ct) => + GetAudited>($"/api/messages/search?q={UriEscape(query)}", ct, []); + + public Task>> GetConversation(string conversationId, CancellationToken ct) => + GetAudited>($"/api/conversations/{UriEscape(conversationId)}?per_page={PageSize}", ct, []); + + /// Follows the relative body_url of an audited message, which names the instance that stores the body. + public async Task GetMessageBody(AuditedMessage message, CancellationToken ct) + { + if (string.IsNullOrEmpty(message.BodyUrl)) + { + throw new SmokeCheckFailedException($"Audited message {message.MessageId} has no body_url, so its stored body cannot be read"); + } + + using var response = await Send(HttpMethod.Get, "/api" + message.BodyUrl, null, ct, HttpStatusCode.OK); + return await response.Content.ReadAsStringAsync(ct); + } + + /// The primary answers 204 until the audit instance has ingested the saga. + public async Task> GetSaga(Guid sagaId, CancellationToken ct) + { + using var response = await Send(HttpMethod.Get, $"/api/sagas/{sagaId}", null, ct, HttpStatusCode.OK, HttpStatusCode.NoContent); + var incomplete = IncompleteInstances(response); + return new Audited(response.StatusCode == HttpStatusCode.NoContent ? null : await Read(response, ct), incomplete); + } + + async Task> GetAudited(string path, CancellationToken ct, T fallback) + { + using var response = await Send(HttpMethod.Get, path, null, ct, HttpStatusCode.OK); + return new Audited(await Read(response, ct) ?? fallback, IncompleteInstances(response)); + } + + async Task Get(string path, CancellationToken ct) + { + using var response = await Send(HttpMethod.Get, path, null, ct, HttpStatusCode.OK); + return await Read(response, ct); + } + + async Task> GetAllPages(string path, CancellationToken ct) + { + var all = new List(); + var separator = path.Contains('?') ? '&' : '?'; + for (var page = 1; page <= MaxPages; page++) + { + var items = await Get>($"{path}{separator}page={page}&per_page={PageSize}", ct) ?? []; + all.AddRange(items); + if (items.Count < PageSize) + { + return all; + } + } + + throw new SmokeCheckFailedException($"GET {path} has more than {MaxPages * PageSize} entries, which the smoke checks do not page through"); + } + + static string? IncompleteInstances(HttpResponseMessage response) => + response.Headers.TryGetValues(IncompleteResultsHeader, out var values) ? string.Join(", ", values) : null; + + static async Task Read(HttpResponseMessage response, CancellationToken ct) + { + try + { + return await response.Content.ReadFromJsonAsync(ServiceControlJson, ct); + } + catch (JsonException ex) + { + throw new SmokeCheckFailedException($"{response.RequestMessage?.RequestUri?.PathAndQuery} returned a body that is not the expected JSON: {ex.Message}"); + } + } + + async Task Run(HttpMethod method, string path, object? body, CancellationToken ct, params HttpStatusCode[] accepted) + { + using var response = await Send(method, path, body, ct, accepted); + } + + Task Send(HttpMethod method, string path, object? body, CancellationToken ct, params HttpStatusCode[] accepted) => + SmokeHttp.Send(http, method, path, body is null ? null : JsonContent.Create(body, body.GetType(), null, ServiceControlJson), ct, accepted); + + public sealed record RemoteInstance(string ApiUri, string Status); + + public sealed record CustomCheckView(string Id, string CustomCheckId, string Status, string? FailureReason, DateTime ReportedAt); + + public sealed record EndpointView(Guid Id, string Name, bool MonitorHeartbeat, HeartbeatInformation? HeartbeatInformation); + + public sealed record HeartbeatInformation(string ReportedStatus); + + public sealed record FailedMessageView(string Id, string MessageId, string Status, string? QueueAddress, bool Edited, string? EditOf); + + public sealed record FailedMessageDetail(string Status, List ProcessingAttempts); + + public sealed record ProcessingAttempt(Dictionary Headers); + + public sealed record RedirectView(Guid MessageRedirectId, string FromPhysicalAddress, string ToPhysicalAddress); + + public sealed record AuditedMessage(string Id, string MessageId, string MessageType, string Status, string? ConversationId, string? BodyUrl, List? Headers, List? InvokedSagas) + { + public string? Header(string name) => Headers?.FirstOrDefault(h => h.Key == name)?.Value; + } + + public sealed record HeaderEntry(string Key, string? Value); + + public sealed record SagaReference(Guid SagaId, string SagaType); + + public sealed record SagaHistory(Guid SagaId, string SagaType, List Changes); + + public sealed record SagaChange(string Status, DateTime FinishTime); + + /// A read that spans instances. names the instances that did not answer. + public sealed record Audited(T Value, string? Incomplete); + + sealed record EditRequest(string MessageBody, Dictionary MessageHeaders); + + sealed record RedirectRequest( + [property: JsonPropertyName("fromphysicaladdress")] string From, + [property: JsonPropertyName("tophysicaladdress")] string To, + [property: JsonPropertyName("retryexisting")] bool RetryExisting); +} + +/// +/// ServiceControl.Monitoring API client for the smoke checks. Routes have no /api prefix and +/// the JSON is camelCase. +/// +public sealed class SmokeMonitoringClient(HttpClient http) +{ + static readonly JsonSerializerOptions MonitoringJson = new(JsonSerializerDefaults.Web); + + public async Task> GetMonitoredEndpoints(CancellationToken ct) + { + using var response = await SmokeHttp.Send(http, HttpMethod.Get, "/monitored-endpoints", null, ct, HttpStatusCode.OK); + return await response.Content.ReadFromJsonAsync>(MonitoringJson, ct) ?? []; + } + + public async Task DeleteInstance(string endpointName, string instanceId, CancellationToken ct) + { + using var response = await SmokeHttp.Send(http, HttpMethod.Delete, + $"/monitored-instance/{Uri.EscapeDataString(endpointName)}/{Uri.EscapeDataString(instanceId)}", null, ct, HttpStatusCode.OK); + } + + public sealed record MonitoredEndpoint(string Name, bool IsStale, string[]? EndpointInstanceIds, Dictionary Metrics); + + public sealed record MonitoredValues(double? Average); +} + +static class SmokeHttp +{ + public static async Task Send(HttpClient http, HttpMethod method, string path, HttpContent? content, CancellationToken ct, params HttpStatusCode[] accepted) + { + using var request = new HttpRequestMessage(method, path) { Content = content }; + HttpResponseMessage response; + try + { + response = await http.SendAsync(request, ct); + } + catch (HttpRequestException ex) + { + throw new SmokeCheckFailedException($"{method} {path} could not reach {http.BaseAddress}: {ex.Message}"); + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + throw new SmokeCheckFailedException($"{method} {path} to {http.BaseAddress} timed out"); + } + + if (!accepted.Contains(response.StatusCode)) + { + var text = await response.Content.ReadAsStringAsync(ct); + var status = (int)response.StatusCode; + response.Dispose(); + throw new SmokeCheckFailedException($"{method} {path} returned {status}: {(text.Length > 300 ? text[..300] : text)}"); + } + + return response; + } +} diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeCheck.cs b/tools/testing-tool/TestingTool/Smoke/SmokeCheck.cs new file mode 100644 index 0000000000..fa1625a1a2 --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeCheck.cs @@ -0,0 +1,82 @@ +namespace TestingTool.Smoke; + +/// +/// One row of the smoke checklist. A null marks a manual row that the runner +/// lists but never executes. +/// +public sealed record SmokeCheck( + string Id, + string Title, + string Description, + Func? Run, + TimeSpan? Timeout = null) +{ + public bool IsManual => Run is null; + + public static SmokeCheck Manual(string id, string title, string description) => new(id, title, description, null); +} + +/// A check's expectation was not met. The message is shown in the UI as the failure detail. +public sealed class SmokeCheckFailedException(string message) : Exception(message); + +public readonly record struct PollResult(bool IsDone, T? Value, string Observed); + +public static class PollResult +{ + public static PollResult Done(T value) => new(true, value, ""); + + public static PollResult Waiting(string observed) => new(false, default, observed); +} + +/// +/// Per-check state: the run identifier that scopes everything the check creates, bounded polling, +/// and cleanup actions the runner always executes after the check. +/// +public sealed class SmokeContext(string runId, TimeSpan pollInterval, TimeSpan pollTimeout) +{ + readonly List> cleanups = []; + readonly List> endpointStops = []; + + public string RunId { get; } = runId; + + /// Text shown as the detail of a passed check. + public string? Detail { get; set; } + + /// Registers an action the runner always awaits after the check. Its token cancels when the cleanup time limit passes. + public void OnCleanup(Func cleanup) => cleanups.Add(cleanup); + + /// + /// Registers the stop of an endpoint host the check started. The runner awaits all stops before any + /// cleanup, so an unavailable API cannot use up the time that stopping the hosts needs. + /// + public void OnEndpointStop(Func stop) => endpointStops.Add(stop); + + public IReadOnlyList> EndpointStops => endpointStops; + + public IReadOnlyList> Cleanups => cleanups; + + /// + /// Calls until it reports done or passes. + /// Exceptions from the probe, such as an API or transport error, fail the check immediately. + /// + public async Task WaitFor(string description, Func>> probe, CancellationToken ct, TimeSpan? timeout = null) + { + var limit = timeout ?? pollTimeout; + var started = System.Diagnostics.Stopwatch.StartNew(); + while (true) + { + var result = await probe(ct); + if (result.IsDone) + { + return result.Value!; + } + + if (started.Elapsed >= limit) + { + throw new SmokeCheckFailedException($"Timed out after {limit.TotalSeconds:0.#}s waiting for {description}. Last observed: {result.Observed}"); + } + + await Task.Delay(pollInterval, ct); + } + } +} diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeChecks.cs b/tools/testing-tool/TestingTool/Smoke/SmokeChecks.cs new file mode 100644 index 0000000000..77bafc24aa --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeChecks.cs @@ -0,0 +1,577 @@ +using System.Text.Json; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Options; +using NServiceBus; +using ServiceControl.Plugin.CustomChecks.Messages; +using static TestingTool.Smoke.SmokeApiClient; + +namespace TestingTool.Smoke; + +/// +/// The smoke checklist. Every automated check sends its own messages with a run-scoped identifier, then +/// reads the effect back through the ServiceControl APIs. Nothing is matched by anything the background +/// load could also produce. +/// +public sealed class SmokeChecks( + SmokeApiClient api, + SmokeMonitoringClient monitoring, + IMessageSession session, + SmokeObservations observations, + IOptions options, + IConfiguration configuration) +{ + /// Heartbeats are marked dead 40 seconds after the last one, checked every 5 seconds. + static readonly TimeSpan HeartbeatDeadTimeout = TimeSpan.FromSeconds(100); + + public IReadOnlyList Create() => + [ + new("custom-check-fail-then-pass", "Custom check fails, then passes", + "Reports a failed then a passed custom check with a run-specific id to the primary input queue, and reads it from GET /api/customchecks?status=fail and ?status=pass.", + CustomCheckFailThenPass), + new("heartbeat-beating-then-dead", "Heartbeat is healthy, then the endpoint is reported dead", + "Starts a real endpoint named after the run with the NServiceBus.Heartbeat plugin and reads heartbeat_information.reported_status from GET /api/endpoints: beating, then dead after the endpoint host stops. Takes about a minute.", + HeartbeatBeatingThenDead, TimeSpan.FromMinutes(4)), + new("audit-ingestion-fulltext", "Audited message is ingested and found by full-text search", + "Processes a message carrying a run-specific word, then finds it with GET /api/messages/search and reads its body from GET /api/messages/{id}/body. Needs an audit instance registered as a remote of the primary.", + AuditIngestionFulltext), + new("fanout-conversation", "Fan-out conversation keeps its parent links", + "Processes a message that sends two children per level for two levels, then reads the seven-message conversation from GET /api/conversations/{id} and checks each NServiceBus.RelatedTo header. Needs an audit instance.", + FanOutConversation), + new("saga-audit", "Saga audit data records new, updated and completed", + "Runs a real saga through three state changes with saga auditing on, finds the audited start message with GET /api/messages/search and reads GET /api/sagas/{id}. Needs an audit instance.", + SagaAudit), + new("monitoring-data", "Monitoring reports processing time for an endpoint", + "Starts a real endpoint named after the run with the NServiceBus.Metrics.ServiceControl plugin, handles three messages that each take 100 ms, and reads the processingTime average for that endpoint from GET /monitored-endpoints on the monitoring instance.", + MonitoringData), + new("integration-event", "MessageFailed integration event is received", + "Subscribes this endpoint to ServiceControl.Contracts.MessageFailed, fails one message, and matches the published event by a run header and the failed message id. Needs SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING=true on the instance that ingests errors.", + IntegrationEvent), + new("retry-single", "Retry one failed message", + "Fails two messages in a run-specific group, retries one with POST /api/errors/{id}/retry, and checks that it was handled and resolved while the other stayed unresolved.", + RetrySingle), + new("retry-group", "Retry a failed message group", + "Fails three messages in a run-specific group, retries the group with POST /api/recoverability/groups/{id}/errors/retry, and checks that each message was handled and resolved.", + RetryGroup), + new("edit-and-retry", "Edit the body of a failed message and retry it", + "Fails a message, sends the edited body that no longer fails through POST /api/edit/{id} with every original header, and checks that the edited message arrived with ServiceControl.EditOf and the edited text. Needs SERVICECONTROL_ALLOWMESSAGEEDITING=true.", + EditAndRetry), + new("retry-through-redirect", "Retry through a redirect", + "Starts a Source and a Target endpoint, fails a message in Source, creates a redirect from the Source input address to the Target input address with POST /api/redirects, retries it, and checks that Target handled it and it is resolved. Runs last because a redirect changes retry routing while it exists.", + RetryThroughRedirect), + + SmokeCheck.Manual("manual-installation", "Instance installation and upgrade", + "Not automated. Upgrade and create instances with the installer and with the PowerShell scripts, on localhost and on a custom hostname, as listed under Instance management installation."), + SmokeCheck.Manual("manual-servicepulse-custom-checks-heartbeats", "ServicePulse: custom checks and heartbeats views", + "Not automated. The API data is verified above. A person confirms that ServicePulse shows the custom check warning and clears it, and moves an endpoint from healthy to unhealthy."), + SmokeCheck.Manual("manual-servicepulse-recoverability", "ServicePulse: recoverability screens", + "Not automated. The API effects are verified above. A person confirms the retry, edit and redirect screens in ServicePulse, including Configuration > Create redirect."), + SmokeCheck.Manual("manual-servicepulse-audit-saga", "ServicePulse: message search, sequence diagram and saga view", + "Not automated. The audit, conversation and saga data is verified above. A person confirms that the search box finds a message, that the sequence diagram draws the fan-out, and that the saga view draws the graph."), + SmokeCheck.Manual("manual-integration-events-sample", "Integration events sample", + "Not automated. This tool verifies reception in its own endpoint. A person runs the public integration events sample on the transport under test and confirms that its subscriber receives MessageFailed."), + SmokeCheck.Manual("manual-monitoring-graphs", "ServicePulse: monitoring tab", + "Not automated. The metric data is verified above for a real run-scoped endpoint. A person confirms that the endpoints, the failed messages indicator and the graphs render."), + SmokeCheck.Manual("manual-chaos", "Chaos testing", + "Not automated. Stop ServiceControl processes gracefully and with kill while ingestion and large retry groups run, and verify storage and logic afterwards."), + SmokeCheck.Manual("manual-performance", "Performance, load and stability testing", + "Not automated. Use the load scenarios and bypass writers for performance on clean, moderate and large databases, and check reboots, service stops, virtual machine kills and upgrades under load.") + ]; + + async Task CustomCheckFailThenPass(SmokeContext ctx, CancellationToken ct) + { + var checkId = $"Smoke.{ctx.RunId}"; + var hostId = Guid.NewGuid(); + var reason = $"Smoke run {ctx.RunId} reports a failure"; + ctx.OnCleanup(async token => + { + foreach (var status in new[] { "fail", "pass" }) + { + foreach (var view in (await api.GetCustomChecks(status, token)).Where(c => c.CustomCheckId == checkId)) + { + await api.DeleteCustomCheck(view.Id, token); + } + } + }); + + await SendCustomCheck(checkId, hostId, ctx.RunId, failed: true, reason, ct); + await ctx.WaitFor("the custom check to appear as failed", async token => + { + var checks = (await api.GetCustomChecks("fail", token)).Where(c => c.CustomCheckId == checkId).ToList(); + return checks.Count == 0 + ? PollResult.Waiting($"no failed check with id {checkId}") + : checks[0].FailureReason == reason + ? PollResult.Done(checks[0]) + : PollResult.Waiting($"failure reason was '{checks[0].FailureReason}'"); + }, ct); + + await SendCustomCheck(checkId, hostId, ctx.RunId, failed: false, null, ct); + await ctx.WaitFor("the custom check to pass and leave the failed list", async token => + { + var passed = (await api.GetCustomChecks("pass", token)).Any(c => c.CustomCheckId == checkId); + var stillFailed = (await api.GetCustomChecks("fail", token)).Any(c => c.CustomCheckId == checkId); + return passed && !stillFailed ? PollResult.Done(true) : PollResult.Waiting($"passed list has it: {passed}, failed list has it: {stillFailed}"); + }, ct); + + ctx.Detail = $"Custom check {checkId} was reported failed, then passed."; + } + + Task SendCustomCheck(string checkId, Guid hostId, string runId, bool failed, string? reason, CancellationToken ct) + { + var send = new SendOptions(); + send.SetDestination(options.Value.ServiceControlInputQueue); + return session.Send(new ReportCustomCheckResult + { + HostId = hostId, + CustomCheckId = checkId, + Category = "Smoke", + HasFailed = failed, + FailureReason = reason, + ReportedAt = DateTime.UtcNow, + EndpointName = $"TestingTool.Smoke.{runId}", + Host = "TestingTool.Smoke" + }, send, ct); + } + + async Task HeartbeatBeatingThenDead(SmokeContext ctx, CancellationToken ct) + { + var name = $"TestingTool.Smoke.{ctx.RunId}"; + DeleteEndpointRecords(ctx, name); + + var endpoint = await StartEndpoint(ctx, name, config => config.SendHeartbeatTo(options.Value.ServiceControlInputQueue), ct); + await ctx.WaitFor("the endpoint to report beating", token => EndpointStatus(name, "beating", token), ct); + var beating = DateTime.UtcNow; + + await endpoint.StopAsync(ct); + await ctx.WaitFor("the endpoint to report dead after it stopped", token => EndpointStatus(name, "dead", token), ct, HeartbeatDeadTimeout); + + ctx.Detail = $"Endpoint {name} sent heartbeats with the NServiceBus.Heartbeat plugin, was reported beating, and was reported dead {(DateTime.UtcNow - beating).TotalSeconds:0}s after its host stopped."; + } + + /// Deletes the primary instance's records of exactly these endpoint names, and no others. It runs after the endpoint hosts stop. + public void DeleteEndpointRecords(SmokeContext ctx, params string[] names) => + ctx.OnCleanup(async token => + { + foreach (var view in (await api.GetEndpoints(token)).Where(e => names.Contains(e.Name))) + { + await api.DeleteEndpoint(view.Id, token); + } + }); + + /// Starts a run-scoped endpoint on the transport of the load endpoint. The cleanup stops it if the check did not. + async Task StartEndpoint(SmokeContext ctx, string name, Action? configure, CancellationToken ct) + { + var endpoint = await SmokeEndpoint.Start(name, config => NServiceBusEndpointExtensions.ConfigureTransport(config, configuration), configure, observations, options.Value.ErrorQueueName, ct); + ctx.OnEndpointStop(token => endpoint.StopAsync(token)); + return endpoint; + } + + async Task> EndpointStatus(string endpoint, string expected, CancellationToken ct) + { + var view = (await api.GetEndpoints(ct)).FirstOrDefault(e => e.Name == endpoint); + var status = view?.HeartbeatInformation?.ReportedStatus; + return view is { MonitorHeartbeat: true } && string.Equals(status, expected, StringComparison.OrdinalIgnoreCase) + ? PollResult.Done(true) + : PollResult.Waiting(view is null ? $"endpoint {endpoint} is not listed" : $"reported_status is '{status}', monitor_heartbeat is {view.MonitorHeartbeat}"); + } + + async Task AuditIngestionFulltext(SmokeContext ctx, CancellationToken ct) + { + await RequireAuditInstance(ct); + var token = Token("smokeaudit"); + var messageId = Guid.NewGuid().ToString(); + await SendSmoke(ctx, new SmokeMessage { RunId = ctx.RunId, Marker = messageId, Note = $"full text {token}" }, messageId, ct: ct); + + var audited = await ctx.WaitFor("the audited message to be found by search", async _ => + { + var result = await api.SearchMessages(token, ct); + var match = result.Value.FirstOrDefault(m => m.MessageId == messageId); + return match is not null ? PollResult.Done(match) : PollResult.Waiting(Describe(result, $"{result.Value.Count} results for '{token}', none with message id {messageId}")); + }, ct); + + if (!string.Equals(audited.Status, "successful", StringComparison.OrdinalIgnoreCase)) + { + throw new SmokeCheckFailedException($"The audited message has status '{audited.Status}', expected successful"); + } + + var body = await api.GetMessageBody(audited, ct); + if (!body.Contains(token, StringComparison.Ordinal)) + { + throw new SmokeCheckFailedException($"The stored body of audited message {audited.Id} does not contain '{token}'"); + } + + ctx.Detail = $"Message {messageId} was found by searching '{token}' and its body contains the word."; + } + + async Task FanOutConversation(SmokeContext ctx, CancellationToken ct) + { + await RequireAuditInstance(ct); + var conversationId = Guid.NewGuid().ToString(); + var rootId = Guid.NewGuid().ToString(); + var expected = (1 << (SmokeFanOutHandler.Levels + 1)) - 1; + await SendSmoke(ctx, new SmokeFanOutMessage(), rootId, send => send.SetHeader(Headers.ConversationId, conversationId), ct: ct); + + var messages = await ctx.WaitFor($"{expected} audited messages in the conversation", async _ => + { + var result = await api.GetConversation(conversationId, ct); + return result.Value.Count >= expected ? PollResult.Done(result.Value) : PollResult.Waiting>(Describe(result, $"{result.Value.Count} messages")); + }, ct); + + var ids = messages.Select(m => m.MessageId).ToHashSet(); + var parentOf = messages.ToDictionary(m => m.MessageId, m => m.Header(Headers.RelatedTo)); + var problems = new List(); + if (messages.Count != expected) + { + problems.Add($"expected {expected} messages, found {messages.Count}"); + } + + if (!parentOf.TryGetValue(rootId, out var rootParent) || rootParent is not null) + { + problems.Add("the root message is missing or has a parent"); + } + + problems.AddRange(parentOf.Where(p => p.Key != rootId && (p.Value is null || !ids.Contains(p.Value))).Select(p => $"message {p.Key} has RelatedTo '{p.Value}' that is not in the conversation")); + var rootChildren = parentOf.Count(p => p.Value == rootId); + if (rootChildren != 2) + { + problems.Add($"the root has {rootChildren} children, expected 2"); + } + + if (problems.Count > 0) + { + throw new SmokeCheckFailedException($"Conversation {conversationId} is wrong: {string.Join("; ", problems)}"); + } + + ctx.Detail = $"Conversation {conversationId} has {messages.Count} messages, each linked to its parent."; + } + + async Task SagaAudit(SmokeContext ctx, CancellationToken ct) + { + await RequireAuditInstance(ct); + var correlationId = Token("smokesaga"); + await session.Send(new SmokeSagaStart { CorrelationId = correlationId }, RouteHere(ctx.RunId), ct); + + var sagaId = await ctx.WaitFor("the audited saga start message with its saga id", async _ => + { + var result = await api.SearchMessages(correlationId, ct); + var saga = result.Value.Select(m => m.InvokedSagas?.FirstOrDefault()).FirstOrDefault(s => s is not null); + return saga is not null ? PollResult.Done(saga) : PollResult.Waiting(Describe(result, $"{result.Value.Count} results for '{correlationId}', none with an invoked saga")); + }, ct); + + var history = await ctx.WaitFor("three saga state changes", async _ => + { + var result = await api.GetSaga(sagaId.SagaId, ct); + var changes = result.Value?.Changes.Count ?? 0; + return changes >= 3 ? PollResult.Done(result.Value!) : PollResult.Waiting(Describe(result, $"{changes} changes")); + }, ct); + + var statuses = history.Changes.OrderBy(c => c.FinishTime).Select(c => c.Status.ToLowerInvariant()).ToArray(); + if (!statuses.SequenceEqual(["new", "updated", "completed"])) + { + throw new SmokeCheckFailedException($"Saga {sagaId.SagaId} has state changes [{string.Join(", ", statuses)}], expected [new, updated, completed]"); + } + + ctx.Detail = $"Saga {sagaId.SagaId} ({history.SagaType}) recorded new, updated and completed."; + } + + async Task MonitoringData(SmokeContext ctx, CancellationToken ct) + { + var name = $"TestingTool.Smoke.{ctx.RunId}"; + ctx.OnCleanup(async token => + { + // The instance ids are the ones monitoring reports for the endpoint, after the host stopped and reports no more. + var reported = (await monitoring.GetMonitoredEndpoints(token)).FirstOrDefault(e => e.Name == name); + foreach (var instanceId in reported?.EndpointInstanceIds ?? []) + { + await monitoring.DeleteInstance(name, instanceId, token); + } + }); + + var endpoint = await StartEndpoint(ctx, name, config => config.EnableMetrics().SendMetricDataToServiceControl(options.Value.MonitoringQueueName, TimeSpan.FromSeconds(2)), ct); + for (var i = 0; i < 3; i++) + { + await SendSmoke(ctx, new SmokeMessage { RunId = ctx.RunId, Marker = $"{ctx.RunId}-monitoring-{i}", Note = "monitoring", DelayMilliseconds = 100 }, destination: endpoint.MainAddress, ct: ct); + } + + var average = await ctx.WaitFor("monitoring to report processing time for the endpoint", async token => + { + var found = (await monitoring.GetMonitoredEndpoints(token)).FirstOrDefault(e => e.Name == name); + var value = found?.Metrics.FirstOrDefault(m => string.Equals(m.Key, "processingTime", StringComparison.OrdinalIgnoreCase)).Value?.Average; + return value > 0 ? PollResult.Done(value.Value) : PollResult.Waiting(found is null ? $"endpoint {name} is not listed" : "processingTime has no average yet"); + }, ct); + + ctx.Detail = $"Endpoint {name} reported an average processing time of {average:0.#} ms with the NServiceBus.Metrics.ServiceControl plugin."; + } + + async Task IntegrationEvent(SmokeContext ctx, CancellationToken ct) + { + await session.Subscribe(ct); + ctx.OnCleanup(token => session.Unsubscribe(token)); + + var failures = await FailMessages(ctx, "event", 1, ct: ct); + var failed = (await WaitForFailures(ctx, failures, ct)).Messages[0]; + var eventFailedId = await ctx.WaitFor( + "the MessageFailed event (the instance that ingests errors needs SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING=true)", + _ => Task.FromResult(observations.FindFailureEvent(failures.MessageIds[0]) is { } id ? PollResult.Done(id) : PollResult.Waiting($"no event for message id {failures.MessageIds[0]}")), + ct); + + if (eventFailedId != failed.Id) + { + throw new SmokeCheckFailedException($"The MessageFailed event carries failed message id {eventFailedId}, the API lists {failed.Id}"); + } + + ctx.Detail = $"MessageFailed was received for failed message {failed.Id}."; + } + + async Task RetrySingle(SmokeContext ctx, CancellationToken ct) + { + var failures = await FailMessages(ctx, "retry-single", 2, ct: ct); + var group = await WaitForFailures(ctx, failures, ct); + failures.Markers.ToList().ForEach(observations.Release); + + var retried = group.Messages[0]; + var untouched = group.Messages[1]; + await api.RetryMessage(retried.Id, ct); + await WaitUntilRetried(ctx, retried, failures.MarkerOf(retried), ct); + + var other = await api.FindFailedMessage(untouched.Id, ct); + if (!string.Equals(other?.Status, "unresolved", StringComparison.OrdinalIgnoreCase) || observations.FindHandled(failures.MarkerOf(untouched)) is not null) + { + throw new SmokeCheckFailedException($"Retrying one message also acted on its sibling {untouched.Id}: status '{other?.Status}'"); + } + + ctx.Detail = $"Message {retried.Id} was handled and resolved. Its sibling {untouched.Id} stayed unresolved."; + } + + async Task RetryGroup(SmokeContext ctx, CancellationToken ct) + { + var failures = await FailMessages(ctx, "retry-group", 3, ct: ct); + var group = await WaitForFailures(ctx, failures, ct); + failures.Markers.ToList().ForEach(observations.Release); + + await api.RetryGroup(group.GroupId, ct); + foreach (var message in group.Messages) + { + await WaitUntilRetried(ctx, message, failures.MarkerOf(message), ct); + } + + ctx.Detail = $"All {group.Messages.Count} messages of group {group.GroupId} were handled and resolved."; + } + + async Task EditAndRetry(SmokeContext ctx, CancellationToken ct) + { + var failures = await FailMessages(ctx, "edit", 1, ct: ct); + var failed = (await WaitForFailures(ctx, failures, ct)).Messages[0]; + var detail = await api.FindFailedMessage(failed.Id, ct) ?? throw new SmokeCheckFailedException($"Failed message {failed.Id} disappeared"); + + var token = Token("smokeedit"); + var editedMarker = $"{failures.MarkerOf(failed)}-edited"; + var body = JsonSerializer.Serialize(new SmokeMessage { RunId = ctx.RunId, Marker = editedMarker, Note = $"edited {token}", Fail = false }); + var accepted = await api.EditMessage(failed.Id, body, new Dictionary(detail.ProcessingAttempts[^1].Headers), ct); + if (!accepted) + { + throw new SmokeCheckFailedException($"ServiceControl ignored the edit of {failed.Id} (edit_ignored)"); + } + + var handled = await ctx.WaitFor("the edited message to be handled", _ => + Task.FromResult(observations.FindHandled(editedMarker) is { } h ? PollResult.Done(h) : PollResult.Waiting("the edited message has not arrived")), ct); + + if (handled.EditOf != failed.Id || !handled.Note.Contains(token, StringComparison.Ordinal)) + { + throw new SmokeCheckFailedException($"The edited message arrived with EditOf '{handled.EditOf}' and note '{handled.Note}', expected EditOf {failed.Id} and the edited text"); + } + + ctx.Detail = $"The edited body of {failed.Id} arrived with ServiceControl.EditOf and the edited text, and no longer failed."; + } + + async Task RetryThroughRedirect(SmokeContext ctx, CancellationToken ct) + { + var sourceName = $"TestingTool.Smoke.{ctx.RunId}.Source"; + var targetName = $"TestingTool.Smoke.{ctx.RunId}.Target"; + // The failure that Source reports makes ServiceControl save an endpoint record for it. + DeleteEndpointRecords(ctx, sourceName, targetName); + var source = await StartEndpoint(ctx, sourceName, null, ct); + var target = await StartEndpoint(ctx, targetName, null, ct); + var from = source.MainAddress; + var to = target.MainAddress; + + var failures = await FailMessages(ctx, "redirect", 1, source.MainAddress, ct); + var failed = (await WaitForFailures(ctx, failures, ct)).Messages[0]; + if (failed.QueueAddress != from) + { + throw new SmokeCheckFailedException($"The failed message has queue '{failed.QueueAddress}', expected the source address '{from}'"); + } + + var marker = failures.MarkerOf(failed); + observations.Release(marker); + + ctx.OnCleanup(async token => + { + foreach (var redirect in (await api.GetRedirects(token)).Where(r => r.FromPhysicalAddress == from)) + { + await api.DeleteRedirect(redirect.MessageRedirectId, token); + } + }); + + await api.CreateRedirect(from, to, ct); + var listed = await ctx.WaitFor("the redirect to be listed", async token => + { + var found = (await api.GetRedirects(token)).FirstOrDefault(r => r.FromPhysicalAddress == from && r.ToPhysicalAddress == to); + return found is not null ? PollResult.Done(found) : PollResult.Waiting($"no redirect from {from} to {to}"); + }, ct); + + await api.RetryMessage(failed.Id, ct); + await WaitUntilRetried(ctx, failed, marker, ct); + RequireHandledBy(observations.FindHandled(marker), target.Name, source.Name); + + await api.DeleteRedirect(listed.MessageRedirectId, ct); + var remaining = (await api.GetRedirects(ct)).Count(r => r.FromPhysicalAddress == from); + if (remaining != 0) + { + throw new SmokeCheckFailedException($"The redirect from {from} is still listed after DELETE"); + } + + ctx.Detail = $"A message that failed in {source.Name} ({from}) was retried through a redirect to {target.Name} ({to}), handled there and resolved. The redirect was removed."; + } + + /// A retry that the source handled itself means the redirect did nothing, so only the target passes. + public static void RequireHandledBy(SmokeObservations.HandledMessage? handled, string target, string source) + { + if (handled?.Endpoint != target) + { + throw new SmokeCheckFailedException($"The retried message was handled by '{handled?.Endpoint ?? "no endpoint"}', expected the redirect target '{target}' and not the source '{source}'"); + } + } + + // --- Shared steps --- + + sealed record Failures(string RunId, string ExceptionType, IReadOnlyList MessageIds, IReadOnlyList Markers) + { + public string MarkerOf(FailedMessageView view) => Markers[MessageIds.ToList().IndexOf(view.MessageId)]; + } + + sealed record FailureGroup(string GroupId, IReadOnlyList Messages); + + /// + /// Sends failing messages that ServiceControl groups under an exception type unique to this check of + /// this run. The group therefore holds only these messages, so a group retry cannot touch anything else. + /// + async Task FailMessages(SmokeContext ctx, string checkId, int count, string? destination = null, CancellationToken ct = default) + { + var exceptionType = $"TestingTool.Smoke.Failure_{ctx.RunId}_{checkId}".Replace('-', '_'); + var messageIds = new List(); + var markers = new List(); + var failures = new Failures(ctx.RunId, exceptionType, messageIds, markers); + ctx.OnCleanup(token => ArchiveLeftovers(failures, token)); + + for (var i = 0; i < count; i++) + { + var messageId = Guid.NewGuid().ToString(); + var marker = $"{ctx.RunId}-{checkId}-{i}"; + messageIds.Add(messageId); + markers.Add(marker); + await SendSmoke(ctx, new SmokeMessage + { + RunId = ctx.RunId, + Marker = marker, + Fail = true, + Note = checkId, + FailureType = exceptionType + }, messageId, destination: destination, ct: ct); + } + + return failures; + } + + async Task WaitForFailures(SmokeContext ctx, Failures failures, CancellationToken ct) + { + var expected = failures.MessageIds.Count; + return await ctx.WaitFor($"{expected} failed message(s) in the group for {failures.ExceptionType}", async token => + { + var group = (await api.GetGroups(token)).FirstOrDefault(g => g.Title.StartsWith(failures.ExceptionType + ":", StringComparison.Ordinal)); + if (group is null) + { + return PollResult.Waiting("the group does not exist yet"); + } + + var mine = (await api.GetGroupErrors(group.Id, token)).Where(m => failures.MessageIds.Contains(m.MessageId)).ToList(); + return mine.Count == expected && mine.All(m => string.Equals(m.Status, "unresolved", StringComparison.OrdinalIgnoreCase)) + ? PollResult.Done(new FailureGroup(group.Id, mine)) + : PollResult.Waiting($"group {group.Id} lists {mine.Count} of the run's messages: [{string.Join(", ", mine.Select(m => m.Status))}]"); + }, ct); + } + + Task WaitUntilRetried(SmokeContext ctx, FailedMessageView message, string marker, CancellationToken ct) => + ctx.WaitFor($"failed message {message.Id} to be handled and resolved", async token => + { + var handled = observations.FindHandled(marker) is not null; + var detail = await api.FindFailedMessage(message.Id, token); + return handled && string.Equals(detail?.Status, "resolved", StringComparison.OrdinalIgnoreCase) + ? PollResult.Done(true) + : PollResult.Waiting($"handled by the endpoint: {handled}, status: {detail?.Status}"); + }, ct); + + async Task ArchiveLeftovers(Failures failures, CancellationToken ct) + { + var group = (await api.GetGroups(ct)).FirstOrDefault(g => g.Title.StartsWith(failures.ExceptionType + ":", StringComparison.Ordinal)); + if (group is null) + { + return; + } + + var leftovers = (await api.GetGroupErrors(group.Id, ct)) + .Where(m => failures.MessageIds.Contains(m.MessageId) && string.Equals(m.Status, "unresolved", StringComparison.OrdinalIgnoreCase)) + .Select(m => m.Id) + .ToList(); + if (leftovers.Count > 0) + { + await api.ArchiveMessages(leftovers, ct); + } + } + + async Task RequireAuditInstance(CancellationToken ct) + { + var remotes = await api.GetRemotes(ct); + if (remotes.Count == 0) + { + throw new SmokeCheckFailedException("The primary instance has no remote audit instance, so it cannot return audit data. Start the AppHost with --audit-instances 1."); + } + + var offline = remotes.Where(r => !string.Equals(r.Status, "online", StringComparison.OrdinalIgnoreCase)).ToList(); + if (offline.Count > 0) + { + throw new SmokeCheckFailedException($"Remote instance(s) not online: {string.Join(", ", offline.Select(r => $"{r.ApiUri} is {r.Status}"))}"); + } + } + + static string Describe(Audited result, string observed) => + result.Incomplete is null ? observed : $"{observed}; the primary reports incomplete results from {result.Incomplete}"; + + static string Token(string prefix) => prefix + Guid.NewGuid().ToString("N")[..10]; + + static SendOptions RouteHere(string runId) + { + var send = new SendOptions(); + send.RouteToThisEndpoint(); + send.SetHeader(SmokeHeaders.RunId, runId); + return send; + } + + Task SendSmoke(SmokeContext ctx, object message, string? messageId = null, Action? configure = null, string? destination = null, CancellationToken ct = default) + { + var send = RouteHere(ctx.RunId); + if (destination is not null) + { + send = new SendOptions(); + send.SetDestination(destination); + send.SetHeader(SmokeHeaders.RunId, ctx.RunId); + } + + if (messageId is not null) + { + send.SetMessageId(messageId); + } + + configure?.Invoke(send); + return session.Send(message, send, ct); + } +} diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeEndpoint.cs b/tools/testing-tool/TestingTool/Smoke/SmokeEndpoint.cs new file mode 100644 index 0000000000..1a7cc2523d --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeEndpoint.cs @@ -0,0 +1,124 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using NServiceBus; + +namespace TestingTool.Smoke; + +/// The name of the endpoint a handler runs in, so a check can prove which endpoint handled a message. +public sealed record SmokeEndpointIdentity(string Name); + +/// +/// A real NServiceBus endpoint that lives for one smoke check, in its own host next to the load endpoint. +/// Stopping it releases its connections and stops its plugins. The queues or tables it created stay in +/// the transport. +/// +public sealed class SmokeEndpoint : IAsyncDisposable +{ + IHost? host; + + SmokeEndpoint(IHost host, string name, string mainAddress) + { + this.host = host; + Name = name; + MainAddress = mainAddress; + Session = host.Services.GetRequiredService(); + } + + public string Name { get; } + + /// The input address the transport reports, for example with the schema and catalog of SQL Server. + public string MainAddress { get; } + + public IMessageSession Session { get; } + + /// Production passes so the endpoint uses the transport of the load endpoint. + public static async Task Start( + string name, + Action configureTransport, + Action? configure, + SmokeObservations observations, + string errorQueue, + CancellationToken ct) + { + var config = new EndpointConfiguration(name); + config.AssemblyScanner().Disable = true; + config.AddHandler(); + config.UseSerialization(); + config.SendFailedMessagesTo(errorQueue); + var recoverability = config.Recoverability(); + recoverability.Immediate(immediate => immediate.NumberOfRetries(0)); + recoverability.Delayed(delayed => delayed.NumberOfRetries(0)); + recoverability.Failed(failed => failed.HeaderCustomization(SmokeHeaders.CustomizeFailure)); + config.EnableInstallers(); + configureTransport(config); + configure?.Invoke(config); + + var builder = Host.CreateApplicationBuilder(); + builder.Logging.SetMinimumLevel(LogLevel.Critical); + builder.Services.AddSingleton(observations); + builder.Services.AddSingleton(new SmokeEndpointIdentity(name)); + builder.Services.AddNServiceBusEndpoint(config); + + var host = builder.Build(); + try + { + await host.StartAsync(ct); + return new SmokeEndpoint(host, name, host.Services.GetRequiredService().MainReceiveAddress); + } + catch (Exception ex) + { + await StopPartiallyStarted(host); + if (ex is OperationCanceledException) + { + throw; + } + + throw new SmokeCheckFailedException($"Endpoint {name} could not start: {ex.Message}"); + } + } + + /// + /// A host whose start failed or was canceled may have started some of its services, so it is stopped + /// before it is disposed. The stop is bounded, and its own failure never replaces the startup error. + /// + static async Task StopPartiallyStarted(IHost host) + { + try + { + using var limit = new CancellationTokenSource(PartialStartStopTimeout); + await host.StopAsync(limit.Token); + } + catch + { + // The startup error is the one to report. + } + finally + { + host.Dispose(); + } + } + + static readonly TimeSpan PartialStartStopTimeout = TimeSpan.FromSeconds(10); + + /// Stops and disposes the host. Calling it again does nothing. + public async Task StopAsync(CancellationToken ct) + { + var current = Interlocked.Exchange(ref host, null); + if (current is null) + { + return; + } + + try + { + await current.StopAsync(ct); + } + finally + { + current.Dispose(); + } + } + + public async ValueTask DisposeAsync() => await StopAsync(CancellationToken.None); +} diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeMessages.cs b/tools/testing-tool/TestingTool/Smoke/SmokeMessages.cs new file mode 100644 index 0000000000..ad92dfc383 --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeMessages.cs @@ -0,0 +1,193 @@ +using System.Collections.Concurrent; +using NServiceBus; + +namespace TestingTool.Smoke; + +/// +/// The message every smoke check sends. is decided by the sender, so a retry or an +/// edit that clears it recovers the message, which the hash-based load scenarios cannot do. +/// +public sealed class SmokeMessage +{ + public string RunId { get; set; } = ""; + + /// Unique per message. lets a failing message succeed on its next attempt. + public string Marker { get; set; } = ""; + + public string Note { get; set; } = ""; + + public bool Fail { get; set; } + + /// The exception type ServiceControl groups the failure under. It makes the group unique to one check of one run. + public string FailureType { get; set; } = ""; + + /// Time the handler waits before it finishes, so the processing time that metrics report is above zero. + public int DelayMilliseconds { get; set; } +} + +public sealed class SmokeFanOutMessage +{ + public int Level { get; set; } +} + +public sealed class SmokeSagaStart +{ + public string CorrelationId { get; set; } = ""; +} + +public sealed class SmokeSagaStep +{ + public string CorrelationId { get; set; } = ""; +} + +public sealed class SmokeSagaFinish +{ + public string CorrelationId { get; set; } = ""; +} + +/// +/// The failure of a . NServiceBus offers headers customization only on the fault +/// headers, not on the message headers, so the exception message carries what needs. +/// +public sealed class SmokeFailureException(string marker, string failureType) + : Exception($"Smoke message {marker} was told to fail{Separator}{failureType}") +{ + const string Separator = "|"; + + public static bool TryDecode(string exceptionMessage, out string failureType) + { + var parts = exceptionMessage.Split(Separator); + var isSmokeFailure = parts.Length == 2 && parts[0].StartsWith("Smoke message ", StringComparison.Ordinal); + failureType = isSmokeFailure ? parts[1] : ""; + return isSmokeFailure; + } +} + +public static class SmokeHeaders +{ + public const string RunId = "TestingTool.Smoke.RunId"; + + public const string EditOf = "ServiceControl.EditOf"; + + /// Rewrites the exception type in the fault headers of smoke messages, so ServiceControl groups each check separately. + public static void CustomizeFailure(Dictionary faultHeaders) + { + if (faultHeaders.TryGetValue("NServiceBus.ExceptionInfo.Message", out var message) && SmokeFailureException.TryDecode(message, out var failureType)) + { + faultHeaders["NServiceBus.ExceptionInfo.ExceptionType"] = failureType; + } + } +} + +/// What the smoke handlers saw, keyed by message marker or message id. Entries are tiny and live as long as the process. +public sealed class SmokeObservations +{ + readonly ConcurrentDictionary released = new(); + readonly ConcurrentDictionary handled = new(); + readonly ConcurrentDictionary failureEvents = new(); + + public void Release(string marker) => released[marker] = 0; + + public bool IsReleased(string marker) => released.ContainsKey(marker); + + public void RecordHandled(string marker, string? editOf, string note, string endpoint) => handled[marker] = new HandledMessage(editOf, note, endpoint); + + public HandledMessage? FindHandled(string marker) => handled.GetValueOrDefault(marker); + + public void RecordFailureEvent(string messageId, string failedMessageId) => failureEvents[messageId] = failedMessageId; + + /// The failed message id carried by the MessageFailed event for this message id, or null if none arrived. + public string? FindFailureEvent(string messageId) => failureEvents.GetValueOrDefault(messageId); + + public sealed record HandledMessage(string? EditOf, string Note, string Endpoint); +} + +public sealed class SmokeMessageHandler(SmokeObservations observations, SmokeEndpointIdentity identity) : IHandleMessages +{ + public async Task Handle(SmokeMessage message, IMessageHandlerContext context) + { + if (message.DelayMilliseconds > 0) + { + await Task.Delay(message.DelayMilliseconds, context.CancellationToken); + } + + Process(observations, message, context.MessageHeaders.GetValueOrDefault(SmokeHeaders.EditOf), identity.Name); + } + + public static void Process(SmokeObservations observations, SmokeMessage message, string? editOf, string endpoint) + { + if (message.Fail && !observations.IsReleased(message.Marker)) + { + Fail(message); + } + + observations.RecordHandled(message.Marker, editOf, message.Note, endpoint); + } + + // A dedicated method so the first stack frame ServiceControl groups on never matches the load scenarios. + static void Fail(SmokeMessage message) => + throw new SmokeFailureException(message.Marker, message.FailureType); +} + +/// Sends two children per level, so the audit data holds a conversation tree with parent links. +public sealed class SmokeFanOutHandler : IHandleMessages +{ + public const int Levels = 2; + + public async Task Handle(SmokeFanOutMessage message, IMessageHandlerContext context) + { + if (message.Level >= Levels) + { + return; + } + + for (var i = 0; i < 2; i++) + { + await context.SendLocal(new SmokeFanOutMessage { Level = message.Level + 1 }); + } + } +} + +public sealed class SmokeSaga : Saga, + IAmStartedByMessages, + IHandleMessages, + IHandleMessages +{ + protected override void ConfigureHowToFindSaga(SagaPropertyMapper mapper) => + mapper.MapSaga(saga => saga.CorrelationId) + .ToMessage(m => m.CorrelationId) + .ToMessage(m => m.CorrelationId) + .ToMessage(m => m.CorrelationId); + + // Each step sends the next one to itself, so the three state changes happen strictly in order. + public Task Handle(SmokeSagaStart message, IMessageHandlerContext context) => + context.SendLocal(new SmokeSagaStep { CorrelationId = message.CorrelationId }); + + public Task Handle(SmokeSagaStep message, IMessageHandlerContext context) => + context.SendLocal(new SmokeSagaFinish { CorrelationId = message.CorrelationId }); + + public Task Handle(SmokeSagaFinish message, IMessageHandlerContext context) + { + MarkAsComplete(); + return Task.CompletedTask; + } +} + +public sealed class SmokeSagaData : ContainSagaData +{ + public string CorrelationId { get; set; } = ""; +} + +/// Records the MessageFailed integration events that ServiceControl publishes to this endpoint. +public sealed class MessageFailedEventHandler(SmokeObservations observations) : IHandleMessages +{ + public Task Handle(ServiceControl.Contracts.MessageFailed message, IMessageHandlerContext context) + { + if (message.MessageDetails?.Headers?.TryGetValue(SmokeHeaders.RunId, out _) == true) + { + observations.RecordFailureEvent(message.MessageDetails.MessageId, message.FailedMessageId); + } + + return Task.CompletedTask; + } +} diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeRunner.cs b/tools/testing-tool/TestingTool/Smoke/SmokeRunner.cs new file mode 100644 index 0000000000..79c270b9bd --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeRunner.cs @@ -0,0 +1,232 @@ +using Microsoft.Extensions.Logging; +using TestingTool.Contracts; + +namespace TestingTool.Smoke; + +/// +/// Runs the smoke checklist once at a time, sequentially. A failed check does not stop later checks. +/// The state of the current or last run stays in memory so the UI can reload and show it. +/// +public sealed class SmokeRunner( + IReadOnlyList checks, + Func findStartConflict, + TimeSpan defaultCheckTimeout, + TimeSpan cleanupTimeout, + TimeSpan pollInterval, + TimeSpan pollTimeout, + ILogger logger) +{ + readonly Lock gate = new(); + readonly CheckState[] states = [.. checks.Select(c => new CheckState(c))]; + RunState? run; + + public bool TryStart(out string? error) + { + lock (gate) + { + if (run is { FinishedAt: null }) + { + error = "A smoke run is already in progress"; + return false; + } + + if (findStartConflict() is { } conflict) + { + error = conflict; + return false; + } + + foreach (var state in states) + { + state.Reset(); + } + + var current = new RunState($"smoke-{Guid.NewGuid():N}"[..14]); + run = current; + current.Completion = Task.Run(() => ExecuteAsync(current)); + } + + error = null; + return true; + } + + public void Stop() + { + lock (gate) + { + if (run is { FinishedAt: null } current) + { + current.Cancellation.Cancel(); + } + } + } + + /// Completes when the current run, if any, has finished and cleaned up. + public Task WaitForCompletionAsync() + { + lock (gate) + { + return run?.Completion ?? Task.CompletedTask; + } + } + + public SmokeRunInfo GetSnapshot() + { + lock (gate) + { + return new SmokeRunInfo + { + RunId = run?.RunId, + Running = run is { FinishedAt: null }, + StartedAt = run?.StartedAt.ToString("O"), + FinishedAt = run?.FinishedAt?.ToString("O"), + Checks = [.. states.Select(s => s.ToInfo())] + }; + } + } + + async Task ExecuteAsync(RunState current) + { + try + { + foreach (var state in states.Where(s => !s.Check.IsManual)) + { + if (current.Cancellation.IsCancellationRequested) + { + Update(state, SmokeCheckStatus.Canceled, "The run was stopped before this check started"); + continue; + } + + await RunCheckAsync(current, state); + } + } + finally + { + lock (gate) + { + current.FinishedAt = DateTimeOffset.UtcNow; + } + + current.Cancellation.Dispose(); + } + } + + async Task RunCheckAsync(RunState current, CheckState state) + { + Update(state, SmokeCheckStatus.Running, null); + var started = DateTimeOffset.UtcNow; + var context = new SmokeContext(current.RunId, pollInterval, pollTimeout); + var timeout = state.Check.Timeout ?? defaultCheckTimeout; + string? cleanupProblem = null; + + SmokeCheckStatus status; + string? detail; + try + { + using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(current.Cancellation.Token); + timeoutSource.CancelAfter(timeout); + try + { + await state.Check.Run!(context, timeoutSource.Token); + (status, detail) = (SmokeCheckStatus.Passed, context.Detail); + } + catch (OperationCanceledException) when (current.Cancellation.IsCancellationRequested) + { + (status, detail) = (SmokeCheckStatus.Canceled, "The run was stopped while this check was running"); + } + catch (OperationCanceledException) when (timeoutSource.IsCancellationRequested) + { + (status, detail) = (SmokeCheckStatus.Failed, $"The check did not finish within {timeout.TotalSeconds:0.#}s"); + } + } + catch (SmokeCheckFailedException ex) + { + (status, detail) = (SmokeCheckStatus.Failed, ex.Message); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Smoke check {Check} failed with an unexpected error", state.Check.Id); + (status, detail) = (SmokeCheckStatus.Failed, $"{ex.GetType().Name}: {ex.Message}"); + } + finally + { + cleanupProblem = await RunCleanupsAsync(context); + } + + if (cleanupProblem is not null) + { + detail = string.IsNullOrEmpty(detail) ? cleanupProblem : $"{detail} {cleanupProblem}"; + } + + Update(state, status, detail, DateTimeOffset.UtcNow - started); + } + + async Task RunCleanupsAsync(SmokeContext context) + { + var failures = new List(); + await RunAll(context.EndpointStops, failures); + await RunAll(context.Cleanups, failures); + return failures.Count == 0 ? null : $"Cleanup failed, leftover data may remain: {string.Join("; ", failures)}"; + } + + // Every action runs in reverse order of registration with the token of one shared time limit, and is awaited to the end. + async Task RunAll(IReadOnlyList> actions, List failures) + { + using var limit = new CancellationTokenSource(cleanupTimeout); + foreach (var action in actions.Reverse()) + { + try + { + await action(limit.Token); + } + catch (OperationCanceledException) when (limit.IsCancellationRequested) + { + failures.Add($"timed out after {cleanupTimeout.TotalSeconds:0.#}s"); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Smoke cleanup failed"); + failures.Add(ex.Message); + } + } + } + + void Update(CheckState state, SmokeCheckStatus status, string? detail, TimeSpan? duration = null) + { + lock (gate) + { + state.Status = status; + state.Detail = detail; + state.Duration = duration; + } + } + + sealed class RunState(string runId) + { + public string RunId { get; } = runId; + public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow; + public DateTimeOffset? FinishedAt { get; set; } + public CancellationTokenSource Cancellation { get; } = new(); + public Task Completion { get; set; } = Task.CompletedTask; + } + + sealed class CheckState(SmokeCheck check) + { + public SmokeCheck Check { get; } = check; + public SmokeCheckStatus Status { get; set; } = check.IsManual ? SmokeCheckStatus.Manual : SmokeCheckStatus.Pending; + public string? Detail { get; set; } + public TimeSpan? Duration { get; set; } + + public void Reset() => (Status, Detail, Duration) = (Check.IsManual ? SmokeCheckStatus.Manual : SmokeCheckStatus.Pending, null, null); + + public SmokeCheckInfo ToInfo() => new() + { + Id = Check.Id, + Title = Check.Title, + Description = Check.Description, + Status = Status, + Detail = Detail, + DurationSeconds = Duration is { } d ? Math.Round(d.TotalSeconds, 1) : null + }; + } +} diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeRunnerLifecycle.cs b/tools/testing-tool/TestingTool/Smoke/SmokeRunnerLifecycle.cs new file mode 100644 index 0000000000..d51e203c7c --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeRunnerLifecycle.cs @@ -0,0 +1,21 @@ +namespace TestingTool.Smoke; + +/// Stops a running smoke run on shutdown and waits for its cleanup to finish. +public sealed class SmokeRunnerLifecycle(SmokeRunner runner) : IHostedService +{ + public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + public async Task StopAsync(CancellationToken cancellationToken) + { + runner.Stop(); + await runner.WaitForCompletionAsync().WaitAsync(cancellationToken); + } +} + +/// The jobs that act on every failed message group, so they must not run together with a smoke run. +public static class SmokeJobConflicts +{ + static readonly HashSet Names = new(["retry", "archive", "retention-sweep"], StringComparer.OrdinalIgnoreCase); + + public static bool Conflicts(string jobName) => Names.Contains(jobName); +} diff --git a/tools/testing-tool/TestingTool/TestingTool.csproj b/tools/testing-tool/TestingTool/TestingTool.csproj index 93fe9978df..f20fd1c1f1 100644 --- a/tools/testing-tool/TestingTool/TestingTool.csproj +++ b/tools/testing-tool/TestingTool/TestingTool.csproj @@ -12,21 +12,24 @@ - + - - - - - - + + + + + + + + + - + \ No newline at end of file diff --git a/tools/testing-tool/TestingTool/TestingToolOptions.cs b/tools/testing-tool/TestingTool/TestingToolOptions.cs index 18402e953b..2f0574e67a 100644 --- a/tools/testing-tool/TestingTool/TestingToolOptions.cs +++ b/tools/testing-tool/TestingTool/TestingToolOptions.cs @@ -81,4 +81,16 @@ public sealed class TestingToolOptions /// ServiceControl monitoring instance input queue that endpoint metrics are sent to. public string MonitoringQueueName { get; set; } = "Particular.Monitoring"; -} \ No newline at end of file + + /// Base URL of the ServiceControl.Monitoring instance (e.g. http://monitoring:33633). Only the smoke tests use it. + public string MonitoringApiUrl { get; set; } = "http://localhost:33633"; + + /// Interval between polls of a ServiceControl API while a smoke check waits for an effect. + public TimeSpan SmokePollInterval { get; set; } = TimeSpan.FromSeconds(1); + + /// How long a smoke check waits for one effect before it fails. + public TimeSpan SmokePollTimeout { get; set; } = TimeSpan.FromSeconds(60); + + /// How long one smoke check may run in total, including all of its waits. + public TimeSpan SmokeCheckTimeout { get; set; } = TimeSpan.FromMinutes(3); +} diff --git a/tools/testing-tool/TestingTool/wwwroot/index.html b/tools/testing-tool/TestingTool/wwwroot/index.html index 0aa7f9ac50..dff3c2dd90 100644 --- a/tools/testing-tool/TestingTool/wwwroot/index.html +++ b/tools/testing-tool/TestingTool/wwwroot/index.html @@ -88,6 +88,13 @@ .tab { padding: .5rem 1rem; border: none; background: none; color: var(--muted); cursor: pointer; font-size: .95rem; border-bottom: 2px solid transparent; margin-bottom: -1px; transition: color .15s, border-color .15s; } .tab.active { color: var(--text); border-bottom-color: var(--accent); } .tab:hover { color: var(--text); } + .smoke-row { background: var(--surface); border: 1px solid var(--border); border-left: 3px solid var(--border); border-radius: var(--radius); padding: .6rem .9rem; margin-bottom: .5rem; } + .smoke-row .head { display: flex; justify-content: space-between; gap: 1rem; font-weight: 600; } + .smoke-row .desc, .smoke-row .detail { color: var(--muted); font-size: .85rem; margin-top: .2rem; } + .smoke-row.passed { border-left-color: var(--ok); } .smoke-row.passed .status { color: var(--ok); } + .smoke-row.failed { border-left-color: var(--err); } .smoke-row.failed .status, .smoke-row.failed .detail { color: var(--err); } + .smoke-row.running { border-left-color: var(--warn); } .smoke-row.running .status { color: var(--warn); } + .smoke-row.manual { border-left-style: dashed; } .tab-panel { display: none; } .tab-panel.active { display: block; } .btn { padding: .4rem .9rem; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface-2); color: var(--text); cursor: pointer; font-size: .85rem; transition: opacity .15s; } @@ -195,6 +202,7 @@

🎯 ServiceControl Testing Tool

+ @@ -264,7 +272,7 @@

Direct Audit-Queue Writer

endpoint would have stamped, so the audit instance records endpoints, message types, conversations and processing times. A share of them are whole saga episodes: the three messages that drove a saga through New, Updated and Completed, each followed by the snapshot it produced, linked by the InvokedSagas headers. Needs an audit instance - on SQL Server or PostgreSQL (--audit-instances with --persistence). + on SQL Server or PostgreSQL (--audit-instances with --storage).
Rate (claims/s): @@ -288,6 +296,24 @@

Direct Audit-Queue Writer

+ +
+ +
+

Smoke tests

+ + + + +
+
+ Sends its own messages with a run-specific identifier and checks the effects through the ServiceControl APIs. Run it against a test instance only: it creates failed messages, custom checks, endpoints and a redirect. Cleanup removes temporary check, endpoint and redirect records, and archives unresolved failures; message data remains subject to ServiceControl retention. Rows marked manual are not automated. +
+
+
Loading checks…
+ +
+