From 689e29fb1a91655a135062cf51e2b67ca852db71 Mon Sep 17 00:00:00 2001 From: Bervianto Leo Pratama Date: Fri, 27 Nov 2026 21:35:07 +0700 Subject: [PATCH] feat: Refactor to use email template & remove deprecates AppRunner --- ServiceMonitor.AWS/AWSInstance.cs | 62 +++--- ServiceMonitor.AWS/AppRunner.cs | 46 ----- ServiceMonitor.AWS/AssemblyInfo.cs | 3 + ServiceMonitor.AWS/ECR.cs | 186 ++++++++--------- ServiceMonitor.AWS/Ecs.cs | 66 ++++++ ServiceMonitor.AWS/Lambda.cs | 56 +++--- ServiceMonitor.AWS/S3.cs | 43 ++-- ServiceMonitor.AWS/ServiceMonitor.AWS.csproj | 3 +- ServiceMonitor.Cleaner/Program.cs | 15 +- .../ServiceMonitor.Cleaner.csproj | 1 + ServiceMonitor.Cloud/AppRunnerProperty.cs | 6 - ServiceMonitor.Cloud/BasicProperty.cs | 12 -- ServiceMonitor.Cloud/FunctionProperty.cs | 8 - ServiceMonitor.Cloud/IAppRunner.cs | 16 +- ServiceMonitor.Cloud/IBucket.cs | 12 +- ServiceMonitor.Cloud/IContainerService.cs | 11 + ServiceMonitor.Cloud/IFunction.cs | 12 +- ServiceMonitor.Cloud/IImage.cs | 15 +- ServiceMonitor.Cloud/IInstance.cs | 10 +- ServiceMonitor.Cloud/InstanceProperty.cs | 7 - .../Model/AppRunnerProperty.cs | 9 + ServiceMonitor.Cloud/Model/BasicProperty.cs | 11 + ServiceMonitor.Cloud/Model/Cluster.cs | 10 + .../Model/FunctionProperty.cs | 7 + .../Model/InstanceProperty.cs | 6 + ServiceMonitor.Cloud/Model/Service.cs | 6 + ServiceMonitor.Cloud/Model/TagItem.cs | 17 +- ServiceMonitor.Cloud/Model/Task.cs | 6 + .../ServiceMonitor.Cloud.csproj | 1 + .../Pages/AppRunner.razor | 72 ------- ServiceMonitor.Dashboard/Pages/EC2.razor | 2 + ServiceMonitor.Dashboard/Pages/ECR.razor | 2 + ServiceMonitor.Dashboard/Pages/Lambda.razor | 2 + ServiceMonitor.Dashboard/Program.cs | 5 +- .../ServiceMonitor.Dashboard.csproj | 1 + ServiceMonitor.Mailer/MailData.cs | 12 ++ ServiceMonitor.Mailer/Program.cs | 166 ++++------------ ServiceMonitor.Mailer/RegionData.cs | 7 + ServiceMonitor.Mailer/ReportMailer.cs | 99 +++++++++ .../ServiceMonitor.Mailer.csproj | 1 + ServiceMonitor.Test/EcsTests.cs | 67 +++++++ ServiceMonitor.Test/ReportMailerTests.cs | 188 ++++++++++++++++++ .../ServiceMonitor.Test.csproj | 7 + 43 files changed, 770 insertions(+), 524 deletions(-) delete mode 100644 ServiceMonitor.AWS/AppRunner.cs create mode 100644 ServiceMonitor.AWS/AssemblyInfo.cs create mode 100644 ServiceMonitor.AWS/Ecs.cs delete mode 100644 ServiceMonitor.Cloud/AppRunnerProperty.cs delete mode 100644 ServiceMonitor.Cloud/BasicProperty.cs delete mode 100644 ServiceMonitor.Cloud/FunctionProperty.cs create mode 100644 ServiceMonitor.Cloud/IContainerService.cs delete mode 100644 ServiceMonitor.Cloud/InstanceProperty.cs create mode 100644 ServiceMonitor.Cloud/Model/AppRunnerProperty.cs create mode 100644 ServiceMonitor.Cloud/Model/BasicProperty.cs create mode 100644 ServiceMonitor.Cloud/Model/Cluster.cs create mode 100644 ServiceMonitor.Cloud/Model/FunctionProperty.cs create mode 100644 ServiceMonitor.Cloud/Model/InstanceProperty.cs create mode 100644 ServiceMonitor.Cloud/Model/Service.cs create mode 100644 ServiceMonitor.Cloud/Model/Task.cs delete mode 100644 ServiceMonitor.Dashboard/Pages/AppRunner.razor create mode 100644 ServiceMonitor.Mailer/MailData.cs create mode 100644 ServiceMonitor.Mailer/RegionData.cs create mode 100644 ServiceMonitor.Mailer/ReportMailer.cs create mode 100644 ServiceMonitor.Test/EcsTests.cs create mode 100644 ServiceMonitor.Test/ReportMailerTests.cs diff --git a/ServiceMonitor.AWS/AWSInstance.cs b/ServiceMonitor.AWS/AWSInstance.cs index 7ef9f7c2..8f64e9dc 100644 --- a/ServiceMonitor.AWS/AWSInstance.cs +++ b/ServiceMonitor.AWS/AWSInstance.cs @@ -8,48 +8,42 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using ServiceMonitor.Cloud.Model; -namespace ServiceMonitor.AWS +namespace ServiceMonitor.AWS; + +public class AwsInstance(IServiceProvider serviceProvider) : IInstance { - public class AWSInstance : IInstance + public async Task> GetInstancesAsync(string region, int limit = 100, CancellationToken cancellationToken = default) { - private readonly IServiceProvider _serviceProvider; - public AWSInstance(IServiceProvider serviceProvider) + // TODO: need better solution for client resolution + var ec2Region = RegionEndpoint.GetBySystemName(region); + using var ec2Client = ActivatorUtilities.CreateInstance(serviceProvider, ec2Region); + if (ec2Client == null) { - _serviceProvider = serviceProvider; + throw new ArgumentNullException(nameof(ec2Client)); } - - public async Task> GetInstancesAsync(string region, int limit = 100, CancellationToken cancellationToken = default) + var collection = new List(); + var request = new DescribeInstancesRequest() { - // TODO: need better solution for client resolution - var ec2Region = RegionEndpoint.GetBySystemName(region); - using var ec2Client = ActivatorUtilities.CreateInstance(_serviceProvider, ec2Region); - if (ec2Client == null) - { - throw new ArgumentNullException(nameof(ec2Client)); - } - var collection = new List(); - var request = new DescribeInstancesRequest() - { - MaxResults = limit, - }; - var nextToken = string.Empty; - var response = await ec2Client.DescribeInstancesAsync(cancellationToken); + MaxResults = limit, + }; + var nextToken = string.Empty; + var response = await ec2Client.DescribeInstancesAsync(cancellationToken); - response.Reservations?.ForEach(x => + response.Reservations?.ForEach(x => + { + var instances = x.Instances?.Select(x => new InstanceProperty { - var instances = x.Instances?.Select(x => new InstanceProperty - { - Name = x.InstanceId, - Type = x.InstanceType.Value, - CreatedAt = x.LaunchTime ?? DateTime.Now, - Status = x.State.Name.Value, - UpdatedAt = x.UsageOperationUpdateTime - }); - collection.AddRange(instances); + Name = x.InstanceId, + Type = x.InstanceType.Value, + CreatedAt = x.LaunchTime ?? DateTime.Now, + Status = x.State.Name.Value, + UpdatedAt = x.UsageOperationUpdateTime }); + collection.AddRange(instances); + }); - return collection; - } + return collection; } -} +} \ No newline at end of file diff --git a/ServiceMonitor.AWS/AppRunner.cs b/ServiceMonitor.AWS/AppRunner.cs deleted file mode 100644 index 9aa38adf..00000000 --- a/ServiceMonitor.AWS/AppRunner.cs +++ /dev/null @@ -1,46 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using ServiceMonitor.Cloud; -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Amazon; -using Amazon.AppRunner; -using Amazon.AppRunner.Model; -using System.Linq; - -namespace ServiceMonitor.AWS -{ - public class AppRunner : IAppRunner - { - private readonly IServiceProvider _serviceProvider; - public AppRunner(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - public async Task> GetAppRunnersAsync(string region, CancellationToken cancellationToken = default) - { - var appRunnerRegion = RegionEndpoint.GetBySystemName(region); - using var appRunnerClient = ActivatorUtilities.CreateInstance(_serviceProvider, appRunnerRegion); - if (appRunnerClient == null) - { - throw new ArgumentNullException(nameof(appRunnerClient)); - } - var collection = new List(); - var request = new ListServicesRequest() - { - MaxResults = 20, - }; - var nextToken = string.Empty; - var response = await appRunnerClient.ListServicesAsync(request, cancellationToken); - - return response.ServiceSummaryList.Select(x => new AppRunnerProperty - { - Status = x.Status, - Name = x.ServiceName, - CreatedAt = x.CreatedAt ?? DateTime.Now, - UpdatedAt = x.UpdatedAt, - }).ToList(); - } - } -} diff --git a/ServiceMonitor.AWS/AssemblyInfo.cs b/ServiceMonitor.AWS/AssemblyInfo.cs new file mode 100644 index 00000000..fbeeb6e8 --- /dev/null +++ b/ServiceMonitor.AWS/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("ServiceMonitor.Test")] \ No newline at end of file diff --git a/ServiceMonitor.AWS/ECR.cs b/ServiceMonitor.AWS/ECR.cs index a62484aa..37a7fc32 100644 --- a/ServiceMonitor.AWS/ECR.cs +++ b/ServiceMonitor.AWS/ECR.cs @@ -11,129 +11,119 @@ using ServiceMonitor.Cloud.Model; using Microsoft.Extensions.Logging; -namespace ServiceMonitor.AWS +namespace ServiceMonitor.AWS; + +public class Ecr(IServiceProvider serviceProvider, ILogger logger) : IImage { - public class ECR : IImage + public async Task> GetImagesAsync(string region, CancellationToken cancellationToken = default) { - private readonly IServiceProvider _serviceProvider; - private readonly ILogger _logger; - - public ECR(IServiceProvider serviceProvider, ILogger logger) + // TODO: need better solution for client resolution + var ecrRegion = RegionEndpoint.GetBySystemName(region); + using var ecrClient = ActivatorUtilities.CreateInstance(serviceProvider, ecrRegion); + if (ecrClient == null) { - _serviceProvider = serviceProvider; - _logger = logger; + throw new ArgumentNullException(nameof(ecrClient)); } + var request = new DescribeRepositoriesRequest + { + MaxResults = 1000, + }; + var nextToken = string.Empty; + var response = await ecrClient.DescribeRepositoriesAsync(request, cancellationToken); - public async Task> GetImagesAsync(string region, CancellationToken cancellationToken = default) + var list = response.Repositories.Select(x => new BasicProperty { - // TODO: need better solution for client resolution - var ecrRegion = RegionEndpoint.GetBySystemName(region); - using var ecrClient = ActivatorUtilities.CreateInstance(_serviceProvider, ecrRegion); - if (ecrClient == null) - { - throw new ArgumentNullException(nameof(ecrClient)); - } - var request = new DescribeRepositoriesRequest - { - MaxResults = 1000, - }; - var nextToken = string.Empty; - var response = await ecrClient.DescribeRepositoriesAsync(request, cancellationToken); + Name = x.RepositoryName, + CreatedAt = x.CreatedAt ?? DateTime.Now, + Status = "-", + }).ToList(); - var list = response.Repositories.Select(x => new BasicProperty - { - Name = x.RepositoryName, - CreatedAt = x.CreatedAt ?? DateTime.Now, - Status = "-", - }).ToList(); + return list; + } - return list; + public async Task> GetTags(string region, string repoName, CancellationToken cancellationToken = default) + { + var ecrRegion = RegionEndpoint.GetBySystemName(region); + using var ecrClient = ActivatorUtilities.CreateInstance(serviceProvider, ecrRegion); + if (ecrClient == null) + { + throw new ArgumentNullException(nameof(ecrClient)); } - - public async Task> GetTags(string region, string repoName, CancellationToken cancellationToken = default) + var imageListRequest = new DescribeImagesRequest { - var ecrRegion = RegionEndpoint.GetBySystemName(region); - using var ecrClient = ActivatorUtilities.CreateInstance(_serviceProvider, ecrRegion); - if (ecrClient == null) + RepositoryName = repoName, + Filter = new DescribeImagesFilter { - throw new ArgumentNullException(nameof(ecrClient)); + TagStatus = TagStatus.TAGGED, } - var imageListRequest = new DescribeImagesRequest - { - RepositoryName = repoName, - Filter = new DescribeImagesFilter - { - TagStatus = TagStatus.TAGGED, - } - }; - var tagsResources = await ecrClient.DescribeImagesAsync(imageListRequest, cancellationToken); - return tagsResources.ImageDetails.Select(x => new TagItem - { - CreatedTime = x.ImagePushedAt ?? DateTime.Now, - Tags = x.ImageTags, - ImageDigest = x.ImageDigest, - }).ToList(); - } + }; + var tagsResources = await ecrClient.DescribeImagesAsync(imageListRequest, cancellationToken); + return tagsResources.ImageDetails.Select(x => new TagItem + { + CreatedTime = x.ImagePushedAt ?? DateTime.Now, + Tags = x.ImageTags, + ImageDigest = x.ImageDigest, + }).ToList(); + } - public async Task<(List, List)> DeleteTags(string region, string repoName, ICollection tags, CancellationToken cancellationToken = default) + public async Task<(List, List)> DeleteTags(string region, string repoName, ICollection tags, CancellationToken cancellationToken = default) + { + var sample = tags.FirstOrDefault(); + if (sample == null) { - var sample = tags.FirstOrDefault(); - if (sample == null) - { - return (new List(), new List()); - } + return (new List(), new List()); + } - var ecrRegion = RegionEndpoint.GetBySystemName(region); - using var ecrClient = ActivatorUtilities.CreateInstance(_serviceProvider, ecrRegion); - if (ecrClient == null) - { - throw new ArgumentNullException(nameof(ecrClient)); - } + var ecrRegion = RegionEndpoint.GetBySystemName(region); + using var ecrClient = ActivatorUtilities.CreateInstance(serviceProvider, ecrRegion); + if (ecrClient == null) + { + throw new ArgumentNullException(nameof(ecrClient)); + } - var isShaMode = sample.Tags.Contains("sha-"); - var deleteImages = new List(); - if (isShaMode) + var isShaMode = sample.Tags.Contains("sha-"); + var deleteImages = new List(); + if (isShaMode) + { + foreach (var tag in tags) { - foreach (var tag in tags) + if (tag.Tags.Contains("main") || tag.Tags.Contains("latest") || tag.Tags.Contains("master")) { - if (tag.Tags.Contains("main") || tag.Tags.Contains("latest") || tag.Tags.Contains("master")) - { - continue; - } - deleteImages.Add(new ImageIdentifier - { - ImageDigest = tag.ImageDigest, - }); + continue; } - } - else - { - var sorted = tags.OrderByDescending(x => x.CreatedTime).Select(x => new ImageIdentifier + deleteImages.Add(new ImageIdentifier { - ImageDigest = x.ImageDigest, - }).ToList(); - sorted.RemoveAt(0); - deleteImages.AddRange(sorted); + ImageDigest = tag.ImageDigest, + }); } - - if (deleteImages.Count == 0) + } + else + { + var sorted = tags.OrderByDescending(x => x.CreatedTime).Select(x => new ImageIdentifier { - return (new List(), new List()); - } + ImageDigest = x.ImageDigest, + }).ToList(); + sorted.RemoveAt(0); + deleteImages.AddRange(sorted); + } - _logger.LogInformation("Will remove {} tags", deleteImages.Count); + if (deleteImages.Count == 0) + { + return (new List(), new List()); + } - var deleteImageRequest = new BatchDeleteImageRequest - { - RepositoryName = repoName, - ImageIds = deleteImages, - }; + logger.LogInformation("Will remove {} tags", deleteImages.Count); - var batchResponse = await ecrClient.BatchDeleteImageAsync(deleteImageRequest, cancellationToken); + var deleteImageRequest = new BatchDeleteImageRequest + { + RepositoryName = repoName, + ImageIds = deleteImages, + }; - _logger.LogInformation("Success remove {0} and fail {1}", batchResponse.ImageIds.Count, batchResponse.Failures.Count); + var batchResponse = await ecrClient.BatchDeleteImageAsync(deleteImageRequest, cancellationToken); - return (batchResponse.ImageIds.Select(x => x.ImageTag).ToList(), batchResponse.Failures.Select(x => x.ImageId.ImageTag).ToList()); - } + logger.LogInformation("Success remove {0} and fail {1}", batchResponse.ImageIds.Count, batchResponse.Failures.Count); + + return (batchResponse.ImageIds.Select(x => x.ImageTag).ToList(), batchResponse.Failures.Select(x => x.ImageId.ImageTag).ToList()); } -} +} \ No newline at end of file diff --git a/ServiceMonitor.AWS/Ecs.cs b/ServiceMonitor.AWS/Ecs.cs new file mode 100644 index 00000000..4d795b02 --- /dev/null +++ b/ServiceMonitor.AWS/Ecs.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Amazon; +using Amazon.ECS; +using Amazon.ECS.Model; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using ServiceMonitor.Cloud; + +namespace ServiceMonitor.AWS; + +public class Ecs(IServiceProvider serviceProvider, ILogger logger) : IContainerService +{ + private readonly ILogger _logger = logger; + + public async Task> GetClusters(string region, CancellationToken cancellationToken = default) + { + // TODO: need better solution for client resolution + var ecsRegion = RegionEndpoint.GetBySystemName(region); + using var ecsClient = ActivatorUtilities.CreateInstance(serviceProvider, ecsRegion); + if (ecsClient == null) + { + throw new ArgumentNullException(nameof(ecsClient)); + } + return await GetClusters(ecsClient, cancellationToken); + } + + internal static async Task> GetClusters(IAmazonECS ecsClient, CancellationToken cancellationToken = default) + { + var clusters = new List(); + var request = new ListClustersRequest(); + do + { + var response = await ecsClient.ListClustersAsync(request, cancellationToken); + foreach (var clusterArn in response.ClusterArns ?? Enumerable.Empty()) + { + var cluster = new Cloud.Model.Cluster { Identity = clusterArn }; + var servicesRequest = new ListServicesRequest { Cluster = clusterArn }; + do + { + var services = await ecsClient.ListServicesAsync(servicesRequest, cancellationToken); + cluster.Services.AddRange((services.ServiceArns ?? Enumerable.Empty()) + .Select(arn => new Cloud.Model.Service { Identity = arn })); + servicesRequest.NextToken = services.NextToken; + } while (!string.IsNullOrEmpty(servicesRequest.NextToken)); + + var tasksRequest = new ListTasksRequest { Cluster = clusterArn }; + do + { + var tasks = await ecsClient.ListTasksAsync(tasksRequest, cancellationToken); + cluster.Tasks.AddRange((tasks.TaskArns ?? Enumerable.Empty()) + .Select(arn => new Cloud.Model.Task { Identity = arn })); + tasksRequest.NextToken = tasks.NextToken; + } while (!string.IsNullOrEmpty(tasksRequest.NextToken)); + + clusters.Add(cluster); + } + request.NextToken = response.NextToken; + } while (!string.IsNullOrEmpty(request.NextToken)); + + return clusters; + } +} \ No newline at end of file diff --git a/ServiceMonitor.AWS/Lambda.cs b/ServiceMonitor.AWS/Lambda.cs index 95d91c82..92a7b3c7 100644 --- a/ServiceMonitor.AWS/Lambda.cs +++ b/ServiceMonitor.AWS/Lambda.cs @@ -8,43 +8,37 @@ using Amazon.Lambda; using Amazon.Lambda.Model; using System.Linq; +using ServiceMonitor.Cloud.Model; -namespace ServiceMonitor.AWS +namespace ServiceMonitor.AWS; + +public class Lambda(IServiceProvider serviceProvider) : IFunction { - public class Lambda : IFunction + public async Task> GetFunctionsAsync(string region, CancellationToken cancellationToken = default) { - private readonly IServiceProvider _serviceProvider; - public Lambda(IServiceProvider serviceProvider) + var lambdaRegion = RegionEndpoint.GetBySystemName(region); + using var lambdaClient = ActivatorUtilities.CreateInstance(serviceProvider, lambdaRegion); + if (lambdaClient == null) { - _serviceProvider = serviceProvider; + throw new ArgumentNullException(nameof(lambdaClient)); } - - public async Task> GetFunctionsAsync(string region, CancellationToken cancellationToken = default) + var collection = new List(); + var request = new ListFunctionsRequest() { - var lambdaRegion = RegionEndpoint.GetBySystemName(region); - using var lambdaClient = ActivatorUtilities.CreateInstance(_serviceProvider, lambdaRegion); - if (lambdaClient == null) - { - throw new ArgumentNullException(nameof(lambdaClient)); - } - var collection = new List(); - var request = new ListFunctionsRequest() - { - MaxItems = 50, - FunctionVersion = FunctionVersion.ALL, - }; - var nextToken = string.Empty; - var response = await lambdaClient.ListFunctionsAsync(request, cancellationToken); + MaxItems = 50, + FunctionVersion = FunctionVersion.ALL, + }; + var nextToken = string.Empty; + var response = await lambdaClient.ListFunctionsAsync(request, cancellationToken); - return response.Functions.Select(x => new FunctionProperty - { - Status = string.Empty, - Name = x.FunctionName, - Version = x.Version, - Runtime = x.Runtime, - CreatedAt = DateTimeOffset.Parse(x.LastModified), - }).ToList(); + return response.Functions.Select(x => new FunctionProperty + { + Status = string.Empty, + Name = x.FunctionName, + Version = x.Version, + Runtime = string.IsNullOrEmpty(x.Runtime) ? string.Empty : x.Runtime, + CreatedAt = DateTimeOffset.Parse(x.LastModified), + }).ToList(); - } } -} +} \ No newline at end of file diff --git a/ServiceMonitor.AWS/S3.cs b/ServiceMonitor.AWS/S3.cs index 28dd79fe..f4d30475 100644 --- a/ServiceMonitor.AWS/S3.cs +++ b/ServiceMonitor.AWS/S3.cs @@ -7,34 +7,29 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using ServiceMonitor.Cloud.Model; -namespace ServiceMonitor.AWS +namespace ServiceMonitor.AWS; + +public class S3(IServiceProvider serviceProvider) : IBucket { - public class S3 : IBucket + public async Task> GetBuckets(string region, CancellationToken cancellationToken = default) { - private readonly IServiceProvider _serviceProvider; - public S3(IServiceProvider serviceProvider) + var s3Region = RegionEndpoint.GetBySystemName(region); + using var s3Client = ActivatorUtilities.CreateInstance(serviceProvider, s3Region); + if (s3Client == null) { - _serviceProvider = serviceProvider; + throw new ArgumentNullException(nameof(s3Client)); } - public async Task> GetBuckets(string region, CancellationToken cancellationToken = default) - { - var s3Region = RegionEndpoint.GetBySystemName(region); - using var s3Client = ActivatorUtilities.CreateInstance(_serviceProvider, s3Region); - if (s3Client == null) - { - throw new ArgumentNullException(nameof(s3Client)); - } - var request = new Amazon.S3.Model.ListBucketsRequest(); - var response = await s3Client.ListBucketsAsync(request, cancellationToken); + var request = new Amazon.S3.Model.ListBucketsRequest(); + var response = await s3Client.ListBucketsAsync(request, cancellationToken); - var list = response.Buckets.Select(x => new BasicProperty - { - Name = x.BucketName, - CreatedAt = x.CreationDate ?? DateTime.Now, - Status = "-", - }).ToList(); - return list; - } + var list = response.Buckets.Select(x => new BasicProperty + { + Name = x.BucketName, + CreatedAt = x.CreationDate ?? DateTime.Now, + Status = "-", + }).ToList(); + return list; } -} +} \ No newline at end of file diff --git a/ServiceMonitor.AWS/ServiceMonitor.AWS.csproj b/ServiceMonitor.AWS/ServiceMonitor.AWS.csproj index d832e063..ecf765f0 100644 --- a/ServiceMonitor.AWS/ServiceMonitor.AWS.csproj +++ b/ServiceMonitor.AWS/ServiceMonitor.AWS.csproj @@ -2,12 +2,13 @@ netstandard2.1 + 15 - + diff --git a/ServiceMonitor.Cleaner/Program.cs b/ServiceMonitor.Cleaner/Program.cs index 2395f90f..bf41cd23 100644 --- a/ServiceMonitor.Cleaner/Program.cs +++ b/ServiceMonitor.Cleaner/Program.cs @@ -1,16 +1,10 @@ - -using Amazon; -using Amazon.EC2.Model; -using Amazon.SimpleEmailV2; -using Amazon.SimpleEmailV2.Model; +using Amazon.SimpleEmailV2; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using ServiceMonitor.AWS; using ServiceMonitor.Cloud; -using System.Text; using System.Text.Json; -using System.Text.Json.Serialization; IConfiguration config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) @@ -27,10 +21,9 @@ configure.AddConsole(); }); serviceCollection.AddAWSService(); -serviceCollection.AddScoped(); -serviceCollection.AddScoped(); +serviceCollection.AddScoped(); serviceCollection.AddScoped(); -serviceCollection.AddScoped(); +serviceCollection.AddScoped(); serviceCollection.AddScoped(); var serviceProvider = serviceCollection.BuildServiceProvider(); @@ -52,7 +45,7 @@ { var tags = await containerImages.GetTags(region, image.Name); var (success, failure) = await containerImages.DeleteTags(region, image.Name, tags); - logger.LogInformation("{}:{}:{}", image.Name, JsonSerializer.Serialize(success, new JsonSerializerOptions + logger.LogInformation("{0}:{1}:{2}", image.Name, JsonSerializer.Serialize(success, new JsonSerializerOptions { WriteIndented = true, }), diff --git a/ServiceMonitor.Cleaner/ServiceMonitor.Cleaner.csproj b/ServiceMonitor.Cleaner/ServiceMonitor.Cleaner.csproj index 94429b09..3f513a96 100644 --- a/ServiceMonitor.Cleaner/ServiceMonitor.Cleaner.csproj +++ b/ServiceMonitor.Cleaner/ServiceMonitor.Cleaner.csproj @@ -5,6 +5,7 @@ net10.0 enable enable + 15 diff --git a/ServiceMonitor.Cloud/AppRunnerProperty.cs b/ServiceMonitor.Cloud/AppRunnerProperty.cs deleted file mode 100644 index 42a71d5b..00000000 --- a/ServiceMonitor.Cloud/AppRunnerProperty.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace ServiceMonitor.Cloud -{ - public class AppRunnerProperty : BasicProperty - { - } -} diff --git a/ServiceMonitor.Cloud/BasicProperty.cs b/ServiceMonitor.Cloud/BasicProperty.cs deleted file mode 100644 index 3ba8f6c1..00000000 --- a/ServiceMonitor.Cloud/BasicProperty.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace ServiceMonitor.Cloud -{ - public class BasicProperty - { - public string Name { get; set; } - public string Status { get; set; } - public DateTimeOffset CreatedAt { get; set; } - public DateTimeOffset? UpdatedAt { get; set; } - } -} diff --git a/ServiceMonitor.Cloud/FunctionProperty.cs b/ServiceMonitor.Cloud/FunctionProperty.cs deleted file mode 100644 index 520018bb..00000000 --- a/ServiceMonitor.Cloud/FunctionProperty.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ServiceMonitor.Cloud -{ - public class FunctionProperty : BasicProperty - { - public string Version { get; set; } - public string Runtime { get; set; } - } -} diff --git a/ServiceMonitor.Cloud/IAppRunner.cs b/ServiceMonitor.Cloud/IAppRunner.cs index 617aee1f..00e760c5 100644 --- a/ServiceMonitor.Cloud/IAppRunner.cs +++ b/ServiceMonitor.Cloud/IAppRunner.cs @@ -1,11 +1,13 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using ServiceMonitor.Cloud.Model; -namespace ServiceMonitor.Cloud +namespace ServiceMonitor.Cloud; + +[Obsolete] +public interface IAppRunner { - public interface IAppRunner - { - Task> GetAppRunnersAsync(string region, CancellationToken cancellationToken = default); - } -} + Task> GetAppRunnersAsync(string region, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/ServiceMonitor.Cloud/IBucket.cs b/ServiceMonitor.Cloud/IBucket.cs index 4e7a10b8..e646216d 100644 --- a/ServiceMonitor.Cloud/IBucket.cs +++ b/ServiceMonitor.Cloud/IBucket.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; +using ServiceMonitor.Cloud.Model; -namespace ServiceMonitor.Cloud +namespace ServiceMonitor.Cloud; + +public interface IBucket { - public interface IBucket - { - Task> GetBuckets(string region, CancellationToken cancellationToken = default); - } -} + Task> GetBuckets(string region, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/ServiceMonitor.Cloud/IContainerService.cs b/ServiceMonitor.Cloud/IContainerService.cs new file mode 100644 index 00000000..688384f1 --- /dev/null +++ b/ServiceMonitor.Cloud/IContainerService.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace ServiceMonitor.Cloud; + +public interface IContainerService +{ + public Task> GetClusters(string region, CancellationToken cancellationToken = default); + +} \ No newline at end of file diff --git a/ServiceMonitor.Cloud/IFunction.cs b/ServiceMonitor.Cloud/IFunction.cs index cbb2b21e..139a5822 100644 --- a/ServiceMonitor.Cloud/IFunction.cs +++ b/ServiceMonitor.Cloud/IFunction.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; +using ServiceMonitor.Cloud.Model; -namespace ServiceMonitor.Cloud +namespace ServiceMonitor.Cloud; + +public interface IFunction { - public interface IFunction - { - Task> GetFunctionsAsync(string region, CancellationToken cancellationToken = default); - } -} + Task> GetFunctionsAsync(string region, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/ServiceMonitor.Cloud/IImage.cs b/ServiceMonitor.Cloud/IImage.cs index 4f15c4c5..41757f8f 100644 --- a/ServiceMonitor.Cloud/IImage.cs +++ b/ServiceMonitor.Cloud/IImage.cs @@ -3,12 +3,11 @@ using System.Threading; using ServiceMonitor.Cloud.Model; -namespace ServiceMonitor.Cloud +namespace ServiceMonitor.Cloud; + +public interface IImage { - public interface IImage - { - Task> GetImagesAsync(string region, CancellationToken cancellationToken = default); - Task> GetTags(string region, string repoName, CancellationToken cancellationToken = default); - Task<(List, List)> DeleteTags(string region, string repoName, ICollection tags, CancellationToken cancellationToken = default); - } -} + Task> GetImagesAsync(string region, CancellationToken cancellationToken = default); + Task> GetTags(string region, string repoName, CancellationToken cancellationToken = default); + Task<(List, List)> DeleteTags(string region, string repoName, ICollection tags, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/ServiceMonitor.Cloud/IInstance.cs b/ServiceMonitor.Cloud/IInstance.cs index d9720e8e..59f484ba 100644 --- a/ServiceMonitor.Cloud/IInstance.cs +++ b/ServiceMonitor.Cloud/IInstance.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using ServiceMonitor.Cloud.Model; -namespace ServiceMonitor.Cloud +namespace ServiceMonitor.Cloud; + +public interface IInstance { - public interface IInstance - { - Task> GetInstancesAsync(string region, int limit = 100, CancellationToken cancellationToken = default); - } + Task> GetInstancesAsync(string region, int limit = 100, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/ServiceMonitor.Cloud/InstanceProperty.cs b/ServiceMonitor.Cloud/InstanceProperty.cs deleted file mode 100644 index 9de4ca92..00000000 --- a/ServiceMonitor.Cloud/InstanceProperty.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ServiceMonitor.Cloud -{ - public class InstanceProperty : BasicProperty - { - public string Type { get; set; } = null!; - } -} diff --git a/ServiceMonitor.Cloud/Model/AppRunnerProperty.cs b/ServiceMonitor.Cloud/Model/AppRunnerProperty.cs new file mode 100644 index 00000000..4234581a --- /dev/null +++ b/ServiceMonitor.Cloud/Model/AppRunnerProperty.cs @@ -0,0 +1,9 @@ +using System; +using System.Diagnostics.CodeAnalysis; + +namespace ServiceMonitor.Cloud.Model; + +[Obsolete] +[ExcludeFromCodeCoverage] +public class AppRunnerProperty : BasicProperty; + diff --git a/ServiceMonitor.Cloud/Model/BasicProperty.cs b/ServiceMonitor.Cloud/Model/BasicProperty.cs new file mode 100644 index 00000000..29534305 --- /dev/null +++ b/ServiceMonitor.Cloud/Model/BasicProperty.cs @@ -0,0 +1,11 @@ +using System; + +namespace ServiceMonitor.Cloud.Model; + +public class BasicProperty +{ + public string Name { get; set; } + public string Status { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset? UpdatedAt { get; set; } +} \ No newline at end of file diff --git a/ServiceMonitor.Cloud/Model/Cluster.cs b/ServiceMonitor.Cloud/Model/Cluster.cs new file mode 100644 index 00000000..8bc14f20 --- /dev/null +++ b/ServiceMonitor.Cloud/Model/Cluster.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; + +namespace ServiceMonitor.Cloud.Model; + +public class Cluster +{ + public string Identity { get; set; } + public List Services { get; private set; } = new List(); + public List Tasks { get; private set; } = new List(); +} \ No newline at end of file diff --git a/ServiceMonitor.Cloud/Model/FunctionProperty.cs b/ServiceMonitor.Cloud/Model/FunctionProperty.cs new file mode 100644 index 00000000..7a680ffe --- /dev/null +++ b/ServiceMonitor.Cloud/Model/FunctionProperty.cs @@ -0,0 +1,7 @@ +namespace ServiceMonitor.Cloud.Model; + +public class FunctionProperty : BasicProperty +{ + public string Version { get; set; } + public string Runtime { get; set; } +} \ No newline at end of file diff --git a/ServiceMonitor.Cloud/Model/InstanceProperty.cs b/ServiceMonitor.Cloud/Model/InstanceProperty.cs new file mode 100644 index 00000000..88cc8c68 --- /dev/null +++ b/ServiceMonitor.Cloud/Model/InstanceProperty.cs @@ -0,0 +1,6 @@ +namespace ServiceMonitor.Cloud.Model; + +public class InstanceProperty : BasicProperty +{ + public string Type { get; set; } = null!; +} \ No newline at end of file diff --git a/ServiceMonitor.Cloud/Model/Service.cs b/ServiceMonitor.Cloud/Model/Service.cs new file mode 100644 index 00000000..bda8b35e --- /dev/null +++ b/ServiceMonitor.Cloud/Model/Service.cs @@ -0,0 +1,6 @@ +namespace ServiceMonitor.Cloud.Model; + +public class Service +{ + public string Identity { get; set; } +} \ No newline at end of file diff --git a/ServiceMonitor.Cloud/Model/TagItem.cs b/ServiceMonitor.Cloud/Model/TagItem.cs index ab6c03ea..bb0e1e83 100644 --- a/ServiceMonitor.Cloud/Model/TagItem.cs +++ b/ServiceMonitor.Cloud/Model/TagItem.cs @@ -1,14 +1,11 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Text; -namespace ServiceMonitor.Cloud.Model +namespace ServiceMonitor.Cloud.Model; + +public class TagItem { - public class TagItem - { - public IReadOnlyCollection Tags { get; set; } - public DateTime CreatedTime { get; set; } - public string ImageDigest { get; set; } - } -} + public IReadOnlyCollection Tags { get; set; } + public DateTime CreatedTime { get; set; } + public string ImageDigest { get; set; } +} \ No newline at end of file diff --git a/ServiceMonitor.Cloud/Model/Task.cs b/ServiceMonitor.Cloud/Model/Task.cs new file mode 100644 index 00000000..b8db552c --- /dev/null +++ b/ServiceMonitor.Cloud/Model/Task.cs @@ -0,0 +1,6 @@ +namespace ServiceMonitor.Cloud.Model; + +public class Task +{ + public string Identity { get; set; } +} \ No newline at end of file diff --git a/ServiceMonitor.Cloud/ServiceMonitor.Cloud.csproj b/ServiceMonitor.Cloud/ServiceMonitor.Cloud.csproj index d4c395e8..4c06cc9c 100644 --- a/ServiceMonitor.Cloud/ServiceMonitor.Cloud.csproj +++ b/ServiceMonitor.Cloud/ServiceMonitor.Cloud.csproj @@ -2,6 +2,7 @@ netstandard2.1 + 15 diff --git a/ServiceMonitor.Dashboard/Pages/AppRunner.razor b/ServiceMonitor.Dashboard/Pages/AppRunner.razor deleted file mode 100644 index 539db9ec..00000000 --- a/ServiceMonitor.Dashboard/Pages/AppRunner.razor +++ /dev/null @@ -1,72 +0,0 @@ -@page "/apprunner" -@using ServiceMonitor.Cloud; -@inject IAppRunner AppRunnerService; - -App Runner - -

App Runner

- - - - -@if (_loading) -{ -
-
- Loading... -
-
-} -else if (AppRunners.Count == 0) -{ -

No Data

-} -else -{ -

Total Data: @AppRunners.Count

- - - - - - - @foreach (var instance in AppRunners) - { - - - - - - } -
NameCreated AtStatus
@instance.Name@instance.CreatedAt@instance.Status
-} - -@code { - private bool _loading = false; - public ICollection AppRunners { get; private set; } = new List(); - public string SelectedRegion { get; set; } = "ap-southeast-1"; - - async Task FetchRegion(ChangeEventArgs e) - { - if (e.Value is not null) - { - var value = (string)e.Value; - if (string.IsNullOrEmpty(value)) - { - return; - } - SelectedRegion = value; - _loading = true; - await FetchData(); - } - } - - private async Task FetchData() - { - AppRunners = await AppRunnerService.GetAppRunnersAsync(region: SelectedRegion); - _loading = false; - } -} diff --git a/ServiceMonitor.Dashboard/Pages/EC2.razor b/ServiceMonitor.Dashboard/Pages/EC2.razor index 45ee58e6..3cdb8b65 100644 --- a/ServiceMonitor.Dashboard/Pages/EC2.razor +++ b/ServiceMonitor.Dashboard/Pages/EC2.razor @@ -1,5 +1,7 @@ @page "/ec2" @using ServiceMonitor.Cloud; +@using ServiceMonitor.Cloud.Model +@using Task = System.Threading.Tasks.Task @inject IInstance InstanceService; EC2 diff --git a/ServiceMonitor.Dashboard/Pages/ECR.razor b/ServiceMonitor.Dashboard/Pages/ECR.razor index e6ad0c6a..5aaa8d4e 100644 --- a/ServiceMonitor.Dashboard/Pages/ECR.razor +++ b/ServiceMonitor.Dashboard/Pages/ECR.razor @@ -1,5 +1,7 @@ @page "/ecr" @using ServiceMonitor.Cloud; +@using ServiceMonitor.Cloud.Model +@using Task = System.Threading.Tasks.Task @inject IImage ECRService; ECR diff --git a/ServiceMonitor.Dashboard/Pages/Lambda.razor b/ServiceMonitor.Dashboard/Pages/Lambda.razor index 7b8d0441..ff46f4f4 100644 --- a/ServiceMonitor.Dashboard/Pages/Lambda.razor +++ b/ServiceMonitor.Dashboard/Pages/Lambda.razor @@ -1,5 +1,7 @@ @page "/lambda" @using ServiceMonitor.Cloud; +@using ServiceMonitor.Cloud.Model +@using Task = System.Threading.Tasks.Task @inject IFunction FunctionsService; Lambda diff --git a/ServiceMonitor.Dashboard/Program.cs b/ServiceMonitor.Dashboard/Program.cs index 4bdf9b19..b593277f 100644 --- a/ServiceMonitor.Dashboard/Program.cs +++ b/ServiceMonitor.Dashboard/Program.cs @@ -4,10 +4,9 @@ var builder = WebApplication.CreateBuilder(args); // Add services to the container. -builder.Services.AddScoped(); -builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.AddScoped(); -builder.Services.AddScoped(); +builder.Services.AddScoped(); builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor(); diff --git a/ServiceMonitor.Dashboard/ServiceMonitor.Dashboard.csproj b/ServiceMonitor.Dashboard/ServiceMonitor.Dashboard.csproj index 6744d0da..d3e99ba2 100644 --- a/ServiceMonitor.Dashboard/ServiceMonitor.Dashboard.csproj +++ b/ServiceMonitor.Dashboard/ServiceMonitor.Dashboard.csproj @@ -4,6 +4,7 @@ net10.0 enable enable + 15 diff --git a/ServiceMonitor.Mailer/MailData.cs b/ServiceMonitor.Mailer/MailData.cs new file mode 100644 index 00000000..c08cdd29 --- /dev/null +++ b/ServiceMonitor.Mailer/MailData.cs @@ -0,0 +1,12 @@ +using ServiceMonitor.Cloud.Model; + +namespace ServiceMonitor.Mailer; + +public class MailData +{ + public string ReportTime { get; set; } = string.Empty; + public List> EC2Services { get; set; } = []; + public List> LambdaList { get; set; } = []; + public List> ECRList { get; set; } = []; + public List> S3List { get; set; } = []; +} \ No newline at end of file diff --git a/ServiceMonitor.Mailer/Program.cs b/ServiceMonitor.Mailer/Program.cs index 1b5f9167..45c4905f 100644 --- a/ServiceMonitor.Mailer/Program.cs +++ b/ServiceMonitor.Mailer/Program.cs @@ -1,151 +1,59 @@ -// See https://aka.ms/new-console-template for more information - using Amazon; +using Amazon.Extensions.NETCore.Setup; using Amazon.SimpleEmailV2; -using Amazon.SimpleEmailV2.Model; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using ServiceMonitor.AWS; using ServiceMonitor.Cloud; -using System.Text; - -IConfiguration config = new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile("appsettings.json", true) - .AddEnvironmentVariables() - .Build(); - -var serviceCollection = new ServiceCollection(); -serviceCollection.AddSingleton(config); -serviceCollection.AddLogging(configure => -{ - configure.ClearProviders(); - configure.AddConfiguration(config.GetSection("Logging")); - configure.AddConsole(); -}); -serviceCollection.AddAWSService(); -serviceCollection.AddScoped(); -serviceCollection.AddScoped(); -serviceCollection.AddScoped(); -serviceCollection.AddScoped(); -serviceCollection.AddScoped(); +using ServiceMonitor.Mailer; -var serviceProvider = serviceCollection.BuildServiceProvider(); +await RunAsync(); -var logger = serviceProvider.GetRequiredService().CreateLogger(); -logger.LogDebug("Starting application"); - -var stringBuilder = new StringBuilder(); - -// get app runners -logger.LogDebug("Populate App Runners"); -var appRunners = serviceProvider.GetRequiredService(); -var data = await appRunners.GetAppRunnersAsync("ap-southeast-1"); -stringBuilder.AppendLine("

App Runner

"); -stringBuilder.AppendLine(""); -stringBuilder.AppendLine(""); -foreach (var appRunner in data) +static async Task RunAsync() { - stringBuilder.AppendLine($""); -} -stringBuilder.AppendLine("
NameCreated AtUpdated AtStatus
{appRunner.Name}{appRunner.CreatedAt}{appRunner.UpdatedAt}{appRunner.Status}
"); + var configuration = BuildConfiguration(); + using var serviceProvider = BuildServiceProvider(configuration); + using var scope = serviceProvider.CreateScope(); -// get instances -logger.LogDebug("Populate EC2 Instances"); -var instances = serviceProvider.GetRequiredService(); + var logger = scope.ServiceProvider.GetRequiredService().CreateLogger("Mailer"); + logger.LogDebug("Starting application"); -var regions = new List -{ - "ap-southeast-1", - "ap-southeast-3", -}; -foreach (var region in regions) -{ - stringBuilder.AppendLine($"

EC2 Instances (Region: {region})

"); - stringBuilder.AppendLine(""); - stringBuilder.AppendLine(""); - var ec2Instances = await instances.GetInstancesAsync(region); - foreach (var ec2Instance in ec2Instances) - { - stringBuilder.AppendLine($""); - } - stringBuilder.AppendLine("
NameCreated AtUpdated AtTypeStatus
{ec2Instance.Name}{ec2Instance.CreatedAt}{ec2Instance.UpdatedAt}{ec2Instance.Type}{ec2Instance.Status}
"); + var mailer = scope.ServiceProvider.GetRequiredService(); + await mailer.SendUsageReportAsync(configuration["TO_EMAIL"], configuration["FROM_EMAIL"]); } -// get lambda -logger.LogDebug("Populate Lambda"); -var lambdaFunction = serviceProvider.GetRequiredService(); -foreach (var region in regions) +static IConfiguration BuildConfiguration() { - stringBuilder.AppendLine($"

Lambda (Region: {region})

"); - stringBuilder.AppendLine(""); - stringBuilder.AppendLine(""); - var functions = await lambdaFunction.GetFunctionsAsync(region); - foreach (var functionData in functions) - { - stringBuilder.AppendLine($""); - } - stringBuilder.AppendLine("
NameCreated AtVersionRuntimeStatus
{functionData.Name}{functionData.CreatedAt}{functionData.Version}{functionData.Runtime}{functionData.Status}
"); + return new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("appsettings.json", optional: true) + .AddEnvironmentVariables() + .Build(); } -logger.LogDebug("Populate ECR"); -var containerImages = serviceProvider.GetRequiredService(); -foreach (var region in regions) +static ServiceProvider BuildServiceProvider(IConfiguration configuration) { - stringBuilder.AppendLine($"

ECR (Region: {region})

"); - stringBuilder.AppendLine(""); - stringBuilder.AppendLine(""); - var images = await containerImages.GetImagesAsync(region); - foreach (var imageData in images) + var services = new ServiceCollection(); + services.AddSingleton(configuration); + services.AddLogging(logging => { - stringBuilder.AppendLine($""); - } - stringBuilder.AppendLine("
NameCreated AtStatus
{imageData.Name}{imageData.CreatedAt}{imageData.Status}
"); -} + logging.ClearProviders(); + logging.AddConfiguration(configuration.GetSection("Logging")); + logging.AddConsole(); + }); -logger.LogDebug("Populate S3"); -var buckets = serviceProvider.GetRequiredService(); -foreach (var region in regions) -{ - stringBuilder.AppendLine($"

S3 (Region: {region})

"); - stringBuilder.AppendLine(""); - stringBuilder.AppendLine(""); - var bucketList = await buckets.GetBuckets(region); - foreach (var bucket in bucketList) + var awsOptions = new AWSOptions { - stringBuilder.AppendLine($""); - } - stringBuilder.AppendLine("
NameCreated AtStatus
{bucket.Name}{bucket.CreatedAt}{bucket.Status}
"); + Region = RegionEndpoint.GetBySystemName(ReportMailer.SesRegion) + }; + services.AddDefaultAWSOptions(awsOptions); + services.AddAWSService(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + + return services.BuildServiceProvider(); } -// sending email -logger.LogDebug("Sending Email"); -var sesRegion = RegionEndpoint.GetBySystemName("ap-southeast-1"); -using var emailClient = new AmazonSimpleEmailServiceV2Client(sesRegion); -var request = new SendEmailRequest -{ - Content = new EmailContent - { - Simple = new Message - { - Subject = new Content - { - Data = "Report Usage" - }, - Body = new Body - { - Html = new Content - { - Data = stringBuilder.ToString() - } - } - } - }, - Destination = new Destination - { - ToAddresses = new List { Environment.GetEnvironmentVariable("TO_EMAIL") ?? "" }, - }, - FromEmailAddress = Environment.GetEnvironmentVariable("FROM_EMAIL") ?? "" -}; -var response = await emailClient.SendEmailAsync(request); -logger.LogDebug($"Sent Email: {response.MessageId}"); diff --git a/ServiceMonitor.Mailer/RegionData.cs b/ServiceMonitor.Mailer/RegionData.cs new file mode 100644 index 00000000..7351d963 --- /dev/null +++ b/ServiceMonitor.Mailer/RegionData.cs @@ -0,0 +1,7 @@ +namespace ServiceMonitor.Mailer; + +public class RegionData +{ + public string Region { get; set; } = string.Empty; + public ICollection Data { get; set; } = []; +} \ No newline at end of file diff --git a/ServiceMonitor.Mailer/ReportMailer.cs b/ServiceMonitor.Mailer/ReportMailer.cs new file mode 100644 index 00000000..481f0b95 --- /dev/null +++ b/ServiceMonitor.Mailer/ReportMailer.cs @@ -0,0 +1,99 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; +using Amazon.SimpleEmailV2; +using Amazon.SimpleEmailV2.Model; +using Microsoft.Extensions.Logging; +using ServiceMonitor.Cloud; +using BasicProperty = ServiceMonitor.Cloud.Model.BasicProperty; +using FunctionProperty = ServiceMonitor.Cloud.Model.FunctionProperty; +using InstanceProperty = ServiceMonitor.Cloud.Model.InstanceProperty; + +namespace ServiceMonitor.Mailer; + +public sealed class ReportMailer( + IInstance instances, + IFunction functions, + IImage images, + IBucket buckets, + IAmazonSimpleEmailServiceV2 emailClient, + ILogger logger) +{ + public const string SesRegion = "ap-southeast-3"; + private const string TemplateName = "MyReport"; + private static readonly string[] Regions = ["ap-southeast-1", "ap-southeast-3"]; + + public async Task CreateMailDataAsync(CancellationToken cancellationToken = default) + { + var mailData = new MailData + { + ReportTime = DateTimeOffset.UtcNow.ToString("O", CultureInfo.InvariantCulture) + }; + + foreach (var region in Regions) + { + logger.LogDebug("Collecting report data for region {Region}", region); + mailData.EC2Services.Add(new RegionData + { + Region = region, + Data = await instances.GetInstancesAsync(region, cancellationToken: cancellationToken) + }); + mailData.LambdaList.Add(new RegionData + { + Region = region, + Data = await functions.GetFunctionsAsync(region, cancellationToken) + }); + mailData.ECRList.Add(new RegionData + { + Region = region, + Data = await images.GetImagesAsync(region, cancellationToken) + }); + mailData.S3List.Add(new RegionData + { + Region = region, + Data = await buckets.GetBuckets(region, cancellationToken) + }); + } + + return mailData; + } + + public async Task SendUsageReportAsync( + string? toEmail, + string? fromEmail, + CancellationToken cancellationToken = default) + { + var recipient = RequireEmailAddress(toEmail, "TO_EMAIL"); + var sender = RequireEmailAddress(fromEmail, "FROM_EMAIL"); + var mailData = await CreateMailDataAsync(cancellationToken); + + var response = await emailClient.SendEmailAsync(new SendEmailRequest + { + Content = new EmailContent + { + Template = new Template + { + TemplateName = TemplateName, + TemplateData = JsonSerializer.Serialize(mailData) + } + }, + Destination = new Destination + { + ToAddresses = [recipient] + }, + FromEmailAddress = sender + }, cancellationToken); + + logger.LogInformation("Sent usage report with message ID {MessageId}", response.MessageId); + } + + private static string RequireEmailAddress(string? address, string settingName) + { + if (string.IsNullOrWhiteSpace(address)) + { + throw new InvalidOperationException($"Required configuration value '{settingName}' is missing."); + } + + return address.Trim(); + } +} \ No newline at end of file diff --git a/ServiceMonitor.Mailer/ServiceMonitor.Mailer.csproj b/ServiceMonitor.Mailer/ServiceMonitor.Mailer.csproj index 002bf898..11534787 100644 --- a/ServiceMonitor.Mailer/ServiceMonitor.Mailer.csproj +++ b/ServiceMonitor.Mailer/ServiceMonitor.Mailer.csproj @@ -5,6 +5,7 @@ net10.0 enable enable + 15 diff --git a/ServiceMonitor.Test/EcsTests.cs b/ServiceMonitor.Test/EcsTests.cs new file mode 100644 index 00000000..8e6c5f05 --- /dev/null +++ b/ServiceMonitor.Test/EcsTests.cs @@ -0,0 +1,67 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Amazon.ECS; +using Amazon.ECS.Model; +using ServiceMonitor.AWS; +using Xunit; +using Task = System.Threading.Tasks.Task; + +namespace ServiceMonitor.Test +{ + public class EcsTests + { + [Fact] + public async Task ListsAllPagesSequentiallyForEachCluster() + { + using var client = new FakeEcsClient(); + using var cancellation = new CancellationTokenSource(); + client.ExpectedToken = cancellation.Token; + + var clusters = (await Ecs.GetClusters(client, cancellation.Token)).ToList(); + + Assert.Equal(new[] { "cluster-1", "cluster-2" }, clusters.Select(x => x.Identity)); + Assert.Equal(new[] { "service-1", "service-2" }, clusters[0].Services.Select(x => x.Identity)); + Assert.Equal(new[] { "task-1", "task-2" }, clusters[0].Tasks.Select(x => x.Identity)); + Assert.Empty(clusters[1].Services); + Assert.Empty(clusters[1].Tasks); + Assert.Equal(new[] { "clusters:", "services:cluster-1:", "services:cluster-1:next", "tasks:cluster-1:", "tasks:cluster-1:next", "clusters:next", "services:cluster-2:", "tasks:cluster-2:" }, client.Calls); + } + + private class FakeEcsClient : AmazonECSClient + { + public readonly List Calls = new List(); + public CancellationToken ExpectedToken; + + public override Task ListClustersAsync(ListClustersRequest request, CancellationToken cancellationToken = default) + { + Assert.Equal(ExpectedToken, cancellationToken); + Calls.Add($"clusters:{request.NextToken}"); + return Task.FromResult(request.NextToken == null + ? new ListClustersResponse { ClusterArns = new List { "cluster-1" }, NextToken = "next" } + : new ListClustersResponse { ClusterArns = new List { "cluster-2" } }); + } + + public override Task ListServicesAsync(ListServicesRequest request, CancellationToken cancellationToken = default) + { + Assert.Equal(ExpectedToken, cancellationToken); + Calls.Add($"services:{request.Cluster}:{request.NextToken}"); + if (request.Cluster == "cluster-2") return Task.FromResult(new ListServicesResponse()); + return Task.FromResult(request.NextToken == null + ? new ListServicesResponse { ServiceArns = new List { "service-1" }, NextToken = "next" } + : new ListServicesResponse { ServiceArns = new List { "service-2" } }); + } + + public override Task ListTasksAsync(ListTasksRequest request, CancellationToken cancellationToken = default) + { + Assert.Equal(ExpectedToken, cancellationToken); + Calls.Add($"tasks:{request.Cluster}:{request.NextToken}"); + if (request.Cluster == "cluster-2") return Task.FromResult(new ListTasksResponse()); + return Task.FromResult(request.NextToken == null + ? new ListTasksResponse { TaskArns = new List { "task-1" }, NextToken = "next" } + : new ListTasksResponse { TaskArns = new List { "task-2" } }); + } + } + } +} \ No newline at end of file diff --git a/ServiceMonitor.Test/ReportMailerTests.cs b/ServiceMonitor.Test/ReportMailerTests.cs new file mode 100644 index 00000000..3f35427a --- /dev/null +++ b/ServiceMonitor.Test/ReportMailerTests.cs @@ -0,0 +1,188 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Amazon.SimpleEmailV2; +using Amazon.SimpleEmailV2.Model; +using Microsoft.Extensions.Logging.Abstractions; +using ServiceMonitor.Cloud; +using ServiceMonitor.Mailer; +using BasicProperty = ServiceMonitor.Cloud.Model.BasicProperty; +using FunctionProperty = ServiceMonitor.Cloud.Model.FunctionProperty; +using InstanceProperty = ServiceMonitor.Cloud.Model.InstanceProperty; +using TagItem = ServiceMonitor.Cloud.Model.TagItem; +using Xunit; + +namespace ServiceMonitor.Test; + +public class ReportMailerTests +{ + [Fact] + public async Task CreateMailDataAsyncCollectsEveryResourceForBothRegions() + { + var resources = new FakeCloudResources(); + using var emailClient = new FakeSesClient(); + var mailer = CreateMailer(resources, emailClient); + + var mailData = await mailer.CreateMailDataAsync(); + + Assert.Equal(2, mailData.EC2Services.Count); + Assert.Equal(2, mailData.LambdaList.Count); + Assert.Equal(2, mailData.ECRList.Count); + Assert.Equal(2, mailData.S3List.Count); + Assert.Equal(new[] { "ap-southeast-1", "ap-southeast-3" }, mailData.EC2Services.Select(region => region.Region)); + Assert.All(mailData.EC2Services, region => Assert.Single(region.Data)); + Assert.All(mailData.LambdaList, region => Assert.Single(region.Data)); + Assert.All(mailData.ECRList, region => Assert.Single(region.Data)); + Assert.All(mailData.S3List, region => Assert.Single(region.Data)); + Assert.Equal(TimeSpan.Zero, DateTimeOffset.Parse(mailData.ReportTime).Offset); + } + + [Fact] + public async Task CreateMailDataAsyncRetainsRegionsWhenServicesReturnNoResults() + { + var resources = new FakeCloudResources(returnEmpty: true); + using var emailClient = new FakeSesClient(); + var mailer = CreateMailer(resources, emailClient); + + var mailData = await mailer.CreateMailDataAsync(); + + Assert.All(mailData.EC2Services, region => Assert.Empty(region.Data)); + Assert.All(mailData.LambdaList, region => Assert.Empty(region.Data)); + Assert.All(mailData.ECRList, region => Assert.Empty(region.Data)); + Assert.All(mailData.S3List, region => Assert.Empty(region.Data)); + Assert.Equal(2, mailData.EC2Services.Count); + Assert.Equal(2, mailData.LambdaList.Count); + Assert.Equal(2, mailData.ECRList.Count); + Assert.Equal(2, mailData.S3List.Count); + } + + [Fact] + public async Task SendUsageReportAsyncSendsMailDataThroughSesTemplate() + { + var resources = new FakeCloudResources(); + using var emailClient = new FakeSesClient(); + var mailer = CreateMailer(resources, emailClient); + + await mailer.SendUsageReportAsync(" recipient@example.com ", " sender@example.com "); + + Assert.NotNull(emailClient.Request); + Assert.Equal("sender@example.com", emailClient.Request.FromEmailAddress); + Assert.Equal(new[] { "recipient@example.com" }, emailClient.Request.Destination.ToAddresses); + Assert.Equal("MyReport", emailClient.Request.Content.Template.TemplateName); + using var templateData = JsonDocument.Parse(emailClient.Request.Content.Template.TemplateData); + var report = templateData.RootElement; + Assert.True(report.TryGetProperty("ReportTime", out _)); + Assert.Equal(2, report.GetProperty("EC2Services").GetArrayLength()); + Assert.Equal(2, report.GetProperty("LambdaList").GetArrayLength()); + Assert.Equal(2, report.GetProperty("ECRList").GetArrayLength()); + Assert.Equal(2, report.GetProperty("S3List").GetArrayLength()); + Assert.Equal(8, resources.CallCount); + } + + [Theory] + [InlineData(null, "sender@example.com", "TO_EMAIL")] + [InlineData(" ", "sender@example.com", "TO_EMAIL")] + [InlineData("recipient@example.com", null, "FROM_EMAIL")] + [InlineData("recipient@example.com", " ", "FROM_EMAIL")] + public async Task SendUsageReportAsyncRejectsMissingAddressesWithoutAwsCalls( + string recipient, + string sender, + string settingName) + { + var resources = new FakeCloudResources(); + using var emailClient = new FakeSesClient(); + var mailer = CreateMailer(resources, emailClient); + + var exception = await Assert.ThrowsAsync( + () => mailer.SendUsageReportAsync(recipient, sender)); + + Assert.Contains(settingName, exception.Message); + Assert.Equal(0, resources.CallCount); + Assert.Null(emailClient.Request); + } + + private static ReportMailer CreateMailer(FakeCloudResources resources, FakeSesClient emailClient) + { + return new ReportMailer( + resources, + resources, + resources, + resources, + emailClient, + NullLogger.Instance); + } + + private sealed class FakeCloudResources(bool returnEmpty = false) : IInstance, IFunction, IImage, IBucket + { + public int CallCount { get; private set; } + + public Task> GetInstancesAsync( + string region, + int limit = 100, + CancellationToken cancellationToken = default) + { + CallCount++; + ICollection resources = returnEmpty + ? [] + : [new InstanceProperty { Name = $"instance-{region}", Type = "t3.micro", Status = "running" }]; + return Task.FromResult(resources); + } + + public Task> GetFunctionsAsync(string region, CancellationToken cancellationToken = default) + { + CallCount++; + ICollection resources = returnEmpty + ? [] + : [new FunctionProperty { Name = $"function-{region}", Version = "1", Runtime = "dotnet", Status = "active" }]; + return Task.FromResult(resources); + } + + public Task> GetImagesAsync(string region, CancellationToken cancellationToken = default) + { + CallCount++; + ICollection resources = returnEmpty + ? [] + : [new BasicProperty { Name = $"image-{region}", Status = "available" }]; + return Task.FromResult(resources); + } + + public Task> GetBuckets(string region, CancellationToken cancellationToken = default) + { + CallCount++; + ICollection resources = returnEmpty + ? [] + : [new BasicProperty { Name = $"bucket-{region}", Status = "available" }]; + return Task.FromResult(resources); + } + + public Task> GetTags(string region, string repoName, CancellationToken cancellationToken = default) + { + return Task.FromResult>([]); + } + + public Task<(List, List)> DeleteTags( + string region, + string repoName, + ICollection tags, + CancellationToken cancellationToken = default) + { + return Task.FromResult((new List(), new List())); + } + } + + private sealed class FakeSesClient : AmazonSimpleEmailServiceV2Client + { + public SendEmailRequest Request { get; private set; } + + public override Task SendEmailAsync( + SendEmailRequest request, + CancellationToken cancellationToken = default) + { + Request = request; + return Task.FromResult(new SendEmailResponse { MessageId = "message-id" }); + } + } +} \ No newline at end of file diff --git a/ServiceMonitor.Test/ServiceMonitor.Test.csproj b/ServiceMonitor.Test/ServiceMonitor.Test.csproj index bbbf999d..39603999 100644 --- a/ServiceMonitor.Test/ServiceMonitor.Test.csproj +++ b/ServiceMonitor.Test/ServiceMonitor.Test.csproj @@ -4,6 +4,8 @@ net10.0 false + + 15 @@ -19,4 +21,9 @@
+ + + + +