repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Security.Claims; using Amazon.Runtime; using Microsoft.AspNetCore.Builder; using System.Net; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Http; using System.Text.Json; using AWS.Deploy.CLI.ServerMode.Models; using AWS.Deploy.Common; namespace AWS.Deploy.CLI.ServerMode { public static class ExtensionMethods { /// <summary> /// Create an AWSCredentials object from the key information set as claims on the current request's ClaimsPrincipal. /// </summary> /// <param name="user"></param> public static AWSCredentials? ToAWSCredentials(this ClaimsPrincipal user) { var awsAccessKeyId = user.Claims.FirstOrDefault(x => string.Equals(x.Type, AwsCredentialsAuthenticationHandler.ClaimAwsAccessKeyId))?.Value; var awsSecretKey = user.Claims.FirstOrDefault(x => string.Equals(x.Type, AwsCredentialsAuthenticationHandler.ClaimAwsSecretKey))?.Value; var awsSessionToken = user.Claims.FirstOrDefault(x => string.Equals(x.Type, AwsCredentialsAuthenticationHandler.ClaimAwsSessionToken))?.Value; if(string.IsNullOrEmpty(awsAccessKeyId) || string.IsNullOrEmpty(awsSecretKey)) { return null; } if(!string.IsNullOrEmpty(awsSessionToken)) { return new SessionAWSCredentials(awsAccessKeyId, awsSecretKey, awsSessionToken); } return new BasicAWSCredentials(awsAccessKeyId, awsSecretKey); } public static void ConfigureExceptionHandler(this IApplicationBuilder app) { app.UseExceptionHandler(error => { error.Run(async context => { context.Response.StatusCode = (int) HttpStatusCode.InternalServerError; context.Response.ContentType = "application/json"; var contextFeature = context.Features.Get<IExceptionHandlerFeature>(); if (contextFeature != null) { var exceptionString = ""; if (contextFeature.Error is DeployToolException deployToolException) { exceptionString = JsonSerializer.Serialize( new DeployToolExceptionSummary( deployToolException.ErrorCode.ToString(), deployToolException.Message, deployToolException.ProcessExitCode)); } else { exceptionString = JsonSerializer.Serialize( new DeployToolExceptionSummary( DeployToolErrorCode.UnexpectedError.ToString(), contextFeature.Error?.Message ?? string.Empty)); } await context.Response.WriteAsync(exceptionString); } }); }); } } }
79
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Orchestration; namespace AWS.Deploy.CLI.ServerMode { public class SessionState { public string SessionId { get; set; } public string ProjectPath { get; set; } public string AWSRegion { get; set; } public string AWSAccountId { get; set; } public ProjectDefinition ProjectDefinition { get; set; } public IList<Recommendation>? NewRecommendations { get; set; } public IList<CloudApplication>? ExistingDeployments { get; set; } public Recommendation? SelectedRecommendation { get; set; } public CloudApplication ApplicationDetails { get; } = new CloudApplication(string.Empty, string.Empty, CloudApplicationResourceType.None, string.Empty); public Task? DeploymentTask { get; set; } public SessionState( string sessionId, string projectPath, string awsRegion, string awsAccountId, ProjectDefinition projectDefinition ) { SessionId = sessionId; ProjectPath = projectPath; AWSRegion = awsRegion; AWSAccountId = awsAccountId; ProjectDefinition = projectDefinition; } } }
51
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Text.Json.Serialization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using AWS.Deploy.CLI.ServerMode.Services; using AWS.Deploy.Orchestration.Data; using AWS.Deploy.Common; using AWS.Deploy.Orchestration.CDK; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.CLI.ServerMode.Hubs; using Microsoft.AspNetCore.HostFiltering; namespace AWS.Deploy.CLI.ServerMode { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<HostFilteringOptions>( options => options.AllowedHosts = new List<string> { "127.0.0.1", "localhost" }); services.AddCustomServices(); services.AddSingleton<IDeploymentSessionStateServer>(new InMemoryDeploymentSessionStateServer()); services.AddAuthentication(options => { options.DefaultScheme = AwsCredentialsAuthenticationHandler.SchemaName; }) .AddScheme<AwsCredentialsAuthenticationSchemeOptions, AwsCredentialsAuthenticationHandler> (AwsCredentialsAuthenticationHandler.SchemaName, _ => { }); services.AddSignalR(); services.AddControllers() .AddJsonOptions(opts => { opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }); services.AddSwaggerGen(c => { c.UseAllOfToExtendReferenceSchemas(); c.EnableAnnotations(); c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "AWS .NET Deploy Tool Server Mode API", Description = "The API exposed by the AWS .NET Deploy tool when started in server mode. This is intended for IDEs like Visual Studio to integrate the deploy tool into the IDE for deployment features.", License = new OpenApiLicense { Name = "Apache 2", Url = new Uri("https://aws.amazon.com/apache-2-0/"), } }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.ConfigureExceptionHandler(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub<DeploymentCommunicationHub>("/DeploymentCommunicationHub"); }); } } }
102
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using System.Threading.Tasks; using Amazon; using Amazon.ElasticLoadBalancingV2; using AWS.Deploy.CLI.Utilities; using AWS.Deploy.Recipes; using AWS.Deploy.Orchestration.CDK; using AWS.Deploy.Orchestration.Data; using AWS.Deploy.Common; using AWS.Deploy.CLI.ServerMode.Tasks; using AWS.Deploy.CLI.ServerMode.Models; using AWS.Deploy.CLI.ServerMode.Services; using AWS.Deploy.Orchestration; using Swashbuckle.AspNetCore.Annotations; using AWS.Deploy.CLI.ServerMode.Hubs; using Microsoft.AspNetCore.SignalR; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.Orchestration.Utilities; using Microsoft.AspNetCore.Authorization; using Amazon.Runtime; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Orchestration.DisplayedResources; using AWS.Deploy.Common.IO; using AWS.Deploy.Orchestration.LocalUserSettings; using AWS.Deploy.CLI.Commands; using AWS.Deploy.CLI.Commands.TypeHints; using AWS.Deploy.Common.TypeHintData; using AWS.Deploy.Orchestration.ServiceHandlers; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.Recipes.Validation; namespace AWS.Deploy.CLI.ServerMode.Controllers { [Produces("application/json")] [ApiController] [Route("api/v1/[controller]")] public class DeploymentController : ControllerBase { private readonly IDeploymentSessionStateServer _stateServer; private readonly IProjectParserUtility _projectParserUtility; private readonly ICloudApplicationNameGenerator _cloudApplicationNameGenerator; private readonly IHubContext<DeploymentCommunicationHub, IDeploymentCommunicationHub> _hubContext; public DeploymentController( IDeploymentSessionStateServer stateServer, IProjectParserUtility projectParserUtility, ICloudApplicationNameGenerator cloudApplicationNameGenerator, IHubContext<DeploymentCommunicationHub, IDeploymentCommunicationHub> hubContext ) { _stateServer = stateServer; _projectParserUtility = projectParserUtility; _cloudApplicationNameGenerator = cloudApplicationNameGenerator; _hubContext = hubContext; } /// <summary> /// Start a deployment session. A session id will be generated. This session id needs to be passed in future API calls to configure and execute deployment. /// </summary> [HttpPost("session")] [SwaggerOperation(OperationId = "StartDeploymentSession")] [SwaggerResponse(200, type: typeof(StartDeploymentSessionOutput))] [Authorize] public async Task<IActionResult> StartDeploymentSession(StartDeploymentSessionInput input) { var output = new StartDeploymentSessionOutput( Guid.NewGuid().ToString() ); var serviceProvider = CreateSessionServiceProvider(output.SessionId, input.AWSRegion); var awsResourceQueryer = serviceProvider.GetRequiredService<IAWSResourceQueryer>(); var state = new SessionState( output.SessionId, input.ProjectPath, input.AWSRegion, (await awsResourceQueryer.GetCallerIdentity(input.AWSRegion)).Account, await _projectParserUtility.Parse(input.ProjectPath) ); _stateServer.Save(output.SessionId, state); var deployedApplicationQueryer = serviceProvider.GetRequiredService<IDeployedApplicationQueryer>(); var session = CreateOrchestratorSession(state); var orchestrator = CreateOrchestrator(state); // Determine what recommendations are possible for the project. var recommendations = await orchestrator.GenerateDeploymentRecommendations(); state.NewRecommendations = recommendations; // Get all existing CloudApplications based on the deploymentTypes filter var allDeployedApplications = await deployedApplicationQueryer.GetExistingDeployedApplications(recommendations.Select(x => x.Recipe.DeploymentType).ToList()); var existingApplications = await deployedApplicationQueryer.GetCompatibleApplications(recommendations, allDeployedApplications, session); state.ExistingDeployments = existingApplications; output.DefaultDeploymentName = _cloudApplicationNameGenerator.GenerateValidName(state.ProjectDefinition, existingApplications); return Ok(output); } /// <summary> /// Closes the deployment session. This removes any session state for the session id. /// </summary> [HttpDelete("session/<sessionId>")] [SwaggerOperation(OperationId = "CloseDeploymentSession")] [Authorize] public IActionResult CloseDeploymentSession(string sessionId) { _stateServer.Delete(sessionId); return Ok(); } /// <summary> /// Gets the list of compatible deployments for the session's project. The list is ordered with the first recommendation in the list being the most compatible recommendation. /// </summary> [HttpGet("session/<sessionId>/recommendations")] [SwaggerOperation(OperationId = "GetRecommendations")] [SwaggerResponse(200, type: typeof(GetRecommendationsOutput))] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)] [Authorize] public async Task<IActionResult> GetRecommendations(string sessionId) { var state = _stateServer.Get(sessionId); if (state == null) { return NotFound($"Session ID {sessionId} not found."); } var orchestrator = CreateOrchestrator(state); var output = new GetRecommendationsOutput(); //NewRecommendations is set during StartDeploymentSession API. It is only updated here if NewRecommendations was null. state.NewRecommendations ??= await orchestrator.GenerateDeploymentRecommendations(); foreach (var recommendation in state.NewRecommendations) { if (recommendation.Recipe.DisableNewDeployments) continue; output.Recommendations.Add(new RecommendationSummary( baseRecipeId: recommendation.Recipe.BaseRecipeId, recipeId: recommendation.Recipe.Id, name: recommendation.Name, settingsCategories: CategorySummary.FromCategories(recommendation.GetConfigurableOptionSettingCategories()), isPersistedDeploymentProject: recommendation.Recipe.PersistedDeploymentProject, shortDescription: recommendation.ShortDescription, description: recommendation.Description, targetService: recommendation.Recipe.TargetService, deploymentType: recommendation.Recipe.DeploymentType )); } return Ok(output); } /// <summary> /// Gets the list of updatable option setting items for the selected recommendation. /// </summary> [HttpGet("session/<sessionId>/settings")] [SwaggerOperation(OperationId = "GetConfigSettings")] [SwaggerResponse(200, type: typeof(GetOptionSettingsOutput))] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)] [Authorize] public IActionResult GetConfigSettings(string sessionId) { var state = _stateServer.Get(sessionId); if (state == null) { return NotFound($"Session ID {sessionId} not found."); } if (state.SelectedRecommendation == null) { return NotFound($"A deployment target is not set for Session ID {sessionId}."); } var orchestrator = CreateOrchestrator(state); var serviceProvider = CreateSessionServiceProvider(state); var optionSettingHandler = serviceProvider.GetRequiredService<IOptionSettingHandler>(); var configurableOptionSettings = state.SelectedRecommendation.GetConfigurableOptionSettingItems(); var output = new GetOptionSettingsOutput(); output.OptionSettings = ListOptionSettingSummary(optionSettingHandler, state.SelectedRecommendation, configurableOptionSettings); return Ok(output); } private List<OptionSettingItemSummary> ListOptionSettingSummary(IOptionSettingHandler optionSettingHandler, Recommendation recommendation, IEnumerable<OptionSettingItem> configurableOptionSettings) { var optionSettingItems = new List<OptionSettingItemSummary>(); foreach (var setting in configurableOptionSettings) { var settingSummary = new OptionSettingItemSummary(setting.Id, setting.FullyQualifiedId, setting.Name, setting.Description, setting.Type.ToString()) { Category = setting.Category, TypeHint = setting.TypeHint?.ToString(), TypeHintData = setting.TypeHintData, Value = optionSettingHandler.GetOptionSettingValue(recommendation, setting), Advanced = setting.AdvancedSetting, ReadOnly = recommendation.IsExistingCloudApplication && !setting.Updatable, Visible = optionSettingHandler.IsOptionSettingDisplayable(recommendation, setting), SummaryDisplayable = optionSettingHandler.IsSummaryDisplayable(recommendation, setting), AllowedValues = setting.AllowedValues, ValueMapping = setting.ValueMapping, Validation = setting.Validation, ChildOptionSettings = ListOptionSettingSummary(optionSettingHandler, recommendation, setting.ChildOptionSettings) }; optionSettingItems.Add(settingSummary); } return optionSettingItems; } /// <summary> /// Applies a value for a list of option setting items on the selected recommendation. /// Option setting updates are provided as Key Value pairs with the Key being the JSON path to the leaf node. /// Only primitive data types are supported for Value updates. The Value is a string value which will be parsed as its corresponding data type. /// </summary> [HttpPut("session/<sessionId>/settings")] [SwaggerOperation(OperationId = "ApplyConfigSettings")] [SwaggerResponse(200, type: typeof(ApplyConfigSettingsOutput))] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest)] [Authorize] public async Task<IActionResult> ApplyConfigSettings(string sessionId, [FromBody] ApplyConfigSettingsInput input) { var state = _stateServer.Get(sessionId); if (state == null) { return NotFound($"Session ID {sessionId} not found."); } if (state.SelectedRecommendation == null) { return NotFound($"A deployment target is not set for Session ID {sessionId}."); } var serviceProvider = CreateSessionServiceProvider(state); var optionSettingHandler = serviceProvider.GetRequiredService<IOptionSettingHandler>(); var output = new ApplyConfigSettingsOutput(); var optionSettingItems = input.UpdatedSettings .Select(x => optionSettingHandler.GetOptionSetting(state.SelectedRecommendation, x.Key)); var readonlySettings = optionSettingItems .Where(x => state.SelectedRecommendation.IsExistingCloudApplication && !x.Updatable); if (readonlySettings.Any()) return BadRequest($"The following settings are read only and cannot be updated: {string.Join(", ", readonlySettings)}"); foreach (var updatedSetting in optionSettingItems) { try { await optionSettingHandler.SetOptionSettingValue(state.SelectedRecommendation, updatedSetting, input.UpdatedSettings[updatedSetting.FullyQualifiedId]); } catch (Exception ex) { output.FailedConfigUpdates.Add(updatedSetting.FullyQualifiedId, ex.Message); } } return Ok(output); } [HttpGet("session/<sessionId>/settings/<configSettingId>/resources")] [SwaggerOperation(OperationId = "GetConfigSettingResources")] [SwaggerResponse(200, type: typeof(GetConfigSettingResourcesOutput))] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)] [Authorize] public async Task<IActionResult> GetConfigSettingResources(string sessionId, string configSettingId) { var state = _stateServer.Get(sessionId); if (state == null) { return NotFound($"Session ID {sessionId} not found."); } if (state.SelectedRecommendation == null) { return NotFound($"A deployment target is not set for Session ID {sessionId}."); } var serviceProvider = CreateSessionServiceProvider(state); var typeHintCommandFactory = serviceProvider.GetRequiredService<ITypeHintCommandFactory>(); var optionSettingHandler = serviceProvider.GetRequiredService<IOptionSettingHandler>(); var configSetting = optionSettingHandler.GetOptionSetting(state.SelectedRecommendation, configSettingId); if (configSetting.TypeHint.HasValue && typeHintCommandFactory.GetCommand(configSetting.TypeHint.Value) is var typeHintCommand && typeHintCommand != null) { var output = new GetConfigSettingResourcesOutput(); var resourceTable = await typeHintCommand.GetResources(state.SelectedRecommendation, configSetting); if (resourceTable == null) { return NotFound("The Config Setting type hint is not recognized."); } output.Columns = resourceTable.Columns?.Select(column => new Models.TypeHintResourceColumn(column.DisplayName)).ToList(); output.Resources = resourceTable.Rows?.Select(resource => new TypeHintResourceSummary(resource.SystemName, resource.DisplayName, resource.ColumnValues)).ToList(); return Ok(output); } return NotFound("The Config Setting type hint is not recognized."); } /// <summary> /// Gets the list of existing deployments that are compatible with the session's project. /// </summary> [HttpGet("session/<sessionId>/deployments")] [SwaggerOperation(OperationId = "GetExistingDeployments")] [SwaggerResponse(200, type: typeof(GetExistingDeploymentsOutput))] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)] [Authorize] public async Task<IActionResult> GetExistingDeployments(string sessionId) { var state = _stateServer.Get(sessionId); if (state == null) { return NotFound($"Session ID {sessionId} not found."); } var serviceProvider = CreateSessionServiceProvider(state); if(state.NewRecommendations == null) { await GetRecommendations(sessionId); } var output = new GetExistingDeploymentsOutput(); if(state.NewRecommendations == null) { return Ok(output); } var deployedApplicationQueryer = serviceProvider.GetRequiredService<IDeployedApplicationQueryer>(); var session = CreateOrchestratorSession(state); //ExistingDeployments is set during StartDeploymentSession API. It is only updated here if ExistingDeployments was null. state.ExistingDeployments ??= await deployedApplicationQueryer.GetCompatibleApplications(state.NewRecommendations.ToList(), session: session); foreach(var deployment in state.ExistingDeployments) { var recommendation = state.NewRecommendations.First(x => string.Equals(x.Recipe.Id, deployment.RecipeId)); output.ExistingDeployments.Add(new ExistingDeploymentSummary( name: deployment.Name, baseRecipeId: recommendation.Recipe.BaseRecipeId, recipeId: deployment.RecipeId, recipeName: recommendation.Name, settingsCategories: CategorySummary.FromCategories(recommendation.GetConfigurableOptionSettingCategories()), isPersistedDeploymentProject: recommendation.Recipe.PersistedDeploymentProject, shortDescription: recommendation.ShortDescription, description: recommendation.Description, targetService: recommendation.Recipe.TargetService, lastUpdatedTime: deployment.LastUpdatedTime, updatedByCurrentUser: deployment.UpdatedByCurrentUser, resourceType: deployment.ResourceType, uniqueIdentifier: deployment.UniqueIdentifier)); } return Ok(output); } /// <summary> /// Set the target recipe and name for the deployment. /// </summary> [HttpPost("session/<sessionId>")] [SwaggerOperation(OperationId = "SetDeploymentTarget")] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest)] [Authorize] public async Task<IActionResult> SetDeploymentTarget(string sessionId, [FromBody] SetDeploymentTargetInput input) { var state = _stateServer.Get(sessionId); if(state == null) { return NotFound($"Session ID {sessionId} not found."); } var serviceProvider = CreateSessionServiceProvider(state); var orchestrator = CreateOrchestrator(state, serviceProvider); var cloudApplicationNameGenerator = serviceProvider.GetRequiredService<ICloudApplicationNameGenerator>(); if (!string.IsNullOrEmpty(input.NewDeploymentRecipeId)) { var newDeploymentName = input.NewDeploymentName ?? string.Empty; state.SelectedRecommendation = state.NewRecommendations?.FirstOrDefault(x => string.Equals(input.NewDeploymentRecipeId, x.Recipe.Id)); if (state.SelectedRecommendation == null) { return NotFound($"Recommendation {input.NewDeploymentRecipeId} not found."); } // We only validate the name when the recipe deployment type is not ElasticContainerRegistryImage. // This is because pushing images to ECR does not need a cloud application name. if (state.SelectedRecommendation.Recipe.DeploymentType != Common.Recipes.DeploymentTypes.ElasticContainerRegistryImage) { var validationResult = cloudApplicationNameGenerator.IsValidName(newDeploymentName, state.ExistingDeployments ?? new List<CloudApplication>(), state.SelectedRecommendation.Recipe.DeploymentType); if (!validationResult.IsValid) return ValidationProblem(validationResult.ErrorMessage); } state.ApplicationDetails.Name = newDeploymentName; state.ApplicationDetails.UniqueIdentifier = string.Empty; state.ApplicationDetails.ResourceType = orchestrator.GetCloudApplicationResourceType(state.SelectedRecommendation.Recipe.DeploymentType); state.ApplicationDetails.RecipeId = input.NewDeploymentRecipeId; await orchestrator.ApplyAllReplacementTokens(state.SelectedRecommendation, newDeploymentName); } else if(!string.IsNullOrEmpty(input.ExistingDeploymentId)) { var templateMetadataReader = serviceProvider.GetRequiredService<ICloudFormationTemplateReader>(); var deployedApplicationQueryer = serviceProvider.GetRequiredService<IDeployedApplicationQueryer>(); var optionSettingHandler = serviceProvider.GetRequiredService<IOptionSettingHandler>(); var existingDeployment = state.ExistingDeployments?.FirstOrDefault(x => string.Equals(input.ExistingDeploymentId, x.UniqueIdentifier)); if (existingDeployment == null) { return NotFound($"Existing deployment {input.ExistingDeploymentId} not found."); } state.SelectedRecommendation = state.NewRecommendations?.FirstOrDefault(x => string.Equals(existingDeployment.RecipeId, x.Recipe.Id)); if (state.SelectedRecommendation == null) { return NotFound($"Recommendation {input.NewDeploymentRecipeId} used in existing deployment {existingDeployment.RecipeId} not found."); } IDictionary<string, object> previousSettings; if (existingDeployment.ResourceType == CloudApplicationResourceType.CloudFormationStack) { var metadata = await templateMetadataReader.LoadCloudApplicationMetadata(existingDeployment.Name); previousSettings = metadata.Settings.Union(metadata.DeploymentBundleSettings).ToDictionary(x => x.Key, x => x.Value); } else { previousSettings = await deployedApplicationQueryer.GetPreviousSettings(existingDeployment, state.SelectedRecommendation); } state.SelectedRecommendation = await orchestrator.ApplyRecommendationPreviousSettings(state.SelectedRecommendation, previousSettings); state.ApplicationDetails.Name = existingDeployment.Name; state.ApplicationDetails.UniqueIdentifier = existingDeployment.UniqueIdentifier; state.ApplicationDetails.RecipeId = existingDeployment.RecipeId; state.ApplicationDetails.ResourceType = existingDeployment.ResourceType; await orchestrator.ApplyAllReplacementTokens(state.SelectedRecommendation, existingDeployment.Name); } return Ok(); } /// <summary> /// Checks the missing System Capabilities for a given session. /// </summary> [HttpPost("session/<sessionId>/compatiblity")] [SwaggerOperation(OperationId = "GetCompatibility")] [SwaggerResponse(200, type: typeof(GetCompatibilityOutput))] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)] [Authorize] public async Task<IActionResult> GetCompatibility(string sessionId) { var state = _stateServer.Get(sessionId); if (state == null) { return NotFound($"Session ID {sessionId} not found."); } if (state.SelectedRecommendation == null) { return NotFound($"A deployment target is not set for Session ID {sessionId}."); } var output = new GetCompatibilityOutput(); var serviceProvider = CreateSessionServiceProvider(state); var systemCapabilityEvaluator = serviceProvider.GetRequiredService<ISystemCapabilityEvaluator>(); var capabilities = await systemCapabilityEvaluator.EvaluateSystemCapabilities(state.SelectedRecommendation); output.Capabilities = capabilities.Select(x => new SystemCapabilitySummary(x.Name, x.Message, x.InstallationUrl)); return Ok(output); } /// <summary> /// Creates the CloudFormation template that will be used by CDK for the deployment. /// This operation returns the CloudFormation template that is created for this deployment. /// </summary> [HttpGet("session/<sessionId>/cftemplate")] [SwaggerOperation(OperationId = "GenerateCloudFormationTemplate")] [SwaggerResponse(200, type: typeof(GenerateCloudFormationTemplateOutput))] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)] [Authorize] public async Task<IActionResult> GenerateCloudFormationTemplate(string sessionId) { var state = _stateServer.Get(sessionId); if (state == null) { return NotFound($"Session ID {sessionId} not found."); } var serviceProvider = CreateSessionServiceProvider(state); var orchestratorSession = CreateOrchestratorSession(state); var orchestrator = CreateOrchestrator(state, serviceProvider); var cdkProjectHandler = CreateCdkProjectHandler(state, serviceProvider); if (state.SelectedRecommendation == null) throw new SelectedRecommendationIsNullException("The selected recommendation is null or invalid."); if (!state.SelectedRecommendation.Recipe.DeploymentType.Equals(Common.Recipes.DeploymentTypes.CdkProject)) throw new SelectedRecommendationIsIncompatibleException($"We cannot generate a CloudFormation template for the selected recommendation as it is not of type '{nameof(Models.DeploymentTypes.CloudFormationStack)}'."); var task = new DeployRecommendationTask(orchestratorSession, orchestrator, state.ApplicationDetails, state.SelectedRecommendation); var cloudFormationTemplate = await task.GenerateCloudFormationTemplate(cdkProjectHandler); var output = new GenerateCloudFormationTemplateOutput(cloudFormationTemplate); return Ok(output); } /// <summary> /// Begin execution of the deployment. /// </summary> [HttpPost("session/<sessionId>/execute")] [SwaggerOperation(OperationId = "StartDeployment")] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status424FailedDependency)] [Authorize] public async Task<IActionResult> StartDeployment(string sessionId) { var state = _stateServer.Get(sessionId); if (state == null) { return NotFound($"Session ID {sessionId} not found."); } var serviceProvider = CreateSessionServiceProvider(state); var orchestratorSession = CreateOrchestratorSession(state); var orchestrator = CreateOrchestrator(state, serviceProvider); if (state.SelectedRecommendation == null) throw new SelectedRecommendationIsNullException("The selected recommendation is null or invalid."); var optionSettingHandler = serviceProvider.GetRequiredService<IOptionSettingHandler>(); var recipeHandler = serviceProvider.GetRequiredService<IRecipeHandler>(); var settingValidatorFailedResults = optionSettingHandler.RunOptionSettingValidators(state.SelectedRecommendation); var recipeValidatorFailedResults = recipeHandler.RunRecipeValidators(state.SelectedRecommendation, orchestratorSession); if (settingValidatorFailedResults.Any() || recipeValidatorFailedResults.Any()) { var settingValidationErrorMessage = $"The deployment configuration needs to be adjusted before it can be deployed:{Environment.NewLine}"; foreach (var result in settingValidatorFailedResults) settingValidationErrorMessage += $" - {result.ValidationFailedMessage}{Environment.NewLine}{Environment.NewLine}"; foreach (var result in recipeValidatorFailedResults) settingValidationErrorMessage += $" - {result.ValidationFailedMessage}{Environment.NewLine}{Environment.NewLine}"; settingValidationErrorMessage += $"{Environment.NewLine}Please adjust your settings"; return Problem(settingValidationErrorMessage); } var systemCapabilityEvaluator = serviceProvider.GetRequiredService<ISystemCapabilityEvaluator>(); var capabilities = await systemCapabilityEvaluator.EvaluateSystemCapabilities(state.SelectedRecommendation); var missingCapabilitiesMessage = ""; foreach (var capability in capabilities) { missingCapabilitiesMessage = $"{missingCapabilitiesMessage}{capability.GetMessage()}{Environment.NewLine}"; } if (capabilities.Any()) return Problem($"Unable to start deployment due to missing system capabilities.{Environment.NewLine}{missingCapabilitiesMessage}", statusCode: Microsoft.AspNetCore.Http.StatusCodes.Status424FailedDependency); var task = new DeployRecommendationTask(orchestratorSession, orchestrator, state.ApplicationDetails, state.SelectedRecommendation); state.DeploymentTask = task.Execute(); return Ok(); } /// <summary> /// Gets the status of the deployment. /// </summary> [HttpGet("session/<sessionId>/execute")] [SwaggerOperation(OperationId = "GetDeploymentStatus")] [SwaggerResponse(200, type: typeof(GetDeploymentStatusOutput))] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)] [Authorize] public IActionResult GetDeploymentStatus(string sessionId) { var state = _stateServer.Get(sessionId); if (state == null) { return NotFound($"Session ID {sessionId} not found."); } var output = new GetDeploymentStatusOutput(); if (state.DeploymentTask == null) output.Status = DeploymentStatus.NotStarted; else if (state.DeploymentTask.IsCompleted && state.DeploymentTask.Status == TaskStatus.RanToCompletion) output.Status = DeploymentStatus.Success; else if (state.DeploymentTask.IsCompleted && state.DeploymentTask.Status == TaskStatus.Faulted) { output.Status = DeploymentStatus.Error; if (state.DeploymentTask.Exception != null) { var innerException = state.DeploymentTask.Exception.InnerException; var message = innerException.GetTruncatedErrorMessage(); if (innerException is DeployToolException deployToolException) { output.Exception = new DeployToolExceptionSummary(deployToolException.ErrorCode.ToString(), message, deployToolException.ProcessExitCode); } else { output.Exception = new DeployToolExceptionSummary(DeployToolErrorCode.UnexpectedError.ToString(), message); } } } else output.Status = DeploymentStatus.Executing; return Ok(output); } /// <summary> /// Gets information about the displayed resources defined in the recipe definition. /// </summary> [HttpGet("session/<sessionId>/details")] [SwaggerOperation(OperationId = "GetDeploymentDetails")] [SwaggerResponse(200, type: typeof(GetDeploymentDetailsOutput))] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)] [Authorize] public async Task<IActionResult> GetDeploymentDetails(string sessionId) { var state = _stateServer.Get(sessionId); if (state == null) { return NotFound($"Session ID {sessionId} not found."); } var serviceProvider = CreateSessionServiceProvider(state); var displayedResourcesHandler = serviceProvider.GetRequiredService<IDisplayedResourcesHandler>(); if (state.SelectedRecommendation == null) { return NotFound($"A deployment target is not set for Session ID {sessionId}."); } var displayedResources = await displayedResourcesHandler.GetDeploymentOutputs(state.ApplicationDetails, state.SelectedRecommendation); var output = new GetDeploymentDetailsOutput( state.ApplicationDetails.Name, displayedResources .Select(x => new DisplayedResourceSummary(x.Id, x.Description, x.Type, x.Data)) .ToList()); return Ok(output); } private IServiceProvider CreateSessionServiceProvider(SessionState state) { return CreateSessionServiceProvider(state.SessionId, state.AWSRegion); } private IServiceProvider CreateSessionServiceProvider(string sessionId, string awsRegion) { var awsCredentials = HttpContext.User.ToAWSCredentials(); if(awsCredentials == null) { throw new FailedToRetrieveAWSCredentialsException("AWS credentials are missing for the current session."); } var interactiveServices = new SessionOrchestratorInteractiveService(sessionId, _hubContext); var services = new ServiceCollection(); services.AddSingleton<IOrchestratorInteractiveService>(interactiveServices); services.AddSingleton<ICommandLineWrapper>(services => { var wrapper = new CommandLineWrapper(interactiveServices, true); wrapper.RegisterAWSContext(awsCredentials, awsRegion); return wrapper; }); services.AddCustomServices(); var serviceProvider = services.BuildServiceProvider(); var awsClientFactory = serviceProvider.GetRequiredService<IAWSClientFactory>(); awsClientFactory.ConfigureAWSOptions(awsOptions => { awsOptions.Credentials = awsCredentials; awsOptions.Region = RegionEndpoint.GetBySystemName(awsRegion); }); return serviceProvider; } private OrchestratorSession CreateOrchestratorSession(SessionState state, AWSCredentials? awsCredentials = null) { return new OrchestratorSession( state.ProjectDefinition, awsCredentials ?? HttpContext.User.ToAWSCredentials() ?? throw new FailedToRetrieveAWSCredentialsException("The tool was not able to retrieve the AWS Credentials."), state.AWSRegion, state.AWSAccountId); } private CdkProjectHandler CreateCdkProjectHandler(SessionState state, IServiceProvider? serviceProvider = null) { if (serviceProvider == null) { serviceProvider = CreateSessionServiceProvider(state); } return new CdkProjectHandler( serviceProvider.GetRequiredService<IOrchestratorInteractiveService>(), serviceProvider.GetRequiredService<ICommandLineWrapper>(), serviceProvider.GetRequiredService<IAWSResourceQueryer>(), serviceProvider.GetRequiredService<ICdkAppSettingsSerializer>(), serviceProvider.GetRequiredService<IFileManager>(), serviceProvider.GetRequiredService<IDirectoryManager>(), serviceProvider.GetRequiredService<IOptionSettingHandler>(), serviceProvider.GetRequiredService<IDeployToolWorkspaceMetadata>(), serviceProvider.GetRequiredService<ICloudFormationTemplateReader>() ); } private Orchestrator CreateOrchestrator(SessionState state, IServiceProvider? serviceProvider = null, AWSCredentials? awsCredentials = null) { if(serviceProvider == null) { serviceProvider = CreateSessionServiceProvider(state); } var session = CreateOrchestratorSession(state, awsCredentials); return new Orchestrator( session, serviceProvider.GetRequiredService<IOrchestratorInteractiveService>(), serviceProvider.GetRequiredService<ICdkProjectHandler>(), serviceProvider.GetRequiredService<ICDKManager>(), serviceProvider.GetRequiredService<ICDKVersionDetector>(), serviceProvider.GetRequiredService<IAWSResourceQueryer>(), serviceProvider.GetRequiredService<IDeploymentBundleHandler>(), serviceProvider.GetRequiredService<ILocalUserSettingsEngine>(), new DockerEngine.DockerEngine( session.ProjectDefinition, serviceProvider.GetRequiredService<IFileManager>(), serviceProvider.GetRequiredService<IDirectoryManager>()), serviceProvider.GetRequiredService<IRecipeHandler>(), serviceProvider.GetRequiredService<IFileManager>(), serviceProvider.GetRequiredService<IDirectoryManager>(), serviceProvider.GetRequiredService<IAWSServiceHandler>(), serviceProvider.GetRequiredService<IOptionSettingHandler>(), serviceProvider.GetRequiredService<IDeployToolWorkspaceMetadata>() ); } } }
769
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; using AWS.Deploy.CLI.ServerMode.Models; using Microsoft.AspNetCore.Mvc; namespace AWS.Deploy.CLI.ServerMode.Controllers { [Produces("application/json")] [ApiController] [Route("api/v1/[controller]")] public class HealthController : ControllerBase { /// <summary> /// Gets the health of the deployment tool. Use this API after starting the command line to see if the tool is ready to handle requests. /// </summary> [HttpGet] public HealthStatusOutput Get() { return new HealthStatusOutput { Status = SystemStatus.Ready }; } } }
30
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.CLI.ServerMode.Models; using AWS.Deploy.Common; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Recipes; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; namespace AWS.Deploy.CLI.ServerMode.Controllers { [Produces("application/json")] [ApiController] [Route("api/v1/[controller]")] public class RecipeController : ControllerBase { private readonly IRecipeHandler _recipeHandler; private readonly IProjectDefinitionParser _projectDefinitionParser; public RecipeController(IRecipeHandler recipeHandler, IProjectDefinitionParser projectDefinitionParser) { _recipeHandler = recipeHandler; _projectDefinitionParser = projectDefinitionParser; } private async Task<List<RecipeDefinition>> GetAllAvailableRecipes(string? projectPath = null) { var recipePaths = new HashSet<string> { RecipeLocator.FindRecipeDefinitionsPath() }; HashSet<string> customRecipePaths = new HashSet<string>(); if (!string.IsNullOrEmpty(projectPath)) { var projectDefinition = await _projectDefinitionParser.Parse(projectPath); customRecipePaths = await _recipeHandler.LocateCustomRecipePaths(projectDefinition); } return await _recipeHandler.GetRecipeDefinitions(recipeDefinitionPaths: recipePaths.Union(customRecipePaths).ToList()); } /// <summary> /// Gets a list of available recipe IDs. /// </summary> [HttpGet("recipes")] [SwaggerOperation(OperationId = "ListAllRecipes")] [SwaggerResponse(200, type: typeof(ListAllRecipesOutput))] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest)] public async Task<IActionResult> ListAllRecipes([FromQuery] string? projectPath = null) { var recipeDefinitions = await GetAllAvailableRecipes(projectPath); var recipes = recipeDefinitions .Select(x => new RecipeSummary( x.Id, x.Version, x.Name, x.Description, x.ShortDescription, x.TargetService, x.DeploymentType.ToString(), x.DeploymentBundle.ToString()) ).ToList(); var output = new ListAllRecipesOutput { Recipes = recipes }; return Ok(output); } /// <summary> /// Gets a summary of the specified Recipe. /// </summary> [HttpGet("{recipeId}")] [SwaggerOperation(OperationId = "GetRecipe")] [SwaggerResponse(200, type: typeof(RecipeSummary))] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest)] public async Task<IActionResult> GetRecipe(string recipeId, [FromQuery] string? projectPath = null) { if (string.IsNullOrEmpty(recipeId)) { return BadRequest($"A Recipe ID was not provided."); } var recipeDefinitions = await GetAllAvailableRecipes(projectPath); var selectedRecipeDefinition = recipeDefinitions.FirstOrDefault(x => x.Id.Equals(recipeId)); if (selectedRecipeDefinition == null) { return BadRequest($"Recipe ID {recipeId} not found."); } var output = new RecipeSummary( selectedRecipeDefinition.Id, selectedRecipeDefinition.Version, selectedRecipeDefinition.Name, selectedRecipeDefinition.Description, selectedRecipeDefinition.ShortDescription, selectedRecipeDefinition.TargetService, selectedRecipeDefinition.DeploymentType.ToString(), selectedRecipeDefinition.DeploymentBundle.ToString() ); return Ok(output); } /// <summary> /// Gets a summary of the specified recipe option settings. /// </summary> [HttpGet("{recipeId}/settings")] [SwaggerOperation(OperationId = "GetRecipeOptionSettings")] [SwaggerResponse(200, type: typeof(List<RecipeOptionSettingSummary>))] [ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest)] public async Task<IActionResult> GetRecipeOptionSettings(string recipeId, [FromQuery] string? projectPath = null) { if (string.IsNullOrEmpty(recipeId)) { return BadRequest($"A Recipe ID was not provided."); } var recipeDefinitions = await GetAllAvailableRecipes(projectPath); var selectedRecipeDefinition = recipeDefinitions.FirstOrDefault(x => x.Id.Equals(recipeId)); if (selectedRecipeDefinition == null) { return BadRequest($"Recipe ID {recipeId} not found."); } var settings = GetOptionSettingSummary(selectedRecipeDefinition.OptionSettings); return Ok(settings); } private List<RecipeOptionSettingSummary> GetOptionSettingSummary(List<OptionSettingItem> optionSettingItems) { var settings = new List<RecipeOptionSettingSummary>(); foreach (var optionSetting in optionSettingItems) { settings.Add(new RecipeOptionSettingSummary( optionSetting.Id, optionSetting.Name, optionSetting.Description, optionSetting.Type.ToString() ) { Settings = GetOptionSettingSummary(optionSetting.ChildOptionSettings) }); } return settings; } } }
160
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Hosting; using Swashbuckle.AspNetCore.Annotations; namespace AWS.Deploy.CLI.ServerMode.Controllers { /// <summary> /// Contains operations to manage the lifecycle of the server /// </summary> [Produces("application/json")] [ApiController] [Route("api/v1/[controller]")] public class ServerController : ControllerBase { private readonly IHostApplicationLifetime _applicationLifetime; public ServerController(IHostApplicationLifetime applicationLifetime) { _applicationLifetime = applicationLifetime; } /// <summary> /// Requests to stop the deployment tool. Any open sessions are implicitly closed. /// This may return <see cref="OkResult"/> prior to the server being stopped, /// clients may need to wait or check the health after requesting shutdown. /// </summary> [HttpPost("Shutdown")] [SwaggerOperation(OperationId = "Shutdown")] [Authorize] public IActionResult Shutdown() { _applicationLifetime.StopApplication(); return Ok(); } } }
41
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; namespace AWS.Deploy.CLI.ServerMode.Hubs { public interface IDeploymentCommunicationHub { Task JoinSession(string sessionId); Task OnLogSectionStart(string sectionName, string? description); Task OnLogDebugMessage(string? message); Task OnLogErrorMessage(string? message); Task OnLogInfoMessage(string? message); } public class DeploymentCommunicationHub : Hub<IDeploymentCommunicationHub> { public async Task JoinSession(string sessionId) { await Groups.AddToGroupAsync(Context.ConnectionId, sessionId); } } }
29
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; namespace AWS.Deploy.CLI.ServerMode.Models { public class ApplyConfigSettingsInput { public Dictionary<string, string> UpdatedSettings { get; set; } = new Dictionary<string, string>(); } }
13
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; namespace AWS.Deploy.CLI.ServerMode.Models { public class ApplyConfigSettingsOutput { public IDictionary<string, string> FailedConfigUpdates { get; set; } = new Dictionary<string, string>(); } }
13
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; namespace AWS.Deploy.CLI.ServerMode.Models { /// <summary> /// A category defined in the recipe that settings will be mapped to via the Id property. /// </summary> public class CategorySummary { /// <summary> /// The id of the category that will be specified on top level settings. /// </summary> public string Id { get; set; } /// <summary> /// The display name of the category shown to users in UI screens. /// </summary> public string DisplayName { get; set; } /// <summary> /// The order used to sort categories in UI screens. Categories will be shown in sorted descending order. /// </summary> public int Order { get; set; } public CategorySummary(string id, string displayName, int order) { Id = id; DisplayName = displayName; Order = order; } /// <summary> /// Transform recipe category types into the this ServerMode model type. /// </summary> /// <param name="categories"></param> /// <returns></returns> public static List<CategorySummary> FromCategories(List<AWS.Deploy.Common.Recipes.Category> categories) { return categories.Select(x => new CategorySummary(id: x.Id, displayName: x.DisplayName, order: x.Order)).ToList(); } } }
48
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.CLI.ServerMode.Models { public enum DeploymentTypes { CloudFormationStack, BeanstalkEnvironment, ElasticContainerRegistryImage } }
13
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.CLI.ServerMode.Models { public class DeployToolExceptionSummary { public string ErrorCode { get; set; } public string Message { get; set; } public int? ProcessExitCode { get; set; } public DeployToolExceptionSummary(string errorCode, string message, int? processExitCode = null) { ErrorCode = errorCode; Message = message; ProcessExitCode = processExitCode; } } }
20
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; namespace AWS.Deploy.CLI.ServerMode.Models { public class DisplayedResourceSummary { /// <summary> /// The Physical ID that represents a CloudFormation resource /// </summary> public string Id { get; set; } /// <summary> /// The description of the resource that is defined in the recipe definition /// </summary> public string Description { get; set; } /// <summary> /// The CloudFormation resource type /// </summary> public string Type { get; set; } /// <summary> /// The Key Value pair of additional data unique to this resource type /// </summary> public Dictionary<string, string> Data { get; set; } public DisplayedResourceSummary(string id, string description, string type, Dictionary<string, string> data) { Id = id; Description = description; Type = type; Data = data; } } }
39
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.CLI.ServerMode.Models { public enum SystemStatus { Ready = 1, Error = 2 }; public enum DeploymentStatus { NotStarted = 1, Executing = 2, Error = 3, Success = 4} }
14
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.Common; namespace AWS.Deploy.CLI.ServerMode.Models { public class ExistingDeploymentSummary { private readonly Dictionary<CloudApplicationResourceType, DeploymentTypes> _deploymentTargetsMapping = new() { { CloudApplicationResourceType.CloudFormationStack, DeploymentTypes.CloudFormationStack }, { CloudApplicationResourceType.BeanstalkEnvironment, DeploymentTypes.BeanstalkEnvironment }, { CloudApplicationResourceType.ElasticContainerRegistryImage, DeploymentTypes.ElasticContainerRegistryImage} }; public string Name { get; set; } public string? BaseRecipeId { get; set; } public string RecipeId { get; set; } public string RecipeName { get; set; } public bool IsPersistedDeploymentProject { get; set; } public string ShortDescription { get; set; } public string Description { get; set; } public string TargetService { get; set; } public DateTime? LastUpdatedTime { get; set; } public bool UpdatedByCurrentUser { get; set; } public DeploymentTypes DeploymentType { get; set; } public List<CategorySummary> SettingsCategories { get; set; } public string ExistingDeploymentId { get; set; } public ExistingDeploymentSummary( string name, string? baseRecipeId, string recipeId, string recipeName, List<CategorySummary> settingsCategories, bool isPersistedDeploymentProject, string shortDescription, string description, string targetService, DateTime? lastUpdatedTime, bool updatedByCurrentUser, CloudApplicationResourceType resourceType, string uniqueIdentifier ) { Name = name; BaseRecipeId = baseRecipeId; RecipeId = recipeId; RecipeName = recipeName; SettingsCategories = settingsCategories; IsPersistedDeploymentProject = isPersistedDeploymentProject; ShortDescription = shortDescription; Description = description; TargetService = targetService; LastUpdatedTime = lastUpdatedTime; UpdatedByCurrentUser = updatedByCurrentUser; ExistingDeploymentId = uniqueIdentifier; if (!_deploymentTargetsMapping.ContainsKey(resourceType)) { var message = $"Failed to find a deployment target mapping for {nameof(CloudApplicationResourceType)} {resourceType}."; throw new FailedToFindDeploymentTargetsMappingException(message); } DeploymentType = _deploymentTargetsMapping[resourceType]; } } }
85
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using AWS.Deploy.CLI.ServerMode.Controllers; namespace AWS.Deploy.CLI.ServerMode.Models { /// <summary> /// The response that will be returned by the <see cref="DeploymentController.GenerateCloudFormationTemplate(string)"/> operation. /// </summary> public class GenerateCloudFormationTemplateOutput { /// <summary> /// The CloudFormation template of the generated CDK deployment project. /// </summary> public string CloudFormationTemplate { get; set; } public GenerateCloudFormationTemplateOutput(string cloudFormationTemplate) { CloudFormationTemplate = cloudFormationTemplate; } } }
24
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; namespace AWS.Deploy.CLI.ServerMode.Models { public class GetCompatibilityOutput { public IEnumerable<SystemCapabilitySummary> Capabilities { get; set; } = new List<SystemCapabilitySummary>(); } }
13
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; namespace AWS.Deploy.CLI.ServerMode.Models { /// <summary> /// Represents a list or table of options, generally used when selecting from /// a list of existing AWS resources to set an OptionSettingItem /// </summary> public class GetConfigSettingResourcesOutput { /// <summary> /// Columns that should appear above the list of resources when /// presenting the user a table to select from /// </summary> /// <remarks> /// If this is null or empty, it implies that there is only a single column. /// This may be better suited for a simple dropdown as opposed to a table or modal select. /// </remarks> public List<TypeHintResourceColumn>? Columns { get; set; } /// <summary> /// List of resources that the user could select from /// </summary> public List<TypeHintResourceSummary>? Resources { get; set; } } }
30
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; namespace AWS.Deploy.CLI.ServerMode.Models { public class GetDeploymentDetailsOutput { /// <summary> /// The CloudApplication Name /// </summary> public string CloudApplicationName { get; set; } /// <summary> /// The list of displayed resources based on the recipe definition /// </summary> public List<DisplayedResourceSummary> DisplayedResources { get; set; } public GetDeploymentDetailsOutput(string cloudApplicationName, List<DisplayedResourceSummary> displayedResources) { CloudApplicationName = cloudApplicationName; DisplayedResources = displayedResources; } } }
27
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AWS.Deploy.CLI.ServerMode.Models { public class GetDeploymentStatusOutput { public DeploymentStatus Status { get; set; } public DeployToolExceptionSummary? Exception { get; set; } } }
17
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AWS.Deploy.CLI.ServerMode.Models { public class GetExistingDeploymentsOutput { public IList<ExistingDeploymentSummary> ExistingDeployments { get; set; } = new List<ExistingDeploymentSummary>(); } }
16
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; namespace AWS.Deploy.CLI.ServerMode.Models { public class GetOptionSettingsOutput { public IList<OptionSettingItemSummary> OptionSettings { get; set; } = new List<OptionSettingItemSummary>(); } }
13
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AWS.Deploy.CLI.ServerMode.Models { public class GetRecommendationsOutput { public IList<RecommendationSummary> Recommendations { get; set; } = new List<RecommendationSummary>(); } }
16
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.CLI.ServerMode.Models { public class HealthStatusOutput { public SystemStatus Status { get; set; } } }
15
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using AWS.Deploy.CLI.ServerMode.Controllers; namespace AWS.Deploy.CLI.ServerMode.Models { /// <summary> /// Output returned by the <see cref="RecipeController.ListAllRecipes"/> API /// </summary> public class ListAllRecipesOutput { /// <summary> /// A list of Recipe IDs /// </summary> public IList<RecipeSummary> Recipes { get; set; } = new List<RecipeSummary>(); } }
20
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.CLI.ServerMode.Models { public class OptionSettingItemSummary { /// <summary> /// The unique id of setting. This value will be persisted in other config files so its value should never change once a recipe is released. /// </summary> public string Id { get; set; } /// <summary> /// The fully qualified id of the setting that includes the Id and all of the parent's Ids. /// This helps easily reference the Option Setting without context of the parent setting. /// </summary> public string FullyQualifiedId { get; set; } /// <summary> /// The display friendly name of the setting. /// </summary> public string Name { get; set; } /// <summary> /// The category for the setting. This value must match an id field in the list of categories. /// </summary> public string? Category { get; set; } /// <summary> /// The description of what the setting is used for. /// </summary> public string Description { get; set; } /// <summary> /// The value used for the recipe if it is set by the user. /// </summary> public object? Value { get; set; } /// <summary> /// The type of primitive value expected for this setting. /// For example String, Int /// </summary> public string Type { get; set; } /// <summary> /// Hint the the UI what type of setting this is optionally add additional UI features to select a value. /// For example a value of BeanstalkApplication tells the UI it can display the list of available Beanstalk applications for the user to pick from. /// </summary> public string? TypeHint { get; set; } /// <summary> /// Type hint additional data required to facilitate handling of the option setting. /// </summary> public Dictionary<string, object> TypeHintData { get; set; } = new(StringComparer.OrdinalIgnoreCase); /// <summary> /// UI can use this to reduce the amount of settings to show to the user when confirming the recommendation. This can make it so the user sees only the most important settings /// they need to know about before deploying. /// </summary> public bool Advanced { get; set; } /// <summary> /// Indicates whether the setting can be edited /// </summary> public bool ReadOnly { get; set; } /// <summary> /// Indicates whether the setting is visible/displayed on the UI /// </summary> public bool Visible { get; set; } /// <summary> /// Indicates whether the setting can be displayed as part of the settings summary of the previous deployment. /// </summary> public bool SummaryDisplayable { get; set; } /// <summary> /// The allowed values for the setting. /// </summary> public IList<string> AllowedValues { get; set; } = new List<string>(); /// <summary> /// The value mapping for allowed values. The key of the dictionary is what is sent to services /// and the value is the display value shown to users. /// </summary> public IDictionary<string, string> ValueMapping { get; set; } = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Child option settings for <see cref="OptionSettingValueType.Object"/> value types /// <see cref="ChildOptionSettings"/> value depends on the values of <see cref="ChildOptionSettings"/> /// </summary> public List<OptionSettingItemSummary> ChildOptionSettings { get; set; } = new(); /// <summary> /// The validation state of the setting that contains the validation status and message. /// </summary> public OptionSettingValidation Validation { get; set; } public OptionSettingItemSummary(string id, string fullyQualifiedId, string name, string description, string type) { Id = id; FullyQualifiedId = fullyQualifiedId; Name = name; Description = description; Type = type; Validation = new OptionSettingValidation(); } } }
114
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.CLI.ServerMode.Models { /// <summary> /// Represents a recipe <see cref="OptionSettingItem"/> returned through server mode. /// </summary> public class RecipeOptionSettingSummary { /// <summary> /// The unique id of setting. /// </summary> public string Id { get; set; } /// <summary> /// The display friendly name of the setting. /// </summary> public string Name { get; set; } /// <summary> /// The description of what the setting is used for. /// </summary> public string Description { get; set; } /// <summary> /// The type of primitive value expected for this setting. /// For example String, Int /// </summary> public string Type { get; set; } /// <summary> /// Child option settings for <see cref="OptionSettingValueType.Object"/> value types. /// </summary> public List<RecipeOptionSettingSummary> Settings { get; set; } = new List<RecipeOptionSettingSummary>(); public RecipeOptionSettingSummary(string id, string name, string description, string type) { Id = id; Name = name; Description = description; Type = type; } } }
49
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.CLI.ServerMode.Models { public class RecipeSummary { public string Id { get; set; } public string Version { get; set; } public string Name { get; set; } public string Description { get; set; } public string ShortDescription { get; set; } public string TargetService { get; set; } public string DeploymentType { get; set; } public string DeploymentBundle { get; set; } public RecipeSummary(string id, string version, string name, string description, string shortDescription, string targetService, string deploymentType, string deploymentBundle) { Id = id; Version = version; Name = name; Description = description; ShortDescription = shortDescription; TargetService = targetService; DeploymentType = deploymentType; DeploymentBundle = deploymentBundle; } } }
37
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.CLI.ServerMode.Models { public class RecommendationSummary { private readonly Dictionary<Common.Recipes.DeploymentTypes, DeploymentTypes> _deploymentTargetsMapping = new() { { Common.Recipes.DeploymentTypes.CdkProject, DeploymentTypes.CloudFormationStack }, { Common.Recipes.DeploymentTypes.BeanstalkEnvironment, DeploymentTypes.BeanstalkEnvironment }, { Common.Recipes.DeploymentTypes.ElasticContainerRegistryImage, DeploymentTypes.ElasticContainerRegistryImage } }; public string? BaseRecipeId { get; set; } public string RecipeId { get; set; } public string Name { get; set; } public bool IsPersistedDeploymentProject { get; set; } public string ShortDescription { get; set; } public string Description { get; set; } public string TargetService { get; set; } public DeploymentTypes DeploymentType { get; set; } public List<CategorySummary> SettingsCategories { get; set; } public RecommendationSummary( string? baseRecipeId, string recipeId, string name, List<CategorySummary> settingsCategories, bool isPersistedDeploymentProject, string shortDescription, string description, string targetService, Common.Recipes.DeploymentTypes deploymentType ) { BaseRecipeId = baseRecipeId; RecipeId = recipeId; Name = name; SettingsCategories = settingsCategories; IsPersistedDeploymentProject = isPersistedDeploymentProject; ShortDescription = shortDescription; Description = description; TargetService = targetService; if (!_deploymentTargetsMapping.ContainsKey(deploymentType)) { var message = $"Failed to find a deployment target mapping for {nameof(Common.Recipes.DeploymentTypes)} {deploymentType}."; throw new FailedToFindDeploymentTargetsMappingException(message); } DeploymentType = _deploymentTargetsMapping[deploymentType]; } } }
60
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.CLI.ServerMode.Models { public class SetDeploymentTargetInput { public string? NewDeploymentName { get; set; } public string? NewDeploymentRecipeId { get; set; } public string? ExistingDeploymentId { get; set; } } }
19
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.CLI.ServerMode.Models { public class StartDeploymentSessionInput { public string AWSRegion { get; set; } public string ProjectPath { get; set; } public StartDeploymentSessionInput( string awsRegion, string projectPath) { AWSRegion = awsRegion; ProjectPath = projectPath; } } }
24
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.CLI.ServerMode.Models { public class StartDeploymentSessionOutput { public string SessionId { get; set; } public string? DefaultDeploymentName { get; set; } public StartDeploymentSessionOutput(string sessionId) { SessionId = sessionId; } } }
22
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.CLI.ServerMode.Models { public class SystemCapabilitySummary { public string Name { get; set; } public string Message { get; set; } public string? InstallationUrl { get; set; } public SystemCapabilitySummary(string name, string message, string? installationUrl = null) { Name = name; Message = message; InstallationUrl = installationUrl; } } }
20
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.CLI.ServerMode.Models { /// <summary> /// Represents a column for a list/grid of <see cref="TypeHintResourceSummary"/> rows /// </summary> public class TypeHintResourceColumn { /// <summary> /// Name of the column to be displayed to users /// </summary> public string DisplayName { get; set; } public TypeHintResourceColumn(string displayName) { DisplayName = displayName; } } }
22
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; namespace AWS.Deploy.CLI.ServerMode.Models { /// <summary> /// Represents a single type hint option, generally used when selecting from /// a list of existing AWS resources to set an OptionSettingItem /// </summary> public class TypeHintResourceSummary { /// <summary> /// Resource Id, used when saving a selected resource to an OptionSettingItem /// </summary> public string SystemName { get; set; } /// <summary> /// Resource name, used for display /// </summary> public string DisplayName { get; set; } /// <summary> /// Additional data about the resource, which may be used when displaying a table /// or grid of options for the user to select from. The indices into this list should /// match the column indicies of a list of <see cref="TypeHintResourceColumn"/> /// </summary> public List<string> ColumnDisplayValues { get; set; } public TypeHintResourceSummary(string systemName, string displayName, List<string> columnDisplayValues) { SystemName = systemName; DisplayName = displayName; ColumnDisplayValues = new List<string>(columnDisplayValues); } } }
40
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Threading.Tasks; namespace AWS.Deploy.CLI.ServerMode.Services { public class AesEncryptionProvider : IEncryptionProvider { private readonly Aes _aes; public AesEncryptionProvider(Aes aes) { _aes = aes; } public byte[] Decrypt(byte[] encryptedData, byte[]? generatedIV) { var decryptor = _aes.CreateDecryptor(_aes.Key, generatedIV); using var inputStream = new MemoryStream(encryptedData); using var decryptStream = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read); using var outputStream = new MemoryStream(); decryptStream.CopyTo(outputStream); return outputStream.ToArray(); } } }
36
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.CLI.ServerMode.Services { public interface IDeploymentSessionStateServer { SessionState? Get(string id); void Save(string id, SessionState state); void Delete(string id); } }
19
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AWS.Deploy.CLI.ServerMode.Services { public interface IEncryptionProvider { byte[] Decrypt(byte[] encryptedData, byte[]? generatedIV); } }
16
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.CLI.ServerMode.Services { public class InMemoryDeploymentSessionStateServer : IDeploymentSessionStateServer { private readonly IDictionary<string, SessionState> _store = new ConcurrentDictionary<string, SessionState>(); public SessionState? Get(string id) { if(_store.TryGetValue(id, out var state)) { return state; } return null; } public void Save(string id, SessionState state) => _store[id] = state; public void Delete(string id) { if(_store.ContainsKey(id)) { _store.Remove(id); } } } }
36
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AWS.Deploy.CLI.ServerMode.Services { public class NoEncryptionProvider : IEncryptionProvider { public byte[] Decrypt(byte[] encryptedData, byte[]? generatedIV) => encryptedData; } }
16
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.CLI.ServerMode.Hubs; using AWS.Deploy.Orchestration; using Microsoft.AspNetCore.SignalR; namespace AWS.Deploy.CLI.ServerMode.Services { public class SessionOrchestratorInteractiveService : IOrchestratorInteractiveService { private readonly string _sessionId; private readonly IHubContext<DeploymentCommunicationHub, IDeploymentCommunicationHub> _hubContext; public SessionOrchestratorInteractiveService(string sessionId, IHubContext<DeploymentCommunicationHub, IDeploymentCommunicationHub> hubContext) { _sessionId = sessionId; _hubContext = hubContext; } public void LogSectionStart(string message, string? description) { _hubContext.Clients.Group(_sessionId).OnLogSectionStart(message, description); } public void LogDebugMessage(string? message) { _hubContext.Clients.Group(_sessionId).OnLogDebugMessage(message); } public void LogErrorMessage(string? message) { _hubContext.Clients.Group(_sessionId).OnLogErrorMessage(message); } public void LogInfoMessage(string? message) { _hubContext.Clients.Group(_sessionId).OnLogInfoMessage(message); } } }
47
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Orchestration; namespace AWS.Deploy.CLI.ServerMode.Tasks { public class DeployRecommendationTask { private readonly CloudApplication _cloudApplication; private readonly Orchestrator _orchestrator; private readonly OrchestratorSession _orchestratorSession; private readonly Recommendation _selectedRecommendation; public DeployRecommendationTask(OrchestratorSession orchestratorSession, Orchestrator orchestrator, CloudApplication cloudApplication, Recommendation selectedRecommendation) { _orchestratorSession = orchestratorSession; _orchestrator = orchestrator; _cloudApplication = cloudApplication; _selectedRecommendation = selectedRecommendation; } public async Task Execute() { await _orchestrator.CreateDeploymentBundle(_cloudApplication, _selectedRecommendation); await _orchestrator.DeployRecommendation(_cloudApplication, _selectedRecommendation); } /// <summary> /// Generates the CloudFormation template that will be used by CDK for the deployment. /// This involves creating a deployment bundle, generating the CDK project and running 'cdk diff' to get the CF template. /// This operation returns the CloudFormation template that is created for this deployment. /// </summary> public async Task<string> GenerateCloudFormationTemplate(CdkProjectHandler cdkProjectHandler) { if (cdkProjectHandler == null) throw new FailedToCreateCDKProjectException(DeployToolErrorCode.FailedToCreateCDKProject, $"We could not create a CDK deployment project due to a missing dependency '{nameof(cdkProjectHandler)}'."); await _orchestrator.CreateDeploymentBundle(_cloudApplication, _selectedRecommendation); var cdkProject = await cdkProjectHandler.ConfigureCdkProject(_orchestratorSession, _cloudApplication, _selectedRecommendation); try { return await cdkProjectHandler.PerformCdkDiff(cdkProject, _cloudApplication); } finally { cdkProjectHandler.DeleteTemporaryCdkProject(cdkProject); } } } }
59
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.CLI.TypeHintResponses { /// <summary> /// The <see cref="BeanstalkApplicationTypeHintResponse"/> class encapsulates /// <see cref="OptionSettingTypeHint.BeanstalkApplication"/> type hint response /// </summary> public class BeanstalkApplicationTypeHintResponse : IDisplayable { public bool CreateNew { get; set; } public string? ApplicationName { get; set; } public string? ExistingApplicationName { get; set; } public BeanstalkApplicationTypeHintResponse( bool createNew) { CreateNew = createNew; } public string ToDisplayString() { if (CreateNew) return ApplicationName!; else return ExistingApplicationName!; } } }
33
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.CLI.TypeHintResponses { /// <summary> /// The <see cref="BeanstalkApplicationTypeHintResponse"/> class encapsulates /// <see cref="OptionSettingTypeHint.BeanstalkEnvironment"/> type hint response /// </summary> public class BeanstalkEnvironmentTypeHintResponse : IDisplayable { public bool CreateNew { get; set; } public string EnvironmentName { get; set; } public BeanstalkEnvironmentTypeHintResponse( bool createNew, string environmentName) { CreateNew = createNew; EnvironmentName = environmentName; } public string ToDisplayString() => EnvironmentName; } }
28
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.CLI.TypeHintResponses { /// <summary> /// The <see cref="ECSClusterTypeHintResponse"/> class encapsulates /// <see cref="AWS.Deploy.Common.Recipes.OptionSettingTypeHint.ECSCluster"/> type hint response /// </summary> public class ECSClusterTypeHintResponse : IDisplayable { public bool CreateNew { get; set; } public string ClusterArn { get; set; } public string NewClusterName { get; set; } public ECSClusterTypeHintResponse( bool createNew, string clusterArn, string newClusterName) { CreateNew = createNew; ClusterArn = clusterArn; NewClusterName = newClusterName; } public string ToDisplayString() { if (CreateNew) return NewClusterName; return ClusterArn; } } }
35
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.CLI.TypeHintResponses { /// <summary> /// <see cref="OptionSettingTypeHint.Vpc"/> type hint response /// </summary> public class ElasticBeanstalkVpcTypeHintResponse : IDisplayable { public bool UseVPC { get; set; } public bool CreateNew { get; set; } public string? VpcId { get; set; } public SortedSet<string> Subnets { get; set; } = new SortedSet<string>(); public SortedSet<string> SecurityGroups { get; set; } = new SortedSet<string>(); public string? ToDisplayString() => null; } }
23
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.CLI.TypeHintResponses { /// <summary> /// The <see cref="IAMRoleTypeHintResponse"/> class encapsulates /// <see cref="OptionSettingTypeHint.IAMRole"/> type hint response /// </summary> public class IAMRoleTypeHintResponse : IDisplayable { public string? RoleArn { get; set; } public bool CreateNew { get; set; } public string ToDisplayString() => CreateNew ? Constants.CLI.CREATE_NEW_LABEL : RoleArn ?? ""; } }
20
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.CLI.TypeHintResponses { /// <summary> /// The <see cref="VPCConnectorTypeHintResponse"/> class encapsulates /// <see cref="OptionSettingTypeHint.VPCConnector"/> type hint response /// </summary> public class VPCConnectorTypeHintResponse : IDisplayable { public string? VpcConnectorId { get; set; } public bool UseVPCConnector { get; set; } public bool CreateNew { get; set; } public bool CreateNewVpc { get; set; } public string? VpcId { get; set; } public SortedSet<string> Subnets { get; set; } = new SortedSet<string>(); public SortedSet<string> SecurityGroups { get; set; } = new SortedSet<string>(); /// <summary> /// Returning null will default to the tool's default display. /// </summary> public string? ToDisplayString() => null; } }
29
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.CLI.TypeHintResponses { /// <summary> /// <see cref="OptionSettingTypeHint.Vpc"/> type hint response /// </summary> public class VpcTypeHintResponse : IDisplayable { /// <summary> /// Indicates if the user has selected to use the default vpc. Note: It's valid /// for this to be true without looking up an setting <see cref="VpcId"/> /// </summary> public bool IsDefault {get; set; } public bool CreateNew { get;set; } public string VpcId { get; set; } public VpcTypeHintResponse( bool isDefault, bool createNew, string vpcId) { IsDefault = isDefault; CreateNew = createNew; VpcId = vpcId; } public string ToDisplayString() { if (CreateNew) return Constants.CLI.CREATE_NEW_LABEL; return $"{VpcId}{(IsDefault ? Constants.CLI.DEFAULT_LABEL : "")}"; } } }
40
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; using Amazon.Runtime; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.CLI.Utilities { /// <summary> /// Handle the callback from AWSCredentials when an MFA token code is required. /// </summary> public class AssumeRoleMfaTokenCodeCallback { private readonly AssumeRoleAWSCredentialsOptions _options; private readonly IToolInteractiveService _toolInteractiveService; private readonly IDirectoryManager _directoryManager; private readonly IOptionSettingHandler _optionSettingHandler; public AssumeRoleMfaTokenCodeCallback(IToolInteractiveService toolInteractiveService, IDirectoryManager directoryManager, IOptionSettingHandler optionSettingHandler, AssumeRoleAWSCredentialsOptions options) { _toolInteractiveService = toolInteractiveService; _options = options; _directoryManager = directoryManager; _optionSettingHandler = optionSettingHandler; } public string Execute() { _toolInteractiveService.WriteLine(); _toolInteractiveService.WriteLine($"Enter MFA code for {_options.MfaSerialNumber}: "); var consoleUtilites = new ConsoleUtilities(_toolInteractiveService, _directoryManager, _optionSettingHandler); var code = consoleUtilites.ReadSecretFromConsole(); return code; } } }
42
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using Amazon.Runtime; using AWS.Deploy.Orchestration.Utilities; namespace AWS.Deploy.CLI.Utilities { public static class AWSContextCommandLineWrapperExtension { /// <summary> /// AWS Credentials and Region information is determined after DI container is built. /// <see cref="RegisterAWSContext"/> extension method allows to register late bound properties (credentials & region) to /// <see cref="ICommandLineWrapper"/> instance. /// </summary> public static void RegisterAWSContext( this ICommandLineWrapper commandLineWrapper, AWSCredentials awsCredentials, string region) { commandLineWrapper.ConfigureProcess(async processStartInfo => { var credentials = await awsCredentials.GetCredentialsAsync(); // use this syntax to make sure we don't create duplicate entries processStartInfo.EnvironmentVariables["AWS_ACCESS_KEY_ID"] = credentials.AccessKey; processStartInfo.EnvironmentVariables["AWS_SECRET_ACCESS_KEY"] = credentials.SecretKey; processStartInfo.EnvironmentVariables["AWS_REGION"] = region; if (credentials.UseToken) { processStartInfo.EnvironmentVariables["AWS_SESSION_TOKEN"] = credentials.Token; } }); } } }
38
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; using AWS.Deploy.Common; using AWS.Deploy.Orchestration; using AWS.Deploy.Orchestration.Utilities; namespace AWS.Deploy.CLI.Utilities { public class CommandLineWrapper : ICommandLineWrapper { private readonly IOrchestratorInteractiveService _interactiveService; private readonly bool _useSeparateWindow; private Action<ProcessStartInfo>? _processStartInfoAction; public CommandLineWrapper( IOrchestratorInteractiveService interactiveService) { _interactiveService = interactiveService; } public CommandLineWrapper( IOrchestratorInteractiveService interactiveService, bool useSeparateWindow) : this(interactiveService) { _useSeparateWindow = useSeparateWindow; } /// <inheritdoc /> public async Task Run( string command, string workingDirectory = "", bool streamOutputToInteractiveService = true, Action<TryRunResult>? onComplete = null, bool redirectIO = true, string? stdin = null, IDictionary<string, string>? environmentVariables = null, CancellationToken cancelToken = default, bool needAwsCredentials = false) { StringBuilder strOutput = new StringBuilder(); StringBuilder strError = new StringBuilder(); var processStartInfo = new ProcessStartInfo { FileName = GetSystemShell(), Arguments = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"/c {command}" : $"-c \"{command}\"", RedirectStandardInput = redirectIO || stdin != null, RedirectStandardOutput = redirectIO, RedirectStandardError = redirectIO, UseShellExecute = false, CreateNoWindow = redirectIO, WorkingDirectory = workingDirectory }; // If the command output is not being redirected check to see if // the output should go to a separate console window. This is important when run from // an IDE which won't have a console window by default. if (!streamOutputToInteractiveService && !redirectIO) { processStartInfo.UseShellExecute = _useSeparateWindow; } UpdateEnvironmentVariables(processStartInfo, environmentVariables); if (needAwsCredentials) _processStartInfoAction?.Invoke(processStartInfo); var process = Process.Start(processStartInfo); if (null == process) throw new Exception("Process.Start failed to return a non-null process"); if (redirectIO) { process.OutputDataReceived += (sender, e) => { if(streamOutputToInteractiveService) { _interactiveService.LogInfoMessage(e.Data); } strOutput.AppendLine(e.Data); }; process.ErrorDataReceived += (sender, e) => { if(streamOutputToInteractiveService) { _interactiveService.LogInfoMessage(e.Data); } strError.AppendLine(e.Data); }; process.BeginOutputReadLine(); process.BeginErrorReadLine(); } if(stdin != null) { process.StandardInput.Write(stdin); process.StandardInput.Close(); } await process.WaitForExitAsync(); if (onComplete != null) { var result = new TryRunResult { ExitCode = process.ExitCode }; if (redirectIO) { result.StandardError = strError.ToString(); result.StandardOut = strOutput.ToString(); } onComplete(result); } } private static void UpdateEnvironmentVariables(ProcessStartInfo processStartInfo, IDictionary<string, string>? environmentVariables) { if (environmentVariables == null) { return; } foreach (var (key, value) in environmentVariables) { if (key == EnvironmentVariableKeys.AWS_EXECUTION_ENV) { var awsExecutionEnvValue = BuildAWSExecutionEnvValue(processStartInfo, value); processStartInfo.EnvironmentVariables[key] = awsExecutionEnvValue; } else { processStartInfo.EnvironmentVariables[key] = value; } } } private static string BuildAWSExecutionEnvValue(ProcessStartInfo processStartInfo, string awsExecutionEnv) { var awsExecutionEnvBuilder = new StringBuilder(); if (processStartInfo.EnvironmentVariables.ContainsKey(EnvironmentVariableKeys.AWS_EXECUTION_ENV) && !string.IsNullOrEmpty(processStartInfo.EnvironmentVariables[EnvironmentVariableKeys.AWS_EXECUTION_ENV])) { awsExecutionEnvBuilder.Append(processStartInfo.EnvironmentVariables[EnvironmentVariableKeys.AWS_EXECUTION_ENV]); } if (!string.IsNullOrEmpty(awsExecutionEnv)) { if (awsExecutionEnvBuilder.Length != 0) { awsExecutionEnvBuilder.Append("_"); } awsExecutionEnvBuilder.Append(awsExecutionEnv); } return awsExecutionEnvBuilder.ToString(); } public void ConfigureProcess(Action<ProcessStartInfo>? processStartInfoAction) { _processStartInfoAction = processStartInfoAction; } private string GetSystemShell() { if (TryGetEnvironmentVariable("COMSPEC", out var comspec)) return comspec!; if (TryGetEnvironmentVariable("SHELL", out var shell)) return shell!; // fall back to defaults return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "cmd.exe" : "/bin/sh"; } private bool TryGetEnvironmentVariable(string variable, out string? value) { value = Environment.GetEnvironmentVariable(variable); return !string.IsNullOrEmpty(value); } } }
208
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; namespace AWS.Deploy.CLI.Utilities { /// <summary> /// Sits on top of <see cref="IProjectDefinitionParser"/> and adds UI specific logic /// for error handling. /// </summary> public interface IProjectParserUtility { Task<ProjectDefinition> Parse(string projectPath); } public class ProjectParserUtility : IProjectParserUtility { private readonly IProjectDefinitionParser _projectDefinitionParser; private readonly IDirectoryManager _directoryManager; public ProjectParserUtility( IProjectDefinitionParser projectDefinitionParser, IDirectoryManager directoryManager) { _projectDefinitionParser = projectDefinitionParser; _directoryManager = directoryManager; } public async Task<ProjectDefinition> Parse(string projectPath) { try { return await _projectDefinitionParser.Parse(projectPath); } catch (ProjectFileNotFoundException ex) { var errorMessage = ex.Message; if (_directoryManager.Exists(projectPath)) { var files = _directoryManager.GetFiles(projectPath, "*.sln").ToList(); if (files.Any()) { errorMessage = "This directory contains a solution file, but the tool requires a project file. " + "Please run the tool from the directory that contains a .csproj/.fsproj or provide a path to the .csproj/.fsproj via --project-path flag."; } } throw new FailedToFindDeployableTargetException(DeployToolErrorCode.FailedToFindDeployableTarget, errorMessage, ex); } } } }
58
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.Common { /// <summary> /// Contains CloudFormation specific configurations /// </summary> public class CloudApplication { private readonly Dictionary<CloudApplicationResourceType, string> _resourceTypeMapping = new() { { CloudApplicationResourceType.CloudFormationStack, "CloudFormation Stack" }, { CloudApplicationResourceType.BeanstalkEnvironment, "Elastic Beanstalk Environment" }, { CloudApplicationResourceType.ElasticContainerRegistryImage, "ECR Repository" } }; private readonly Dictionary<CloudApplicationResourceType, DeploymentTypes> _deploymentTypeMapping = new() { { CloudApplicationResourceType.CloudFormationStack, DeploymentTypes.CdkProject}, { CloudApplicationResourceType.BeanstalkEnvironment, DeploymentTypes.BeanstalkEnvironment }, { CloudApplicationResourceType.ElasticContainerRegistryImage, DeploymentTypes.ElasticContainerRegistryImage } }; /// <summary> /// Name of the CloudApplication resource /// </summary> public string Name { get; set; } /// <summary> /// The unique Id to identify the CloudApplication. /// The ID is set to the StackId if the CloudApplication is an existing Cloudformation stack. /// The ID is set to the EnvironmentId if the CloudApplication is an existing Elastic Beanstalk environment. /// The ID is set to string.Empty for new CloudApplications. /// </summary> public string UniqueIdentifier { get; set; } /// <summary> /// The id of the AWS .NET deployment tool recipe used to create or re-deploy the cloud application. /// </summary> public string RecipeId { get; set; } /// <summary> /// Indicates the type of the AWS resource which serves as the deployment target. /// </summary> public CloudApplicationResourceType ResourceType { get; set; } /// <summary> /// Last updated time of CloudFormation stack /// </summary> public DateTime? LastUpdatedTime { get; set; } /// <summary> /// Indicates whether the Cloud Application has been redeployed by the current user. /// </summary> public bool UpdatedByCurrentUser { get; set; } /// <summary> /// This name is shown to the user when the CloudApplication is presented as an existing re-deployment target. /// </summary> public string DisplayName => $"{Name} ({_resourceTypeMapping[ResourceType]})"; /// <summary> /// Display the name of the Cloud Application /// </summary> public override string ToString() => Name; /// <summary> /// Gets the deployment type of the recommendation that was used to deploy the cloud application. /// </summary> public DeploymentTypes DeploymentType => _deploymentTypeMapping[ResourceType]; public CloudApplication(string name, string uniqueIdentifier, CloudApplicationResourceType resourceType, string recipeId, DateTime? lastUpdatedTime = null) { Name = name; UniqueIdentifier = uniqueIdentifier; ResourceType = resourceType; RecipeId = recipeId; LastUpdatedTime = lastUpdatedTime; } } }
89
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.Common { /// <summary> /// This class represents the metadata stored with the CloudFormation template. /// </summary> public class CloudApplicationMetadata { /// <summary> /// The ID of the recipe used to deploy the application. /// </summary> public string RecipeId { get; set; } /// <summary> /// The version of the recipe used to deploy the application. /// </summary> public string RecipeVersion { get; set; } /// <summary> /// All of the settings configured for the deployment of the application with the recipe. /// </summary> public IDictionary<string, object> Settings { get; set; } = new Dictionary<string, object>(); /// <summary> /// Comprises of option settings that are part of the deployment bundle definition. /// </summary> public IDictionary<string, object> DeploymentBundleSettings { get; set; } = new Dictionary<string , object>(); public CloudApplicationMetadata(string recipeId, string recipeVersion) { RecipeId = recipeId; RecipeVersion = recipeVersion; } } }
42
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.Common { public enum CloudApplicationResourceType { None, CloudFormationStack, BeanstalkEnvironment, ElasticContainerRegistryImage } }
18
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using Amazon; using Amazon.Extensions.NETCore.Setup; using Amazon.Runtime; namespace AWS.Deploy.Common { public class DefaultAWSClientFactory : IAWSClientFactory { private Action<AWSOptions>? _awsOptionsAction; public void ConfigureAWSOptions(Action<AWSOptions> awsOptionsAction) { _awsOptionsAction = awsOptionsAction; } public T GetAWSClient<T>(string? awsRegion = null) where T : IAmazonService { var awsOptions = new AWSOptions(); _awsOptionsAction?.Invoke(awsOptions); if (!string.IsNullOrEmpty(awsRegion)) awsOptions.Region = RegionEndpoint.GetBySystemName(awsRegion); return awsOptions.CreateServiceClient<T>(); } } }
33
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace AWS.Deploy.Common { /// <summary> /// A container for User Deployment Settings file that is supplied with the deployment /// to apply defaults and bypass some user prompts. /// </summary> public class DeploymentSettings { /// <summary> /// The AWS profile to use from the AWS credentials file /// </summary> public string? AWSProfile { get; set; } /// <summary> /// The AWS region where the <see cref="CloudApplication"/> will be deployed /// </summary> public string? AWSRegion { get; set; } /// <summary> /// The name of the <see cref="CloudApplication"/> /// </summary> public string? ApplicationName { get; set; } /// <summary> /// The unique identifier of the recipe used to deploy the <see cref="CloudApplication"/> /// </summary> public string? RecipeId { get; set; } /// <summary> /// key-value pairs of OptionSettingItems /// </summary> public Dictionary<string, object>? Settings { get; set; } } }
45
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Common { /// <summary> /// Contains shared environment variable keys /// </summary> public static class EnvironmentVariableKeys { public const string AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; } }
14
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.Common { public abstract class DeployToolException : Exception { public DeployToolErrorCode ErrorCode { get; set; } public int? ProcessExitCode { get; set; } public DeployToolException(DeployToolErrorCode errorCode, string message, Exception? innerException = null, int? processExitCode = null) : base(message, innerException) { ErrorCode = errorCode; ProcessExitCode = processExitCode; } } public enum DeployToolErrorCode { ProjectPathNotFound = 10000100, ProjectParserNoSdkAttribute = 10000200, InvalidCliArguments = 10000300, SilentArgumentNeedsApplicationNameArgument = 10000400, SilentArgumentNeedsDeploymentRecipe = 10000500, DeploymentProjectPathNotFound = 10000600, RuleHasInvalidTestType = 10000700, MissingSystemCapabilities = 10000800, NoDeploymentRecipesFound = 10000900, NoCompatibleDeploymentRecipesFound = 10001000, DeploymentProjectNotSupported = 10001100, InvalidValueForOptionSettingItem = 10001200, InvalidDockerBuildArgs = 10001300, InvalidDockerExecutionDirectory = 10001400, InvalidDotnetPublishArgs = 10001500, ErrorParsingApplicationMetadata = 10001600, FailedToCreateContainerDeploymentBundle = 10001700, FailedToCreateDotnetPublishDeploymentBundle = 10001800, OptionSettingItemDoesNotExistInRecipe = 10001900, UnableToCreateValidatorInstance = 10002000, OptionSettingItemValueValidationFailed = 10002100, StackCreatedFromDifferentDeploymentRecommendation = 10002200, DeploymentConfigurationNeedsAdjusting = 10002300, UserDeploymentInvalidStackName = 10002400, InvalidPropertyValueForUserDeployment = 10002500, FailedToDeserializeUserDeploymentFile = 10002600, DeploymentBundleDefinitionNotFound = 10002700, DeploymentManifestUpdateFailed = 10002800, DockerFileTemplateNotFound = 10002900, UnableToMapProjectToDockerImage = 10003000, NoValidDockerImageForProject = 10003100, NoValidDockerMappingForSdkType = 10003200, NoValidDockerMappingForTargetFramework = 10003300, FailedToGenerateCDKProjectFromTemplate = 10003400, FailedToInstallProjectTemplates = 10003500, FailedToWritePackageJsonFile = 10003600, FailedToInstallNpmPackages = 10003700, DockerBuildFailed = 10003800, FailedToGetCDKVersion = 10003900, DockerLoginFailed = 10004000, DockerTagFailed = 10004100, DockerPushFailed = 10004200, FailedToFindRecipeDefinitions = 10004300, DotnetPublishFailed = 10004400, FailedToFindZipUtility = 10004500, ZipUtilityFailedToZip = 10004600, FailedToGenerateDockerFile = 10004700, BaseTemplatesInvalidPath = 10004800, InvalidSolutionPath = 10004900, InvalidAWSDeployRecipesCDKCommonVersion = 10005000, FailedToDeployCdkApplication = 10005100, AppRunnerServiceDoesNotExist = 10005200, BeanstalkEnvironmentDoesNotExist = 10005300, LoadBalancerDoesNotExist = 10005400, LoadBalancerListenerDoesNotExist = 10005500, CloudWatchRuleDoesNotExist = 10005600, InvalidLocalUserSettingsFile = 10005700, FailedToUpdateLocalUserSettingsFile = 10005800, FailedToCheckDockerInfo = 10005900, UnableToResolveAWSCredentials = 10006000, UnableToCreateAWSCredentials = 10006100, FailedToDeleteStack = 10006200, FailedToFindDeployableTarget = 10006300, BeanstalkAppPromptForNameReturnedNull = 10006400, BeanstalkEnvPromptForNameReturnedNull = 10006500, EC2KeyPairPromptForNameReturnedNull = 10006600, TcpPortInUse = 10006700, CompatibleRecommendationForRedeploymentNotFound = 10006800, InvalidSaveDirectoryForCdkProject = 10006900, FailedToFindDeploymentProjectRecipeId = 10007000, UnexpectedError = 10007100, FailedToCreateCdkStack = 10007200, FailedToFindElasticBeanstalkSolutionStack = 10007300, FailedToCreateDeploymentCommandInstance = 10007400, FailedToFindElasticBeanstalkApplication = 10007500, FailedS3Upload = 10007600, FailedToCreateElasticBeanstalkApplicationVersion = 10007700, FailedToUpdateElasticBeanstalkEnvironment = 10007800, FailedToCreateElasticBeanstalkStorageLocation = 10007900, UnableToAccessAWSRegion = 10008000, OptInRegionDisabled = 10008100, ECRRepositoryPromptForNameReturnedNull = 10008200, FailedToFindCloudApplicationResourceType = 10008300, ECRRepositoryDoesNotExist = 10008400, FailedToDeserializeRecipe = 10008500, FailedToDeserializeDeploymentBundle = 10008600, FailedToDeserializeDeploymentProjectRecipe = 10008700, FailedToRunCDKBootstrap = 10008800, FailedToGetCredentialsForProfile = 10008900, FailedToRunCDKDiff = 10009000, FailedToCreateCDKProject = 10009100, ResourceQuery = 10009200, FailedToRetrieveStackId = 10009300, FailedToGetECRAuthorizationToken = 10009400, InvalidCloudApplicationName = 10009500, SelectedValueIsNotAllowed = 10009600, MissingValidatorConfiguration = 10009700, InvalidFilePath = 10009800, InvalidDeployToolWorkspace = 10009900, InvalidDeploymentManifestModel = 10010000, FailedToCreateDeepCopy = 10010100, FailedToGetOptionSettingValue = 10010200, ECRRepositoryNameIsNull = 10010300, FailedToReadCdkBootstrapVersion = 10010400, UnsupportedOptionSettingType = 10010500, FailedToSaveDeploymentSettings = 10010600, InvalidWindowsManifestFile = 10010700, UserDeploymentFileNotFound = 10010800, } public class ProjectFileNotFoundException : DeployToolException { public ProjectFileNotFoundException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Common exception if the user has passed invalid input from the command line /// </summary> public class InvalidCliArgumentException : DeployToolException { public InvalidCliArgumentException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if the user attempts to deploy a <see cref="RecipeDefinition"/> but the recipe definition is invalid /// </summary> public class InvalidRecipeDefinitionException : DeployToolException { public InvalidRecipeDefinitionException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if the user attempts to deploy a <see cref="ProjectDefinition"/> but the project definition is invalid /// </summary> public class InvalidProjectDefinitionException : DeployToolException { public InvalidProjectDefinitionException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Thrown if there is a missing System Capability. /// </summary> public class MissingSystemCapabilityException : DeployToolException { public MissingSystemCapabilityException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if Recommendation Engine is unable to generate /// recommendations for a given target context /// </summary> public class FailedToGenerateAnyRecommendations : DeployToolException { public FailedToGenerateAnyRecommendations(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if a value is set that is not part of the allowed values /// of an option setting item /// </summary> public class InvalidOverrideValueException : DeployToolException { public InvalidOverrideValueException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if there is a parse error reading the existing Cloud Application's metadata /// </summary> public class ParsingExistingCloudApplicationMetadataException : DeployToolException { public ParsingExistingCloudApplicationMetadataException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if Orchestrator is unable to create /// the deployment bundle. /// </summary> public class FailedToCreateDeploymentBundleException : DeployToolException { public FailedToCreateDeploymentBundleException(DeployToolErrorCode errorCode, string message, int? processExitCode, Exception? innerException = null) : base(errorCode, message, innerException, processExitCode) { } } /// <summary> /// Throw if Option Setting Item does not exist /// </summary> public class OptionSettingItemDoesNotExistException : DeployToolException { public OptionSettingItemDoesNotExistException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } public class InvalidValidatorTypeException : DeployToolException { public InvalidValidatorTypeException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Thrown if <see cref="OptionSettingItem.SetValueOverride"/> is given an invalid value. /// </summary> public class ValidationFailedException : DeployToolException { public ValidationFailedException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Thrown if <see cref="OptionSettingItem.SetValue"/> is setting a value with an incompatible type. /// </summary> public class UnsupportedOptionSettingType : DeployToolException { public UnsupportedOptionSettingType(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Thrown if Option Setting Item Validator has missing or invalid configuration. /// </summary> public class MissingValidatorConfigurationException : DeployToolException { public MissingValidatorConfigurationException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception thrown if Project Path contains an invalid path /// </summary> public class InvalidProjectPathException : DeployToolException { public InvalidProjectPathException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if an invalid <see cref="DeploymentSettings"/> is used. /// </summary> public class InvalidDeploymentSettingsException : DeployToolException { public InvalidDeploymentSettingsException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception is thrown if we cannot retrieve deployment bundle definitions /// </summary> public class NoDeploymentBundleDefinitionsFoundException : DeployToolException { public NoDeploymentBundleDefinitionsFoundException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception thrown if a failure occured while trying to update the deployment manifest file. /// </summary> public class FailedToUpdateDeploymentManifestFileException : DeployToolException { public FailedToUpdateDeploymentManifestFileException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception thrown if a failure occured while trying to deserialize a file. /// </summary> public class FailedToDeserializeException : DeployToolException { public FailedToDeserializeException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception thrown if a failure occured while querying resources in AWS. It must be used in conjunction with <see cref="DeployToolErrorCode.ResourceQuery"/>. /// </summary> public class ResourceQueryException : DeployToolException { public ResourceQueryException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Thrown when an invalid file path is specified as an <see cref="OptionSettingItem"/> value /// </summary> public class InvalidFilePath : DeployToolException { public InvalidFilePath(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if an error occurred while saving the deployment settings to a config file /// </summary> public class FailedToSaveDeploymentSettingsException : DeployToolException { public FailedToSaveDeploymentSettingsException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } public static class ExceptionExtensions { /// <summary> /// True if the <paramref name="e"/> inherits from /// <see cref="DeployToolException"/>. /// </summary> public static bool IsAWSDeploymentExpectedException(this Exception e) => e is DeployToolException; public static string PrettyPrint(this Exception? e) { if (null == e) return string.Empty; return $"{Environment.NewLine}{e.Message}{Environment.NewLine}{e.StackTrace}{PrettyPrint(e.InnerException)}"; } /// <summary> /// Returns the truncated error message by only preserving the leading and trailing k characters. /// The message will only be truncated if its length is greater than 2*k. /// </summary> /// <param name="numChars">Species the number of leading and trailing characters to preserve.</param> /// <returns>The truncated error message or <see cref="string.Empty"/> if the error message is null or empty.</returns> public static string GetTruncatedErrorMessage(this Exception? e, int numChars = 500) { var message = e?.Message; if (string.IsNullOrEmpty(message)) return string.Empty; if (message.Length <= 2*numChars) return message; var firstKChars = message.Substring(0, numChars); var lastkChars = message.Substring(message.Length - numChars); var seperator = $"{Environment.NewLine}...{Environment.NewLine}Error truncated to the first and last {numChars} characters{Environment.NewLine}...{Environment.NewLine}"; return $"{firstKChars}{seperator}{lastkChars}"; } } }
347
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using Amazon.Extensions.NETCore.Setup; using Amazon.Runtime; namespace AWS.Deploy.Common { public interface IAWSClientFactory { T GetAWSClient<T>(string? awsRegion = null) where T : IAmazonService; void ConfigureAWSOptions(Action<AWSOptions> awsOptionsAction); } }
16
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Common { public interface IUserInputOption { string Name { get; } string? Description { get; } } }
12
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; namespace AWS.Deploy.Common { /// <summary> /// Models metadata about a parsed .csproj or .fsproj project. /// Use <see cref="IProjectDefinitionParser.Parse"/> to build /// </summary> public class ProjectDefinition { /// <summary> /// The name of the project /// </summary> public string ProjectName => GetProjectName(); /// <summary> /// Xml file contents of the Project file. /// </summary> public XmlDocument Contents { get; set; } /// <summary> /// Full path to the project file /// </summary> public string ProjectPath { get; set; } /// <summary> /// The Solution file path of the project. /// </summary> public string ProjectSolutionPath { get;set; } /// <summary> /// Value of the Sdk property of the root project element in a .csproj /// </summary> public string SdkType { get; set; } /// <summary> /// Value of the TargetFramework property of the project /// </summary> public string? TargetFramework { get; set; } /// <summary> /// Value of the AssemblyName property of the project /// </summary> public string? AssemblyName { get; set; } /// <summary> /// True if we found a docker file corresponding to the .csproj /// </summary> public bool HasDockerFile => CheckIfDockerFileExists(ProjectPath); public ProjectDefinition( XmlDocument contents, string projectPath, string projectSolutionPath, string sdkType) { Contents = contents; ProjectPath = projectPath; ProjectSolutionPath = projectSolutionPath; SdkType = sdkType; } public string? GetMSPropertyValue(string? propertyName) { if (string.IsNullOrEmpty(propertyName)) return null; var propertyValue = Contents.SelectSingleNode($"//PropertyGroup/{propertyName}")?.InnerText; return propertyValue; } public string? GetPackageReferenceVersion(string? packageName) { if (string.IsNullOrEmpty(packageName)) return null; var packageReference = Contents.SelectSingleNode($"//ItemGroup/PackageReference[@Include='{packageName}']") as XmlElement; return packageReference?.GetAttribute("Version"); } private bool CheckIfDockerFileExists(string projectPath) { var dir = Directory.GetFiles(new FileInfo(projectPath).DirectoryName ?? throw new InvalidProjectPathException(DeployToolErrorCode.ProjectPathNotFound, "The project path is invalid."), Constants.Docker.DefaultDockerfileName); return dir.Length == 1; } private string GetProjectName() { if (string.IsNullOrEmpty(ProjectPath)) return string.Empty; return Path.GetFileNameWithoutExtension(ProjectPath); } } }
101
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using AWS.Deploy.Common.IO; namespace AWS.Deploy.Common { public interface IProjectDefinitionParser { /// <summary> /// Scans<paramref name="projectPath"/> for a valid project file and reads it to /// fully populate a <see cref="ProjectDefinition"/> /// </summary> /// <exception cref="ProjectFileNotFoundException"> /// Thrown if no project can be found at <paramref name="projectPath"/> /// </exception> Task<ProjectDefinition> Parse(string projectPath); } public class ProjectDefinitionParser : IProjectDefinitionParser { private readonly IFileManager _fileManager; private readonly IDirectoryManager _directoryManager; public ProjectDefinitionParser(IFileManager fileManager, IDirectoryManager directoryManager) { _fileManager = fileManager; _directoryManager = directoryManager; } /// <summary> /// This method parses the target application project and sets the /// appropriate metadata as part of the <see cref="ProjectDefinition"/> /// </summary> /// <param name="projectPath">The project path can be an absolute or a relative path to the /// target application project directory or the application project file.</param> /// <returns><see cref="ProjectDefinition"/></returns> public async Task<ProjectDefinition> Parse(string projectPath) { if (_directoryManager.Exists(projectPath)) { projectPath = _directoryManager.GetDirectoryInfo(projectPath).FullName; var files = _directoryManager.GetFiles(projectPath, "*.csproj"); if (files.Length == 1) { projectPath = Path.Combine(projectPath, files[0]); } else if (files.Length == 0) { files = _directoryManager.GetFiles(projectPath, "*.fsproj"); if (files.Length == 1) { projectPath = Path.Combine(projectPath, files[0]); } } } if (!_fileManager.Exists(projectPath)) { throw new ProjectFileNotFoundException(DeployToolErrorCode.ProjectPathNotFound, $"Failed to find a valid .csproj or .fsproj file at path {projectPath}"); } var extension = Path.GetExtension(projectPath); if (!string.Equals(extension, ".csproj") && !string.Equals(extension, ".fsproj")) { var errorMeesage = $"Invalid project path {projectPath}. The project path must point to a .csproj or .fsproj file"; throw new ProjectFileNotFoundException(DeployToolErrorCode.ProjectPathNotFound, errorMeesage); } var xmlProjectFile = new XmlDocument(); xmlProjectFile.LoadXml(await _fileManager.ReadAllTextAsync(projectPath)); var projectDefinition = new ProjectDefinition( xmlProjectFile, projectPath, await GetProjectSolutionFile(projectPath), xmlProjectFile.DocumentElement?.Attributes["Sdk"]?.Value ?? throw new InvalidProjectDefinitionException(DeployToolErrorCode.ProjectParserNoSdkAttribute, "The project file that is being referenced does not contain and 'Sdk' attribute.") ); var targetFramework = xmlProjectFile.GetElementsByTagName("TargetFramework"); if (targetFramework.Count > 0) { projectDefinition.TargetFramework = targetFramework[0]?.InnerText; } var assemblyName = xmlProjectFile.GetElementsByTagName("AssemblyName"); if (assemblyName.Count > 0) { projectDefinition.AssemblyName = (string.IsNullOrWhiteSpace(assemblyName[0]?.InnerText) ? Path.GetFileNameWithoutExtension(projectPath) : assemblyName[0]?.InnerText); } else { projectDefinition.AssemblyName = Path.GetFileNameWithoutExtension(projectPath); } return projectDefinition; } private async Task<string> GetProjectSolutionFile(string projectPath) { var projectDirectory = Directory.GetParent(projectPath); while (projectDirectory != null) { var files = _directoryManager.GetFiles(projectDirectory.FullName, "*.sln"); foreach (var solutionFile in files) { if (await ValidateProjectInSolution(projectPath, solutionFile)) { return solutionFile; } } projectDirectory = projectDirectory.Parent; } return string.Empty; } private async Task<bool> ValidateProjectInSolution(string projectPath, string solutionFile) { var projectFileName = Path.GetFileName(projectPath); if (string.IsNullOrWhiteSpace(solutionFile) || string.IsNullOrWhiteSpace(projectFileName)) { return false; } var lines = await _fileManager.ReadAllLinesAsync(solutionFile); var projectLines = lines.Where(x => x.StartsWith("Project")); var projectPaths = projectLines .Select(x => x.Split(',')) .Where(x => x.Length > 1) .Select(x => x[1] .Replace('\"', ' ') .Trim()) .Select(x => x.Replace('\\', Path.DirectorySeparatorChar)) .ToList(); //Validate project exists in solution return projectPaths.Select(x => Path.GetFileName(x)).Any(x => x.Equals(projectFileName)); } } }
152
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using AWS.Deploy.Common.Extensions; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.Common { public class Recommendation : IUserInputOption { /// <summary> /// Returns the full path to the project file /// </summary> public string ProjectPath => ProjectDefinition.ProjectPath; public ProjectDefinition ProjectDefinition { get; } public RecipeDefinition Recipe { get; } public int ComputedPriority { get; } public string Name => Recipe.Name; public bool IsExistingCloudApplication { get; set; } public string Description => Recipe.Description; public string ShortDescription => Recipe.ShortDescription; public DeploymentBundle DeploymentBundle { get; } public readonly Dictionary<string, object> ReplacementTokens = new(); public Recommendation(RecipeDefinition recipe, ProjectDefinition projectDefinition, int computedPriority, Dictionary<string, object> additionalReplacements) { additionalReplacements ??= new Dictionary<string, object>(); Recipe = recipe; ComputedPriority = computedPriority; ProjectDefinition = projectDefinition; DeploymentBundle = new DeploymentBundle(); CollectRecommendationReplacementTokens(GetConfigurableOptionSettingItems().ToList()); foreach (var replacement in additionalReplacements) { ReplacementTokens[replacement.Key] = replacement.Value; } } public List<Category> GetConfigurableOptionSettingCategories() { var categories = Recipe.Categories; // If any top level settings has a category of General make sure the General category is added to the list. if(!categories.Any(x => string.Equals(x.Id, Category.General.Id)) && Recipe.OptionSettings.Any(x => string.IsNullOrEmpty(x.Category) || string.Equals(x.Category, Category.General.Id))) { categories.Insert(0, Category.General); } // Add the build settings category if it is not already in the list of categories. if(!categories.Any(x => string.Equals(x.Id, Category.DeploymentBundle.Id))) { categories.Add(Category.DeploymentBundle); } return categories; } public IEnumerable<OptionSettingItem> GetConfigurableOptionSettingItems() { // For any top level settings that don't have a category assigned to them assign the General category. foreach(var setting in Recipe.OptionSettings) { if(string.IsNullOrEmpty(setting.Category)) { setting.Category = Category.General.Id; } } return Recipe.OptionSettings; } private void CollectRecommendationReplacementTokens(List<OptionSettingItem> optionSettings) { foreach (var optionSetting in optionSettings) { string defaultValue = optionSetting.DefaultValue?.ToString() ?? ""; Regex regex = new Regex(@"^.*\{[\w\d]+\}.*$"); Match match = regex.Match(defaultValue); if (match.Success) { var replacement = defaultValue.Substring(defaultValue.IndexOf("{"), defaultValue.IndexOf("}") + 1); ReplacementTokens[replacement] = ""; } if (optionSetting.ChildOptionSettings.Any()) CollectRecommendationReplacementTokens(optionSetting.ChildOptionSettings); } } public void AddReplacementToken(string key, object value) { ReplacementTokens[key] = value; } /// <summary> /// Helper to get the project's directory /// </summary> /// <returns>Full name of directory containing this recommendation's project file</returns> public string GetProjectDirectory() { var projectDirectory = new FileInfo(ProjectPath).Directory?.FullName; if (string.IsNullOrEmpty(projectDirectory)) throw new InvalidProjectPathException(DeployToolErrorCode.ProjectPathNotFound, "The project path provided is invalid."); return projectDirectory; } } }
129
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace AWS.Deploy.Common { public class SerializeModelContractResolver : DefaultContractResolver { protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { JsonProperty property = base.CreateProperty(member, memberSerialization); if (property != null && property.PropertyType != null && property.PropertyName != null && property.PropertyType != typeof(string)) { if (property.PropertyType.GetInterface(nameof(IEnumerable)) != null) { property.ShouldSerialize = instance => { var instanceValue = instance?.GetType()?.GetProperty(property.PropertyName)?.GetValue(instance); if (instanceValue is IEnumerable<object> list) { return list.Any(); } else if(instanceValue is System.Collections.IDictionary map) { return map.Count > 0; } return false; }; } } return property ?? throw new ArgumentException(); } } }
45
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Common { public class UserInputOption : IUserInputOption { public UserInputOption(string value) { Name = value; } public string Name { get; set; } public string? Description { get; set; } } }
18
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.Threading.Tasks; using Amazon.AppRunner.Model; using Amazon.CloudFormation.Model; using Amazon.CloudFront.Model; using Amazon.CloudWatchEvents.Model; using Amazon.EC2.Model; using Amazon.ECR.Model; using Amazon.ECS.Model; using Amazon.ElasticBeanstalk.Model; using Amazon.ElasticLoadBalancingV2; using Amazon.IdentityManagement.Model; using Amazon.S3.Model; using Amazon.SecurityToken.Model; using LoadBalancer = Amazon.ElasticLoadBalancingV2.Model.LoadBalancer; using Listener = Amazon.ElasticLoadBalancingV2.Model.Listener; using Amazon.CloudControlApi.Model; namespace AWS.Deploy.Common.Data { /// <summary> /// Enum for filtering the type of Elastic Beanstalk platform to deploy to. /// </summary> public enum BeanstalkPlatformType { Linux, Windows } /// <summary> /// Retrieves AWS resources /// </summary> /// <remarks> /// This is meant to be a lightweight wrapper around the SDK, /// business logic should generally be implemented in the caller. /// </remarks> public interface IAWSResourceQueryer { Task<Vpc> GetDefaultVpc(); Task<ResourceDescription> GetCloudControlApiResource(string type, string identifier); Task<List<StackEvent>> GetCloudFormationStackEvents(string stackName); /// <summary> /// Lists all of the EC2 instance types available in the deployment region without any filtering /// </summary> /// <returns>List of <see cref="InstanceTypeInfo"/></returns> Task<List<InstanceTypeInfo>> ListOfAvailableInstanceTypes(); /// <summary> /// Describes a single EC2 instance type /// </summary> /// <param name="instanceType">Instance type (for example, "t2.micro")</param> /// <returns>The first <see cref="InstanceTypeInfo"/> if the specified type exists</returns> Task<InstanceTypeInfo?> DescribeInstanceType(string instanceType); Task<Amazon.AppRunner.Model.Service> DescribeAppRunnerService(string serviceArn); Task<List<StackResource>> DescribeCloudFormationResources(string stackName); Task<EnvironmentDescription> DescribeElasticBeanstalkEnvironment(string environmentName); Task<LoadBalancer> DescribeElasticLoadBalancer(string loadBalancerArn); Task<List<Listener>> DescribeElasticLoadBalancerListeners(string loadBalancerArn); Task<DescribeRuleResponse> DescribeCloudWatchRule(string ruleName); Task<string> GetS3BucketLocation(string bucketName); Task<Amazon.S3.Model.WebsiteConfiguration> GetS3BucketWebSiteConfiguration(string bucketName); Task<List<Cluster>> ListOfECSClusters(string? ecsClusterName = null); Task<List<ApplicationDescription>> ListOfElasticBeanstalkApplications(string? applicationName = null); Task<List<EnvironmentDescription>> ListOfElasticBeanstalkEnvironments(string? applicationName = null, string? environmentName = null); Task<List<Amazon.ElasticBeanstalk.Model.Tag>> ListElasticBeanstalkResourceTags(string resourceArn); Task<List<KeyPairInfo>> ListOfEC2KeyPairs(); Task<string> CreateEC2KeyPair(string keyName, string saveLocation); Task<List<Role>> ListOfIAMRoles(string? servicePrincipal); Task<List<Vpc>> GetListOfVpcs(); Task<List<PlatformSummary>> GetElasticBeanstalkPlatformArns(params BeanstalkPlatformType[]? platformTypes); Task<PlatformSummary> GetLatestElasticBeanstalkPlatformArn(BeanstalkPlatformType platformType); Task<List<AuthorizationData>> GetECRAuthorizationToken(); Task<List<Repository>> GetECRRepositories(List<string>? repositoryNames = null); Task<Repository> CreateECRRepository(string repositoryName); Task<List<Stack>> GetCloudFormationStacks(); Task<Stack?> GetCloudFormationStack(string stackName); Task<GetCallerIdentityResponse> GetCallerIdentity(string awsRegion); Task<List<LoadBalancer>> ListOfLoadBalancers(LoadBalancerTypeEnum loadBalancerType); Task<Distribution> GetCloudFrontDistribution(string distributionId); Task<List<string>> ListOfDyanmoDBTables(); Task<List<string>> ListOfSQSQueuesUrls(); Task<List<string>> ListOfSNSTopicArns(); Task<List<S3Bucket>> ListOfS3Buckets(); Task<List<ConfigurationOptionSetting>> GetBeanstalkEnvironmentConfigurationSettings(string environmentName); Task<Repository> DescribeECRRepository(string respositoryName); Task<List<VpcConnector>> DescribeAppRunnerVpcConnectors(); Task<List<Subnet>> DescribeSubnets(string? vpcID = null); Task<List<SecurityGroup>> DescribeSecurityGroups(string? vpcID = null); Task<string?> GetParameterStoreTextValue(string parameterName); } }
94
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.IO; namespace AWS.Deploy.Common { /// <summary> /// The container for the deployment bundle used by an application. /// </summary> public class DeploymentBundle { /// <summary> /// The directory from which the docker build command will be executed. /// </summary> public string DockerExecutionDirectory { get; set; } = ""; /// <summary> /// The list of additional dotnet publish args passed to the target application. /// </summary> public string DockerBuildArgs { get; set; } = ""; /// <summary> /// The path to the Dockerfile. This can either be an absolute path or relative to the project directory. /// </summary> public string DockerfilePath { get; set; } = ""; /// <summary> /// The ECR Repository Name where the docker image will be pushed to. /// </summary> public string ECRRepositoryName { get; set; } = ""; /// <summary> /// The ECR Image Tag of the docker image. /// </summary> public string ECRImageTag { get; set; } = ""; /// <summary> /// The path of the zip file containing the assemblies produced by the dotnet publish command. /// </summary> public string DotnetPublishZipPath { get; set; } = ""; /// <summary> /// The directory containing the assemblies produced by the dotnet publish command. /// </summary> public string DotnetPublishOutputDirectory { get; set; } = ""; /// <summary> /// The build configuration to use for the dotnet build. /// </summary> public string DotnetPublishBuildConfiguration { get; set; } = "Release"; /// <summary> /// Publishing your app as self-contained produces an application that includes the .NET runtime and libraries. /// Users can run it on a machine that doesn't have the .NET runtime installed. /// </summary> public bool DotnetPublishSelfContainedBuild { get; set; } = false; /// <summary> /// The list of additional dotnet publish args passed to the target application. /// </summary> public string DotnetPublishAdditionalBuildArguments { get; set; } = ""; } }
65
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.Common { /// <summary> /// The container for the deployment bundle used by an application. /// </summary> public class DeploymentBundleDefinition { /// <summary> /// The type of deployment bundle used by the application. /// </summary> public DeploymentBundleTypes Type { get; set; } public List<OptionSettingItem> Parameters { get; set; } public DeploymentBundleDefinition(DeploymentBundleTypes type, List<OptionSettingItem> parameters) { Type = type; Parameters = parameters; } } }
28
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using AWS.Deploy.Common.IO; using Newtonsoft.Json; namespace AWS.Deploy.Common.DeploymentManifest { public interface IDeploymentManifestEngine { Task UpdateDeploymentManifestFile(string saveCdkDirectoryFullPath, string targetApplicationFullPath); Task<List<string>> GetRecipeDefinitionPaths(string targetApplicationFullPath); } /// <summary> /// This class contains the helper methods to update the deployment manifest file /// that keeps track of the save CDK deployment projects. /// </summary> public class DeploymentManifestEngine : IDeploymentManifestEngine { private readonly IDirectoryManager _directoryManager; private readonly IFileManager _fileManager; private const string DEPLOYMENT_MANIFEST_FILE_NAME = "aws-deployments.json"; public DeploymentManifestEngine(IDirectoryManager directoryManager, IFileManager fileManager) { _directoryManager = directoryManager; _fileManager = fileManager; } /// <summary> /// This method updates the deployment manifest json file by adding the directory path at which the CDK deployment project is saved. /// If the manifest file does not exists then a new file is generated. /// <param name="saveCdkDirectoryFullPath">The absolute path to the directory at which the CDK deployment project is saved</param> /// <param name="targetApplicationFullPath">The absolute path to the target application csproj or fsproj file.</param> /// <exception cref="FailedToUpdateDeploymentManifestFileException">Thrown if an error occured while trying to update the deployment manifest file.</exception> /// </summary> /// <returns></returns> public async Task UpdateDeploymentManifestFile(string saveCdkDirectoryFullPath, string targetApplicationFullPath) { try { if (!_directoryManager.Exists(saveCdkDirectoryFullPath)) return; var deploymentManifestFilePath = GetDeploymentManifestFilePath(targetApplicationFullPath); var targetApplicationDirectoryPath = _directoryManager.GetDirectoryInfo(targetApplicationFullPath).Parent?.FullName ?? string.Empty; var saveCdkDirectoryRelativePath = _directoryManager.GetRelativePath(targetApplicationDirectoryPath, saveCdkDirectoryFullPath); DeploymentManifestModel deploymentManifestModel; if (_fileManager.Exists(deploymentManifestFilePath)) { deploymentManifestModel = await ReadManifestFile(deploymentManifestFilePath); if (deploymentManifestModel.DeploymentProjects == null) { deploymentManifestModel.DeploymentProjects = new List<DeploymentManifestEntry> { new DeploymentManifestEntry(saveCdkDirectoryRelativePath) }; } else { deploymentManifestModel.DeploymentProjects.Add(new DeploymentManifestEntry(saveCdkDirectoryRelativePath)); } } else { var deploymentManifestEntries = new List<DeploymentManifestEntry> { new DeploymentManifestEntry(saveCdkDirectoryRelativePath) }; deploymentManifestModel = new DeploymentManifestModel(deploymentManifestEntries); } var manifestFileJsonString = SerializeManifestModel(deploymentManifestModel); await _fileManager.WriteAllTextAsync(deploymentManifestFilePath, manifestFileJsonString); } catch (Exception ex) { throw new FailedToUpdateDeploymentManifestFileException(DeployToolErrorCode.DeploymentManifestUpdateFailed, $"Failed to update the deployment manifest file " + $"for the deployment project stored at '{saveCdkDirectoryFullPath}'", ex); } } /// <summary> /// This method deserializes the deployment-manifest file and returns a list of absolute paths of directories at which different CDK /// deployment projects are stored. The custom recipe snapshots are stored in this directory. /// <param name="targetApplicationFullPath">The absolute path to the target application csproj or fsproj file</param> /// </summary> /// <returns> A list containing absolute directory paths for CDK deployment projects.</returns> public async Task<List<string>> GetRecipeDefinitionPaths(string targetApplicationFullPath) { var recipeDefinitionPaths = new List<string>(); var deploymentManifestFilePath = GetDeploymentManifestFilePath(targetApplicationFullPath); var targetApplicationDirectoryPath = _directoryManager.GetDirectoryInfo(targetApplicationFullPath).Parent?.FullName ?? string.Empty; if (_fileManager.Exists(deploymentManifestFilePath)) { var deploymentManifestModel = await ReadManifestFile(deploymentManifestFilePath); if (deploymentManifestModel.DeploymentProjects == null) return recipeDefinitionPaths; foreach (var entry in deploymentManifestModel.DeploymentProjects) { var saveCdkDirectoryRelativePath = entry.SaveCdkDirectoryRelativePath; if (string.IsNullOrEmpty(saveCdkDirectoryRelativePath)) continue; var saveCdkDirectoryAbsolutePath = _directoryManager.GetAbsolutePath(targetApplicationDirectoryPath, saveCdkDirectoryRelativePath); if (_directoryManager.Exists(saveCdkDirectoryAbsolutePath)) recipeDefinitionPaths.Add(saveCdkDirectoryAbsolutePath); } } return recipeDefinitionPaths; } /// <summary> /// This method parses the deployment-manifest file into a <see cref="DeploymentManifestModel"/> /// </summary> /// <param name="filePath">The path to the deployment-manifest file</param> /// <returns>An instance of <see cref="DeploymentManifestModel"/></returns> private async Task<DeploymentManifestModel> ReadManifestFile(string filePath) { var manifestFilejsonString = await _fileManager.ReadAllTextAsync(filePath); return JsonConvert.DeserializeObject<DeploymentManifestModel>(manifestFilejsonString) ?? throw new FailedToDeserializeException(DeployToolErrorCode.InvalidDeploymentManifestModel, "The deployment manifest file is invalid."); } /// <summary> /// This method parses the <see cref="DeploymentManifestModel"/> into a string /// </summary> /// <param name="deploymentManifestModel"><see cref="DeploymentManifestModel"/></param> /// <returns>A formatted string representation of <see cref="DeploymentManifestModel"></returns> private string SerializeManifestModel(DeploymentManifestModel deploymentManifestModel) { return JsonConvert.SerializeObject(deploymentManifestModel, Formatting.Indented); } /// <summary> /// This method returns the path at which the deployment-manifest file will be stored. /// <param name="targetApplicationFullPath">The absolute path to the target application csproj or fsproj file</param> /// </summary> /// <returns>The path to the deployment-manifest file.</returns> private string GetDeploymentManifestFilePath(string targetApplicationFullPath) { var projectDirectoryFullPath = _directoryManager.GetDirectoryInfo(targetApplicationFullPath).Parent?.FullName ?? string.Empty; var deploymentManifestFileFullPath = Path.Combine(projectDirectoryFullPath, DEPLOYMENT_MANIFEST_FILE_NAME); return deploymentManifestFileFullPath; } } }
155
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Newtonsoft.Json; namespace AWS.Deploy.Common.DeploymentManifest { /// <summary> /// This class supports serialization and de-serialization of the deployment-manifest file. /// </summary> public class DeploymentManifestEntry { [JsonProperty("Path")] public string SaveCdkDirectoryRelativePath { get; set; } public DeploymentManifestEntry(string saveCdkDirectoryRelativePath) { SaveCdkDirectoryRelativePath = saveCdkDirectoryRelativePath; } } }
22
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; namespace AWS.Deploy.Common.DeploymentManifest { /// <summary> /// This class supports serialization and de-serialization of the deployment-manifest file. /// </summary> public class DeploymentManifestModel { public List<DeploymentManifestEntry> DeploymentProjects { get; set; } public DeploymentManifestModel(List<DeploymentManifestEntry> deploymentProjects) { DeploymentProjects = deploymentProjects; } } }
21
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.IO; using System.Reflection; namespace AWS.Deploy.Common.Extensions { public static class AssemblyReadEmbeddedFileExtension { public static string ReadEmbeddedFile(this Assembly assembly, string resourceName) { using var resource = assembly.GetManifestResourceStream(resourceName); if (resource == null) { throw new FileNotFoundException($"The resource {resourceName} was not found in {assembly}"); } try { using var reader = new StreamReader(resource); return reader.ReadToEnd(); } catch (Exception exception) { throw new Exception($"Failed to read {resourceName} in assembly {assembly}.{Environment.NewLine}{exception.Message}"); } } } }
33
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using Amazon; using Amazon.Runtime; namespace AWS.Deploy.Common.Extensions { public static class AWSContextAWSClientFactoryExtension { /// AWS Credentials and Region information is determined after DI container is built. /// <see cref="RegisterAWSContext"/> extension method allows to register late bound properties (credentials & region) to /// <see cref="IAWSClientFactory"/> instance. public static void RegisterAWSContext(this IAWSClientFactory awsClientFactory, AWSCredentials awsCredentials, string region) { awsClientFactory.ConfigureAWSOptions(awsOption => { awsOption.Credentials = awsCredentials; awsOption.Region = RegionEndpoint.GetBySystemName(region); }); } } }
26
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using Newtonsoft.Json; namespace AWS.Deploy.Common.Extensions { public static class GenericExtensions { public static T DeepCopy<T>(this T obj) { var serializedObject = JsonConvert.SerializeObject(obj); return JsonConvert.DeserializeObject<T>(serializedObject) ?? throw new FailedToDeserializeException(DeployToolErrorCode.FailedToCreateDeepCopy, "Failed to create a deep copy."); } public static bool TryDeserialize<T>(this object obj, out T? inputList) { try { string serializedObject = ""; if (obj is string) { serializedObject = obj.ToString() ?? string.Empty; } else { serializedObject = JsonConvert.SerializeObject(obj); } inputList = JsonConvert.DeserializeObject<T>(serializedObject); if (inputList == null) return false; return true; } catch (Exception) { inputList = default(T); return false; } } } }
46
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using AWS.Deploy.Common.Utilities; namespace AWS.Deploy.Common.IO { public interface IDirectoryManager { DirectoryInfo CreateDirectory(string path); DirectoryInfo GetDirectoryInfo(string path); /// <summary> /// Determines whether the given path refers to an existing directory on disk. /// This can either be an absolute path or relative to the current working directory. /// </summary> /// <param name="path">The path to test</param> /// <returns> /// true if path refers to an existing directory; /// false if the directory does not exist or an error occurs when trying to determine if the specified directory exists /// </returns> bool Exists(string path); /// <summary> /// Determines whether the given path refers to an existing directory on disk. /// This can either be an absolute path or relative to the given directory. /// </summary> /// <param name="path">The path to test</param> /// <param name="relativeTo">Directory to consider the path as relative to</param> /// <returns> /// true if path refers to an existing directory; /// false if the directory does not exist or an error occurs when trying to determine if the specified directory exists /// </returns> bool Exists(string path, string relativeTo); string[] GetFiles(string path, string? searchPattern = null, SearchOption searchOption = SearchOption.TopDirectoryOnly); string[] GetDirectories(string path, string? searchPattern = null, SearchOption searchOption = SearchOption.TopDirectoryOnly); bool IsEmpty(string path); bool ExistsInsideDirectory(string parentDirectoryPath, string childPath); void Delete(string path, bool recursive = false); string GetRelativePath(string referenceFullPath, string targetFullPath); string GetAbsolutePath(string referenceFullPath, string targetRelativePath); public string[] GetProjFiles(string path); } public class DirectoryManager : IDirectoryManager { private readonly HashSet<string> _projFileExtensions = new() { ".csproj", ".fsproj" }; public DirectoryInfo CreateDirectory(string path) => Directory.CreateDirectory(path); public DirectoryInfo GetDirectoryInfo(string path) => new DirectoryInfo(path); public bool Exists(string path) => IsDirectoryValid(path); public bool Exists(string path, string relativeTo) { if (Path.IsPathRooted(path)) { return Exists(path); } else { return Exists(Path.Combine(relativeTo, path)); } } public string[] GetFiles(string path, string? searchPattern = null, SearchOption searchOption = SearchOption.TopDirectoryOnly) => Directory.GetFiles(path, searchPattern ?? "*", searchOption); public string[] GetDirectories(string path, string? searchPattern = null, SearchOption searchOption = SearchOption.TopDirectoryOnly) => Directory.GetDirectories(path, searchPattern ?? "*", searchOption); public bool IsEmpty(string path) => GetFiles(path).Length == 0 && GetDirectories(path).Length == 0; public bool ExistsInsideDirectory(string parentDirectoryPath, string childPath) { var parentDirectoryFullPath = GetDirectoryInfo(parentDirectoryPath).FullName; var childFullPath = GetDirectoryInfo(childPath).FullName; return childFullPath.Contains(parentDirectoryFullPath + Path.DirectorySeparatorChar, StringComparison.InvariantCulture); } public void Delete(string path, bool recursive = false) => Directory.Delete(path, recursive); public string GetRelativePath(string referenceFullPath, string targetFullPath) => Path.GetRelativePath(referenceFullPath, targetFullPath); public string GetAbsolutePath(string referenceFullPath, string targetRelativePath) => Path.GetFullPath(targetRelativePath, referenceFullPath); public string[] GetProjFiles(string path) { return Directory.GetFiles(path).Where(filePath => _projFileExtensions.Contains(Path.GetExtension(filePath).ToLower())).ToArray(); } private bool IsDirectoryValid(string directoryPath) { if (!PathUtilities.IsPathValid(directoryPath)) return false; if (!Directory.Exists(directoryPath)) return false; return true; } } }
113
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using AWS.Deploy.Common.Utilities; namespace AWS.Deploy.Common.IO { public interface IFileManager { /// <summary> /// Determines whether the specified file is at a valid path and exists. /// This can either be an absolute path or relative to the current working directory. /// </summary> /// <param name="path">The file to check</param> /// <returns> /// True if the path is valid, the caller has the required permissions, /// and path contains the name of an existing file /// </returns> bool Exists(string path); /// <summary> /// Determines whether the specified file is at a valid path and exists. /// This can either be an absolute path or relative to the given directory. /// </summary> /// <param name="path">The file to check</param> /// <param name="directory">Directory to consider the path as relative to</param> /// <returns> /// True if the path is valid, the caller has the required permissions, /// and path contains the name of an existing file /// </returns> bool Exists(string path, string directory); /// <summary> /// Determines that the specified file path is structurally valid and its parent directory exists on disk. /// This file path can be absolute or relative to the current working directory. /// Note - This method does not check for the existence of a file at the specified path. Use <see cref="Exists(string)"/> or <see cref="Exists(string, string)"/> to check for existence of a file. /// </summary> /// <param name="filePath"></param> /// <returns></returns> bool IsFileValidPath(string filePath); Task<string> ReadAllTextAsync(string path); Task<string[]> ReadAllLinesAsync(string path); Task WriteAllTextAsync(string filePath, string contents, CancellationToken cancellationToken = default); FileStream OpenRead(string filePath); string GetExtension(string filePath); long GetSizeInBytes(string filePath); } /// <summary> /// Wrapper for <see cref="File"/> class to allow mock-able behavior for static methods. /// </summary> public class FileManager : IFileManager { public bool Exists(string path) { if (!PathUtilities.IsPathValid(path)) return false; return File.Exists(path); } public bool Exists(string path, string directory) { if (Path.IsPathRooted(path)) { return Exists(path); } else { return Exists(Path.Combine(directory, path)); } } public Task<string> ReadAllTextAsync(string path) => File.ReadAllTextAsync(path); public Task<string[]> ReadAllLinesAsync(string path) => File.ReadAllLinesAsync(path); public Task WriteAllTextAsync(string filePath, string contents, CancellationToken cancellationToken) => File.WriteAllTextAsync(filePath, contents, cancellationToken); public FileStream OpenRead(string filePath) => File.OpenRead(filePath); public string GetExtension(string filePath) => Path.GetExtension(filePath); public long GetSizeInBytes(string filePath) => new FileInfo(filePath).Length; public bool IsFileValidPath(string filePath) { if (!PathUtilities.IsPathValid(filePath)) return false; var parentDirectory = Path.GetDirectoryName(filePath); if (string.IsNullOrEmpty(parentDirectory)) { return false; } return PathUtilities.IsPathValid(parentDirectory) && Directory.Exists(parentDirectory); } } }
106
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.Common.Recipes { /// <summary> /// A category defined in the recipe that settings will be mapped to via the Id property. /// </summary> public class Category { public static readonly Category General = new Category("General", "General", 0); public static readonly Category DeploymentBundle = new Category("DeploymentBuildSettings", "Project Build", 1000); /// <summary> /// The id of the category that will be specified on top level settings. /// </summary> public string Id { get; set; } /// <summary> /// The display name of the category shown to users in UI screens. /// </summary> public string DisplayName { get; set; } /// <summary> /// The order used to sort categories in UI screens. Categories will be shown in sorted descending order. /// </summary> public int Order { get; set; } public Category(string id, string displayName, int order) { Id = id; DisplayName = displayName; Order = order; } } }
41
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Common.Recipes { public enum DeploymentBundleTypes { DotnetPublishZipFile, Container } }
12
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.Common.Recipes { public class DeploymentConfirmationType { public string DefaultMessage { get; set; } public DeploymentConfirmationType( string defaultMessage) { DefaultMessage = defaultMessage; } } }
21
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Common.Recipes { public enum DeploymentTypes { CdkProject, BeanstalkEnvironment, ElasticContainerRegistryImage } }
13
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Common.Recipes { public class DisplayedResource { /// <summary> /// The CloudFormation ID that represents a resource. /// </summary> public string LogicalId { get; set; } /// <summary> /// The Description gives context to the metadata of the CloudFormation resource. /// </summary> public string Description { get; set; } public DisplayedResource(string logicalId, string description) { LogicalId = logicalId; Description = description; } } }
25
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Common.Recipes { /// <summary> /// The type of effects to apply. /// </summary> public class EffectOptions { /// <summary> /// When the recipe should be included or not. /// </summary> public bool? Include { get; set; } /// <summary> /// Adjust the priority or the recipe. /// </summary> public int? PriorityAdjustment { get; set; } } }
22
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.Threading.Tasks; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes.Validation; namespace AWS.Deploy.Common.Recipes { /// <summary> /// This interface defines a contract used to control access to getting an setting values for <see cref="OptionSettingItem"/> /// </summary> public interface IOptionSettingHandler { /// <summary> /// This method runs all the option setting validators for the configurable settings. /// In case of a first time deployment, all settings and validators are run. /// In case of a redeployment, only the updatable settings are considered. /// </summary> List<ValidationResult> RunOptionSettingValidators(Recommendation recommendation, IEnumerable<OptionSettingItem>? optionSettings = null); /// <summary> /// This method is used to set values for <see cref="OptionSettingItem"/>. /// Due to different validations that could be put in place, access to other services may be needed. /// This method is meant to control access to those services and determine the value to be set. /// </summary> Task SetOptionSettingValue(Recommendation recommendation, OptionSettingItem optionSettingItem, object value, bool skipValidation = false); /// <summary> /// This method is used to set values for <see cref="OptionSettingItem"/> bases on the fullyQualifiedId of the option setting. /// Due to different validations that could be put in place, access to other services may be needed. /// This method is meant to control access to those services and determine the value to be set. /// </summary> Task SetOptionSettingValue(Recommendation recommendation, string fullyQualifiedId, object value, bool skipValidation = false); /// <summary> /// This method retrieves the <see cref="OptionSettingItem"/> related to a specific <see cref="Recommendation"/>. /// </summary> OptionSettingItem GetOptionSetting(Recommendation recommendation, string? jsonPath); /// <summary> /// This method retrieves the <see cref="OptionSettingItem"/> related to a specific <see cref="Recipe"/>. /// </summary> OptionSettingItem GetOptionSetting(RecipeDefinition recipe, string? jsonPath); /// <summary> /// Retrieve the <see cref="OptionSettingItem"/> value for a specific <see cref="Recommendation"/> /// This method retrieves the value in a specified type. /// </summary> T? GetOptionSettingValue<T>(Recommendation recommendation, OptionSettingItem optionSetting); /// <summary> /// Retrieve the <see cref="OptionSettingItem"/> value for a specific <see cref="Recommendation"/> /// This method retrieves the value as an object type. /// </summary> object GetOptionSettingValue(Recommendation recommendation, OptionSettingItem optionSetting); /// <summary> /// Retrieve the <see cref="OptionSettingItem"/> default value for a specific <see cref="Recommendation"/> /// This method retrieves the default value in a specified type. /// </summary> T? GetOptionSettingDefaultValue<T>(Recommendation recommendation, OptionSettingItem optionSetting); /// <summary> /// Retrieve the <see cref="OptionSettingItem"/> default value for a specific <see cref="Recommendation"/> /// This method retrieves the default value as an object type. /// </summary> object? GetOptionSettingDefaultValue(Recommendation recommendation, OptionSettingItem optionSetting); /// <summary> /// Checks whether all the dependencies are satisfied or not, if there exists an unsatisfied dependency then returns false. /// It allows caller to decide whether we want to display an <see cref="OptionSettingItem"/> to configure or not. /// </summary> /// <returns>Returns true, if all the dependencies are satisfied, else false.</returns> bool IsOptionSettingDisplayable(Recommendation recommendation, OptionSettingItem optionSetting); /// <summary> /// Checks whether the Option Setting Item can be displayed as part of the settings summary of the previous deployment. /// </summary> bool IsSummaryDisplayable(Recommendation recommendation, OptionSettingItem optionSettingItem); /// <summary> /// Checks whether the option setting item has been modified by the user. If it has been modified, then it will hold a non-default value /// </summary> /// <returns>true if the option setting item has been modified or false otherwise</returns> bool IsOptionSettingModified(Recommendation recommendation, OptionSettingItem optionSetting); /// <summary> /// <para>Returns a Dictionary containing the configurable option settings for the specified recommendation. The returned dictionary can contain specific types of option settings depending on the value of <see cref="OptionSettingsType"/>.</para> /// <para>The key in the dictionary is the fully qualified ID of each option setting</para> /// <para>The value in the dictionary is the value of each option setting</para> /// </summary> Dictionary<string, object> GetOptionSettingsMap(Recommendation recommendation, ProjectDefinition projectDefinition, IDirectoryManager directoryManager, OptionSettingsType optionSettingsType = OptionSettingsType.All); } }
97
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using System.Threading.Tasks; using AWS.Deploy.Common.Recipes.Validation; namespace AWS.Deploy.Common.Recipes { public interface IRecipeHandler { /// <summary> /// Retrieves all the <see cref="RecipeDefinition"/> that are defined by the system as well as any other recipes that are retrieved from an external source. /// </summary> Task<List<RecipeDefinition>> GetRecipeDefinitions(List<string>? recipeDefinitionPaths = null); /// <summary> /// Wrapper method to fetch custom recipe definition paths from a deployment-manifest file as well as /// other locations that are monitored by the same source control root as the target application that needs to be deployed. /// </summary> Task<HashSet<string>> LocateCustomRecipePaths(ProjectDefinition projectDefinition); /// <summary> /// Wrapper method to fetch custom recipe definition paths from a deployment-manifest file as well as /// other locations that are monitored by the same source control root as the target application that needs to be deployed. /// </summary> Task<HashSet<string>> LocateCustomRecipePaths(string targetApplicationFullPath, string solutionDirectoryPath); /// <summary> /// Runs the recipe level validators and returns a list of failed validations /// </summary> List<ValidationResult> RunRecipeValidators(Recommendation recommendation, IDeployToolValidationContext deployToolValidationContext); } }
35
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.Common.Recipes.Validation; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace AWS.Deploy.Common.Recipes { /// <summary> /// Defines a contract for <see cref="OptionSettingItem"/> for getters and setters. /// </summary> public interface IOptionSettingItem { /// <summary> /// Retrieve the value of an <see cref="OptionSettingItem"/> as a specified type. /// </summary> T? GetValue<T>(IDictionary<string, object> replacementTokens, IDictionary<string, bool>? displayableOptionSettings = null); /// <summary> /// Retrieve the value of an <see cref="OptionSettingItem"/> as an object. /// </summary> object GetValue(IDictionary<string, object> replacementTokens, IDictionary<string, bool>? displayableOptionSettings = null); /// <summary> /// Retrieve the default value of an <see cref="OptionSettingItem"/> as a specified type. /// </summary> T? GetDefaultValue<T>(IDictionary<string, object> replacementTokens); /// <summary> /// Retrieve the default value of an <see cref="OptionSettingItem"/> as an object. /// </summary> object? GetDefaultValue(IDictionary<string, object> replacementTokens); /// <summary> /// Set the value of an <see cref="OptionSettingItem"/> while validating the provided input. /// </summary> /// <param name="optionSettingHandler">Handler use to set any child option settings</param> /// <param name="value">Value to set</param> /// <param name="validators">Validators for this item</param> /// <param name="recommendation">Selected recommendation</param> /// <param name="skipValidation">Enables or disables running validators specified in <paramref name="validators"/></param> Task SetValue(IOptionSettingHandler optionSettingHandler, object value, IOptionSettingItemValidator[] validators, Recommendation recommendation, bool skipValidation); } /// <summary> /// Container for the setting values /// </summary> public partial class OptionSettingItem : IOptionSettingItem { /// <summary> /// The unique id of setting. This value will be persisted in other config files so its value should never change once a recipe is released. /// </summary> public string Id { get; set; } /// <summary> /// The fully qualified id of the setting that includes the Id and all of the parent's Ids. /// This helps easily reference the Option Setting without context of the parent setting. /// </summary> public string FullyQualifiedId { get; set; } /// <summary> /// The parent Option Setting Item that allows an option setting item to reference it's parent. /// </summary> public string? ParentId { get; set; } /// <summary> /// The id of the parent option setting. This is used for tooling that wants to look up the existing resources for a setting based on the TypeHint but needs /// to know the parent AWS resource. For example if listing the available Beanstalk environments the listing should be for the environments of the Beanstalk application. /// </summary> public string? ParentSettingId { get; set; } /// <summary> /// The display friendly name of the setting. /// </summary> public string Name { get; set; } /// <summary> /// The category for the setting. This value must match an id field in the list of categories. /// </summary> public string? Category { get; set; } /// <summary> /// The description of what the setting is used for. /// </summary> public string Description { get; set; } /// <summary> /// The type of primitive value expected for this setting. /// For example String, Int /// </summary> [JsonConverter(typeof(StringEnumConverter))] public OptionSettingValueType Type { get; set; } /// <summary> /// Hint the the UI what type of setting this is optionally add additional UI features to select a value. /// For example a value of BeanstalkApplication tells the UI it can display the list of available Beanstalk applications for the user to pick from. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public OptionSettingTypeHint? TypeHint { get; set; } /// <summary> /// The default value used for the recipe if the user doesn't override the value. /// </summary> public object? DefaultValue { get; set; } /// <summary> /// The value used for the recipe if it is set by the user. /// </summary> private object? _value { get; set; } /// <summary> /// UI can use this to reduce the amount of settings to show to the user when confirming the recommendation. This can make it so the user sees only the most important settings /// they need to know about before deploying. /// </summary> public bool AdvancedSetting { get; set; } /// <summary> /// If true the setting can be changed during a redeployment. /// </summary> public bool Updatable { get; set; } /// <summary> /// List of all validators that should be run when configuring this OptionSettingItem. /// </summary> public List<OptionSettingItemValidatorConfig> Validators { get; set; } = new (); /// <summary> /// The allowed values for the setting. /// </summary> public IList<string> AllowedValues { get; set; } = new List<string>(); /// <summary> /// The value mapping for allowed values. The key of the dictionary is what is sent to services /// and the value is the display value shown to users. /// </summary> public IDictionary<string, string> ValueMapping { get; set; } = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Property will be displayed if specified dependencies are true /// </summary> public IList<PropertyDependency> DependsOn { get; set; } = new List<PropertyDependency>(); /// <summary> /// Child option settings for <see cref="OptionSettingValueType.Object"/> value types /// <see cref="ChildOptionSettings"/> value depends on the values of <see cref="ChildOptionSettings"/> /// </summary> public List<OptionSettingItem> ChildOptionSettings { get; set; } = new (); /// <summary> /// Type hint additional data required to facilitate handling of the option setting. /// </summary> public Dictionary<string, object> TypeHintData { get; set; } = new (); /// <summary> /// Indicates which option setting items need to be validated if a value update occurs. /// </summary> public List<string> Dependents { get; set; } = new List<string> (); /// <summary> /// The validation state of the setting that contains the validation status and message. /// </summary> [JsonIgnore] public OptionSettingValidation Validation { get; set; } public OptionSettingItem(string id, string fullyQualifiedId, string name, string description) { Id = id; FullyQualifiedId = fullyQualifiedId; Name = name; Description = description; Validation = new OptionSettingValidation(); } /// <summary> /// Helper method to get strongly type <see cref="TypeHintData"/>. /// </summary> /// <typeparam name="T">Type of the type hint data</typeparam> /// <returns>Returns strongly type type hint data. Returns default value if <see cref="TypeHintData"/> is empty.</returns> public T? GetTypeHintData<T>() { if (!TypeHintData.Any()) { return default; } var serialized = JsonConvert.SerializeObject(TypeHintData); return JsonConvert.DeserializeObject<T>(serialized); } } }
196
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.Common.Recipes.Validation; using Newtonsoft.Json; namespace AWS.Deploy.Common.Recipes { /// <see cref="GetValue{T}"/>, <see cref="GetValue"/> and <see cref="SetValueOverride"/> methods public partial class OptionSettingItem { public T? GetValue<T>(IDictionary<string, object> replacementTokens, IDictionary<string, bool>? displayableOptionSettings = null) { var value = GetValue(replacementTokens, displayableOptionSettings); return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(value)); } public object GetValue(IDictionary<string, object> replacementTokens, IDictionary<string, bool>? displayableOptionSettings = null) { if (_value != null) { return _value; } if (Type == OptionSettingValueType.Object) { var objectValue = new Dictionary<string, object>(); foreach (var childOptionSetting in ChildOptionSettings) { var childValue = childOptionSetting.GetValue(replacementTokens); if ( displayableOptionSettings != null && displayableOptionSettings.TryGetValue(childOptionSetting.Id, out bool isDisplayable)) { if (!isDisplayable) continue; } objectValue[childOptionSetting.Id] = childValue; } return objectValue; } if (DefaultValue == null) { return string.Empty; } if (DefaultValue is string defaultValueString) { return ApplyReplacementTokens(replacementTokens, defaultValueString); } return DefaultValue; } public T? GetDefaultValue<T>(IDictionary<string, object> replacementTokens) { var value = GetDefaultValue(replacementTokens); if (value == null) { return default; } return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(value)); } public object? GetDefaultValue(IDictionary<string, object> replacementTokens) { if (DefaultValue == null) { return null; } if (DefaultValue is string defaultValueString) { return ApplyReplacementTokens(replacementTokens, defaultValueString); } return DefaultValue; } /// <summary> /// Assigns a value to the OptionSettingItem. /// </summary> /// <param name="valueOverride">Value to assign</param> /// <param name="recommendation">Current deployment recommendation, may be used if the validator needs to consider properties other than itself</param> /// <exception cref="ValidationFailedException"> /// Thrown if one or more <see cref="Validators"/> determine /// <paramref name="valueOverride"/> is not valid. /// </exception> public async Task SetValue(IOptionSettingHandler optionSettingHandler, object valueOverride, IOptionSettingItemValidator[] validators, Recommendation recommendation, bool skipValidation) { if (!skipValidation) { foreach (var validator in validators) { var result = await validator.Validate(valueOverride, recommendation, this); if (!result.IsValid) { Validation.ValidationStatus = ValidationStatus.Invalid; Validation.ValidationMessage = result.ValidationFailedMessage?.Trim() ?? $"The value '{valueOverride}' is invalid for option setting '{Name}'."; Validation.InvalidValue = valueOverride; throw new ValidationFailedException(DeployToolErrorCode.OptionSettingItemValueValidationFailed, Validation.ValidationMessage); } } } if (AllowedValues != null && AllowedValues.Count > 0 && valueOverride != null && !AllowedValues.Contains(valueOverride.ToString() ?? "")) { Validation.ValidationStatus = ValidationStatus.Invalid; Validation.ValidationMessage = $"Invalid value for option setting item '{Name}'"; Validation.InvalidValue = valueOverride; throw new InvalidOverrideValueException(DeployToolErrorCode.InvalidValueForOptionSettingItem, Validation.ValidationMessage); } Validation.ValidationStatus = ValidationStatus.Valid; Validation.ValidationMessage = string.Empty; Validation.InvalidValue = null; try { if (valueOverride is bool || valueOverride is int || valueOverride is long || valueOverride is double || valueOverride is Dictionary<string, string> || valueOverride is SortedSet<string>) { _value = valueOverride; } else if (Type.Equals(OptionSettingValueType.KeyValue)) { var deserialized = JsonConvert.DeserializeObject<Dictionary<string, string>>(valueOverride?.ToString() ?? ""); _value = deserialized; } else if (Type.Equals(OptionSettingValueType.List)) { var deserialized = JsonConvert.DeserializeObject<SortedSet<string>>(valueOverride?.ToString() ?? ""); _value = deserialized; } else if (valueOverride is string valueOverrideString) { if (bool.TryParse(valueOverrideString, out var valueOverrideBool)) { _value = valueOverrideBool; } else if (int.TryParse(valueOverrideString, out var valueOverrideInt)) { _value = valueOverrideInt; } else { _value = valueOverrideString; } } else { var deserialized = JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(valueOverride)); foreach (var childOptionSetting in ChildOptionSettings) { if (deserialized?.TryGetValue(childOptionSetting.Id, out var childValueOverride) ?? false) { await optionSettingHandler.SetOptionSettingValue(recommendation, childOptionSetting, childValueOverride, skipValidation: skipValidation); } } } } catch (JsonReaderException ex) { Validation.ValidationStatus = ValidationStatus.Invalid; Validation.ValidationMessage = $"The value you are trying to set is invalid."; Validation.InvalidValue = valueOverride; throw new UnsupportedOptionSettingType(DeployToolErrorCode.UnsupportedOptionSettingType, $"The value you are trying to set for the option setting '{Name}' is invalid.", ex); } } private object ApplyReplacementTokens(IDictionary<string, object> replacementTokens, object defaultValue) { var defaultValueString = defaultValue?.ToString(); if (!string.IsNullOrEmpty(defaultValueString)) { if (Type != OptionSettingValueType.String) { foreach (var token in replacementTokens) { if (defaultValueString.Equals(token.Key)) defaultValue = token.Value; } } else { foreach (var token in replacementTokens) { defaultValueString = defaultValueString.Replace(token.Key, token.Value.ToString()); } defaultValue = defaultValueString; } } return defaultValue ?? string.Empty; } } }
209
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.Common.Recipes { /// <summary> /// This enum is used to specify the type of option settings that are retrieved when invoking <see cref="IOptionSettingHandler.GetOptionSettingsMap(Recommendation, ProjectDefinition, IO.IDirectoryManager, OptionSettingsType)"/> /// </summary> public enum OptionSettingsType { /// <summary> /// Theses option settings are part of the individual recipe files. /// </summary> Recipe, /// <summary> /// These option settings are part of the deployment bundle definitions. /// </summary> DeploymentBundle, /// <summary> /// Comprises of all types of option settings /// </summary> All } }
31
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Common.Recipes { public enum OptionSettingTypeHint { BeanstalkApplication, BeanstalkEnvironment, InstanceType, WindowsInstanceType, IAMRole, ECSCluster, ECSService, ECSTaskSchedule, EC2KeyPair, Vpc, ExistingApplicationLoadBalancer, DotnetBeanstalkPlatformArn, DotnetWindowsBeanstalkPlatformArn, DotnetPublishSelfContainedBuild, DotnetPublishBuildConfiguration, DotnetPublishAdditionalBuildArguments, DockerExecutionDirectory, DockerBuildArgs, AppRunnerService, DynamoDBTableName, SQSQueueUrl, SNSTopicArn, S3BucketName, BeanstalkRollingUpdates, ExistingIAMRole, ExistingECSCluster, ExistingVpc, ExistingBeanstalkApplication, ECRRepository, ExistingVpcConnector, ExistingSubnets, ExistingSecurityGroups, VPCConnector, FilePath, ElasticBeanstalkVpc }; }
45
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Common.Recipes { public enum ValidationStatus { Valid, Invalid } public class OptionSettingValidation { /// <summary> /// Determines whether the current value as set by the user is in a valid or invalid state. /// </summary> public ValidationStatus ValidationStatus { get; set; } = ValidationStatus.Valid; /// <summary> /// The validation message in the case where the value set by the user is an invalid one. /// This is empty in the case where the value set by the user is a valid one. /// </summary> public string ValidationMessage { get; set; } = string.Empty; /// <summary> /// The value last attempted to be set by the user in the case where that value is invalid. /// This is null in the case where the value is valid. /// </summary> public object? InvalidValue { get; set; } } }
32
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Common.Recipes { /// <summary> /// <para>Specifies the type of value held by the OptionSettingItem.</para> /// <para>The following peices will also need to be updated when adding a new OptionSettingValueType</para> /// <para>1. DeployCommand.ConfigureDeploymentFromCli(Recommendation recommendation, OptionSettingItem setting)</para> /// <para>2. OptionSettingItem.SetValue(IOptionSettingHandler optionSettingHandler, object valueOverride, IOptionSettingItemValidator[] validators, Recommendation recommendation, bool skipValidation)</para> /// <para>3. OptionSettingHandler.IsOptionSettingDisplayable(Recommendation recommendation, OptionSettingItem optionSetting)</para> /// <para>4. OptionSettingHandler.IsOptionSettingModified(Recommendation recommendation, OptionSettingItem optionSetting)</para> /// </summary> public enum OptionSettingValueType { String, Int, Double, Bool, KeyValue, Object, List }; }
25
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Common.Recipes { /// <summary> /// Container for property dependencies /// </summary> public class PropertyDependency { public string Id { get; set; } public PropertyDependencyOperationType? Operation { get; set; } public object Value { get; set; } public PropertyDependency( string id, PropertyDependencyOperationType? operation, object value) { Id = id; Operation = operation; Value = value; } } public enum PropertyDependencyOperationType { Equals, NotEmpty } }
32
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; using AWS.Deploy.Common.Recipes.Validation; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace AWS.Deploy.Common.Recipes { /// <summary> /// Used to deserialize a JSON recipe definition into. /// </summary> public class RecipeDefinition { /// <summary> /// The unique id of the recipe. That value will be persisted in other config files so it should never be changed once the recipe definition is released. /// </summary> public string Id { get; set; } /// <summary> /// The version of the recipe /// </summary> public string Version { get; set; } /// <summary> /// The display friendly name of the recipe definition /// </summary> public string Name { get; set; } /// <summary> /// Indicates if this recipe should be presented as an option during new deployments. /// </summary> public bool DisableNewDeployments { get; set; } /// <summary> /// Description of the recipe informing the user what this recipe does and why it is recommended. /// </summary> public string Description { get; set; } /// <summary> /// Short Description of the recipe informing the user what this recipe does and why it is recommended. /// </summary> public string ShortDescription { get; set; } /// <summary> /// A runtime property set when the recipe definition is loaded to the location of the definition. This property is used to find /// other assets like the CDK template project in relation to the recipe definition. /// </summary> public string? RecipePath { get; set; } /// <summary> /// The name of the AWS service the recipe deploys to. This is used for display purposes back to the user to inform then what AWS service the project /// will be deployed to. /// </summary> public string TargetService { get; set; } /// <summary> /// The environment platform the recipe deploys to. This is used to publish a self-contained .NET application for that platform. /// </summary> public TargetPlatform? TargetPlatform { get; set; } /// <summary> /// The list of DisplayedResources that lists logical CloudFormation IDs with a description. /// </summary> public List<DisplayedResource>? DisplayedResources { get; set; } /// <summary> /// Confirmation messages to display to the user before performing deployment. /// </summary> public DeploymentConfirmationType? DeploymentConfirmation { get; set; } /// <summary> /// The type of deployment to perform. This controls what other tool to use to perform the deployment. For example a value of `CdkProject` means that CDK should /// be used to perform the deployment. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public DeploymentTypes DeploymentType { get; set; } /// <summary> /// The type of deployment bundle the project should be converted into before deploying. For example turning the project into a build container or a zip file of the build binaries. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public DeploymentBundleTypes DeploymentBundle { get; set; } /// <summary> /// The location of the CDK project template relative from the recipe definition file. /// </summary> public string? CdkProjectTemplate { get; set; } /// <summary> /// The ID of the CDK project template for the template generator. /// </summary> public string? CdkProjectTemplateId { get; set; } /// <summary> /// The rules used by the recommendation engine to determine if the recipe definition is compatible with the project. /// </summary> public List<RecommendationRuleItem> RecommendationRules { get; set; } = new (); /// <summary> /// The list of categories for the recipes. /// </summary> public List<Category> Categories { get; set; } = new (); /// <summary> /// The settings that can be configured by the user before deploying. /// </summary> public List<OptionSettingItem> OptionSettings { get; set; } = new (); /// <summary> /// List of all validators that should be run against this recipe before deploying. /// </summary> public List<RecipeValidatorConfig> Validators { get; set; } = new (); /// <summary> /// The priority of the recipe. The highest priority is the top choice for deploying to. /// </summary> public int RecipePriority { get; set; } /// <summary> /// Flag to indicate if this recipe is generated while saving a deployment project. /// </summary> public bool PersistedDeploymentProject { get; set; } /// <summary> /// The recipe ID of the parent recipe which was used to create the CDK deployment project. /// </summary> public string? BaseRecipeId { get; set; } /// <summary> /// The settings that are specific to the Deployment Bundle. /// These settings are populated by the <see cref="IRecipeHandler"/>. /// </summary> public List<OptionSettingItem> DeploymentBundleSettings = new(); public RecipeDefinition( string id, string version, string name, DeploymentTypes deploymentType, DeploymentBundleTypes deploymentBundle, string cdkProjectTemplate, string cdkProjectTemplateId, string description, string shortDescription, string targetService) { Id = id; Version = version; Name = name; DeploymentType = deploymentType; DeploymentBundle = deploymentBundle; CdkProjectTemplate = cdkProjectTemplate; CdkProjectTemplateId = cdkProjectTemplateId; Description = description; ShortDescription = shortDescription; TargetService = targetService; } public override string ToString() { return $"{Name} ({Id})"; } } }
166
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; namespace AWS.Deploy.Common.Recipes { /// <summary> /// Container for the types of rules used by the recommendation engine. /// </summary> public class RecommendationRuleItem { /// <summary> /// The list of tests to run for the rule. /// </summary> public IList<RuleTest> Tests { get; set; } = new List<RuleTest>(); /// <summary> /// The effect of the rule based on whether the test pass or not. If the effect is not defined /// the effect is the Include option matches the result of the test passing. /// </summary> public RuleEffect? Effect { get; set; } } }
25
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; namespace AWS.Deploy.Common.Recipes { /// <summary> /// The conditions for the test used by the rule. /// </summary> public class RuleCondition { /// <summary> /// The value to check for. Used by the MSProjectSdkAttribute test /// </summary> public string? Value { get; set; } /// <summary> /// The name of the ms property for tests. Used by the MSProperty and MSPropertyExists /// </summary> public string? PropertyName { get; set; } /// <summary> /// The list of allowed values to check for. Used by the MSProperty test /// </summary> public IList<string> AllowedValues { get; set; } = new List<string>(); /// <summary> /// The name of file to search for. Used by the FileExists test. /// </summary> public string? FileName { get; set; } /// <summary> /// The name of a NuGet package for tests. Used to see if projects are taking dependencies on specific packages. /// </summary> public string? NuGetPackageName { get; set; } } }
39
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Common.Recipes { /// <summary> /// The effect to apply for the test run. /// </summary> public class RuleEffect { /// <summary> /// The effects to run if all the test pass. /// </summary> public EffectOptions? Pass { get; set; } /// <summary> /// The effects to run if all the test fail. /// </summary> public EffectOptions? Fail { get; set; } } }
23
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Common.Recipes { /// <summary> /// Test for a rule /// </summary> public class RuleTest { /// <summary> /// The type of test to run /// </summary> public string Type { get; set; } /// <summary> /// The conditions for the tests /// </summary> public RuleCondition Condition { get; set; } public RuleTest( string type, RuleCondition condition) { Type = type; Condition = condition; } } }
30
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Common.Recipes { public enum TargetPlatform { Linux, Windows } }
12