-
Notifications
You must be signed in to change notification settings - Fork 51
Report deployment and storage environment data in the usage report #5828
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
johnsimons
wants to merge
1
commit into
master
Choose a base branch
from
john/telemetry
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
140 changes: 140 additions & 0 deletions
140
src/ServiceControl.AcceptanceTests/Licensing/When_reporting_the_environment.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| namespace ServiceControl.AcceptanceTests.Licensing | ||
| { | ||
| using System; | ||
| using System.IO; | ||
| using System.IO.Compression; | ||
| using System.Linq; | ||
| using System.Text.Json; | ||
| using System.Threading.Tasks; | ||
| using AcceptanceTesting; | ||
| using AcceptanceTesting.EndpointTemplates; | ||
| using NServiceBus; | ||
| using NServiceBus.AcceptanceTesting; | ||
| using NServiceBus.Routing; | ||
| using NServiceBus.Transport; | ||
| using NUnit.Framework; | ||
| using Particular.LicensingComponent.Contracts; | ||
| using Particular.LicensingComponent.MonitoringThroughput; | ||
| using Particular.LicensingComponent.Shared; | ||
|
|
||
| class When_reporting_the_environment : AcceptanceTest | ||
| { | ||
| [Test] | ||
| public async Task Should_describe_how_the_instance_is_deployed() | ||
| { | ||
| JsonDocument report = null; | ||
|
|
||
| await Define<Context>() | ||
| .WithEndpoint<MonitoringInstance>() | ||
| .Do("Wait for the throughput data to be recorded", async _ => | ||
| { | ||
| var available = await this.TryGet<ReportGenerationState>( | ||
| "/api/licensing/report/available", state => state.ReportCanBeGenerated); | ||
|
|
||
| return available.HasResult; | ||
| }) | ||
| .Do("Download the report", async _ => | ||
| { | ||
| var archive = await this.DownloadData("/api/licensing/report/file?spVersion=1.2.3"); | ||
|
|
||
| report = ReadReport(archive); | ||
|
|
||
| return true; | ||
| }) | ||
| .Done(_ => true) | ||
| .Run(); | ||
|
|
||
| var data = report.RootElement | ||
| .GetProperty("ReportData") | ||
| .GetProperty("EnvironmentInformation") | ||
| .GetProperty("EnvironmentData") | ||
| .EnumerateObject() | ||
| .ToDictionary(entry => entry.Name, entry => entry.Value.GetString()); | ||
|
|
||
| using (Assert.EnterMultipleScope()) | ||
| { | ||
| Assert.That(data.Keys, Is.SupersetOf(ExpectedKeys)); | ||
|
|
||
| Assert.That(data["Host.Model"], Is.AnyOf("Container", "WindowsService", "Console")); | ||
| Assert.That(data["Persistence.Type"], Is.Not.Empty); | ||
| Assert.That(data["Persistence.BodyStorage.Type"], Is.Not.Empty); | ||
| Assert.That(data["Persistence.BodyStorage.Auth"], Is.AnyOf("ManagedIdentity", "SharedKeyOrSas", "IamRole", "StaticCredentials", "NotApplicable")); | ||
| Assert.That(data["Security.Authentication"], Is.AnyOf("Enabled", "Disabled")); | ||
| Assert.That(data["Features.EmailNotifications"], Is.AnyOf("Enabled", "Disabled", "NotConfigured")); | ||
| Assert.That(int.Parse(data["Retention.ErrorHours"]), Is.GreaterThan(0)); | ||
|
|
||
| Assert.That(data.Values, Has.None.Contains(Environment.MachineName), | ||
| "The report must not carry anything that identifies the customer's machine"); | ||
| } | ||
| } | ||
|
|
||
| static readonly string[] ExpectedKeys = | ||
| [ | ||
| "Host.Model", | ||
| "Host.Orchestrator", | ||
| "Host.OSPlatform", | ||
| "Host.OSVersion", | ||
| "Host.Architecture", | ||
| "Host.RuntimeVersion", | ||
| "Host.ProcessorCount", | ||
| "Host.AvailableMemoryGB", | ||
| "Persistence.Type", | ||
| "Persistence.Hosting", | ||
| "Persistence.ServerVersion", | ||
| "Persistence.FullTextSearch", | ||
| "Persistence.BodyStorage.Type", | ||
| "Persistence.BodyStorage.Auth", | ||
| "Security.Authentication", | ||
| "Security.RoleBasedAuthorization", | ||
| "Security.Https", | ||
| "Features.IntegratedServicePulse", | ||
| "Features.MessageEditing", | ||
| "Features.ExternalIntegrationsPublishing", | ||
| "Features.ForwardErrorMessages", | ||
| "Features.EmailNotifications", | ||
| "Retention.ErrorHours", | ||
| "Retention.AuditHours", | ||
| "Retention.EventsHours" | ||
| ]; | ||
|
|
||
| static JsonDocument ReadReport(byte[] archive) | ||
| { | ||
| using var zip = new ZipArchive(new MemoryStream(archive), ZipArchiveMode.Read); | ||
| using var entry = zip.Entries.Single().Open(); | ||
|
|
||
| return JsonDocument.Parse(entry); | ||
| } | ||
|
|
||
| const string SalesEndpoint = "Particular.Sales"; | ||
|
|
||
| class Context : ScenarioContext, ISequenceContext | ||
| { | ||
| public int Step { get; set; } | ||
| } | ||
|
|
||
| class MonitoringInstance : EndpointConfigurationBuilder | ||
| { | ||
| public MonitoringInstance() => | ||
| EndpointSetup<DefaultServerWithoutAudit>(c => c.EnableFeature<ReportThroughput>()); | ||
|
|
||
| class ReportThroughput : DispatchRawMessages<Context> | ||
| { | ||
| protected override TransportOperations CreateMessage(Context context) | ||
| { | ||
| var recorded = new RecordEndpointThroughputData | ||
| { | ||
| StartDateTime = DateTime.UtcNow.AddDays(-1).AddHours(-1), | ||
| EndDateTime = DateTime.UtcNow.AddDays(-1), | ||
| EndpointThroughputData = [new EndpointThroughputData { Name = SalesEndpoint, Throughput = 42 }] | ||
| }; | ||
|
|
||
| var body = JsonSerializer.SerializeToUtf8Bytes(recorded); | ||
| var message = new OutgoingMessage(Guid.NewGuid().ToString(), [], body); | ||
|
|
||
| return new TransportOperations( | ||
| new TransportOperation(message, new UnicastAddressTag(ServiceControlSettings.ServiceControlThroughputDataQueue))); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } |
95 changes: 95 additions & 0 deletions
95
src/ServiceControl.Persistence.EFCore.PostgreSql/PostgreSqlDatabaseHostingProbe.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| namespace ServiceControl.Persistence.EFCore.PostgreSql; | ||
|
|
||
| using System.Data.Common; | ||
| using System.Globalization; | ||
| using Microsoft.EntityFrameworkCore; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Logging; | ||
| using Npgsql; | ||
| using ServiceControl.Persistence; | ||
| using ServiceControl.Persistence.EFCore.DbContexts; | ||
| using ServiceControl.Persistence.EFCore.Infrastructure; | ||
|
|
||
| class PostgreSqlDatabaseHostingProbe(PostgreSqlPersisterSettings settings, IServiceScopeFactory scopeFactory, ILogger<PostgreSqlDatabaseHostingProbe> logger) : IDatabaseHostingProbe | ||
| { | ||
| public string StorageName => "PostgreSQL"; | ||
|
|
||
| public async Task<DatabaseHosting> Probe(CancellationToken cancellationToken = default) | ||
| { | ||
| try | ||
| { | ||
| await using var scope = scopeFactory.CreateAsyncScope(); | ||
| var dbContext = scope.ServiceProvider.GetRequiredService<ServiceControlDbContext>(); | ||
|
|
||
| await using var command = dbContext.Database.GetDbConnection().CreateCommand(); | ||
| command.CommandText = ProbeSql; | ||
| command.CommandTimeout = ProbeTimeoutSeconds; | ||
|
|
||
| await dbContext.Database.OpenConnectionAsync(cancellationToken); | ||
|
|
||
| await using var reader = await command.ExecuteReaderAsync(cancellationToken); | ||
|
|
||
| if (!await reader.ReadAsync(cancellationToken)) | ||
| { | ||
| return HostingFromConnectionString(); | ||
| } | ||
|
|
||
| return new DatabaseHosting(HostingFromRoles(reader), MajorVersion(reader)); | ||
| } | ||
| catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) | ||
| { | ||
| throw; | ||
| } | ||
| catch (Exception e) | ||
| { | ||
| logger.LogDebug(e, "Could not ask PostgreSQL how it is hosted, falling back to the connection string"); | ||
|
|
||
| return HostingFromConnectionString(); | ||
| } | ||
| } | ||
|
|
||
| // PostgreSQL has no equivalent of SQL Server's EngineEdition, but every managed offering creates | ||
| // a distinctive administrative role that a self-hosted server does not have. | ||
| string HostingFromRoles(DbDataReader reader) | ||
| { | ||
| if (reader.GetBoolean(1)) | ||
| { | ||
| return "AzurePostgres"; | ||
| } | ||
|
|
||
| if (reader.GetBoolean(2)) | ||
| { | ||
| return "AwsRds"; | ||
| } | ||
|
|
||
| return reader.GetBoolean(3) ? "GoogleCloudSql" : HostingFromConnectionString().Hosting; | ||
| } | ||
|
|
||
| static string MajorVersion(DbDataReader reader) => | ||
| reader.IsDBNull(0) ? DatabaseHostClassifier.Unknown : (reader.GetInt32(0) / 10000).ToString(CultureInfo.InvariantCulture); | ||
|
|
||
| DatabaseHosting HostingFromConnectionString() | ||
| { | ||
| try | ||
| { | ||
| var host = new NpgsqlConnectionStringBuilder(settings.ConnectionString).Host; | ||
|
|
||
| return new DatabaseHosting(DatabaseHostClassifier.Classify(host), DatabaseHostClassifier.Unknown); | ||
| } | ||
| catch (Exception e) | ||
| { | ||
| logger.LogDebug(e, "Could not classify the configured PostgreSQL host"); | ||
|
|
||
| return DatabaseHosting.Unavailable; | ||
| } | ||
| } | ||
|
|
||
| const string ProbeSql = """ | ||
| SELECT current_setting('server_version_num')::int, | ||
| EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'azure_pg_admin'), | ||
| EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'rds_superuser'), | ||
| EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'cloudsqlsuperuser') | ||
| """; | ||
|
|
||
| const int ProbeTimeoutSeconds = 5; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If the probe query succeeded, and we get to here, and its not azure, aws, or google, is this not evidence that its self hosted?