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 namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// Captures some basic information about the context the deployment tool is being running in. /// Originally, this is to support <see cref="IRecipeValidator"/> implementations having the ability /// to customize validation based on things like <see cref="AWSRegion"/>. /// <para /> /// WARNING: Please be careful adding additional properties to this interface or trying to re-purpose this interface /// for something other than validation. Consider if it instead makes more sense to use /// Interface Segregation to define a different interface for your use case. It's fine for OrchestratorSession /// to implement multiple interfaces. /// </summary> public interface IDeployToolValidationContext { ProjectDefinition ProjectDefinition { get; } string? AWSRegion { get; } } }
22
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// This interface outlines the framework for <see cref="OptionSettingItem"/> validators. /// Validators such as <see cref="RegexValidator"/> implement this interface and provide custom validation logic /// on OptionSettingItems /// </summary> public interface IOptionSettingItemValidator { /// <summary> /// Validates an override value for an <see cref="OptionSettingItem"/> /// </summary> /// <param name="input">Raw input for an option</param> /// <param name="recommendation">Selected recommendation, which may be used if the validator needs to consider properties other than itself</param> /// <param name="optionSettingItem">Selected option setting item, which may be used if the validator needs to consider properties other than itself</param> /// <returns>Whether or not the input is valid</returns> Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem); } }
25
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// This interface outlines the framework for recipe validators. /// Validators such as <see cref="FargateTaskCpuMemorySizeValidator"/> implement this interface /// and provide custom validation logic on recipes. /// </summary> public interface IRecipeValidator { Task<ValidationResult> Validate(Recommendation recommendation, IDeployToolValidationContext deployValidationContext); } }
18
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// This class is used to store the OptionSettingItem validator type and its corresponding configuration /// after parsing the validator from the deployment recipes. /// </summary> public class OptionSettingItemValidatorConfig { [JsonConverter(typeof(StringEnumConverter))] public OptionSettingItemValidatorList ValidatorType {get;set;} public object? Configuration {get;set;} } }
20
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.Common.Recipes.Validation { public enum OptionSettingItemValidatorList { /// <summary> /// Must be paired with <see cref="RangeValidator"/> /// </summary> Range, /// <summary> /// Must be paired with <see cref="RegexValidator"/> /// </summary> Regex, /// <summary> /// Must be paired with <see cref="RequiredValidator"/> /// </summary> Required, /// <summary> /// Must be paired with <see cref="DirectoryExistsValidator"/> /// </summary> DirectoryExists, /// <summary> /// Must be paired with <see cref="DockerBuildArgsValidator"/> /// </summary> DockerBuildArgs, /// <summary> /// Must be paried with <see cref="DotnetPublishArgsValidator"/> /// </summary> DotnetPublishArgs, /// <summary> /// Must be paired with <see cref="ExistingResourceValidator"/> /// </summary> ExistingResource, /// <summary> /// Must be paired with <see cref="FileExistsValidator"/> /// </summary> FileExists, /// <summary> /// Must be paired with <see cref="StringLengthValidator"/> /// </summary> StringLength, /// <summary> /// Must be paired with <see cref="LinuxInstanceTypeValidator"/> /// </summary> InstanceType, /// <summary> /// Must be paired with <see cref="WindowsInstanceTypeValidator"/> /// </summary> WindowsInstanceType, /// <summary> /// Must be paired with <see cref="SubnetsInVpcValidator"/> /// </summary> SubnetsInVpc, /// <summary> /// Must be paired with <see cref="SecurityGroupsInVpcValidator"/> /// </summary> SecurityGroupsInVpc, /// <summary> /// Must be paired with <see cref="UriValidator"/> /// </summary> Uri, /// <summary> /// Must be paired with <see cref="ComparisonValidator"/> /// </summary> Comparison, /// <summary> /// Must be paired with <see cref="VPCSubnetsInDifferentAZsValidator"/> /// </summary> VPCSubnetsInDifferentAZs, /// <summary> /// Must be paired with <see cref="VpcExistsValidator"/> /// </summary> VpcExists } }
78
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// This class is used to store the Recipe validator type and its corresponding configuration /// after parsing the validator from the deployment recipes. /// </summary> public class RecipeValidatorConfig { [JsonConverter(typeof(StringEnumConverter))] public RecipeValidatorList ValidatorType {get;set;} public object? Configuration {get;set;} } }
20
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.Common.Recipes.Validation { public enum RecipeValidatorList { /// <summary> /// Must be paired with <see cref="FargateTaskCpuMemorySizeValidator"/> /// </summary> FargateTaskSizeCpuMemoryLimits, /// <summary> /// Must be paired with <see cref="DockerfilePathValidator"/> /// </summary> ValidDockerfilePath } }
19
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; namespace AWS.Deploy.Common.Recipes.Validation { public class ValidationResult { public bool IsValid { get; set; } public string? ValidationFailedMessage { get;set; } public static ValidationResult Failed(string message) { return new ValidationResult { IsValid = false, ValidationFailedMessage = message }; } public static Task<ValidationResult> FailedAsync(string message) { return Task.FromResult<ValidationResult>(Failed(message)); } public static ValidationResult Valid() { return new ValidationResult { IsValid = true }; } public static Task<ValidationResult> ValidAsync() { return Task.FromResult<ValidationResult>(Valid()); } } }
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 Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// Factory that builds the validators for a given option or recipe /// </summary> public interface IValidatorFactory { /// <summary> /// Builds the validators that apply to the given option /// </summary> /// <param name="optionSettingItem">Option to validate</param> /// <param name="filter">Applies a filter to the list of validators</param> /// <returns>Array of validators for the given option</returns> IOptionSettingItemValidator[] BuildValidators(OptionSettingItem optionSettingItem, Func<OptionSettingItemValidatorConfig, bool>? filter = null); /// <summary> /// Builds the validators that apply to the given recipe /// </summary> /// <param name="recipeDefinition">Recipe to validate</param> /// <returns>Array of validators for the given recipe</returns> IRecipeValidator[] BuildValidators(RecipeDefinition recipeDefinition); } /// <summary> /// Builds <see cref="IOptionSettingItemValidator"/> and <see cref="IRecipeValidator"/> instances. /// </summary> public class ValidatorFactory : IValidatorFactory { private readonly IServiceProvider _serviceProvider; public ValidatorFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } private static readonly Dictionary<OptionSettingItemValidatorList, Type> _optionSettingItemValidatorTypeMapping = new() { { OptionSettingItemValidatorList.Range, typeof(RangeValidator) }, { OptionSettingItemValidatorList.Regex, typeof(RegexValidator) }, { OptionSettingItemValidatorList.Required, typeof(RequiredValidator) }, { OptionSettingItemValidatorList.DirectoryExists, typeof(DirectoryExistsValidator) }, { OptionSettingItemValidatorList.DockerBuildArgs, typeof(DockerBuildArgsValidator) }, { OptionSettingItemValidatorList.DotnetPublishArgs, typeof(DotnetPublishArgsValidator) }, { OptionSettingItemValidatorList.ExistingResource, typeof(ExistingResourceValidator) }, { OptionSettingItemValidatorList.FileExists, typeof(FileExistsValidator) }, { OptionSettingItemValidatorList.StringLength, typeof(StringLengthValidator) }, { OptionSettingItemValidatorList.InstanceType, typeof(LinuxInstanceTypeValidator) }, { OptionSettingItemValidatorList.WindowsInstanceType, typeof(WindowsInstanceTypeValidator) }, { OptionSettingItemValidatorList.SubnetsInVpc, typeof(SubnetsInVpcValidator) }, { OptionSettingItemValidatorList.SecurityGroupsInVpc, typeof(SecurityGroupsInVpcValidator) }, { OptionSettingItemValidatorList.Uri, typeof(UriValidator) }, { OptionSettingItemValidatorList.Comparison, typeof(ComparisonValidator) }, { OptionSettingItemValidatorList.VPCSubnetsInDifferentAZs, typeof(VPCSubnetsInDifferentAZsValidator) }, { OptionSettingItemValidatorList.VpcExists, typeof(VpcExistsValidator) } }; private static readonly Dictionary<RecipeValidatorList, Type> _recipeValidatorTypeMapping = new() { { RecipeValidatorList.FargateTaskSizeCpuMemoryLimits, typeof(FargateTaskCpuMemorySizeValidator) }, { RecipeValidatorList.ValidDockerfilePath, typeof(DockerfilePathValidator) } }; public IOptionSettingItemValidator[] BuildValidators(OptionSettingItem optionSettingItem, Func<OptionSettingItemValidatorConfig, bool>? filter = null) { return optionSettingItem.Validators .Where(validator => filter != null ? filter(validator) : true) .Select(v => Activate(v.ValidatorType, v.Configuration, _optionSettingItemValidatorTypeMapping)) .OfType<IOptionSettingItemValidator>() .ToArray(); } public IRecipeValidator[] BuildValidators(RecipeDefinition recipeDefinition) { return recipeDefinition.Validators .Select(v => Activate(v.ValidatorType, v.Configuration, _recipeValidatorTypeMapping)) .OfType<IRecipeValidator>() .ToArray(); } private object? Activate<TValidatorList>(TValidatorList validatorType, object? configuration, Dictionary<TValidatorList, Type> typeMappings) where TValidatorList : struct { if (null == configuration) { var validatorInstance = ActivatorUtilities.CreateInstance(_serviceProvider, typeMappings[validatorType]); if (validatorInstance == null) throw new InvalidValidatorTypeException(DeployToolErrorCode.UnableToCreateValidatorInstance, $"Could not create an instance of validator type {validatorType}"); return validatorInstance; } if (configuration is JObject jObject) { var validatorInstance = JsonConvert.DeserializeObject( JsonConvert.SerializeObject(jObject), typeMappings[validatorType], new JsonSerializerSettings { ContractResolver = new ServiceContractResolver(_serviceProvider) }); if (validatorInstance == null) throw new InvalidValidatorTypeException(DeployToolErrorCode.UnableToCreateValidatorInstance, $"Could not create an instance of validator type {validatorType}"); return validatorInstance; } return configuration; } } /// <summary> /// Custom contract resolver that can inject services from an IServiceProvider /// into the constructor of the type that is being deserialized from Json /// </summary> public class ServiceContractResolver : DefaultContractResolver { private readonly IServiceProvider _serviceProvider; public ServiceContractResolver(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } protected override JsonObjectContract CreateObjectContract(Type objectType) { var contract = base.CreateObjectContract(objectType); contract.DefaultCreator = () => ActivatorUtilities.CreateInstance(_serviceProvider, objectType); return contract; } } }
143
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; namespace AWS.Deploy.Common.Recipes.Validation { public enum ComparisonValidatorOperation { GreaterThan } /// <summary> /// The validator is typically used with OptionSettingItems which have a numeric type. /// The validator requires two configuration options to be specific, the Operation and the SettingId. /// The validator checks if the set value of the OptionSettingItem satisfies the comparison operation with SettingId. /// </summary> public class ComparisonValidator : IOptionSettingItemValidator { public ComparisonValidatorOperation? Operation { get; set; } public string? SettingId { get;set; } private readonly IOptionSettingHandler _optionSettingHandler; public ComparisonValidator(IOptionSettingHandler optionSettingHandler) { _optionSettingHandler = optionSettingHandler; } public Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { if (Operation == null) throw new MissingValidatorConfigurationException(DeployToolErrorCode.MissingValidatorConfiguration, $"The validator of type '{typeof(ComparisonValidator)}' is missing the configuration property '{nameof(Operation)}'."); if (string.IsNullOrEmpty(SettingId)) throw new MissingValidatorConfigurationException(DeployToolErrorCode.MissingValidatorConfiguration, $"The validator of type '{typeof(ComparisonValidator)}' is missing the configuration property '{nameof(SettingId)}'."); if (!double.TryParse(input?.ToString(), out double inputDouble)) return ValidationResult.FailedAsync($"The value of '{optionSettingItem.Name}' is not a numeric value."); var comparisonSetting = _optionSettingHandler.GetOptionSetting(recommendation, SettingId); var comparisonSettingValue = _optionSettingHandler.GetOptionSettingValue(recommendation, comparisonSetting); if (!double.TryParse(comparisonSettingValue?.ToString(), out double comparisonSettingValueDouble)) return ValidationResult.FailedAsync($"The value of '{comparisonSetting.Name}' is not a numeric value."); if (Operation == ComparisonValidatorOperation.GreaterThan) { if (inputDouble > comparisonSettingValueDouble) return ValidationResult.ValidAsync(); else return ValidationResult.FailedAsync($"The value of '{optionSettingItem.Name}' must be greater than the value of '{comparisonSetting.Name}'."); } else { return ValidationResult.FailedAsync($"The operation '{Operation}' is not yet supported."); } } } }
57
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using AWS.Deploy.Common.IO; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// Validator that validates if a given directory exists /// </summary> public class DirectoryExistsValidator : IOptionSettingItemValidator { private readonly IDirectoryManager _directoryManager; public DirectoryExistsValidator(IDirectoryManager directoryManager) { _directoryManager = directoryManager; } /// <summary> /// Validates that the given directory exists. /// This can be either an absolute path, or a path relative to the project directory. /// </summary> /// <param name="input">Path to validate</param> /// <param name="recommendation">Selected recommendation, which may be used if the validator needs to consider properties other than itself</param> /// <param name="optionSettingItem">Selected option setting item, which may be used if the validator needs to consider properties other than itself</param> /// <returns>Valid if the directory exists, invalid otherwise</returns> public Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { var executionDirectory = (string)input; if (!string.IsNullOrEmpty(executionDirectory) && !_directoryManager.Exists(executionDirectory)) return ValidationResult.FailedAsync("The specified directory does not exist."); else return ValidationResult.ValidAsync(); } } }
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.Threading.Tasks; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// Validator for Docker build-time variables, passed via --build-arg /// </summary> public class DockerBuildArgsValidator : IOptionSettingItemValidator { /// <summary> /// Validates that additional Docker build options don't collide /// with those set by the deploy tool /// </summary> /// <param name="input">Proposed Docker build args</param> /// <param name="recommendation">Selected recommendation, which may be used if the validator needs to consider properties other than itself</param> /// <param name="optionSettingItem">Selected option setting item, which may be used if the validator needs to consider properties other than itself</param> /// <returns>Valid if the options do not contain those set by the deploy tool, invalid otherwise</returns> public Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { var buildArgs = Convert.ToString(input); var errorMessage = string.Empty; if (string.IsNullOrEmpty(buildArgs)) { return ValidationResult.ValidAsync(); } if (buildArgs.Contains("-t ") || buildArgs.Contains("--tag ")) errorMessage += "You must not include -t/--tag as an additional argument as it is used internally. " + "You may set the Image Tag property in the advanced settings for some recipes." + Environment.NewLine; if (buildArgs.Contains("-f ") || buildArgs.Contains("--file ")) errorMessage += "You must not include -f/--file as an additional argument as it is used internally." + Environment.NewLine; if (!string.IsNullOrEmpty(errorMessage)) return ValidationResult.FailedAsync("Invalid value for additional Docker build options." + Environment.NewLine + errorMessage.Trim()); return ValidationResult.ValidAsync(); } } }
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.Threading.Tasks; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// Validator for additional arguments to 'dotnet publish' /// </summary> public class DotnetPublishArgsValidator : IOptionSettingItemValidator { /// <summary> /// Validates that additional 'dotnet publish' arguments do not collide with those used by the deploy tool /// </summary> /// <param name="input">Additional publish arguments</param> /// <param name="recommendation">Selected recommendation, which may be used if the validator needs to consider properties other than itself</param> /// <param name="optionSettingItem">Selected option setting item, which may be used if the validator needs to consider properties other than itself</param> /// <returns>Valid if the arguments don't interfere with the deploy tool, invalid otherwise</returns> public Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { var publishArgs = Convert.ToString(input); var errorMessage = string.Empty; if (string.IsNullOrEmpty(publishArgs)) { return ValidationResult.ValidAsync(); } if (publishArgs.Contains("-o ") || publishArgs.Contains("--output ")) errorMessage += "You must not include -o/--output as an additional argument as it is used internally." + Environment.NewLine; if (publishArgs.Contains("-c ") || publishArgs.Contains("--configuration ")) errorMessage += "You must not include -c/--configuration as an additional argument. You can set the build configuration in the advanced settings." + Environment.NewLine; if (publishArgs.Contains("--self-contained") || publishArgs.Contains("--no-self-contained")) errorMessage += "You must not include --self-contained/--no-self-contained as an additional argument. You can set the self-contained property in the advanced settings." + Environment.NewLine; if (!string.IsNullOrEmpty(errorMessage)) return ValidationResult.FailedAsync("Invalid value for Dotnet Publish Arguments." + Environment.NewLine + errorMessage.Trim()); return ValidationResult.ValidAsync(); } } }
47
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Linq; using System.Threading.Tasks; using Amazon.CloudControlApi.Model; using AWS.Deploy.Common.Data; using Amazon.ElasticBeanstalk; namespace AWS.Deploy.Common.Recipes.Validation { public class ExistingResourceValidator : IOptionSettingItemValidator { private readonly IAWSResourceQueryer _awsResourceQueryer; /// <summary> /// The Cloud Control API resource type that will be used to query Cloud Control API for the existance of a resource. /// </summary> public string? ResourceType { get; set; } public ExistingResourceValidator(IAWSResourceQueryer awsResourceQueryer) { _awsResourceQueryer = awsResourceQueryer; } public async Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { if (string.IsNullOrEmpty(ResourceType)) throw new MissingValidatorConfigurationException(DeployToolErrorCode.MissingValidatorConfiguration, $"The validator of type '{typeof(ExistingResourceValidator)}' is missing the configuration property '{nameof(ResourceType)}'."); var resourceName = input?.ToString() ?? string.Empty; if (string.IsNullOrEmpty(resourceName)) return ValidationResult.Valid(); switch (ResourceType) { case "AWS::ElasticBeanstalk::Application": var beanstalkApplications = await _awsResourceQueryer.ListOfElasticBeanstalkApplications(resourceName); if (beanstalkApplications.Any(x => x.ApplicationName.Equals(resourceName))) return ValidationResult.Failed($"An Elastic Beanstalk application already exists with the name '{resourceName}'. Check the AWS Console for more information on the existing resource."); break; case "AWS::ElasticBeanstalk::Environment": var beanstalkEnvironments = await _awsResourceQueryer.ListOfElasticBeanstalkEnvironments(environmentName: resourceName); if (beanstalkEnvironments.Any(x => x.EnvironmentName.Equals(resourceName) && x.Status != EnvironmentStatus.Terminated)) return ValidationResult.Failed($"An Elastic Beanstalk environment already exists with the name '{resourceName}'. Check the AWS Console for more information on the existing resource."); break; default: try { var resource = await _awsResourceQueryer.GetCloudControlApiResource(ResourceType, resourceName); return ValidationResult.Failed($"A resource of type '{ResourceType}' and name '{resourceName}' already exists. Check the AWS Console for more information on the existing resource."); } catch (ResourceQueryException ex) when (ex.InnerException is ResourceNotFoundException) { break; } } return ValidationResult.Valid(); } } }
64
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using AWS.Deploy.Common.IO; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// Validates that a recipe or deployment bundle option with a FilePath typehint points to an actual file. /// This can either be an absolute path to the file or relative to the project path /// </summary> public class FileExistsValidator : IOptionSettingItemValidator { private readonly IFileManager _fileManager; public FileExistsValidator(IFileManager fileManager) { _fileManager = fileManager; } public string ValidationFailedMessage { get; set; } = "The specified file does not exist"; /// <summary> /// Whether or not an empty filepath is valid (essentially whether this option is required) /// </summary> public bool AllowEmptyString { get; set; } = true; public Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { var inputFilePath = input?.ToString() ?? string.Empty; if (string.IsNullOrEmpty(inputFilePath)) { if (AllowEmptyString) { return ValidationResult.ValidAsync(); } else { return ValidationResult.FailedAsync("A file must be specified"); } } // Otherwise if there is a value, verify that it points to an actual file if (_fileManager.Exists(inputFilePath, recommendation.GetProjectDirectory())) { return ValidationResult.ValidAsync(); } else { return ValidationResult.FailedAsync($"The specified file {inputFilePath} does not exist"); } } } }
57
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.Threading.Tasks; using Amazon.EC2; using Amazon.EC2.Model; using AWS.Deploy.Common.Data; using AWS.Deploy.Constants; namespace AWS.Deploy.Common.Recipes.Validation { public class WindowsInstanceTypeValidator : InstanceTypeValidator { public WindowsInstanceTypeValidator(IAWSResourceQueryer awsResourceQueryer) : base(awsResourceQueryer, EC2.FILTER_PLATFORM_WINDOWS) { } } public class LinuxInstanceTypeValidator : InstanceTypeValidator { public LinuxInstanceTypeValidator(IAWSResourceQueryer awsResourceQueryer) : base(awsResourceQueryer, EC2.FILTER_PLATFORM_LINUX) { } } /// <summary> /// Validates that a given EC2 instance is valid for the deployment region /// </summary> public abstract class InstanceTypeValidator : IOptionSettingItemValidator { private readonly IAWSResourceQueryer _awsResourceQueryer; private readonly string _platform; public InstanceTypeValidator(IAWSResourceQueryer awsResourceQueryer, string platform) { _awsResourceQueryer = awsResourceQueryer; _platform = platform; } public async Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { var rawInstanceType = Convert.ToString(input); InstanceTypeInfo? instanceTypeInfo; if (string.IsNullOrEmpty(rawInstanceType)) { return ValidationResult.Valid(); } try { instanceTypeInfo = await _awsResourceQueryer.DescribeInstanceType(rawInstanceType); } catch (ResourceQueryException ex) { // Check for the expected exception if the provided instance type is invalid if (ex.InnerException is AmazonEC2Exception ec2Exception && string.Equals(ec2Exception.ErrorCode, "InvalidInstanceType", StringComparison.InvariantCultureIgnoreCase)) { instanceTypeInfo = null; } else // Anything else is unexpected, so proceed with usual exception handling { throw ex; } } if(instanceTypeInfo == null) { return ValidationResult.Failed($"The specified instance type {rawInstanceType} does not exist in the deployment region."); } if (string.Equals(_platform, EC2.FILTER_PLATFORM_WINDOWS) && !instanceTypeInfo.ProcessorInfo.SupportedArchitectures.Contains(EC2.FILTER_ARCHITECTURE_X86_64)) { return ValidationResult.Failed($"The specified instance type {rawInstanceType} does not support {EC2.FILTER_ARCHITECTURE_X86_64}."); } return ValidationResult.Valid(); } } }
85
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// The validator is typically used with OptionSettingItems which have a numeric type. /// The minimum and maximum values are specified in the deployment recipe /// and this validator checks if the set value of the OptionSettingItem falls within this range or not. /// </summary> public class RangeValidator : IOptionSettingItemValidator { private static readonly string defaultValidationFailedMessage = "Value must be greater than or equal to {{Min}} and less than or equal to {{Max}}"; public int Min { get; set; } = int.MinValue; public int Max { get;set; } = int.MaxValue; /// <summary> /// Supports replacement tokens {{Min}} and {{Max}} /// </summary> public string ValidationFailedMessage { get; set; } = defaultValidationFailedMessage; public bool AllowEmptyString { get; set; } public Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { if (AllowEmptyString && string.IsNullOrEmpty(input?.ToString())) return ValidationResult.ValidAsync(); if (int.TryParse(input?.ToString(), out var result) && result >= Min && result <= Max) { return ValidationResult.ValidAsync(); } var message = ValidationFailedMessage .Replace("{{Min}}", Min.ToString()) .Replace("{{Max}}", Max.ToString()); return ValidationResult.FailedAsync(message); } } }
48
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.Text.RegularExpressions; using System.Threading.Tasks; using AWS.Deploy.Common.Extensions; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// The validator is typically used with OptionSettingItems which have a string type. /// The regex string is specified in the deployment recipe /// and this validator checks if the set value of the OptionSettingItem matches the regex or not. /// </summary> public class RegexValidator : IOptionSettingItemValidator { private static readonly string defaultRegex = "(.*)"; private static readonly string defaultValidationFailedMessage = "Value must match Regex {{Regex}}"; public string Regex { get; set; } = defaultRegex; public string ValidationFailedMessage { get; set; } = defaultValidationFailedMessage; public bool AllowEmptyString { get; set; } public Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { var regex = new Regex(Regex); var message = ValidationFailedMessage.Replace("{{Regex}}", Regex); if (input?.TryDeserialize<SortedSet<string>>(out var inputList) ?? false) { foreach (var item in inputList!) { var valid = regex.IsMatch(item) || (AllowEmptyString && string.IsNullOrEmpty(item)); if (!valid) return Task.FromResult<ValidationResult>(new ValidationResult { IsValid = false, ValidationFailedMessage = message }); } return Task.FromResult<ValidationResult>(new ValidationResult { IsValid = true, ValidationFailedMessage = message }); } return Task.FromResult<ValidationResult>(new ValidationResult { IsValid = regex.IsMatch(input?.ToString() ?? "") || (AllowEmptyString && string.IsNullOrEmpty(input?.ToString())), ValidationFailedMessage = message }); } } }
59
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.Extensions; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// The validator is used to enforce that a particular OptionSettingItem has a value before deployment. /// </summary> public class RequiredValidator : IOptionSettingItemValidator { private static readonly string defaultValidationFailedMessage = "The option setting '{{OptionSetting}}' can not be empty. Please select a valid value."; public string ValidationFailedMessage { get; set; } = defaultValidationFailedMessage; public Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { var message = ValidationFailedMessage.Replace("{{OptionSetting}}", optionSettingItem.Name); if (input?.TryDeserialize<SortedSet<string>>(out var inputList) ?? false && inputList != null) { return Task.FromResult<ValidationResult>(new() { IsValid = inputList!.Any(), ValidationFailedMessage = message }); } return Task.FromResult<ValidationResult>(new() { IsValid = !string.IsNullOrEmpty(input?.ToString()), ValidationFailedMessage = message }); } } }
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.Linq; using System.Collections.Generic; using System.Threading.Tasks; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.Extensions; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// Validates that the selected security groups are part of the selected VPC /// </summary> public class SecurityGroupsInVpcValidator : IOptionSettingItemValidator { private static readonly string defaultValidationFailedMessage = "The selected security groups are not part of the selected VPC."; /// <summary> /// Path to the OptionSetting that stores a selected Vpc Id /// </summary> public string VpcId { get; set; } = ""; /// <summary> /// Path to the OptionSetting that determines if the default VPC should be used /// </summary> public string IsDefaultVpcOptionSettingId { get; set; } = ""; public string ValidationFailedMessage { get; set; } = defaultValidationFailedMessage; private readonly IAWSResourceQueryer _awsResourceQueryer; private readonly IOptionSettingHandler _optionSettingHandler; public SecurityGroupsInVpcValidator(IAWSResourceQueryer awsResourceQueryer, IOptionSettingHandler optionSettingHandler) { _awsResourceQueryer = awsResourceQueryer; _optionSettingHandler = optionSettingHandler; } public async Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { if (string.IsNullOrEmpty(VpcId)) return ValidationResult.Failed($"The '{nameof(SecurityGroupsInVpcValidator)}' validator is missing the '{nameof(VpcId)}' configuration."); var vpcId = ""; // The ECS Fargate recipes expose a separate radio button to select the default VPC which is mutually exclusive // with specifying an explicit VPC Id. Because we give preference to "UseDefault" in the CDK project, // we should do so here as well and validate the security groups against the default VPC if it's selected. if (!string.IsNullOrEmpty(IsDefaultVpcOptionSettingId)) { var isDefaultVpcOptionSetting = _optionSettingHandler.GetOptionSetting(recommendation, IsDefaultVpcOptionSettingId); var shouldUseDefaultVpc = _optionSettingHandler.GetOptionSettingValue<bool>(recommendation, isDefaultVpcOptionSetting); if (shouldUseDefaultVpc) { vpcId = (await _awsResourceQueryer.GetDefaultVpc()).VpcId; } } // If the "Use default?" option doesn't exist in the recipe, or it does and was false, or // we failed to look up the default VPC, then use the explicity VPC Id if (string.IsNullOrEmpty(vpcId)) { var vpcIdSetting = _optionSettingHandler.GetOptionSetting(recommendation, VpcId); vpcId = _optionSettingHandler.GetOptionSettingValue<string>(recommendation, vpcIdSetting); } if (string.IsNullOrEmpty(vpcId)) return ValidationResult.Failed("The VpcId setting is not set or is empty. Make sure to set the VPC Id first."); var securityGroupIds = (await _awsResourceQueryer.DescribeSecurityGroups(vpcId)).Select(x => x.GroupId); // The ASP.NET Fargate recipe uses a list of security groups if (input?.TryDeserialize<SortedSet<string>>(out var inputList) ?? false) { var invalidSecurityGroups = new List<string>(); foreach (var securityGroup in inputList!) { if (!securityGroupIds.Contains(securityGroup)) invalidSecurityGroups.Add(securityGroup); } if (invalidSecurityGroups.Any()) { return ValidationResult.Failed($"The selected security group(s) ({string.Join(", ", invalidSecurityGroups)}) " + $"are invalid since they do not belong to the currently selected VPC {vpcId}."); } return ValidationResult.Valid(); } // The Console ECS Fargate Service recipe uses a comma-separated string, which will fall through the TryDeserialize above if (input is string) { // Security groups aren't required if (string.IsNullOrEmpty(input.ToString())) { return ValidationResult.Valid(); } var securityGroupList = input.ToString()?.Split(',') ?? new string[0]; var invalidSecurityGroups = new List<string>(); foreach (var securityGroup in securityGroupList) { if (!securityGroupIds.Contains(securityGroup)) invalidSecurityGroups.Add(securityGroup); } if (invalidSecurityGroups.Any()) { return ValidationResult.Failed($"The selected security group(s) ({string.Join(", ", invalidSecurityGroups)}) " + $"are invalid since they do not belong to the currently selected VPC {vpcId}."); } return ValidationResult.Valid(); } return new ValidationResult { IsValid = securityGroupIds.Contains(input?.ToString()), ValidationFailedMessage = ValidationFailedMessage }; } } }
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.Generic; using System.Text; using System.Threading.Tasks; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// Validates that an OptionSettingItem of type string satisifes the required length constraints /// </summary> public class StringLengthValidator : IOptionSettingItemValidator { public int MinLength { get; set; } = 0; public int MaxLength { get; set; } = 1000; public string ValidationFailedMessage { get; set; } = "Invalid value. Number of characters must be between {{min}} and {{max}}"; public Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { var inputString = input?.ToString() ?? string.Empty; var stringLength = inputString.Length; if (stringLength < MinLength || stringLength > MaxLength) { var message = ValidationFailedMessage .Replace("{{min}}", MinLength.ToString()) .Replace("{{max}}", MaxLength.ToString()); return ValidationResult.FailedAsync(message); } return ValidationResult.ValidAsync(); } } }
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.Linq; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.EC2; using Amazon.EC2.Model; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.Extensions; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// Validates that the selected subnets are part of the selected VPC /// </summary> public class SubnetsInVpcValidator : IOptionSettingItemValidator { private static readonly string defaultValidationFailedMessage = "The selected subnets are not part of the selected VPC."; public string VpcId { get; set; } = ""; public string ValidationFailedMessage { get; set; } = defaultValidationFailedMessage; private readonly IAWSResourceQueryer _awsResourceQueryer; private readonly IOptionSettingHandler _optionSettingHandler; public SubnetsInVpcValidator(IAWSResourceQueryer awsResourceQueryer, IOptionSettingHandler optionSettingHandler) { _awsResourceQueryer = awsResourceQueryer; _optionSettingHandler = optionSettingHandler; } public async Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { if (string.IsNullOrEmpty(VpcId)) return ValidationResult.Failed($"The '{nameof(SubnetsInVpcValidator)}' validator is missing the '{nameof(VpcId)}' configuration."); var vpcIdSetting = _optionSettingHandler.GetOptionSetting(recommendation, VpcId); var vpcId = _optionSettingHandler.GetOptionSettingValue<string>(recommendation, vpcIdSetting); if (string.IsNullOrEmpty(vpcId)) return ValidationResult.Failed("The VpcId setting is not set or is empty. Make sure to set the VPC Id first."); var subnetIds = (await _awsResourceQueryer.DescribeSubnets(vpcId)).Select(x => x.SubnetId); if (input?.TryDeserialize<SortedSet<string>>(out var inputList) ?? false) { foreach (var subnet in inputList!) { if (!subnetIds.Contains(subnet)) return ValidationResult.Failed("The selected subnet(s) are invalid since they do not belong to the currently selected VPC."); } return ValidationResult.Valid(); } return new ValidationResult { IsValid = subnetIds.Contains(input?.ToString()), ValidationFailedMessage = ValidationFailedMessage }; } } }
62
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; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// Checks if a URI is structurally valid /// </summary> public class UriValidator : IOptionSettingItemValidator { public string ValidationFailedMessage { get; set; } = "{{URI}} is not a valid URI."; public Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSetting) { var uri = input?.ToString() ?? string.Empty; /// It is possible that a URI specific option setting item is optional and can be null or empty. /// To enforce the presence of a non-null or non-empty value, you must combine this validator with a <see cref="RequiredValidator"/> if (string.IsNullOrEmpty(uri)) { return ValidationResult.ValidAsync(); } var message = ValidationFailedMessage.Replace("{{URI}}", uri); try { var uriResult = new Uri(uri); if (!Uri.IsWellFormedUriString(uri, UriKind.Absolute)) return ValidationResult.FailedAsync(message); } catch (UriFormatException) { return ValidationResult.FailedAsync(message); } return ValidationResult.ValidAsync(); } } }
45
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Linq; using System.Threading.Tasks; using AWS.Deploy.Common.Data; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// Validates that a VPC exists in the account /// </summary> public class VpcExistsValidator : IOptionSettingItemValidator { private static readonly string defaultValidationFailedMessage = "A VPC could not be found."; public string ValidationFailedMessage { get; set; } = defaultValidationFailedMessage; /// <summary> /// The value of the option setting that will cause the validator to fail if a VPC is not found. /// </summary> public object FailValue { get; set; } = true; /// <summary> /// The value type of the option setting and <see cref="FailValue"/>. /// </summary> public OptionSettingValueType ValueType { get; set; } = OptionSettingValueType.Bool; /// <summary> /// Indicates whether this validator will only check for the existence of the default VPC. /// </summary> public bool DefaultVpc { get; set; } = false; private readonly IAWSResourceQueryer _awsResourceQueryer; public VpcExistsValidator(IAWSResourceQueryer awsResourceQueryer) { _awsResourceQueryer = awsResourceQueryer; } public async Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { // Check for the existence of VPCs which will cause the Validator to pass if VPCs exist if (DefaultVpc) { var vpc = await _awsResourceQueryer.GetDefaultVpc(); if (vpc != null) return ValidationResult.Valid(); } else { var vpcs = await _awsResourceQueryer.GetListOfVpcs(); if (vpcs.Any()) return ValidationResult.Valid(); } // If VPCs don't exist, based on the type, check if the option setting value is equal to the FailValue var inputString = input?.ToString() ?? string.Empty; if (ValueType == OptionSettingValueType.Bool) { if (bool.TryParse(inputString, out var inputBool) && FailValue is bool FailValueBool) { if (inputBool == FailValueBool) return ValidationResult.Failed(ValidationFailedMessage); else return ValidationResult.Valid(); } else { return ValidationResult.Failed($"The option setting value or '{nameof(FailValue)}' are not of type '{ValueType}'."); } } else { return ValidationResult.Failed($"The value '{ValueType}' for '{nameof(ValueType)}' is not supported."); } } } }
79
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.Data; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// Validates that the selected VPC must have at least two subnets in two different Availability Zones /// </summary> public class VPCSubnetsInDifferentAZsValidator : IOptionSettingItemValidator { private static readonly string defaultValidationFailedMessage = "Selected VPC must have at least two subnets in two different Availability Zones."; public string ValidationFailedMessage { get; set; } = defaultValidationFailedMessage; private readonly IAWSResourceQueryer _awsResourceQueryer; public VPCSubnetsInDifferentAZsValidator(IAWSResourceQueryer awsResourceQueryer) { _awsResourceQueryer = awsResourceQueryer; } public async Task<ValidationResult> Validate(object input, Recommendation recommendation, OptionSettingItem optionSettingItem) { var vpcId = input?.ToString(); if (string.IsNullOrEmpty(vpcId)) return ValidationResult.Failed("A VPC ID is not specified. Please select a valid VPC ID."); var subnets = await _awsResourceQueryer.DescribeSubnets(vpcId); var availabilityZones = new HashSet<string>(); foreach (var subnet in subnets) availabilityZones.Add(subnet.AvailabilityZoneId); if (availabilityZones.Count >= 2) return ValidationResult.Valid(); else return ValidationResult.Failed(ValidationFailedMessage); } } }
43
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.Threading.Tasks; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Utilities; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// This validates that the Dockerfile is within the build context. /// /// Per https://docs.docker.com/engine/reference/commandline/build/#text-files /// "The path must be to a file within the build context." /// </summary> public class DockerfilePathValidator : IRecipeValidator { private readonly IDirectoryManager _directoryManager; private readonly IFileManager _fileManager; public DockerfilePathValidator(IDirectoryManager directoryManager, IFileManager fileManager) { _directoryManager = directoryManager; _fileManager = fileManager; } public Task<ValidationResult> Validate(Recommendation recommendation, IDeployToolValidationContext deployValidationContext) { DockerUtilities.TryGetAbsoluteDockerfile(recommendation, _fileManager, _directoryManager, out var absoluteDockerfilePath); // Docker execution directory has its own typehint, which sets the value here var dockerExecutionDirectory = recommendation.DeploymentBundle.DockerExecutionDirectory; // We're only checking the interaction here against a user-specified file and execution directory, // it's still possible that we generate a dockerfile and/or compute the execution directory later. if (absoluteDockerfilePath == string.Empty || dockerExecutionDirectory == string.Empty) { return ValidationResult.ValidAsync(); } // Convert both to absolute paths in case they were specified relative to the project directory var projectPath = recommendation.GetProjectDirectory(); var absoluteDockerExecutionDirectory = Path.IsPathRooted(dockerExecutionDirectory) ? dockerExecutionDirectory : _directoryManager.GetAbsolutePath(projectPath, dockerExecutionDirectory); if (!_directoryManager.ExistsInsideDirectory(absoluteDockerExecutionDirectory, absoluteDockerfilePath)) { return ValidationResult.FailedAsync($"The specified Dockerfile \"{absoluteDockerfilePath}\" is not located within " + $"the specified Docker execution directory \"{dockerExecutionDirectory}\""); } return ValidationResult.ValidAsync(); } } }
59
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.Linq; using System.Threading.Tasks; namespace AWS.Deploy.Common.Recipes.Validation { /// <summary> /// Enforces Fargate cpu and memory conditional requirements: /// <para/> CPU value Memory value (MiB) /// <para/> 256 (.25 vCPU) 512 (0.5 GB), 1024 (1 GB), 2048 (2 GB) /// <para/> 512 (.5 vCPU) 1024 (1 GB), 2048 (2 GB), 3072 (3 GB), 4096 (4 GB) /// <para/> 1024 (1 vCPU) 2048 (2 GB), 3072 (3 GB), 4096 (4 GB), 5120 (5 GB), 6144 (6 GB), 7168 (7 GB), 8192 (8 GB) /// <para/> 2048 (2 vCPU) Between 4096 (4 GB) and 16384 (16 GB) in increments of 1024 (1 GB) /// <para/> 4096 (4 vCPU) Between 8192 (8 GB) and 30720 (30 GB) in increments of 1024 (1 GB) /// <para /> /// See https://docs.aws.amazon.com/AmazonECS/latest/userguide/task_definition_parameters.html#task_size /// for more details. /// </summary> public class FargateTaskCpuMemorySizeValidator : IRecipeValidator { private readonly IOptionSettingHandler _optionSettingHandler; public FargateTaskCpuMemorySizeValidator(IOptionSettingHandler optionSettingHandler) { _optionSettingHandler = optionSettingHandler; } private readonly Dictionary<string, string[]> _cpuMemoryMap = new() { { "256", new[] { "512", "1024", "2048" } }, { "512", new[] { "1024", "2048", "3072", "4096" } }, { "1024", new[] { "2048", "3072", "4096", "5120", "6144", "7168", "8192" } }, { "2048", BuildMemoryArray(4096, 16384).ToArray() }, { "4096", BuildMemoryArray(8192, 30720).ToArray()} }; private static IEnumerable<string> BuildMemoryArray(int start, int end, int increment = 1024) { while (start <= end) { yield return start.ToString(); start += increment; } } public string CpuOptionSettingsId { get; set; } = "TaskCpu"; public string MemoryOptionSettingsId { get; set; } = "TaskMemory"; /// <summary> /// Supports replacement tokens {{cpu}}, {{memory}}, and {{memoryList}} /// </summary> public string ValidationFailedMessage { get; set; } = "Cpu value {{cpu}} is not compatible with memory value {{memory}}. Allowed values are {{memoryList}}"; public string? InvalidCpuValueValidationFailedMessage { get; set; } /// <inheritdoc cref="FargateTaskCpuMemorySizeValidator"/> public Task<ValidationResult> Validate(Recommendation recommendation, IDeployToolValidationContext deployValidationContext) { string? cpu; string? memory; try { cpu = _optionSettingHandler.GetOptionSettingValue<string>(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, CpuOptionSettingsId)); memory = _optionSettingHandler.GetOptionSettingValue<string>(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, MemoryOptionSettingsId)); } catch (OptionSettingItemDoesNotExistException) { return Task.FromResult<ValidationResult>(ValidationResult.Failed("Could not find a valid value for Task CPU or Task Memory " + "as part of of the ECS Fargate deployment configuration. Please provide a valid value and try again.")); } if (cpu == null) return ValidationResult.FailedAsync("Task CPU is null."); if (memory == null) return ValidationResult.FailedAsync("Task Memory is null."); if (!_cpuMemoryMap.ContainsKey(cpu)) { // this could happen, but shouldn't. // either there is mismatch between _cpuMemoryMap and the AllowedValues // or the UX flow calling in here doesn't enforce AllowedValues. var message = InvalidCpuValueValidationFailedMessage?.Replace("{{cpu}}", cpu); return Task.FromResult<ValidationResult>(ValidationResult.Failed(message?? "Cpu validation failed")); } var validMemoryValues = _cpuMemoryMap[cpu]; if (validMemoryValues.Contains(memory)) { return Task.FromResult<ValidationResult>(ValidationResult.Valid()); } var failed = ValidationFailedMessage .Replace("{{cpu}}", cpu) .Replace("{{memory}}", memory) .Replace("{{memoryList}}", string.Join(", ", validMemoryValues)); return Task.FromResult<ValidationResult>(ValidationResult.Failed(failed)); } } }
112
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.Common.TypeHintData { /// <summary> /// Holds additional data for <see cref="OptionSettingTypeHint.DynamoDBTableName"/> processing. /// </summary> public class DynamoDBTableTypeHintData { /// <summary> /// Determines whether to allow no value or not. /// </summary> public bool AllowNoValue { get; set; } public DynamoDBTableTypeHintData(bool allowNoValue) { AllowNoValue = allowNoValue; } } }
24
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.TypeHintData { /// <summary> /// Additional typehint data for file options /// </summary> public class FilePathTypeHintData { /// <summary> /// Corresponds to a Filter property for a System.Windows.Forms.FileDialog /// to determine the choices that would appear in the dialog box if a wrapping tool prompted the user for a file path via a UI. public string Filter { get; set; } = "All files (*.*)|*.*"; /// <summary> /// Corresponds to the DefaultExt property for a System.Windows.Forms.FileDialog /// to specify the default extension used if the user specifies a file name /// without an extension. /// </summary> public string DefaultExtension { get; set; } = ""; /// <summary> /// Corresponds to the Title property for a System.Windows.Forms.FileDialog /// to specify the title of the file dialog box. /// </summary> public string Title { get; set; } = "Open"; /// <summary> /// Corresponds to the CheckFileExists property for a System.Windows.Forms.FileDialog /// to indicate whether the dialog box should display a warning if the user specifies a file that does not exist. /// </summary> public bool CheckFileExists { get; set; } = true; /// <summary> /// Corresponds to the the AllowEmpty parameter for ConsoleUtilities.AskUserForValue /// This lets a recipe option that uses the FilePathCommand typehint /// control whether an empty value is allowed during CLI mode /// </summary> public bool AllowEmpty { get; set; } = true; } }
43
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.Common.TypeHintData { /// <summary> /// Holds additional data for <see cref="OptionSettingTypeHint.IAMRole"/> processing. /// </summary> public class IAMRoleTypeHintData { /// <summary> /// ServicePrincipal to filter IAM roles. /// </summary> public string ServicePrincipal { get; set; } public IAMRoleTypeHintData(string servicePrincipal) { ServicePrincipal = servicePrincipal; } } }
24
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.Common.TypeHintData { /// <summary> /// Holds additional data for <see cref="OptionSettingTypeHint.S3BucketName"/> processing. /// </summary> public class S3BucketNameTypeHintData { /// <summary> /// Determines whether to allow no value or not. /// </summary> public bool AllowNoValue { get; set; } public S3BucketNameTypeHintData(bool allowNoValue) { AllowNoValue = allowNoValue; } } }
24
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.Common.TypeHintData { /// <summary> /// Holds additional data for <see cref="OptionSettingTypeHint.SNSTopicArn"/> processing. /// </summary> public class SNSTopicArnsTypeHintData { /// <summary> /// Determines whether to allow no value or not. /// </summary> public bool AllowNoValue { get; set; } public SNSTopicArnsTypeHintData(bool allowNoValue) { AllowNoValue = allowNoValue; } } }
24
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.Common.TypeHintData { /// <summary> /// Holds additional data for <see cref="OptionSettingTypeHint.SQSQueueUrl"/> processing. /// </summary> public class SQSQueueUrlTypeHintData { /// <summary> /// Determines whether to allow no value or not. /// </summary> public bool AllowNoValue { get; set; } public SQSQueueUrlTypeHintData(bool allowNoValue) { AllowNoValue = allowNoValue; } } }
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.Common.TypeHintData { /// <summary> /// Represents a single AWS resource, generally used when selecting from /// a list of existing resources to set an OptionSettingItem /// </summary> public class TypeHintResource { /// <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 <see cref="TypeHintResourceTable.Columns"/> /// </summary> public List<string> ColumnValues { get; set; } = new List<string>(); public TypeHintResource(string systemName, string displayName) { SystemName = systemName; DisplayName = displayName; } } }
38
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.TypeHintData { /// <summary> /// Represents the column for a list/grid of <see cref="TypeHintResource"/> 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. // SPDX-License-Identifier: Apache-2.0 using System.Collections.Generic; namespace AWS.Deploy.Common.TypeHintData { /// <summary> /// Represents a list or table of existing AWS resources to allow selecting from /// a list of existing resources when setting an OptionSettingItem /// </summary> public class TypeHintResourceTable { /// <summary> /// Columns that should appear above the list of resources when presenting the /// user a table or grid to select from /// </summary> /// <remarks>If this is null or empty, it implies that there is only a single column</remarks> public List<TypeHintResourceColumn>? Columns { get; set; } /// <summary> /// List of AWS resources that the user could select from /// </summary> public List<TypeHintResource> Rows { get; set; } = new List<TypeHintResource>(); } }
27
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 AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.Common.Utilities { /// <summary> /// Utility methods for working with a recommendation's Docker configuration /// </summary> public static class DockerUtilities { /// <summary> /// Gets the path of a Dockerfile if it exists at the default location: "{ProjectPath}/Dockerfile" /// </summary> /// <param name="recommendation">The selected recommendation settings used for deployment</param> /// <param name="fileManager">File manager, used for validating that the Dockerfile exists</param> /// <param name="dockerfilePath">Path to the Dockerfile, relative to the recommendation's project directory</param> /// <returns>True if the Dockerfile exists at the default location, false otherwise</returns> public static bool TryGetDefaultDockerfile(Recommendation recommendation, IFileManager? fileManager, out string dockerfilePath) { if (fileManager == null) { fileManager = new FileManager(); } if (fileManager.Exists(Constants.Docker.DefaultDockerfileName, recommendation.GetProjectDirectory())) { // Set the default value to the OS-specific ".\Dockerfile" dockerfilePath = Path.Combine(".", Constants.Docker.DefaultDockerfileName); return true; } else { dockerfilePath = string.Empty; return false; } } /// <summary> /// Gets the path of a the project's Dockerfile if it exists, from either a user-specified or the default location /// </summary> /// <param name="recommendation">The selected recommendation settings used for deployment</param> /// <param name="fileManager">File manager, used for validating that the Dockerfile exists</param> /// <param name="dockerfilePath">Path to a Dockerfile,which may be absolute or relative</param> /// <returns>True if a Dockerfile is specified for this deployment, false otherwise</returns> public static bool TryGetDockerfile(Recommendation recommendation, IFileManager fileManager, out string dockerfilePath) { dockerfilePath = recommendation.DeploymentBundle.DockerfilePath; if (!string.IsNullOrEmpty(dockerfilePath)) { // Double-check that it still exists in case it was move/deleted after being specified. if (fileManager.Exists(dockerfilePath, recommendation.GetProjectDirectory())) { return true; } else { throw new InvalidFilePath(DeployToolErrorCode.InvalidFilePath, $"A dockerfile was specified at {dockerfilePath} but does not exist."); } } else { // Check the default location again, for the case where a file was NOT specified // in the option but we generated one in the default location right before calling docker build. var defaultExists = TryGetDefaultDockerfile(recommendation, fileManager, out dockerfilePath); return defaultExists; } } /// <summary> /// Gets the path of a the project's Dockerfile if it exists, from either a user-specified or the default location /// </summary> /// <param name="recommendation">The selected recommendation settings used for deployment</param> /// <param name="fileManager">File manager, used for validating that the Dockerfile exists</param> /// <param name="absoluteDockerfilePath">Absolute path to the Dockerfile</param> /// <returns>True if a Dockerfile is specified for this deployment, false otherwise</returns> public static bool TryGetAbsoluteDockerfile(Recommendation recommendation, IFileManager fileManager, IDirectoryManager directoryManager, out string absoluteDockerfilePath) { var dockerfileExists = TryGetDockerfile(recommendation, fileManager, out var dockerfilePath); if (dockerfileExists) { absoluteDockerfilePath = Path.IsPathRooted(dockerfilePath) ? dockerfilePath : directoryManager.GetAbsolutePath(recommendation.GetProjectDirectory(), dockerfilePath); } else { absoluteDockerfilePath = string.Empty; } return dockerfileExists; } } }
100
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; namespace AWS.Deploy.Common.Utilities { public class PathUtilities { public static bool IsPathValid(string path) { path = path.Trim(); if (string.IsNullOrEmpty(path)) return false; if (path.StartsWith(@"\\")) return false; if (path.Contains("&")) return false; if (Path.GetInvalidPathChars().Any(x => path.Contains(x))) return false; return true; } } }
31
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; namespace AWS.Deploy.Constants { internal static class CDK { /// <summary> /// Default version of CDK CLI /// </summary> public static readonly Version DefaultCDKVersion = Version.Parse("2.13.0"); /// <summary> /// The name of the CDK bootstrap CloudFormation stack /// </summary> public const string CDKBootstrapStackName = "CDKToolkit"; } }
22
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.Constants { internal static class CLI { // Represents the default STS AWS region that is used for the purposes of // retrieving the caller identity and determining if a user is in an opt-in region. public const string DEFAULT_STS_AWS_REGION = "us-east-1"; // labels public const string CREATE_NEW_LABEL = "*** Create new ***"; public const string DEFAULT_LABEL = "*** Default ***"; public const string EMPTY_LABEL = "*** Empty ***"; public const string CREATE_NEW_APPLICATION_LABEL = "*** Deploy to a new Cloud Application ***"; // input prompts public const string PROMPT_NEW_STACK_NAME = "Enter the name of the new CloudFormationStack stack"; public const string PROMPT_ECR_REPOSITORY_NAME = "Enter the name of the ECR repository"; public const string PROMPT_CHOOSE_DEPLOYMENT_TARGET = "Choose deployment target"; public const string CLI_APP_NAME = "AWS .NET Deployment Tool"; public const string WORKSPACE_ENV_VARIABLE = "AWS_DOTNET_DEPLOYTOOL_WORKSPACE"; } }
28
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.Constants { internal static class CloudFormationIdentifier { /// <summary> /// The CDK context parameter name used to pass in the location of the AWS .NET deployment tool's settings file. /// </summary> public const string SETTINGS_PATH_CDK_CONTEXT_PARAMETER = "aws-deploy-tool-setting"; /// <summary> /// The name of the identifier tag applied to CloudFormation stacks deployed by the AWS .NET deployment tool. The value of the /// tag is the recipe id used by the AWS .NET deployment tool. /// </summary> public const string STACK_TAG = "aws-dotnet-deploy"; /// <summary> /// AWS .NET deployment tool CloudFormation stacks will prefix the description with this value to help identify stacks that are created by the AWS .NET deployment tool. /// </summary> public const string STACK_DESCRIPTION_PREFIX = "AWSDotnetDeployCDKStack"; /// <summary> /// The CloudFormation template metadata key used to hold the last used recipe option settings to deploy the application. /// </summary> public const string STACK_METADATA_SETTINGS = "aws-dotnet-deploy-settings"; /// <summary> /// The CloudFormation template metadata key used to hold the last used deployment bundle settings to deploy the application. /// </summary> public const string STACK_METADATA_DEPLOYMENT_BUNDLE_SETTINGS = "aws-dotnet-deploy-deployment-bundle-settings"; /// <summary> /// The CloudFormation template metadata key for storing the id of the AWS .NET deployment tool recipe. /// </summary> public const string STACK_METADATA_RECIPE_ID = "aws-dotnet-deploy-recipe-id"; /// <summary> /// The CloudFormation template metadata key for storing the version of the AWS .NET deployment tool recipe. /// </summary> public const string STACK_METADATA_RECIPE_VERSION = "aws-dotnet-deploy-recipe-version"; } }
46
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Constants { internal class Docker { /// <summary> /// Name of the default Dockerfile that the deployment tool attempts to detect in the project directory /// </summary> public static readonly string DefaultDockerfileName = "Dockerfile"; /// <summary> /// Id for the Docker Execution Directory recipe option /// </summary> public const string DockerExecutionDirectoryOptionId = "DockerExecutionDirectory"; /// <summary> /// Id for the Dockerfile Path recipe option /// </summary> public const string DockerfileOptionId = "DockerfilePath"; /// <summary> /// Id for the Docker Build Args recipe option /// </summary> public const string DockerBuildArgsOptionId = "DockerBuildArgs"; /// <summary> /// Id for the ECR Repository Name recipe option /// </summary> public const string ECRRepositoryNameOptionId = "ECRRepositoryName"; /// <summary> /// Id for the Docker Image Tag recipe option /// </summary> public const string ImageTagOptionId = "ImageTag"; } }
39
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.Constants { internal static class EC2 { public const string FILTER_PLATFORM_WINDOWS = "windows"; public const string FILTER_PLATFORM_LINUX = "linux"; public const string FILTER_ARCHITECTURE_X86_64 = "x86_64"; public const string FILTER_ARCHITECTURE_ARM64 = "arm64"; } }
16
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.Constants { internal static class ElasticBeanstalk { public const string EnhancedHealthReportingOptionId = "EnhancedHealthReporting"; public const string EnhancedHealthReportingOptionNameSpace = "aws:elasticbeanstalk:healthreporting:system"; public const string EnhancedHealthReportingOptionName = "SystemType"; public const string XRayTracingOptionId = "XRayTracingSupportEnabled"; public const string XRayTracingOptionNameSpace = "aws:elasticbeanstalk:xray"; public const string XRayTracingOptionName = "XRayEnabled"; public const string ProxyOptionId = "ReverseProxy"; public const string ProxyOptionNameSpace = "aws:elasticbeanstalk:environment:proxy"; public const string ProxyOptionName = "ProxyServer"; public const string HealthCheckURLOptionId = "HealthCheckURL"; public const string HealthCheckURLOptionNameSpace = "aws:elasticbeanstalk:application"; public const string HealthCheckURLOptionName = "Application Healthcheck URL"; public const string LinuxPlatformType = ".NET Core"; public const string WindowsPlatformType = "Windows Server"; public const string IISAppPathOptionId = "IISAppPath"; public const string IISWebSiteOptionId = "IISWebSite"; public const string WindowsManifestName = "aws-windows-deployment-manifest.json"; /// <summary> /// This list stores a named tuple of OptionSettingId, OptionSettingNameSpace and OptionSettingName. /// <para>OptionSettingId refers to the Id property for an option setting item in the recipe file.</para> /// <para>OptionSettingNameSpace and OptionSettingName provide a way to configure the environments metadata and update its behaviour.</para> /// <para>A comprehensive list of all configurable settings can be found <see href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/beanstalk-environment-configuration-advanced.html">here</see></para> /// </summary> public static List<(string OptionSettingId, string OptionSettingNameSpace, string OptionSettingName)> OptionSettingQueryList = new() { new (EnhancedHealthReportingOptionId, EnhancedHealthReportingOptionNameSpace, EnhancedHealthReportingOptionName), new (XRayTracingOptionId, XRayTracingOptionNameSpace, XRayTracingOptionName), new (ProxyOptionId, ProxyOptionNameSpace, ProxyOptionName), new (HealthCheckURLOptionId, HealthCheckURLOptionNameSpace, HealthCheckURLOptionName) }; /// <summary> /// This is the list of option settings available for Windows Beanstalk deployments. /// This list stores a named tuple of OptionSettingId, OptionSettingNameSpace and OptionSettingName. /// <para>OptionSettingId refers to the Id property for an option setting item in the recipe file.</para> /// <para>OptionSettingNameSpace and OptionSettingName provide a way to configure the environments metadata and update its behaviour.</para> /// <para>A comprehensive list of all configurable settings can be found <see href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/beanstalk-environment-configuration-advanced.html">here</see></para> /// </summary> public static List<(string OptionSettingId, string OptionSettingNameSpace, string OptionSettingName)> WindowsOptionSettingQueryList = new() { new (EnhancedHealthReportingOptionId, EnhancedHealthReportingOptionNameSpace, EnhancedHealthReportingOptionName), new (XRayTracingOptionId, XRayTracingOptionNameSpace, XRayTracingOptionName), new (HealthCheckURLOptionId, HealthCheckURLOptionNameSpace, HealthCheckURLOptionName) }; } }
62
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.Constants { internal static class RecipeIdentifier { // Recipe IDs public const string EXISTING_BEANSTALK_ENVIRONMENT_RECIPE_ID = "AspNetAppExistingBeanstalkEnvironment"; public const string EXISTING_BEANSTALK_WINDOWS_ENVIRONMENT_RECIPE_ID = "AspNetAppExistingBeanstalkWindowsEnvironment"; public const string PUSH_TO_ECR_RECIPE_ID = "PushContainerImageEcr"; // Replacement Tokens public const string REPLACE_TOKEN_STACK_NAME = "{StackName}"; public const string REPLACE_TOKEN_LATEST_DOTNET_BEANSTALK_PLATFORM_ARN = "{LatestDotnetBeanstalkPlatformArn}"; public const string REPLACE_TOKEN_LATEST_DOTNET_WINDOWS_BEANSTALK_PLATFORM_ARN = "{LatestDotnetWindowsBeanstalkPlatformArn}"; public const string REPLACE_TOKEN_ECR_REPOSITORY_NAME = "{DefaultECRRepositoryName}"; public const string REPLACE_TOKEN_ECR_IMAGE_TAG = "{DefaultECRImageTag}"; public const string REPLACE_TOKEN_DOCKERFILE_PATH = "{DockerfilePath}"; public const string REPLACE_TOKEN_DEFAULT_VPC_ID = "{DefaultVpcId}"; public const string REPLACE_TOKEN_HAS_DEFAULT_VPC = "{HasDefaultVpc}"; public const string REPLACE_TOKEN_HAS_NOT_VPCS = "{HasNotVpcs}"; /// <summary> /// Id for the 'dotnet publish --configuration' recipe option /// </summary> public const string DotnetPublishConfigurationOptionId = "DotnetBuildConfiguration"; /// <summary> /// Id for the additional args for 'dotnet publish' recipe option /// </summary> public const string DotnetPublishArgsOptionId = "DotnetPublishArgs"; /// <summary> /// Id for the 'dotnet build --self-contained' recipe option /// </summary> public const string DotnetPublishSelfContainedBuildOptionId = "SelfContainedBuild"; public const string TARGET_SERVICE_ELASTIC_BEANSTALK = "AWS Elastic Beanstalk"; } }
43
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.Linq; using System.Threading.Tasks; using AWS.Deploy.DocGenerator.Generators; using Microsoft.Extensions.DependencyInjection; namespace AWS.Deploy.DocGenerator { public class App { private readonly IServiceProvider _serviceProvider; public App(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public async Task Run(string[] args) { var generatorTypes = System.Reflection.Assembly.GetExecutingAssembly() .GetTypes() .Where(type => typeof(IDocGenerator).IsAssignableFrom(type) && !type.IsInterface); foreach (var generatorType in generatorTypes) { var instance = (IDocGenerator) ActivatorUtilities.CreateInstance(_serviceProvider, generatorType); await instance.Generate(); } } } }
35
aws-dotnet-deploy
aws
C#
using System; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using AWS.Deploy.CLI.Extensions; using AWS.Deploy.DocGenerator.Utilities; using AWS.Deploy.CLI; using System.Threading; using AWS.Deploy.ServerMode.Client; using AWS.Deploy.CLI.Commands; using AWS.Deploy.ServerMode.Client.Utilities; namespace AWS.Deploy.DocGenerator { public class Program { public static async Task Main(string[] args) { var serviceCollection = new ServiceCollection(); serviceCollection.AddCustomServices(); serviceCollection.AddGeneratorServices(); serviceCollection.AddSingleton<IRestAPIClient, RestAPIClient>(serviceProvider => { var interactiveService = serviceProvider.GetRequiredService<IToolInteractiveService>(); var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(ServerModeUtilities.ResolveDefaultCredentials); var serverCommand = new ServerModeCommand(interactiveService, 4152, null, true); _ = serverCommand.ExecuteAsync(new CancellationTokenSource().Token); var baseUrl = $"http://localhost:{4152}/"; var client = new RestAPIClient(baseUrl, httpClient); client.WaitUntilServerModeReady().GetAwaiter().GetResult(); return client; }); var serviceProvider = serviceCollection.BuildServiceProvider(); // calls the Run method in App, which is replacing Main var app = serviceProvider.GetService<App>(); if (app == null) { throw new Exception("App dependencies aren't injected correctly." + " Verify DocGeneratorExtensions has all the required dependencies to instantiate App."); } await app.Run(args); } } }
54
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.Linq; using System.Text; using System.Threading.Tasks; using AWS.Deploy.Common.IO; using AWS.Deploy.DocGenerator.Utilities; using AWS.Deploy.ServerMode.Client; namespace AWS.Deploy.DocGenerator.Generators { /// <summary> /// Creates documentation for the deployment settings file that can be used as part of a CI/CD pipeline. /// </summary> public class DeploymentSettingsFileGenerator : IDocGenerator { private readonly IRestAPIClient _restAPIClient; private readonly IFileManager _fileManager; public DeploymentSettingsFileGenerator(IRestAPIClient restAPIClient, IFileManager fileManager) { _restAPIClient = restAPIClient; _fileManager = fileManager; } /// <summary> /// Creates markdown files per recipe that lists all the option settings that can be used in the deployment settings file. /// </summary> public async Task Generate() { var recipes = await _restAPIClient.ListAllRecipesAsync(null); foreach (var recipeSummary in recipes.Recipes) { var stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"**Recipe ID:** {recipeSummary.Id}"); stringBuilder.AppendLine(); stringBuilder.AppendLine($"**Recipe Description:** {recipeSummary.Description}"); stringBuilder.AppendLine(); stringBuilder.AppendLine("**Settings:**"); stringBuilder.AppendLine(); var optionSettings = await _restAPIClient.GetRecipeOptionSettingsAsync(recipeSummary.Id, null); GenerateChildSettings(stringBuilder, 0, optionSettings); var fullPath = DocGeneratorExtensions.DetermineDocsPath($"content/docs/cicd/recipes/{recipeSummary.Name}.md"); await _fileManager.WriteAllTextAsync(fullPath, stringBuilder.ToString()); } } private void GenerateChildSettings(StringBuilder stringBuilder, int level, ICollection<RecipeOptionSettingSummary> settings) { var titlePadding = new string(' ', level * 4); var detailsPadding = new string(' ', (level + 1) * 4); foreach (var setting in settings) { stringBuilder.AppendLine($"{titlePadding}* **{setting.Name}**"); stringBuilder.AppendLine($"{detailsPadding}* ID: {setting.Id}"); stringBuilder.AppendLine($"{detailsPadding}* Description: {setting.Description}"); stringBuilder.AppendLine($"{detailsPadding}* Type: {setting.Type}"); if (setting.Settings.Any()) { stringBuilder.AppendLine($"{detailsPadding}* Settings:"); GenerateChildSettings(stringBuilder, level + 2, setting.Settings); } } } } }
75
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; namespace AWS.Deploy.DocGenerator.Generators { /// <summary> /// Interface for documentation generators such as <see cref="DeploymentSettingsFileGenerator"/> /// </summary> public interface IDocGenerator { /// <summary> /// Generates documentation content into the documentation folder of the repository. /// </summary> public Task Generate(); } }
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 Microsoft.Extensions.DependencyInjection; using AWS.Deploy.DocGenerator.Generators; using System.IO; namespace AWS.Deploy.DocGenerator.Utilities { public static class DocGeneratorExtensions { /// <summary> /// Extension method for <see cref="IServiceCollection"/> that injects essential app dependencies. /// </summary> /// <param name="serviceCollection"><see cref="IServiceCollection"/> instance that holds the app dependencies.</param> /// <param name="lifetime"></param> public static void AddGeneratorServices(this IServiceCollection serviceCollection, ServiceLifetime lifetime = ServiceLifetime.Singleton) { serviceCollection.AddSingleton<DeploymentSettingsFileGenerator>(); // required to run the application serviceCollection.AddSingleton<App>(); } /// <summary> /// Locates the documentation folder in the current repository. /// </summary> /// <param name="subdirectory">A sub-directory to add to the documentation path</param> /// <returns>The path to a specific folder in the documentation folder of the repository.</returns> public static string DetermineDocsPath(string subdirectory) { var dir = new DirectoryInfo(Directory.GetCurrentDirectory()); while (!string.Equals(dir?.Name, "src") && !string.Equals(dir?.Name, "test")) { if (dir == null) break; dir = dir.Parent; } if (dir == null || dir.Parent == null) throw new Exception("Could not determine file path of current directory."); return Path.Combine(dir.Parent.FullName, "site", subdirectory); } } }
50
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; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Utilities; using Newtonsoft.Json; namespace AWS.Deploy.DockerEngine { public interface IDockerEngine { /// <summary> /// Generates a docker file /// </summary> void GenerateDockerFile(); /// <summary> /// Inspects the Dockerfile associated with the recommendation /// and determines the appropriate Docker Execution Directory, /// if one is not set. /// </summary> void DetermineDockerExecutionDirectory(Recommendation recommendation); } /// <summary> /// Orchestrates the moving parts involved in creating a dockerfile for a project /// </summary> public class DockerEngine : IDockerEngine { private readonly ProjectDefinition _project; private readonly IFileManager _fileManager; private readonly IDirectoryManager _directoryManager; private readonly string _projectPath; public DockerEngine(ProjectDefinition project, IFileManager fileManager, IDirectoryManager directoryManager) { if (project == null) { throw new ArgumentNullException(nameof(project), "Cannot instantiate DockerEngine due to a null ProjectDefinition"); } _project = project; _projectPath = project.ProjectPath; _fileManager = fileManager; _directoryManager = directoryManager; } /// <summary> /// Generates a docker file /// </summary> public void GenerateDockerFile() { var projectFileName = Path.GetFileName(_projectPath); var imageMapping = GetImageMapping(); if (imageMapping == null) { throw new UnknownDockerImageException(DeployToolErrorCode.NoValidDockerImageForProject, $"Unable to determine a valid docker base and build image for project of type {_project.SdkType} and Target Framework {_project.TargetFramework}"); } var dockerFile = new DockerFile(imageMapping, projectFileName, _project.AssemblyName); var projectDirectory = Path.GetDirectoryName(_projectPath) ?? ""; var projectList = GetProjectList(); dockerFile.WriteDockerFile(projectDirectory, projectList); } /// <summary> /// Retrieves a list of projects from a solution file /// </summary> private List<string>? GetProjectsFromSolutionFile(string solutionFile) { var projectFileName = Path.GetFileName(_projectPath); if (string.IsNullOrWhiteSpace(solutionFile) || string.IsNullOrWhiteSpace(projectFileName)) { return null; } List<string> lines = File.ReadAllLines(solutionFile).ToList(); var projectLines = lines.Where(x => x.StartsWith("Project")); var projectPaths = projectLines .Select(x => x.Split(',')[1].Replace('\"', ' ').Trim()) .Where(x => x.EndsWith(".csproj") || x.EndsWith(".fsproj")) .Select(x => x.Replace('\\', Path.DirectorySeparatorChar)) .ToList(); //Validate project exists in solution if (projectPaths.Select(x => Path.GetFileName(x)).Where(x => x.Equals(projectFileName)).ToList().Count == 0) { return null; } return projectPaths; } /// <summary> /// Finds the project solution file (if one exists) and retrieves a list of projects that are part of one solution /// </summary> private List<string>? GetProjectList() { var solutionDirectory = Directory.GetParent(_projectPath); // Climb upward from the csproj until we find a directory with one or more slns while (solutionDirectory != null) { var allSolutionFiles = solutionDirectory.GetFiles("*.sln"); if (allSolutionFiles.Length > 0) { foreach (var solutionFile in allSolutionFiles) { var projectList = GetProjectsFromSolutionFile(solutionFile.FullName); if (projectList != null) { // Validate that all referenced projects are at or below the solution, otherwise we'd have to use // a wider Docker execution directory that is potentially sending more than the project to the Docker daemon foreach (var project in projectList) { var absoluteProjectPath = _directoryManager.GetAbsolutePath(solutionDirectory.FullName, project); if (!_directoryManager.ExistsInsideDirectory(solutionDirectory.FullName, absoluteProjectPath)) { throw new DockerEngineException(DeployToolErrorCode.FailedToGenerateDockerFile, "Unable to generate a Dockerfile for this project becuase project reference(s) were detected above the solution (.sln) file. " + "Consider crafting your own Dockerfile or deploying to an AWS compute service that does not use Docker."); } } return projectList; } } } solutionDirectory = solutionDirectory.Parent; } return null; } /// <summary> /// Gets image mapping specific to this project /// </summary> private ImageMapping GetImageMapping() { var content = ProjectUtilities.ReadDockerFileConfig(); var definitions = JsonConvert.DeserializeObject<List<ImageDefinition>>(content); var sdkType = _project.SdkType; // For the Microsoft.NET.Sdk.Workersdk type we want to use the same container as Microsoft.NET.Sdk since a project // using Microsoft.NET.Sdk.Worker is still just a regular console application. if (string.Equals(sdkType, "Microsoft.NET.Sdk.Worker", StringComparison.OrdinalIgnoreCase)) { sdkType = "Microsoft.NET.Sdk"; } var mappings = definitions?.FirstOrDefault(x => x.SdkType.Equals(sdkType)); if (mappings == null) throw new UnsupportedProjectException(DeployToolErrorCode.NoValidDockerMappingForSdkType, $"The project with SDK Type {_project.SdkType} is not supported."); return mappings.ImageMapping.FirstOrDefault(x => x.TargetFramework.Equals(_project.TargetFramework)) ?? throw new UnsupportedProjectException(DeployToolErrorCode.NoValidDockerMappingForTargetFramework, $"The project with Target Framework {_project.TargetFramework} is not supported."); } /// <summary> /// Inspects the Dockerfile associated with the recommendation /// and determines the appropriate Docker Execution Directory, /// if one is not set. /// </summary> /// <param name="recommendation"></param> public void DetermineDockerExecutionDirectory(Recommendation recommendation) { if (string.IsNullOrEmpty(recommendation.DeploymentBundle.DockerExecutionDirectory)) { var projectFilename = Path.GetFileName(recommendation.ProjectPath); if (DockerUtilities.TryGetAbsoluteDockerfile(recommendation, _fileManager, _directoryManager, out var dockerFilePath)) { using (var stream = File.OpenRead(dockerFilePath)) using (var reader = new StreamReader(stream)) { string? line; while ((line = reader.ReadLine()) != null) { var noSpaceLine = line.Replace(" ", ""); if (noSpaceLine.StartsWith("COPY") && (noSpaceLine.EndsWith(".sln./") || (projectFilename != null && noSpaceLine.Contains("/" + projectFilename)))) { recommendation.DeploymentBundle.DockerExecutionDirectory = Path.GetDirectoryName(recommendation.ProjectDefinition.ProjectSolutionPath) ?? ""; } } } } } } } }
202
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; namespace AWS.Deploy.DockerEngine { /// <summary> /// Encapsulates a DockerFile object /// </summary> public class DockerFile { private const string DockerFileName = "Dockerfile"; private readonly ImageMapping _imageMapping; private readonly string _projectName; private readonly string _assemblyName; public DockerFile(ImageMapping imageMapping, string projectName, string? assemblyName) { if (imageMapping == null) { throw new ArgumentNullException(nameof(imageMapping), "Cannot instantiate a DockerFile with a null ImageMapping."); } if (string.IsNullOrWhiteSpace(projectName)) { throw new ArgumentNullException(nameof(projectName), "Cannot instantiate a DockerFile with an empty Project Name."); } if (string.IsNullOrWhiteSpace(assemblyName)) { throw new ArgumentNullException(nameof(assemblyName), "Cannot instantiate a DockerFile with an empty AssemblyName."); } _imageMapping = imageMapping; _projectName = projectName; _assemblyName = assemblyName; } /// <summary> /// Writes a docker file based on project information /// </summary> public void WriteDockerFile(string projectDirectory, List<string>? projectList) { var dockerFileTemplate = ProjectUtilities.ReadTemplate(); var projects = ""; var projectPath = ""; var projectFolder = ""; if (projectList == null) { projects = $"COPY [\"{_projectName}\", \"\"]"; projectPath = _projectName; } else { projectList = projectList.Select(x => x.Replace("\\", "/")).ToList(); for (int i = 0; i < projectList.Count; i++) { projects += $"COPY [\"{projectList[i]}\", \"{projectList[i].Substring(0, projectList[i].LastIndexOf("/") + 1)}\"]" + (i < projectList.Count - 1 ? Environment.NewLine : ""); } projectPath = projectList.First(x => x.EndsWith(_projectName)); if (projectPath.LastIndexOf("/") > -1) { projectFolder = projectPath.Substring(0, projectPath.LastIndexOf("/")); } } var dockerFile = dockerFileTemplate .Replace("{docker-base-image}", _imageMapping.BaseImage) .Replace("{docker-build-image}", _imageMapping.BuildImage) .Replace("{project-path-list}", projects) .Replace("{project-path}", projectPath) .Replace("{project-folder}", projectFolder) .Replace("{project-name}", _projectName) .Replace("{assembly-name}", _assemblyName); // ProjectDefinitionParser will have transformed projectDirectory to an absolute path, // and DockerFileName is static so traversal should not be possible here. // nosemgrep: csharp.lang.security.filesystem.unsafe-path-combine.unsafe-path-combine File.WriteAllText(Path.Combine(projectDirectory, DockerFileName), dockerFile); } } }
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 AWS.Deploy.Common; namespace AWS.Deploy.DockerEngine { public class DockerFileTemplateException : DockerEngineExceptionBase { public DockerFileTemplateException(DeployToolErrorCode errorCode, string message) : base(errorCode, message) { } } public class DockerEngineException : DockerEngineExceptionBase { public DockerEngineException(DeployToolErrorCode errorCode, string message) : base(errorCode, message) { } } public class UnknownDockerImageException : DockerEngineExceptionBase { public UnknownDockerImageException(DeployToolErrorCode errorCode, string message) : base(errorCode, message) { } } public class DockerEngineExceptionBase : DeployToolException { public DockerEngineExceptionBase(DeployToolErrorCode errorCode, string message) : base(errorCode, message) { } } public class UnsupportedProjectException : DockerEngineExceptionBase { public UnsupportedProjectException(DeployToolErrorCode errorCode, string message) : base(errorCode, message) { } } }
34
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.DockerEngine { public class ImageDefinition { public string SdkType { get; set; } public List<ImageMapping> ImageMapping { get; set; } public ImageDefinition(string sdkType, List<ImageMapping> imageMapping) { SdkType = sdkType; ImageMapping = imageMapping; } public override string ToString() { return $"Image Definition for {SdkType}"; } } public class ImageMapping { public string TargetFramework { get; set; } public string BaseImage { get; set; } public string BuildImage { get; set; } public ImageMapping(string targetFramework, string baseImage, string buildImage) { TargetFramework = targetFramework; BaseImage = baseImage; BuildImage = buildImage; } public override string ToString() { return $"Image Mapping for {TargetFramework}"; } } }
44
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.Reflection; using AWS.Deploy.Common; using AWS.Deploy.Common.Extensions; namespace AWS.Deploy.DockerEngine { public class ProjectUtilities { private const string DockerFileConfig = "AWS.Deploy.DockerEngine.Properties.DockerFileConfig.json"; private const string DockerfileTemplate = "AWS.Deploy.DockerEngine.Templates.Dockerfile.template"; /// <summary> /// Retrieves the Docker File Config /// </summary> internal static string ReadDockerFileConfig() { var template = Assembly.GetExecutingAssembly().ReadEmbeddedFile(DockerFileConfig); if (string.IsNullOrWhiteSpace(template)) { throw new DockerEngineException(DeployToolErrorCode.UnableToMapProjectToDockerImage, $"The DockerEngine could not find the embedded config file responsible for mapping projects to Docker images."); } return template; } /// <summary> /// Reads dockerfile template file /// </summary> internal static string ReadTemplate() { var template = Assembly.GetExecutingAssembly().ReadEmbeddedFile(DockerfileTemplate); if (string.IsNullOrWhiteSpace(template)) { throw new DockerFileTemplateException(DeployToolErrorCode.DockerFileTemplateNotFound, "The Dockerfile template for the project was not found."); } return template; } } }
47
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // In SDK-style projects such as this one, several assembly attributes that were historically // defined in this file are now automatically added during build and populated with // values defined in project properties. For details of which attributes are included // and how to customise this process see: https://aka.ms/assembly-info-properties // Setting ComVisible to false makes the types in this assembly not visible to COM // components. If you need to access a type in this assembly from COM, set the ComVisible // attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM. [assembly: Guid("d45912ca-430a-4c26-8a90-fb2a6f81dac7")] [assembly: InternalsVisibleTo("AWS.Deploy.CLI.UnitTests")]
23
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 AWS.Deploy.Common; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Recipes.CDK.Common; using Newtonsoft.Json; namespace AWS.Deploy.Orchestration { public interface ICdkAppSettingsSerializer { /// <summary> /// Creates the contents for the appsettings.json file inside the CDK project. This file is deserialized into <see cref="IRecipeProps{T}"/> to be used the by the CDK templates. /// </summary> string Build(CloudApplication cloudApplication, Recommendation recommendation, OrchestratorSession session); } public class CdkAppSettingsSerializer : ICdkAppSettingsSerializer { private readonly IOptionSettingHandler _optionSettingHandler; private readonly IDirectoryManager _directoryManager; public CdkAppSettingsSerializer(IOptionSettingHandler optionSettingHandler, IDirectoryManager directoryManager) { _optionSettingHandler = optionSettingHandler; _directoryManager = directoryManager; } public string Build(CloudApplication cloudApplication, Recommendation recommendation, OrchestratorSession session) { var projectPath = new FileInfo(recommendation.ProjectPath).Directory?.FullName; if (string.IsNullOrEmpty(projectPath)) throw new InvalidProjectPathException(DeployToolErrorCode.ProjectPathNotFound, "The project path provided is invalid."); // General Settings var appSettingsContainer = new RecipeProps<Dictionary<string, object>>( cloudApplication.Name, projectPath, recommendation.Recipe.Id, recommendation.Recipe.Version, session.AWSAccountId, session.AWSRegion, settings: _optionSettingHandler.GetOptionSettingsMap(recommendation, session.ProjectDefinition, _directoryManager, OptionSettingsType.Recipe) ) { // These deployment bundle settings need to be set separately because they are not configurable by the user. // These settings will not be part of the CloudFormation template metadata. // The only exception to this is the ECR Repository name. ECRRepositoryName = recommendation.DeploymentBundle.ECRRepositoryName ?? "", ECRImageTag = recommendation.DeploymentBundle.ECRImageTag ?? "", DotnetPublishZipPath = recommendation.DeploymentBundle.DotnetPublishZipPath ?? "", DotnetPublishOutputDirectory = recommendation.DeploymentBundle.DotnetPublishOutputDirectory ?? "" }; // Persist deployment bundle settings var deploymentBundleSettingsMap = _optionSettingHandler.GetOptionSettingsMap(recommendation, session.ProjectDefinition, _directoryManager, OptionSettingsType.DeploymentBundle); appSettingsContainer.DeploymentBundleSettings = JsonConvert.SerializeObject(deploymentBundleSettingsMap); return JsonConvert.SerializeObject(appSettingsContainer, Formatting.Indented); } } }
67
aws-dotnet-deploy
aws
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Amazon.CloudFormation; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.Extensions; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Orchestration.CDK; using AWS.Deploy.Orchestration.Data; using AWS.Deploy.Orchestration.Utilities; using Stack = Amazon.CloudFormation.Model.Stack; namespace AWS.Deploy.Orchestration { public interface ICdkProjectHandler { Task<string> ConfigureCdkProject(OrchestratorSession session, CloudApplication cloudApplication, Recommendation recommendation); string CreateCdkProject(Recommendation recommendation, OrchestratorSession session, string? saveDirectoryPath = null); Task DeployCdkProject(OrchestratorSession session, CloudApplication cloudApplication, string cdkProjectPath, Recommendation recommendation); void DeleteTemporaryCdkProject(string cdkProjectPath); Task<string> PerformCdkDiff(string cdkProjectPath, CloudApplication cloudApplication); } public class CdkProjectHandler : ICdkProjectHandler { private readonly IOrchestratorInteractiveService _interactiveService; private readonly ICommandLineWrapper _commandLineWrapper; private readonly ICdkAppSettingsSerializer _appSettingsBuilder; private readonly IDirectoryManager _directoryManager; private readonly IAWSResourceQueryer _awsResourceQueryer; private readonly IFileManager _fileManager; private readonly IDeployToolWorkspaceMetadata _workspaceMetadata; private readonly ICloudFormationTemplateReader _cloudFormationTemplateReader; public CdkProjectHandler( IOrchestratorInteractiveService interactiveService, ICommandLineWrapper commandLineWrapper, IAWSResourceQueryer awsResourceQueryer, ICdkAppSettingsSerializer cdkAppSettingsSerializer, IFileManager fileManager, IDirectoryManager directoryManager, IOptionSettingHandler optionSettingHandler, IDeployToolWorkspaceMetadata workspaceMetadata, ICloudFormationTemplateReader cloudFormationTemplateReader) { _interactiveService = interactiveService; _commandLineWrapper = commandLineWrapper; _awsResourceQueryer = awsResourceQueryer; _appSettingsBuilder = cdkAppSettingsSerializer; _directoryManager = directoryManager; _fileManager = fileManager; _workspaceMetadata = workspaceMetadata; _cloudFormationTemplateReader = cloudFormationTemplateReader; } public async Task<string> ConfigureCdkProject(OrchestratorSession session, CloudApplication cloudApplication, Recommendation recommendation) { string? cdkProjectPath; if (recommendation.Recipe.PersistedDeploymentProject) { if (string.IsNullOrEmpty(recommendation.Recipe.RecipePath)) throw new InvalidOperationException($"{nameof(recommendation.Recipe.RecipePath)} cannot be null"); // The CDK deployment project is already saved in the same directory. cdkProjectPath = _directoryManager.GetDirectoryInfo(recommendation.Recipe.RecipePath).Parent?.FullName; if (string.IsNullOrEmpty(cdkProjectPath)) throw new InvalidOperationException($"The CDK Project Path cannot be null."); } else { // Create a new temporary CDK project for a new deployment _interactiveService.LogInfoMessage("Generating AWS Cloud Development Kit (AWS CDK) deployment project"); cdkProjectPath = CreateCdkProject(recommendation, session); } // Write required configuration in appsettings.json var appSettingsBody = _appSettingsBuilder.Build(cloudApplication, recommendation, session); var appSettingsFilePath = Path.Combine(cdkProjectPath, "appsettings.json"); await using var appSettingsFile = new StreamWriter(appSettingsFilePath); await appSettingsFile.WriteAsync(appSettingsBody); return cdkProjectPath; } /// <summary> /// Run 'cdk diff' on the deployment project <param name="cdkProjectPath"/> to get the CF template that will be used by CDK to deploy the application. /// </summary> /// <returns>The CloudFormation template that is created for this deployment.</returns> public async Task<string> PerformCdkDiff(string cdkProjectPath, CloudApplication cloudApplication) { var appSettingsFilePath = Path.Combine(cdkProjectPath, "appsettings.json"); var cdkDiff = await _commandLineWrapper.TryRunWithResult($"npx cdk diff -c {Constants.CloudFormationIdentifier.SETTINGS_PATH_CDK_CONTEXT_PARAMETER}=\"{appSettingsFilePath}\"", workingDirectory: cdkProjectPath, needAwsCredentials: true); if (cdkDiff.ExitCode != 0) throw new FailedToRunCDKDiffException(DeployToolErrorCode.FailedToRunCDKDiff, "The CDK Diff command encountered an error and failed.", cdkDiff.ExitCode); var templateFilePath = Path.Combine(cdkProjectPath, "cdk.out", $"{cloudApplication.Name}.template.json"); return await _fileManager.ReadAllTextAsync(templateFilePath); } public async Task DeployCdkProject(OrchestratorSession session, CloudApplication cloudApplication, string cdkProjectPath, Recommendation recommendation) { var recipeInfo = $"{recommendation.Recipe.Id}_{recommendation.Recipe.Version}"; var environmentVariables = new Dictionary<string, string> { { EnvironmentVariableKeys.AWS_EXECUTION_ENV, recipeInfo } }; var appSettingsFilePath = Path.Combine(cdkProjectPath, "appsettings.json"); if (await DetermineIfCDKBootstrapShouldRun()) { // Ensure region is bootstrapped var cdkBootstrap = await _commandLineWrapper.TryRunWithResult($"npx cdk bootstrap aws://{session.AWSAccountId}/{session.AWSRegion} --template \"{_workspaceMetadata.CDKBootstrapTemplatePath}\"", workingDirectory: _workspaceMetadata.DeployToolWorkspaceDirectoryRoot, needAwsCredentials: true, redirectIO: true, streamOutputToInteractiveService: true); if (cdkBootstrap.ExitCode != 0) throw new FailedToDeployCDKAppException(DeployToolErrorCode.FailedToRunCDKBootstrap, "The AWS CDK Bootstrap, which is the process of provisioning initial resources for the deployment environment, has failed. Please review the output above for additional details [and check out our troubleshooting guide for the most common failure reasons]. You can learn more about CDK bootstrapping at https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html.", cdkBootstrap.ExitCode); } else { _interactiveService.LogInfoMessage("Confirmed CDK Bootstrap CloudFormation stack already exists."); } _interactiveService.LogSectionStart("Deploying AWS CDK project", "Use the CDK project to create or update the AWS CloudFormation stack and deploy the project to the AWS resources in the stack."); // Handover to CDK command line tool // Use a CDK Context parameter to specify the settings file that has been serialized. var cdkDeployTask = _commandLineWrapper.TryRunWithResult( $"npx cdk deploy --require-approval never -c {Constants.CloudFormationIdentifier.SETTINGS_PATH_CDK_CONTEXT_PARAMETER}=\"{appSettingsFilePath}\"", workingDirectory: cdkProjectPath, environmentVariables: environmentVariables, needAwsCredentials: true, redirectIO: true, streamOutputToInteractiveService: true); var cancellationTokenSource = new CancellationTokenSource(); var retrieveStackIdTask = RetrieveStackId(cloudApplication, cancellationTokenSource.Token); var deploymentStartDate = DateTime.UtcNow; var firstCompletedTask = await Task.WhenAny(cdkDeployTask, retrieveStackIdTask); // Deployment end date is captured at this point after 1 of the 2 running tasks yields. var deploymentEndDate = DateTime.UtcNow; TryRunResult? cdkDeploy = null; if (firstCompletedTask == retrieveStackIdTask) { // If retrieveStackIdTask completes first, that means a stack was created and exists in CloudFormation. // We can proceed with checking for deployment failures. var stackId = cloudApplication.Name; if (!retrieveStackIdTask.IsFaulted) stackId = retrieveStackIdTask.Result; cdkDeploy = await cdkDeployTask; // We recapture the deployment end date at this point after the deployment task completes. deploymentEndDate = DateTime.UtcNow; await CheckCdkDeploymentFailure(stackId, deploymentStartDate, deploymentEndDate, cdkDeploy); } else { // If cdkDeployTask completes first, that means 'cdk deploy' failed before creating a stack in CloudFormation. // In this case, we skip checking for deployment failures since a stack does not exist. cdkDeploy = cdkDeployTask.Result; cancellationTokenSource.Cancel(); } var deploymentTotalTime = Math.Round((deploymentEndDate - deploymentStartDate).TotalSeconds, 2); if (cdkDeploy.ExitCode != 0) throw new FailedToDeployCDKAppException(DeployToolErrorCode.FailedToDeployCdkApplication, $"We had an issue deploying your application to AWS. Check the deployment output for more details. Deployment took {deploymentTotalTime}s.", cdkDeploy.ExitCode); } public async Task<bool> DetermineIfCDKBootstrapShouldRun() { var cdkTemplateVersion = await _cloudFormationTemplateReader.ReadCDKTemplateVersion(); var stack = await _awsResourceQueryer.GetCloudFormationStack(AWS.Deploy.Constants.CDK.CDKBootstrapStackName); if (stack == null) { _interactiveService.LogDebugMessage("CDK Bootstrap stack not found."); return true; } var qualiferParameter = stack.Parameters.FirstOrDefault(x => string.Equals("Qualifier", x.ParameterKey)); if (qualiferParameter == null || string.IsNullOrEmpty(qualiferParameter.ParameterValue)) { _interactiveService.LogDebugMessage("CDK Bootstrap SSM parameter store value missing."); return true; } var bootstrapVersionStr = await _awsResourceQueryer.GetParameterStoreTextValue($"/cdk-bootstrap/{qualiferParameter.ParameterValue}/version"); if (string.IsNullOrEmpty(bootstrapVersionStr) || !int.TryParse(bootstrapVersionStr, out var bootstrapVersion) || bootstrapVersion < cdkTemplateVersion) { _interactiveService.LogDebugMessage($"CDK Bootstrap version is out of date: \"{cdkTemplateVersion}\" < \"{bootstrapVersionStr}\"."); return true; } return false; } private async Task<string> RetrieveStackId(CloudApplication cloudApplication, CancellationToken cancellationToken) { Stack? stack = null; await Helpers.WaitUntil(async () => { try { stack = await _awsResourceQueryer.GetCloudFormationStack(cloudApplication.Name); return stack != null; } catch (ResourceQueryException exception) when (exception.InnerException != null && exception.InnerException.Message.Equals($"Stack with id {cloudApplication.Name} does not exist")) { return false; } }, TimeSpan.FromSeconds(3), TimeSpan.FromMinutes(5), cancellationToken); return stack?.StackId ?? throw new ResourceQueryException(DeployToolErrorCode.FailedToRetrieveStackId, "We were unable to retrieve the CloudFormation stack identifier."); } private async Task CheckCdkDeploymentFailure(string stackId, DateTime deploymentStartDate, DateTime deploymentEndDate, TryRunResult cdkDeployResult) { try { var stackEvents = await _awsResourceQueryer.GetCloudFormationStackEvents(stackId); var failedEvents = stackEvents .Where(x => x.Timestamp.ToUniversalTime() >= deploymentStartDate) .Where(x => x.ResourceStatus.Equals(ResourceStatus.CREATE_FAILED) || x.ResourceStatus.Equals(ResourceStatus.DELETE_FAILED) || x.ResourceStatus.Equals(ResourceStatus.UPDATE_FAILED) || x.ResourceStatus.Equals(ResourceStatus.IMPORT_FAILED) || x.ResourceStatus.Equals(ResourceStatus.IMPORT_ROLLBACK_FAILED) || x.ResourceStatus.Equals(ResourceStatus.UPDATE_ROLLBACK_FAILED) || x.ResourceStatus.Equals(ResourceStatus.ROLLBACK_FAILED) ); if (failedEvents.Any()) { var errors = string.Join(". ", failedEvents.Reverse().Select(x => x.ResourceStatusReason)); throw new FailedToDeployCDKAppException(DeployToolErrorCode.FailedToDeployCdkApplication, errors, cdkDeployResult.ExitCode); } } catch (ResourceQueryException exception) when (exception.InnerException != null && exception.InnerException.Message.Equals($"Stack [{stackId}] does not exist")) { var deploymentTotalTime = Math.Round((deploymentEndDate - deploymentStartDate).TotalSeconds, 2); throw new FailedToDeployCDKAppException(DeployToolErrorCode.FailedToCreateCdkStack, $"A CloudFormation stack was not created. Check the deployment output for more details. Deployment took {deploymentTotalTime}s.", cdkDeployResult.ExitCode); } } public string CreateCdkProject(Recommendation recommendation, OrchestratorSession session, string? saveCdkDirectoryPath = null) { string? assemblyName; if (string.IsNullOrEmpty(saveCdkDirectoryPath)) { saveCdkDirectoryPath = Path.Combine( _workspaceMetadata.ProjectsDirectory, Path.GetFileNameWithoutExtension(Path.GetRandomFileName())); assemblyName = recommendation.ProjectDefinition.AssemblyName; } else { assemblyName = _directoryManager.GetDirectoryInfo(saveCdkDirectoryPath).Name; } if (string.IsNullOrEmpty(assemblyName)) throw new ArgumentNullException("The assembly name for the CDK deployment project cannot be null"); _directoryManager.CreateDirectory(saveCdkDirectoryPath); var templateEngine = new TemplateEngine(); templateEngine.GenerateCDKProjectFromTemplate(recommendation, session, saveCdkDirectoryPath, assemblyName); _interactiveService.LogDebugMessage($"Saving AWS CDK deployment project to: {saveCdkDirectoryPath}"); return saveCdkDirectoryPath; } public void DeleteTemporaryCdkProject(string cdkProjectPath) { var parentPath = Path.GetFullPath(_workspaceMetadata.ProjectsDirectory); cdkProjectPath = Path.GetFullPath(cdkProjectPath); if (!cdkProjectPath.StartsWith(parentPath)) return; try { _directoryManager.Delete(cdkProjectPath, true); } catch (Exception exception) { _interactiveService.LogDebugMessage(exception.PrettyPrint()); _interactiveService.LogErrorMessage($"We were unable to delete the temporary project that was created for this deployment. Please manually delete it at this location: {cdkProjectPath}"); } } } }
312
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.Text; using System.Threading.Tasks; using Amazon.ECR.Model; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Utilities; using AWS.Deploy.Constants; using AWS.Deploy.Orchestration.Data; using AWS.Deploy.Orchestration.Utilities; using Recommendation = AWS.Deploy.Common.Recommendation; namespace AWS.Deploy.Orchestration { public interface IDeploymentBundleHandler { Task BuildDockerImage(CloudApplication cloudApplication, Recommendation recommendation, string imageTag); Task<string> CreateDotnetPublishZip(Recommendation recommendation); Task PushDockerImageToECR(Recommendation recommendation, string repositoryName, string sourceTag); } public class DeploymentBundleHandler : IDeploymentBundleHandler { private readonly ICommandLineWrapper _commandLineWrapper; private readonly IAWSResourceQueryer _awsResourceQueryer; private readonly IOrchestratorInteractiveService _interactiveService; private readonly IDirectoryManager _directoryManager; private readonly IZipFileManager _zipFileManager; private readonly IFileManager _fileManager; public DeploymentBundleHandler( ICommandLineWrapper commandLineWrapper, IAWSResourceQueryer awsResourceQueryer, IOrchestratorInteractiveService interactiveService, IDirectoryManager directoryManager, IZipFileManager zipFileManager, IFileManager fileManager) { _commandLineWrapper = commandLineWrapper; _awsResourceQueryer = awsResourceQueryer; _interactiveService = interactiveService; _directoryManager = directoryManager; _zipFileManager = zipFileManager; _fileManager = fileManager; } public async Task BuildDockerImage(CloudApplication cloudApplication, Recommendation recommendation, string imageTag) { _interactiveService.LogInfoMessage(string.Empty); _interactiveService.LogInfoMessage("Building the docker image..."); var dockerExecutionDirectory = GetDockerExecutionDirectory(recommendation); var buildArgs = GetDockerBuildArgs(recommendation); DockerUtilities.TryGetAbsoluteDockerfile(recommendation, _fileManager, _directoryManager, out var dockerFile); var dockerBuildCommand = $"docker build -t {imageTag} -f \"{dockerFile}\"{buildArgs} ."; _interactiveService.LogInfoMessage($"Docker Execution Directory: {Path.GetFullPath(dockerExecutionDirectory)}"); _interactiveService.LogInfoMessage($"Docker Build Command: {dockerBuildCommand}"); recommendation.DeploymentBundle.DockerfilePath = dockerFile; recommendation.DeploymentBundle.DockerExecutionDirectory = dockerExecutionDirectory; var result = await _commandLineWrapper.TryRunWithResult(dockerBuildCommand, dockerExecutionDirectory, streamOutputToInteractiveService: true); if (result.ExitCode != 0) { var errorMessage = "We were unable to build the docker image."; if (!string.IsNullOrEmpty(result.StandardError)) errorMessage = $"We were unable to build the docker image due to the following error:{Environment.NewLine}{result.StandardError}"; errorMessage += $"{Environment.NewLine}Docker builds usually fail due to executing them from a working directory that is incompatible with the Dockerfile."; errorMessage += $"{Environment.NewLine}You can try setting the 'Docker Execution Directory' in the option settings."; throw new DockerBuildFailedException(DeployToolErrorCode.DockerBuildFailed, errorMessage, result.ExitCode); } } public async Task PushDockerImageToECR(Recommendation recommendation, string repositoryName, string sourceTag) { _interactiveService.LogInfoMessage(string.Empty); _interactiveService.LogInfoMessage("Pushing the docker image to ECR repository..."); await InitiateDockerLogin(); var tagSuffix = sourceTag.Split(":")[1]; var repository = await SetupECRRepository(repositoryName); var targetTag = $"{repository.RepositoryUri}:{tagSuffix}"; await TagDockerImage(sourceTag, targetTag); await PushDockerImage(targetTag); recommendation.DeploymentBundle.ECRRepositoryName = repository.RepositoryName; recommendation.DeploymentBundle.ECRImageTag = tagSuffix; } public async Task<string> CreateDotnetPublishZip(Recommendation recommendation) { _interactiveService.LogInfoMessage(string.Empty); _interactiveService.LogInfoMessage("Creating Dotnet Publish Zip file..."); // Since Beanstalk doesn't currently have .NET 7 preinstalled we need to make sure we are doing a self contained publish when creating the deployment bundle. if (recommendation.Recipe.TargetService == RecipeIdentifier.TARGET_SERVICE_ELASTIC_BEANSTALK && recommendation.ProjectDefinition.TargetFramework == "net7.0") { _interactiveService.LogInfoMessage("Using self contained publish since AWS Elastic Beanstalk does not currently have .NET 7 preinstalled"); recommendation.DeploymentBundle.DotnetPublishSelfContainedBuild = true; } var publishDirectoryInfo = _directoryManager.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())); var additionalArguments = recommendation.DeploymentBundle.DotnetPublishAdditionalBuildArguments; var runtimeArg = recommendation.DeploymentBundle.DotnetPublishSelfContainedBuild && !additionalArguments.Contains("--runtime ") && !additionalArguments.Contains("-r ") ? $"--runtime {(recommendation.Recipe.TargetPlatform == TargetPlatform.Windows ? "win-x64" : "linux-x64")}" : ""; var publishCommand = $"dotnet publish \"{recommendation.ProjectPath}\"" + $" -o \"{publishDirectoryInfo}\"" + $" -c {recommendation.DeploymentBundle.DotnetPublishBuildConfiguration}" + $" {runtimeArg}" + $" {additionalArguments}"; // Blazor applications do not build with the default of setting self-contained to false. // So only add the --self-contained true if the user explicitly sets it to true. if(recommendation.DeploymentBundle.DotnetPublishSelfContainedBuild) { publishCommand += " --self-contained true"; } var result = await _commandLineWrapper.TryRunWithResult(publishCommand, streamOutputToInteractiveService: true); if (result.ExitCode != 0) { var errorMessage = "We were unable to package the application using 'dotnet publish'"; if (!string.IsNullOrEmpty(result.StandardError)) errorMessage = $"We were unable to package the application using 'dotnet publish' due to the following error:{Environment.NewLine}{result.StandardError}"; throw new DotnetPublishFailedException(DeployToolErrorCode.DotnetPublishFailed, errorMessage, result.ExitCode); } var zipFilePath = $"{publishDirectoryInfo.FullName}.zip"; await _zipFileManager.CreateFromDirectory(publishDirectoryInfo.FullName, zipFilePath); recommendation.DeploymentBundle.DotnetPublishZipPath = zipFilePath; recommendation.DeploymentBundle.DotnetPublishOutputDirectory = publishDirectoryInfo.FullName; return zipFilePath; } /// <summary> /// Determines the appropriate docker execution directory for the project. /// In order of precedence: /// 1. DeploymentBundle.DockerExecutionDirectory, if already set /// 2. The solution level if ProjectDefinition.ProjectSolutionPath is set /// 3. The project directory /// </summary> /// <param name="recommendation"></param> private string GetDockerExecutionDirectory(Recommendation recommendation) { var dockerExecutionDirectory = recommendation.DeploymentBundle.DockerExecutionDirectory; var projectDirectory = recommendation.GetProjectDirectory(); var projectSolutionPath = recommendation.ProjectDefinition.ProjectSolutionPath; if (string.IsNullOrEmpty(dockerExecutionDirectory)) { if (string.IsNullOrEmpty(projectSolutionPath)) { dockerExecutionDirectory = new FileInfo(projectDirectory).FullName; } else { var projectSolutionDirectory = new FileInfo(projectSolutionPath).Directory?.FullName; dockerExecutionDirectory = projectSolutionDirectory ?? throw new InvalidSolutionPathException(DeployToolErrorCode.InvalidSolutionPath, "The solution path is invalid."); } } // The docker build command will fail if a relative path is provided dockerExecutionDirectory = _directoryManager.GetAbsolutePath(projectDirectory, dockerExecutionDirectory); return dockerExecutionDirectory; } private string GetDockerBuildArgs(Recommendation recommendation) { var buildArgs = recommendation.DeploymentBundle.DockerBuildArgs; if (string.IsNullOrEmpty(buildArgs)) return buildArgs; // Ensure it starts with a space so it doesn't collide with the previous option if (!char.IsWhiteSpace(buildArgs[0])) return $" {buildArgs}"; else return buildArgs; } private async Task InitiateDockerLogin() { var authorizationTokens = await _awsResourceQueryer.GetECRAuthorizationToken(); if (authorizationTokens.Count == 0) throw new DockerLoginFailedException(DeployToolErrorCode.FailedToGetECRAuthorizationToken, "Failed to login to Docker", null); var authTokenBytes = Convert.FromBase64String(authorizationTokens[0].AuthorizationToken); var authToken = Encoding.UTF8.GetString(authTokenBytes); var decodedTokens = authToken.Split(':'); var dockerLoginCommand = $"docker login --username {decodedTokens[0]} --password-stdin {authorizationTokens[0].ProxyEndpoint}"; var result = await _commandLineWrapper.TryRunWithResult(dockerLoginCommand, streamOutputToInteractiveService: true, stdin: decodedTokens[1]); if (result.ExitCode != 0) { var errorMessage = "Failed to login to Docker"; if (!string.IsNullOrEmpty(result.StandardError)) errorMessage = $"Failed to login to Docker due to the following reason:{Environment.NewLine}{result.StandardError}"; throw new DockerLoginFailedException(DeployToolErrorCode.DockerLoginFailed, errorMessage, result.ExitCode); } } private async Task<Repository> SetupECRRepository(string ecrRepositoryName) { var existingRepositories = await _awsResourceQueryer.GetECRRepositories(new List<string> { ecrRepositoryName }); if (existingRepositories.Count == 1) { return existingRepositories[0]; } else { return await _awsResourceQueryer.CreateECRRepository(ecrRepositoryName); } } private async Task TagDockerImage(string sourceTagName, string targetTagName) { var dockerTagCommand = $"docker tag {sourceTagName} {targetTagName}"; var result = await _commandLineWrapper.TryRunWithResult(dockerTagCommand, streamOutputToInteractiveService: true); if (result.ExitCode != 0) { var errorMessage = "Failed to tag Docker image"; if (!string.IsNullOrEmpty(result.StandardError)) errorMessage = $"Failed to tag Docker Image due to the following reason:{Environment.NewLine}{result.StandardError}"; throw new DockerTagFailedException(DeployToolErrorCode.DockerTagFailed, errorMessage, result.ExitCode); } } private async Task PushDockerImage(string targetTagName) { var dockerPushCommand = $"docker push {targetTagName}"; var result = await _commandLineWrapper.TryRunWithResult(dockerPushCommand, streamOutputToInteractiveService: true); if (result.ExitCode != 0) { var errorMessage = "Failed to push Docker Image"; if (!string.IsNullOrEmpty(result.StandardError)) errorMessage = $"Failed to push Docker Image due to the following reason:{Environment.NewLine}{result.StandardError}"; throw new DockerPushFailedException(DeployToolErrorCode.DockerPushFailed, errorMessage, result.ExitCode); } } } }
268
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.Text; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Orchestration.Utilities; using Newtonsoft.Json; namespace AWS.Deploy.Orchestration { public interface IDeploymentSettingsHandler { /// <summary> /// Read the JSON content at the specified file and deserializes it into <see cref="DeploymentSettings"/> /// </summary> Task<DeploymentSettings?> ReadSettings(string filePath); /// <summary> /// Iterates over the option setting values found at <see cref="DeploymentSettings"/> and applies them to the selected recommendation /// </summary> Task ApplySettings(DeploymentSettings deploymentSettings, Recommendation recommendation, IDeployToolValidationContext deployToolValidationContext); /// <summary> /// Save the deployment settings at the specified file path. /// </summary> /// <exception cref="FailedToSaveDeploymentSettingsException">Thrown if this operation fails.</exception> Task SaveSettings(SaveSettingsConfiguration saveSettingsConfig, Recommendation recommendation, CloudApplication cloudApplication, OrchestratorSession orchestratorSession); } public class DeploymentSettingsHandler : IDeploymentSettingsHandler { private readonly IFileManager _fileManager; private readonly IDirectoryManager _directoryManager; private readonly IOptionSettingHandler _optionSettingHandler; private readonly IRecipeHandler _recipeHandler; public DeploymentSettingsHandler(IFileManager fileManager, IDirectoryManager directoryManager, IOptionSettingHandler optionSettingHandler, IRecipeHandler recipeHandler) { _fileManager = fileManager; _directoryManager = directoryManager; _optionSettingHandler = optionSettingHandler; _recipeHandler = recipeHandler; } public async Task<DeploymentSettings?> ReadSettings(string filePath) { if (_fileManager.Exists(filePath)) { try { var contents = await _fileManager.ReadAllTextAsync(filePath); var userDeploymentSettings = JsonConvert.DeserializeObject<DeploymentSettings>(contents); return userDeploymentSettings; } catch (Exception ex) { throw new InvalidDeploymentSettingsException(DeployToolErrorCode.FailedToDeserializeUserDeploymentFile, $"An error occurred while trying to deserialize the deployment settings file located at {filePath}.\n {ex.Message}", ex); } } else { throw new InvalidDeploymentSettingsException(DeployToolErrorCode.UserDeploymentFileNotFound, $"The deployment settings file located at {filePath} doesn't exist."); } } public async Task ApplySettings(DeploymentSettings deploymentSettings, Recommendation recommendation, IDeployToolValidationContext deployToolValidationContext) { var optionSettings = deploymentSettings.Settings ?? new Dictionary<string, object>(); foreach (var entry in optionSettings) { try { var optionSettingId = entry.Key; var optionSettingValue = entry.Value; var optionSetting = _optionSettingHandler.GetOptionSetting(recommendation, optionSettingId); await _optionSettingHandler.SetOptionSettingValue(recommendation, optionSetting, optionSettingValue, true); } catch (OptionSettingItemDoesNotExistException ex) { throw new InvalidDeploymentSettingsException(DeployToolErrorCode.DeploymentConfigurationNeedsAdjusting, ex.Message, ex); } } var optionSettingValidationFailedResult = _optionSettingHandler.RunOptionSettingValidators(recommendation); var recipeValidationFailedResult = _recipeHandler.RunRecipeValidators(recommendation, deployToolValidationContext); if (!optionSettingValidationFailedResult.Any() && !recipeValidationFailedResult.Any()) { // All validations are successful return; } var errorMessage = "The deployment configuration needs to be adjusted before it can be deployed:" + Environment.NewLine; var failedValidations = optionSettingValidationFailedResult.Concat(recipeValidationFailedResult); foreach (var validation in failedValidations) { errorMessage += validation.ValidationFailedMessage + Environment.NewLine; } throw new InvalidDeploymentSettingsException(DeployToolErrorCode.DeploymentConfigurationNeedsAdjusting, errorMessage.Trim()); } public async Task SaveSettings(SaveSettingsConfiguration saveSettingsConfig, Recommendation recommendation, CloudApplication cloudApplication, OrchestratorSession orchestratorSession) { if (saveSettingsConfig.SettingsType == SaveSettingsType.None) { // We are not throwing an expected exception here as this issue is not caused by the user. throw new InvalidOperationException($"Cannot persist settings with {SaveSettingsType.None}"); } if (!_fileManager.IsFileValidPath(saveSettingsConfig.FilePath)) { var message = $"Failed to save deployment settings because {saveSettingsConfig.FilePath} is invalid or its parent directory does not exist on disk."; throw new FailedToSaveDeploymentSettingsException(DeployToolErrorCode.FailedToSaveDeploymentSettings, message); } var projectDirectory = Path.GetDirectoryName(orchestratorSession.ProjectDefinition.ProjectPath); if (string.IsNullOrEmpty(projectDirectory)) { var message = "Failed to save deployment settings because the current deployment session does not have a valid project path"; throw new FailedToSaveDeploymentSettingsException(DeployToolErrorCode.FailedToSaveDeploymentSettings, message); } var deploymentSettings = new DeploymentSettings { AWSProfile = orchestratorSession.AWSProfileName, AWSRegion = orchestratorSession.AWSRegion, ApplicationName = recommendation.Recipe.DeploymentType == DeploymentTypes.ElasticContainerRegistryImage ? null : cloudApplication.Name, RecipeId = cloudApplication.RecipeId, Settings = _optionSettingHandler.GetOptionSettingsMap(recommendation, orchestratorSession.ProjectDefinition, _directoryManager) }; if (saveSettingsConfig.SettingsType == SaveSettingsType.Modified) { foreach (var optionSetting in recommendation.GetConfigurableOptionSettingItems()) { if (!_optionSettingHandler.IsOptionSettingModified(recommendation, optionSetting)) { deploymentSettings.Settings.Remove(optionSetting.FullyQualifiedId); } } } try { var content = JsonConvert.SerializeObject(deploymentSettings, new JsonSerializerSettings { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, ContractResolver = new SerializeModelContractResolver() }); await _fileManager.WriteAllTextAsync(saveSettingsConfig.FilePath, content); } catch (Exception ex) { var message = $"Failed to save the deployment settings at {saveSettingsConfig.FilePath} due to the following error: {Environment.NewLine}{ex.Message}"; throw new FailedToSaveDeploymentSettingsException(DeployToolErrorCode.FailedToSaveDeploymentSettings, message, ex); } } } }
172
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.Text; using System.Threading.Tasks; using AWS.Deploy.Common.Extensions; using AWS.Deploy.Common.IO; using AWS.Deploy.Orchestration.Utilities; namespace AWS.Deploy.Orchestration { public interface IDeployToolWorkspaceMetadata { /// <summary> /// Deployment tool workspace directory to create CDK app during the deployment. /// </summary> string DeployToolWorkspaceDirectoryRoot { get; } /// <summary> /// Directory that contains CDK projects /// </summary> string ProjectsDirectory { get; } /// <summary> /// The file path of the CDK bootstrap template to be used /// </summary> string CDKBootstrapTemplatePath { get; } } public class DeployToolWorkspaceMetadata : IDeployToolWorkspaceMetadata { private readonly IDirectoryManager _directoryManager; private readonly IFileManager _fileManager; private readonly IEnvironmentVariableManager _environmentVariableManager; public string DeployToolWorkspaceDirectoryRoot { get { var workspace = Helpers.GetDeployToolWorkspaceDirectoryRoot(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), _directoryManager, _environmentVariableManager); if (!_directoryManager.Exists(workspace)) _directoryManager.CreateDirectory(workspace); return workspace; } } public string ProjectsDirectory => Path.Combine(DeployToolWorkspaceDirectoryRoot, "Projects"); public string CDKBootstrapTemplatePath { get { var bootstrapTemplate = Path.Combine(DeployToolWorkspaceDirectoryRoot, "CDKBootstrapTemplate.yaml"); if (!_fileManager.Exists(bootstrapTemplate)) { // The CDK bootstrap template can be generated by running 'cdk bootstrap --show-template'. // We need to keep the template up to date while making sure that the 'Staging Bucket' retention policies are set to 'Delete'. var cdkBootstrapTemplate = typeof(CdkProjectHandler).Assembly.ReadEmbeddedFile(TemplateIdentifier); using var cdkBootstrapTemplateFile = new StreamWriter(bootstrapTemplate); cdkBootstrapTemplateFile.Write(cdkBootstrapTemplate); } return bootstrapTemplate; } } private const string TemplateIdentifier = "AWS.Deploy.Orchestration.CDK.CDKBootstrapTemplate.yaml"; public DeployToolWorkspaceMetadata(IDirectoryManager directoryManager, IEnvironmentVariableManager environmentVariableManager, IFileManager fileManager) { _directoryManager = directoryManager; _environmentVariableManager = environmentVariableManager; _fileManager = fileManager; } } }
79
aws-dotnet-deploy
aws
C#
using System; using AWS.Deploy.Common; using AWS.Deploy.Orchestration.DeploymentCommands; namespace AWS.Deploy.Orchestration { /// <summary> /// Exception is thrown if Microsoft Templating Engine is unable to generate a template /// </summary> public class TemplateGenerationFailedException : DeployToolException { public TemplateGenerationFailedException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception is thrown if Microsoft Templating Engine is unable to find location to install templates from /// </summary> public class DefaultTemplateInstallationFailedException : DeployToolException { public DefaultTemplateInstallationFailedException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception is thrown if Microsoft Templating Engine returns an error when running a command /// </summary> public class RunCommandFailedException : DeployToolException { public RunCommandFailedException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception is thrown if package.json file IO fails. /// </summary> public class PackageJsonFileException : DeployToolException { public PackageJsonFileException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception is thrown if docker build attempt failed /// </summary> public class DockerBuildFailedException : DeployToolException { public DockerBuildFailedException(DeployToolErrorCode errorCode, string message, int processExitCode, Exception? innerException = null) : base(errorCode, message, innerException, processExitCode) { } } /// <summary> /// Exception is thrown if npm command fails to execute. /// </summary> public class NPMCommandFailedException : DeployToolException { public NPMCommandFailedException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception is thrown if docker login attempt failed /// </summary> public class DockerLoginFailedException : DeployToolException { public DockerLoginFailedException(DeployToolErrorCode errorCode, string message, int? processExitCode, Exception? innerException = null) : base(errorCode, message, innerException, processExitCode) { } } /// <summary> /// Exception is thrown if docker tag attempt failed /// </summary> public class DockerTagFailedException : DeployToolException { public DockerTagFailedException(DeployToolErrorCode errorCode, string message, int processExitCode, Exception? innerException = null) : base(errorCode, message, innerException, processExitCode) { } } /// <summary> /// Exception is thrown if ECR repository name is invalid. /// </summary> public class InvalidECRRepositoryNameException : DeployToolException { public InvalidECRRepositoryNameException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception is thrown if docker push attempt failed /// </summary> public class DockerPushFailedException : DeployToolException { public DockerPushFailedException(DeployToolErrorCode errorCode, string message, int processExitCode, Exception? innerException = null) : base(errorCode, message, innerException, processExitCode) { } } /// <summary> /// Exception is thrown if unable to read CDK Bootstrap version from template /// </summary> public class FailedToReadCdkBootstrapVersionException : DeployToolException { public FailedToReadCdkBootstrapVersionException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception is thrown if we cannot retrieve recipe definitions /// </summary> public class NoRecipeDefinitionsFoundException : DeployToolException { public NoRecipeDefinitionsFoundException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception is thrown if dotnet publish attempt failed /// </summary> public class DotnetPublishFailedException : DeployToolException { public DotnetPublishFailedException(DeployToolErrorCode errorCode, string message, int processExitCode, Exception? innerException = null) : base(errorCode, message, innerException, processExitCode) { } } /// <summary> /// Throw if Zip File Manager fails to create a Zip File /// </summary> public class FailedToCreateZipFileException : DeployToolException { public FailedToCreateZipFileException(DeployToolErrorCode errorCode, string message, int? processExitCode, Exception? innerException = null) : base(errorCode, message, innerException, processExitCode) { } } /// <summary> /// Exception thrown if Docker file could not be generated /// </summary> public class FailedToGenerateDockerFileException : DeployToolException { public FailedToGenerateDockerFileException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception thrown if RecipePath contains an invalid path /// </summary> public class InvalidRecipePathException : DeployToolException { public InvalidRecipePathException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception thrown if Solution Path contains an invalid path /// </summary> public class InvalidSolutionPathException : DeployToolException { public InvalidSolutionPathException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception thrown if AWS Deploy Recipes CDK Common Product Version is invalid. /// </summary> public class InvalidAWSDeployRecipesCDKCommonVersionException : DeployToolException { public InvalidAWSDeployRecipesCDKCommonVersionException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception thrown if the 'cdk deploy' command failed. /// </summary> public class FailedToDeployCDKAppException : DeployToolException { public FailedToDeployCDKAppException(DeployToolErrorCode errorCode, string message, int processExitCode, Exception? innerException = null) : base(errorCode, message, innerException, processExitCode) { } } /// <summary> /// Exception thrown if the 'cdk diff' command failed. /// </summary> public class FailedToRunCDKDiffException : DeployToolException { public FailedToRunCDKDiffException(DeployToolErrorCode errorCode, string message, int processExitCode, Exception? innerException = null) : base(errorCode, message, innerException, processExitCode) { } } /// <summary> /// Exception thrown if an AWS Resource is not found or does not exist. /// </summary> public class AWSResourceNotFoundException : DeployToolException { public AWSResourceNotFoundException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception thrown if the Local User Settings File is invalid. /// </summary> public class InvalidLocalUserSettingsFileException : DeployToolException { public InvalidLocalUserSettingsFileException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Exception thrown if a failure occured while trying to update the Local User Settings file. /// </summary> public class FailedToUpdateLocalUserSettingsFileException : DeployToolException { public FailedToUpdateLocalUserSettingsFileException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if docker info failed to return output. /// </summary> public class DockerInfoException : DeployToolException { public DockerInfoException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if unable to find an Elastic Beanstalk .NET solution stack. /// </summary> public class FailedToFindElasticBeanstalkSolutionStackException : DeployToolException { public FailedToFindElasticBeanstalkSolutionStackException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if could not create an instance of <see cref="IDeploymentCommand"/> /// </summary> public class FailedToCreateDeploymentCommandInstanceException : DeployToolException { public FailedToCreateDeploymentCommandInstanceException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if an error occured while calling a S3 API. /// </summary> public class S3Exception : DeployToolException { public S3Exception(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if an error occured while calling an Elastic Beanstalk API. /// </summary> public class ElasticBeanstalkException : DeployToolException { public ElasticBeanstalkException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if unable to access the specified AWS Region. /// </summary> public class UnableToAccessAWSRegionException : DeployToolException { public UnableToAccessAWSRegionException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if unable to determine the CloudApplication resource type /// </summary> public class FailedToFindCloudApplicationResourceType : DeployToolException { public FailedToFindCloudApplicationResourceType(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if we are unable to generate a CDK Project /// </summary> public class FailedToCreateCDKProjectException : DeployToolException { public FailedToCreateCDKProjectException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if the deploy tool workspace is invalid /// </summary> public class InvalidDeployToolWorkspaceException : DeployToolException { public InvalidDeployToolWorkspaceException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } /// <summary> /// Throw if the deploy tool detects an invalid windows elastic beanstalk manifest file. /// </summary> public class InvalidWindowsManifestFileException : DeployToolException { public InvalidWindowsManifestFileException(DeployToolErrorCode errorCode, string message, Exception? innerException = null) : base(errorCode, message, innerException) { } } }
272
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Orchestration { public interface IOrchestratorInteractiveService { void LogSectionStart(string sectionName, string? description); void LogErrorMessage(string? message); void LogInfoMessage(string? message); void LogDebugMessage(string? message); } }
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.IO; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.Extensions; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; namespace AWS.Deploy.Orchestration { public class OptionSettingHandler : IOptionSettingHandler { private readonly IValidatorFactory _validatorFactory; public OptionSettingHandler(IValidatorFactory validatorFactory) { _validatorFactory = validatorFactory; } /// <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> public List<ValidationResult> RunOptionSettingValidators(Recommendation recommendation, IEnumerable<OptionSettingItem>? optionSettings = null) { if (optionSettings == null) optionSettings = recommendation.GetConfigurableOptionSettingItems().Where(x => !recommendation.IsExistingCloudApplication || x.Updatable); List<ValidationResult> settingValidatorFailedResults = new List<ValidationResult>(); foreach (var optionSetting in optionSettings) { if (!IsOptionSettingDisplayable(recommendation, optionSetting)) { optionSetting.Validation.ValidationStatus = ValidationStatus.Valid; optionSetting.Validation.ValidationMessage = string.Empty; optionSetting.Validation.InvalidValue = null; continue; } var optionSettingValue = GetOptionSettingValue(recommendation, optionSetting); var failedValidators = _validatorFactory.BuildValidators(optionSetting) .Select(async validator => await validator.Validate(optionSettingValue, recommendation, optionSetting)) .Select(x => x.Result) .Where(x => !x.IsValid) .ToList(); if (failedValidators.Any()) { optionSetting.Validation.ValidationStatus = ValidationStatus.Invalid; optionSetting.Validation.ValidationMessage = string.Join(Environment.NewLine, failedValidators.Select(x => x.ValidationFailedMessage)).Trim(); optionSetting.Validation.InvalidValue = optionSettingValue; } else { optionSetting.Validation.ValidationStatus = ValidationStatus.Valid; optionSetting.Validation.ValidationMessage = string.Empty; optionSetting.Validation.InvalidValue = null; } settingValidatorFailedResults.AddRange(failedValidators); settingValidatorFailedResults.AddRange(RunOptionSettingValidators(recommendation, optionSetting.ChildOptionSettings)); } return settingValidatorFailedResults; } /// <summary> /// Assigns a value to the OptionSettingItem. /// </summary> /// <exception cref="ValidationFailedException"> /// Thrown if one or more <see cref="Validators"/> determine /// <paramref name="value"/> is not valid. /// </exception> public async Task SetOptionSettingValue(Recommendation recommendation, OptionSettingItem optionSettingItem, object value, bool skipValidation = false) { IOptionSettingItemValidator[] validators = new IOptionSettingItemValidator[0]; if (!skipValidation && IsOptionSettingDisplayable(recommendation, optionSettingItem)) validators = _validatorFactory.BuildValidators(optionSettingItem); await optionSettingItem.SetValue(this, value, validators, recommendation, skipValidation); if (!skipValidation) RunOptionSettingValidators(recommendation, optionSettingItem.Dependents.Select(x => GetOptionSetting(recommendation, x))); // If the optionSettingItem came from the selected recommendation's deployment bundle, // set the corresponding property on recommendation.DeploymentBundle SetDeploymentBundleProperty(recommendation, optionSettingItem, value); } /// <summary> /// Assigns a value to the OptionSettingItem based on the fullyQualifiedId /// </summary> /// <exception cref="ValidationFailedException"> /// Thrown if one or more <see cref="Validators"/> determine /// <paramref name="value"/> is not valid. /// </exception> /// <exception cref="OptionSettingItemDoesNotExistException"> /// Thrown if there doesn't exist an option setting with the given fullyQualifiedId /// </exception> public async Task SetOptionSettingValue(Recommendation recommendation, string fullyQualifiedId, object value, bool skipValidation = false) { var optionSetting = GetOptionSetting(recommendation, fullyQualifiedId); await SetOptionSettingValue(recommendation, optionSetting, value, skipValidation); } /// <summary> /// Sets the corresponding value in <see cref="DeploymentBundle"/> when the /// corresponding <see cref="OptionSettingItem"> was just set /// </summary> /// <param name="recommendation">Selected recommendation</param> /// <param name="optionSettingItem">Option setting that was just set</param> /// <param name="value">Value that was just set, assumed to be valid</param> private void SetDeploymentBundleProperty(Recommendation recommendation, OptionSettingItem optionSettingItem, object value) { switch (optionSettingItem.Id) { case Constants.Docker.DockerExecutionDirectoryOptionId: recommendation.DeploymentBundle.DockerExecutionDirectory = value.ToString() ?? string.Empty; break; case Constants.Docker.DockerfileOptionId: recommendation.DeploymentBundle.DockerfilePath = value.ToString() ?? string.Empty; break; case Constants.Docker.DockerBuildArgsOptionId: recommendation.DeploymentBundle.DockerBuildArgs = value.ToString() ?? string.Empty; break; case Constants.Docker.ECRRepositoryNameOptionId: recommendation.DeploymentBundle.ECRRepositoryName = value.ToString() ?? string.Empty; break; case Constants.RecipeIdentifier.DotnetPublishConfigurationOptionId: recommendation.DeploymentBundle.DotnetPublishBuildConfiguration = value.ToString() ?? string.Empty; break; case Constants.RecipeIdentifier.DotnetPublishArgsOptionId: recommendation.DeploymentBundle.DotnetPublishAdditionalBuildArguments = value.ToString() ?? string.Empty; break; case Constants.RecipeIdentifier.DotnetPublishSelfContainedBuildOptionId: recommendation.DeploymentBundle.DotnetPublishSelfContainedBuild = Convert.ToBoolean(value); break; default: return; } } /// <summary> /// Interactively traverses given json path and returns target option setting. /// Throws exception if there is no <see cref="OptionSettingItem" /> that matches <paramref name="jsonPath"/> /> /// In case an option setting of type <see cref="OptionSettingValueType.KeyValue"/> is encountered, /// that <paramref name="jsonPath"/> can have the key value pair name as the leaf node with the option setting Id as the node before that. /// </summary> /// <param name="jsonPath"> /// Dot (.) separated key values string pointing to an option setting. /// Read more <see href="https://tools.ietf.org/id/draft-goessner-dispatch-jsonpath-00.html"/> /// </param> /// <returns>Option setting at the json path. Throws <see cref="OptionSettingItemDoesNotExistException"/> if there doesn't exist an option setting.</returns> public OptionSettingItem GetOptionSetting(Recommendation recommendation, string? jsonPath) { if (string.IsNullOrEmpty(jsonPath)) throw new OptionSettingItemDoesNotExistException(DeployToolErrorCode.OptionSettingItemDoesNotExistInRecipe, $"The Option Setting Item {jsonPath} does not exist as part of the" + $" {recommendation.Recipe.Name} recipe"); var ids = jsonPath.Split('.'); OptionSettingItem? optionSetting = null; for (int i = 0; i < ids.Length; i++) { var optionSettings = optionSetting?.ChildOptionSettings ?? recommendation.GetConfigurableOptionSettingItems(); optionSetting = optionSettings.FirstOrDefault(os => os.Id.Equals(ids[i])); if (optionSetting == null) { throw new OptionSettingItemDoesNotExistException(DeployToolErrorCode.OptionSettingItemDoesNotExistInRecipe, $"The Option Setting Item {jsonPath} does not exist as part of the" + $" {recommendation.Recipe.Name} recipe"); } if (optionSetting.Type.Equals(OptionSettingValueType.KeyValue)) { return optionSetting; } } return optionSetting!; } /// <summary> /// Interactively traverses given json path and returns target option setting. /// Throws exception if there is no <see cref="OptionSettingItem" /> that matches <paramref name="jsonPath"/> /> /// In case an option setting of type <see cref="OptionSettingValueType.KeyValue"/> is encountered, /// that <paramref name="jsonPath"/> can have the key value pair name as the leaf node with the option setting Id as the node before that. /// </summary> /// <param name="jsonPath"> /// Dot (.) separated key values string pointing to an option setting. /// Read more <see href="https://tools.ietf.org/id/draft-goessner-dispatch-jsonpath-00.html"/> /// </param> /// <returns>Option setting at the json path. Throws <see cref="OptionSettingItemDoesNotExistException"/> if there doesn't exist an option setting.</returns> public OptionSettingItem GetOptionSetting(RecipeDefinition recipe, string? jsonPath) { if (string.IsNullOrEmpty(jsonPath)) throw new OptionSettingItemDoesNotExistException(DeployToolErrorCode.OptionSettingItemDoesNotExistInRecipe, $"An option setting item with the specified fully qualified Id '{jsonPath}' cannot be found in the" + $" '{recipe.Name}' recipe."); var ids = jsonPath.Split('.'); OptionSettingItem? optionSetting = null; for (int i = 0; i < ids.Length; i++) { var optionSettings = optionSetting?.ChildOptionSettings ?? recipe.OptionSettings; optionSetting = optionSettings.FirstOrDefault(os => os.Id.Equals(ids[i])); if (optionSetting == null) { throw new OptionSettingItemDoesNotExistException(DeployToolErrorCode.OptionSettingItemDoesNotExistInRecipe, $"An option setting item with the specified fully qualified Id '{jsonPath}' cannot be found in the" + $" '{recipe.Name}' recipe."); } if (optionSetting.Type.Equals(OptionSettingValueType.KeyValue)) { return optionSetting; } } return optionSetting!; } /// <summary> /// Retrieves the value of the Option Setting Item in a given recommendation. /// </summary> public T? GetOptionSettingValue<T>(Recommendation recommendation, OptionSettingItem optionSetting) { var displayableOptionSettings = new Dictionary<string, bool>(); if (optionSetting.Type == OptionSettingValueType.Object) { foreach (var childOptionSetting in optionSetting.ChildOptionSettings) { displayableOptionSettings.Add(childOptionSetting.Id, IsOptionSettingDisplayable(recommendation, childOptionSetting)); } } return optionSetting.GetValue<T>(recommendation.ReplacementTokens, displayableOptionSettings); } /// <summary> /// Retrieves the value of the Option Setting Item in a given recommendation. /// </summary> public object GetOptionSettingValue(Recommendation recommendation, OptionSettingItem optionSetting) { var displayableOptionSettings = new Dictionary<string, bool>(); if (optionSetting.Type == OptionSettingValueType.Object) { foreach (var childOptionSetting in optionSetting.ChildOptionSettings) { displayableOptionSettings.Add(childOptionSetting.Id, IsOptionSettingDisplayable(recommendation, childOptionSetting)); } } return optionSetting.GetValue(recommendation.ReplacementTokens, displayableOptionSettings); } /// <summary> /// Retrieves the default value of the Option Setting Item in a given recommendation. /// </summary> public T? GetOptionSettingDefaultValue<T>(Recommendation recommendation, OptionSettingItem optionSetting) { return optionSetting.GetDefaultValue<T>(recommendation.ReplacementTokens); } /// <summary> /// Retrieves the default value of the Option Setting Item in a given recommendation. /// </summary> public object? GetOptionSettingDefaultValue(Recommendation recommendation, OptionSettingItem optionSetting) { return optionSetting.GetDefaultValue(recommendation.ReplacementTokens); } /// <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> public bool IsOptionSettingDisplayable(Recommendation recommendation, OptionSettingItem optionSetting) { if (!optionSetting.DependsOn.Any()) { return true; } foreach (var dependency in optionSetting.DependsOn) { var dependsOnOptionSetting = GetOptionSetting(recommendation, dependency.Id); var dependsOnOptionSettingValue = GetOptionSettingValue(recommendation, dependsOnOptionSetting); if ( dependsOnOptionSetting != null) { if (dependsOnOptionSettingValue == null) { if (dependency.Operation == null || dependency.Operation == PropertyDependencyOperationType.Equals) { if (dependency.Value != null) return false; } else if (dependency.Operation == PropertyDependencyOperationType.NotEmpty) { return false; } } else { if (dependency.Operation == null || dependency.Operation == PropertyDependencyOperationType.Equals) { if (!dependsOnOptionSettingValue.Equals(dependency.Value)) return false; } else if (dependency.Operation == PropertyDependencyOperationType.NotEmpty) { if (dependsOnOptionSetting.Type == OptionSettingValueType.List && dependsOnOptionSettingValue.TryDeserialize<SortedSet<string>>(out var listValue) && listValue != null && !listValue.Any()) { return false; } else if (dependsOnOptionSetting.Type == OptionSettingValueType.KeyValue && dependsOnOptionSettingValue.TryDeserialize<Dictionary<string, string>>(out var keyValue) && keyValue != null && !keyValue.Any()) { return false; } else if (string.IsNullOrEmpty(dependsOnOptionSettingValue?.ToString())) { return false; } } } } } return true; } /// <summary> /// Checks whether the Option Setting Item can be displayed as part of the settings summary of the previous deployment. /// </summary> public bool IsSummaryDisplayable(Recommendation recommendation, OptionSettingItem optionSettingItem) { if (!IsOptionSettingDisplayable(recommendation, optionSettingItem)) return false; var value = GetOptionSettingValue(recommendation, optionSettingItem); if (string.IsNullOrEmpty(value?.ToString())) return false; return true; } /// <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> public bool IsOptionSettingModified(Recommendation recommendation, OptionSettingItem optionSetting) { // If the option setting is not displayable, that means its dependencies are not satisfied and it does not play any role in the deployment. // We do not need to evaluate whether it has been modified or not. if (!IsOptionSettingDisplayable(recommendation, optionSetting)) { return false; } if (optionSetting.Type.Equals(OptionSettingValueType.List)) { var currentSet = GetOptionSettingValue<SortedSet<string>>(recommendation, optionSetting) ?? new SortedSet<string>(); var defaultSet = GetOptionSettingDefaultValue<SortedSet<string>>(recommendation, optionSetting) ?? new SortedSet<string>(); // return true if both have different lengths or all elements in currentSet are not present in defaultSet return defaultSet.Count != currentSet.Count || !currentSet.All(x => defaultSet.Contains(x)); } if (optionSetting.Type.Equals(OptionSettingValueType.KeyValue)) { var currentDict = GetOptionSettingValue<Dictionary<string, string>>(recommendation, optionSetting) ?? new Dictionary<string, string>(); var defaultDict = GetOptionSettingDefaultValue<Dictionary<string, string>>(recommendation, optionSetting) ?? new Dictionary<string, string>(); // return true if both have different lengths or all keyValue pairs are not equal between currentDict and defaultDict return defaultDict.Count != currentDict.Count || !currentDict.All(keyPair => defaultDict.ContainsKey(keyPair.Key) && string.Equals(defaultDict[keyPair.Key], currentDict[keyPair.Key])); } if (optionSetting.Type.Equals(OptionSettingValueType.Int)) { var currentValue = GetOptionSettingValue<int>(recommendation, optionSetting); var defaultValue = GetOptionSettingDefaultValue<int>(recommendation, optionSetting); return defaultValue != currentValue; } if (optionSetting.Type.Equals(OptionSettingValueType.Double)) { var currentValue = GetOptionSettingValue<double>(recommendation, optionSetting); var defaultValue = GetOptionSettingDefaultValue<double>(recommendation, optionSetting); return defaultValue != currentValue; } if (optionSetting.Type.Equals(OptionSettingValueType.Bool)) { var currentValue = GetOptionSettingValue<bool>(recommendation, optionSetting); var defaultValue = GetOptionSettingDefaultValue<bool>(recommendation, optionSetting); return defaultValue != currentValue; } if (optionSetting.Type.Equals(OptionSettingValueType.String)) { var currentValue = GetOptionSettingValue<string>(recommendation, optionSetting); var defaultValue = GetOptionSettingDefaultValue<string>(recommendation, optionSetting); if (string.IsNullOrEmpty(currentValue) && string.IsNullOrEmpty(defaultValue)) return false; return !string.Equals(currentValue, defaultValue); } // The option setting is of type Object and it has nested child settings. // return true is any of the child settings are modified. foreach (var childSetting in optionSetting.ChildOptionSettings) { if (IsOptionSettingModified(recommendation, childSetting)) return true; } return false; } /// <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> public Dictionary<string, object> GetOptionSettingsMap(Recommendation recommendation, ProjectDefinition projectDefinition, IDirectoryManager directoryManager, OptionSettingsType optionSettingsType = OptionSettingsType.All) { var projectDirectory = Path.GetDirectoryName(projectDefinition.ProjectPath); if (string.IsNullOrEmpty(projectDirectory)) { var message = $"Failed to get deployment settings container because {projectDefinition.ProjectPath} is null or empty"; throw new InvalidOperationException(message); } var settingsContainer = new Dictionary<string, object>(); IEnumerable<string> optionSettingsId; var recipeOptionSettingsId = recommendation.GetConfigurableOptionSettingItems().Select(x => x.FullyQualifiedId); var deploymentBundleOptionSettingsId = recommendation.Recipe.DeploymentBundleSettings.Select(x => x.FullyQualifiedId); switch (optionSettingsType) { case OptionSettingsType.Recipe: optionSettingsId = recipeOptionSettingsId.Except(deploymentBundleOptionSettingsId); break; case OptionSettingsType.DeploymentBundle: optionSettingsId = deploymentBundleOptionSettingsId; break; case OptionSettingsType.All: optionSettingsId = recipeOptionSettingsId.Union(deploymentBundleOptionSettingsId); break; default: throw new InvalidOperationException($"{nameof(optionSettingsType)} doest not have a valid type"); } foreach (var optionSettingId in optionSettingsId) { var optionSetting = GetOptionSetting(recommendation, optionSettingId); var value = GetOptionSettingValue(recommendation, optionSetting); if (optionSetting.TypeHint.HasValue && (optionSetting.TypeHint == OptionSettingTypeHint.FilePath || optionSetting.TypeHint == OptionSettingTypeHint.DockerExecutionDirectory)) { var path = value?.ToString(); if (string.IsNullOrEmpty(path)) { continue; } // All file paths or directory paths must be persisted relative the the customers .NET project. // This is a done to ensure that the resolved paths work correctly across all cloned repos. // The relative path is also canonicalized to work across Unix and Windows OS. var absolutePath = directoryManager.GetAbsolutePath(projectDirectory, path); value = directoryManager.GetRelativePath(projectDirectory, absolutePath) .Replace(Path.DirectorySeparatorChar, '/'); } if (value != null) { settingsContainer[optionSetting.FullyQualifiedId] = value; } } return settingsContainer; } } }
496
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.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.Extensions; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Utilities; using AWS.Deploy.DockerEngine; using AWS.Deploy.Orchestration.CDK; using AWS.Deploy.Orchestration.Data; using AWS.Deploy.Orchestration.DeploymentCommands; using AWS.Deploy.Orchestration.LocalUserSettings; using AWS.Deploy.Orchestration.ServiceHandlers; using AWS.Deploy.Orchestration.Utilities; using AWS.Deploy.Recipes; namespace AWS.Deploy.Orchestration { /// <summary> /// The Orchestrator holds all the metadata that the CLI and the AWS toolkit for Visual studio interact with to perform a deployment. /// It is responsible for generating deployment recommendations, creating deployment bundles and also acts as a mediator /// between the client UI and the CDK. /// </summary> public class Orchestrator { internal readonly ICdkProjectHandler? _cdkProjectHandler; internal readonly ICDKManager? _cdkManager; internal readonly ICDKVersionDetector? _cdkVersionDetector; internal readonly IOrchestratorInteractiveService? _interactiveService; internal readonly IAWSResourceQueryer? _awsResourceQueryer; internal readonly IDeploymentBundleHandler? _deploymentBundleHandler; internal readonly ILocalUserSettingsEngine? _localUserSettingsEngine; internal readonly IDockerEngine? _dockerEngine; internal readonly IRecipeHandler? _recipeHandler; internal readonly IFileManager? _fileManager; internal readonly IDirectoryManager? _directoryManager; internal readonly OrchestratorSession? _session; internal readonly IAWSServiceHandler? _awsServiceHandler; private readonly IOptionSettingHandler? _optionSettingHandler; internal readonly IDeployToolWorkspaceMetadata? _workspaceMetadata; public Orchestrator( OrchestratorSession session, IOrchestratorInteractiveService interactiveService, ICdkProjectHandler cdkProjectHandler, ICDKManager cdkManager, ICDKVersionDetector cdkVersionDetector, IAWSResourceQueryer awsResourceQueryer, IDeploymentBundleHandler deploymentBundleHandler, ILocalUserSettingsEngine localUserSettingsEngine, IDockerEngine dockerEngine, IRecipeHandler recipeHandler, IFileManager fileManager, IDirectoryManager directoryManager, IAWSServiceHandler awsServiceHandler, IOptionSettingHandler optionSettingHandler, IDeployToolWorkspaceMetadata deployToolWorkspaceMetadata) { _session = session; _interactiveService = interactiveService; _cdkProjectHandler = cdkProjectHandler; _cdkManager = cdkManager; _cdkVersionDetector = cdkVersionDetector; _awsResourceQueryer = awsResourceQueryer; _deploymentBundleHandler = deploymentBundleHandler; _dockerEngine = dockerEngine; _recipeHandler = recipeHandler; _localUserSettingsEngine = localUserSettingsEngine; _fileManager = fileManager; _directoryManager = directoryManager; _awsServiceHandler = awsServiceHandler; _optionSettingHandler = optionSettingHandler; _workspaceMetadata = deployToolWorkspaceMetadata; } public Orchestrator(OrchestratorSession session, IRecipeHandler recipeHandler) { _session = session; _recipeHandler = recipeHandler; } /// <summary> /// Method that generates the list of recommendations to deploy with. /// </summary> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public async Task<List<Recommendation>> GenerateDeploymentRecommendations() { if (_session == null) throw new InvalidOperationException($"{nameof(_session)} is null as part of the orchestartor object"); if (_recipeHandler == null) throw new InvalidOperationException($"{nameof(_recipeHandler)} is null as part of the orchestartor object"); var engine = new RecommendationEngine.RecommendationEngine(_session, _recipeHandler); var recipePaths = new HashSet<string> { RecipeLocator.FindRecipeDefinitionsPath() }; var customRecipePaths = await _recipeHandler.LocateCustomRecipePaths(_session.ProjectDefinition); return await engine.ComputeRecommendations(recipeDefinitionPaths: recipePaths.Union(customRecipePaths).ToList()); } /// <summary> /// Method to generate the list of recommendations to create deployment projects for. /// </summary> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public async Task<List<Recommendation>> GenerateRecommendationsToSaveDeploymentProject() { if (_session == null) throw new InvalidOperationException($"{nameof(_session)} is null as part of the orchestartor object"); if (_recipeHandler == null) throw new InvalidOperationException($"{nameof(_recipeHandler)} is null as part of the orchestartor object"); var engine = new RecommendationEngine.RecommendationEngine(_session, _recipeHandler); var compatibleRecommendations = await engine.ComputeRecommendations(); var cdkRecommendations = compatibleRecommendations.Where(x => x.Recipe.DeploymentType == DeploymentTypes.CdkProject).ToList(); return cdkRecommendations; } /// <summary> /// Include in the list of recommendations the recipe the deploymentProjectPath implements. /// </summary> /// <param name="deploymentProjectPath"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> /// <exception cref="InvalidCliArgumentException"></exception> public async Task<List<Recommendation>> GenerateRecommendationsFromSavedDeploymentProject(string deploymentProjectPath) { if (_session == null) throw new InvalidOperationException($"{nameof(_session)} is null as part of the orchestartor object"); if (_recipeHandler == null) throw new InvalidOperationException($"{nameof(_recipeHandler)} is null as part of the orchestartor object"); if (_directoryManager == null) throw new InvalidOperationException($"{nameof(_directoryManager)} is null as part of the orchestartor object"); if (!_directoryManager.Exists(deploymentProjectPath)) throw new InvalidCliArgumentException(DeployToolErrorCode.DeploymentProjectPathNotFound, $"The path '{deploymentProjectPath}' does not exists on the file system. Please provide a valid deployment project path and try again."); var engine = new RecommendationEngine.RecommendationEngine(_session, _recipeHandler); return await engine.ComputeRecommendations(recipeDefinitionPaths: new List<string> { deploymentProjectPath }); } /// <summary> /// Creates a deep copy of the recommendation object and applies the previous settings to that recommendation. /// </summary> public async Task<Recommendation> ApplyRecommendationPreviousSettings(Recommendation recommendation, IDictionary<string, object> previousSettings) { if (_optionSettingHandler == null) throw new InvalidOperationException($"{nameof(_optionSettingHandler)} is null as part of the orchestartor object"); if (_interactiveService == null) throw new InvalidOperationException($"{nameof(_interactiveService)} is null as part of the orchestrator object"); var recommendationCopy = recommendation.DeepCopy(); recommendationCopy.IsExistingCloudApplication = true; foreach (var optionSetting in recommendationCopy.Recipe.OptionSettings) { if (previousSettings.TryGetValue(optionSetting.Id, out var value)) { try { await _optionSettingHandler.SetOptionSettingValue(recommendationCopy, optionSetting, value, skipValidation: true); } catch (UnsupportedOptionSettingType ex) { _interactiveService.LogErrorMessage($"Unable to retrieve value of '{optionSetting.Name}' from previous deployment. Make sure to set it again prior to redeployment."); _interactiveService.LogDebugMessage(ex.Message); } } } return recommendationCopy; } public async Task ApplyAllReplacementTokens(Recommendation recommendation, string cloudApplicationName) { if (recommendation.ReplacementTokens.ContainsKey(Constants.RecipeIdentifier.REPLACE_TOKEN_LATEST_DOTNET_BEANSTALK_PLATFORM_ARN)) { if (_awsResourceQueryer == null) throw new InvalidOperationException($"{nameof(_awsResourceQueryer)} is null as part of the Orchestrator object"); var latestPlatform = await _awsResourceQueryer.GetLatestElasticBeanstalkPlatformArn(BeanstalkPlatformType.Linux); recommendation.AddReplacementToken(Constants.RecipeIdentifier.REPLACE_TOKEN_LATEST_DOTNET_BEANSTALK_PLATFORM_ARN, latestPlatform.PlatformArn); } if (recommendation.ReplacementTokens.ContainsKey(Constants.RecipeIdentifier.REPLACE_TOKEN_LATEST_DOTNET_WINDOWS_BEANSTALK_PLATFORM_ARN)) { if (_awsResourceQueryer == null) throw new InvalidOperationException($"{nameof(_awsResourceQueryer)} is null as part of the Orchestrator object"); var latestPlatform = await _awsResourceQueryer.GetLatestElasticBeanstalkPlatformArn(BeanstalkPlatformType.Windows); recommendation.AddReplacementToken(Constants.RecipeIdentifier.REPLACE_TOKEN_LATEST_DOTNET_WINDOWS_BEANSTALK_PLATFORM_ARN, latestPlatform.PlatformArn); } if (recommendation.ReplacementTokens.ContainsKey(Constants.RecipeIdentifier.REPLACE_TOKEN_STACK_NAME)) { // Apply the user entered stack name to the recommendation so that any default settings based on stack name are applied. recommendation.AddReplacementToken(Constants.RecipeIdentifier.REPLACE_TOKEN_STACK_NAME, cloudApplicationName); } if (recommendation.ReplacementTokens.ContainsKey(Constants.RecipeIdentifier.REPLACE_TOKEN_ECR_REPOSITORY_NAME)) { recommendation.AddReplacementToken(Constants.RecipeIdentifier.REPLACE_TOKEN_ECR_REPOSITORY_NAME, cloudApplicationName.ToLower()); } if (recommendation.ReplacementTokens.ContainsKey(Constants.RecipeIdentifier.REPLACE_TOKEN_ECR_IMAGE_TAG)) { recommendation.AddReplacementToken(Constants.RecipeIdentifier.REPLACE_TOKEN_ECR_IMAGE_TAG, DateTime.UtcNow.Ticks.ToString()); } if (recommendation.ReplacementTokens.ContainsKey(Constants.RecipeIdentifier.REPLACE_TOKEN_DOCKERFILE_PATH)) { if (_deploymentBundleHandler != null && DockerUtilities.TryGetDefaultDockerfile(recommendation, _fileManager, out var defaultDockerfilePath)) { recommendation.AddReplacementToken(Constants.RecipeIdentifier.REPLACE_TOKEN_DOCKERFILE_PATH, defaultDockerfilePath); } } if (recommendation.ReplacementTokens.ContainsKey(Constants.RecipeIdentifier.REPLACE_TOKEN_DEFAULT_VPC_ID)) { if (_awsResourceQueryer == null) throw new InvalidOperationException($"{nameof(_awsResourceQueryer)} is null as part of the Orchestrator object"); var defaultVPC = await _awsResourceQueryer.GetDefaultVpc(); recommendation.AddReplacementToken(Constants.RecipeIdentifier.REPLACE_TOKEN_DEFAULT_VPC_ID, defaultVPC?.VpcId ?? string.Empty); } if (recommendation.ReplacementTokens.ContainsKey(Constants.RecipeIdentifier.REPLACE_TOKEN_HAS_DEFAULT_VPC)) { if (_awsResourceQueryer == null) throw new InvalidOperationException($"{nameof(_awsResourceQueryer)} is null as part of the Orchestrator object"); var defaultVPC = await _awsResourceQueryer.GetDefaultVpc(); recommendation.AddReplacementToken(Constants.RecipeIdentifier.REPLACE_TOKEN_HAS_DEFAULT_VPC, defaultVPC != null); } if (recommendation.ReplacementTokens.ContainsKey(Constants.RecipeIdentifier.REPLACE_TOKEN_HAS_NOT_VPCS)) { if (_awsResourceQueryer == null) throw new InvalidOperationException($"{nameof(_awsResourceQueryer)} is null as part of the Orchestrator object"); var vpcs = await _awsResourceQueryer.GetListOfVpcs(); recommendation.AddReplacementToken(Constants.RecipeIdentifier.REPLACE_TOKEN_HAS_NOT_VPCS, !vpcs.Any()); } } public async Task DeployRecommendation(CloudApplication cloudApplication, Recommendation recommendation) { var deploymentCommand = DeploymentCommandFactory.BuildDeploymentCommand(recommendation.Recipe.DeploymentType); await deploymentCommand.ExecuteAsync(this, cloudApplication, recommendation); } public async Task CreateDeploymentBundle(CloudApplication cloudApplication, Recommendation recommendation) { if (_interactiveService == null) throw new InvalidOperationException($"{nameof(_interactiveService)} is null as part of the orchestrator object"); if (recommendation.Recipe.DeploymentBundle == DeploymentBundleTypes.Container) { _interactiveService.LogSectionStart("Creating deployment image", "Using the docker CLI to perform a docker build to create a container image."); try { await CreateContainerDeploymentBundle(cloudApplication, recommendation); } catch (DeployToolException ex) { throw new FailedToCreateDeploymentBundleException(ex.ErrorCode, ex.Message, ex.ProcessExitCode, ex); } } else if (recommendation.Recipe.DeploymentBundle == DeploymentBundleTypes.DotnetPublishZipFile) { _interactiveService.LogSectionStart("Creating deployment zip bundle", "Using the dotnet CLI build the project and zip the publish artifacts."); try { await CreateDotnetPublishDeploymentBundle(recommendation); } catch (DeployToolException ex) { throw new FailedToCreateDeploymentBundleException(ex.ErrorCode, ex.Message, ex.ProcessExitCode, ex); } } } private async Task CreateContainerDeploymentBundle(CloudApplication cloudApplication, Recommendation recommendation) { if (_interactiveService == null) throw new InvalidOperationException($"{nameof(_interactiveService)} is null as part of the orchestartor object"); if (_dockerEngine == null) throw new InvalidOperationException($"{nameof(_dockerEngine)} is null as part of the orchestartor object"); if (_deploymentBundleHandler == null) throw new InvalidOperationException($"{nameof(_deploymentBundleHandler)} is null as part of the orchestrator object"); if (_optionSettingHandler == null) throw new InvalidOperationException($"{nameof(_optionSettingHandler)} is null as part of the orchestrator object"); if (_fileManager == null) throw new InvalidOperationException($"{nameof(_fileManager)} is null as part of the orchestrator object"); if (!DockerUtilities.TryGetDockerfile(recommendation, _fileManager, out _)) { _interactiveService.LogInfoMessage("Generating Dockerfile..."); try { _dockerEngine.GenerateDockerFile(); } catch (DockerEngineExceptionBase ex) { var errorMessage = "Failed to generate a docker file due to the following error:" + Environment.NewLine + ex.Message; throw new FailedToGenerateDockerFileException(DeployToolErrorCode.FailedToGenerateDockerFile, errorMessage, ex); } } _dockerEngine.DetermineDockerExecutionDirectory(recommendation); // Read this from the OptionSetting instead of recommendation.DeploymentBundle. // When its value comes from a replacement token, it wouldn't have been set back to the DeploymentBundle var respositoryName = _optionSettingHandler.GetOptionSettingValue<string>(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, Constants.Docker.ECRRepositoryNameOptionId)); if (respositoryName == null) throw new InvalidECRRepositoryNameException(DeployToolErrorCode.ECRRepositoryNameIsNull, "The ECR Repository Name is null."); string imageTag; try { var tagSuffix = _optionSettingHandler.GetOptionSettingValue<string>(recommendation, _optionSettingHandler.GetOptionSetting(recommendation, Constants.Docker.ImageTagOptionId)); imageTag = $"{respositoryName}:{tagSuffix}"; } catch (OptionSettingItemDoesNotExistException) { imageTag = $"{respositoryName}:{DateTime.UtcNow.Ticks}"; } await _deploymentBundleHandler.BuildDockerImage(cloudApplication, recommendation, imageTag); // These option settings need to be persisted back as they are not always provided by the user and we have custom logic to determine their values await _optionSettingHandler.SetOptionSettingValue(recommendation, Constants.Docker.DockerExecutionDirectoryOptionId, recommendation.DeploymentBundle.DockerExecutionDirectory); await _optionSettingHandler.SetOptionSettingValue(recommendation, Constants.Docker.DockerfileOptionId, recommendation.DeploymentBundle.DockerfilePath); _interactiveService.LogSectionStart("Pushing container image to Elastic Container Registry (ECR)", "Using the docker CLI to log on to ECR and push the local image to ECR."); await _deploymentBundleHandler.PushDockerImageToECR(recommendation, respositoryName, imageTag); } private async Task CreateDotnetPublishDeploymentBundle(Recommendation recommendation) { if (_deploymentBundleHandler == null) throw new InvalidOperationException($"{nameof(_deploymentBundleHandler)} is null as part of the orchestartor object"); if (_interactiveService == null) throw new InvalidOperationException($"{nameof(_interactiveService)} is null as part of the orchestartor object"); await _deploymentBundleHandler.CreateDotnetPublishZip(recommendation); } public CloudApplicationResourceType GetCloudApplicationResourceType(DeploymentTypes deploymentType) { switch (deploymentType) { case DeploymentTypes.CdkProject: return CloudApplicationResourceType.CloudFormationStack; case DeploymentTypes.BeanstalkEnvironment: return CloudApplicationResourceType.BeanstalkEnvironment; case DeploymentTypes.ElasticContainerRegistryImage: return CloudApplicationResourceType.ElasticContainerRegistryImage; default: var errorMessage = $"Failed to find ${nameof(CloudApplicationResourceType)} from {nameof(DeploymentTypes)} {deploymentType}"; throw new FailedToFindCloudApplicationResourceType(DeployToolErrorCode.FailedToFindCloudApplicationResourceType, errorMessage); } } } }
368
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; using Amazon.Runtime; using AWS.Deploy.Common; using AWS.Deploy.Common.Recipes.Validation; namespace AWS.Deploy.Orchestration { /// <summary> /// The Orchestrator session holds the relevant metadata about the project that needs to be deployed /// and also contains information about the AWS account and region used for deployment. /// </summary> public class OrchestratorSession : IDeployToolValidationContext { public ProjectDefinition ProjectDefinition { get; set; } public string? AWSProfileName { get; set; } public AWSCredentials? AWSCredentials { get; set; } public string? AWSRegion { get; set; } public string? AWSAccountId { get; set; } public OrchestratorSession( ProjectDefinition projectDefinition, AWSCredentials awsCredentials, string awsRegion, string awsAccountId) { ProjectDefinition = projectDefinition; AWSCredentials = awsCredentials; AWSRegion = awsRegion; AWSAccountId = awsAccountId; } public OrchestratorSession(ProjectDefinition projectDefinition) { ProjectDefinition = projectDefinition; } } }
41
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 System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.DeploymentManifest; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Common.Recipes.Validation; using AWS.Deploy.Recipes; using Newtonsoft.Json; namespace AWS.Deploy.Orchestration { public class RecipeHandler : IRecipeHandler { private readonly string _ignorePathSubstring = Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar; private readonly IOrchestratorInteractiveService _orchestratorInteractiveService; private readonly IDeploymentManifestEngine _deploymentManifestEngine; private readonly IDirectoryManager _directoryManager; private readonly IFileManager _fileManager; private readonly IOptionSettingHandler _optionSettingHandler; private readonly IValidatorFactory _validatorFactory; public RecipeHandler(IDeploymentManifestEngine deploymentManifestEngine, IOrchestratorInteractiveService orchestratorInteractiveService, IDirectoryManager directoryManager, IFileManager fileManager, IOptionSettingHandler optionSettingHandler, IValidatorFactory validatorFactory) { _orchestratorInteractiveService = orchestratorInteractiveService; _deploymentManifestEngine = deploymentManifestEngine; _directoryManager = directoryManager; _fileManager = fileManager; _optionSettingHandler = optionSettingHandler; _validatorFactory = validatorFactory; } public async Task<List<RecipeDefinition>> GetRecipeDefinitions(List<string>? recipeDefinitionPaths = null) { recipeDefinitionPaths ??= new List<string> { RecipeLocator.FindRecipeDefinitionsPath() }; var recipeDefinitions = new List<RecipeDefinition>(); var uniqueRecipeId = new HashSet<string>(); try { foreach(var recipeDefinitionsPath in recipeDefinitionPaths) { foreach (var recipeDefinitionFile in _directoryManager.GetFiles(recipeDefinitionsPath, "*.recipe", SearchOption.TopDirectoryOnly)) { try { var content = await _fileManager.ReadAllTextAsync(recipeDefinitionFile); var definition = JsonConvert.DeserializeObject<RecipeDefinition>(content); if (definition == null) throw new FailedToDeserializeException(DeployToolErrorCode.FailedToDeserializeRecipe, $"Failed to Deserialize Recipe Definition [{recipeDefinitionFile}]"); definition.RecipePath = recipeDefinitionFile; if (!uniqueRecipeId.Contains(definition.Id)) { definition.DeploymentBundleSettings = GetDeploymentBundleSettings(definition.DeploymentBundle); definition.OptionSettings.AddRange(definition.DeploymentBundleSettings); var dependencyTree = new Dictionary<string, List<string>>(); BuildDependencyTree(definition, definition.OptionSettings, dependencyTree); foreach (var dependee in dependencyTree.Keys) { var optionSetting = _optionSettingHandler.GetOptionSetting(definition, dependee); optionSetting.Dependents = dependencyTree[dependee]; } recipeDefinitions.Add(definition); uniqueRecipeId.Add(definition.Id); } } catch (Exception e) { throw new FailedToDeserializeException(DeployToolErrorCode.FailedToDeserializeRecipe, $"Failed to Deserialize Recipe Definition [{recipeDefinitionFile}]: {e.Message}", e); } } } } catch(IOException) { throw new NoRecipeDefinitionsFoundException(DeployToolErrorCode.FailedToFindRecipeDefinitions, "Failed to find recipe definitions"); } return recipeDefinitions; } private List<OptionSettingItem> GetDeploymentBundleSettings(DeploymentBundleTypes deploymentBundleTypes) { var deploymentBundleDefinitionsPath = DeploymentBundleDefinitionLocator.FindDeploymentBundleDefinitionPath(); try { foreach (var deploymentBundleFile in Directory.GetFiles(deploymentBundleDefinitionsPath, "*.deploymentbundle", SearchOption.TopDirectoryOnly)) { try { var content = File.ReadAllText(deploymentBundleFile); var definition = JsonConvert.DeserializeObject<DeploymentBundleDefinition>(content); if (definition == null) throw new FailedToDeserializeException(DeployToolErrorCode.FailedToDeserializeDeploymentBundle, $"Failed to Deserialize Deployment Bundle [{deploymentBundleFile}]"); if (definition.Type.Equals(deploymentBundleTypes)) { // Assign Build category to all of the deployment bundle settings. foreach (var setting in definition.Parameters) { setting.Category = Category.DeploymentBundle.Id; } return definition.Parameters; } } catch (Exception e) { throw new FailedToDeserializeException(DeployToolErrorCode.FailedToDeserializeDeploymentBundle, $"Failed to Deserialize Deployment Bundle [{deploymentBundleFile}]: {e.Message}", e); } } } catch (IOException) { throw new NoDeploymentBundleDefinitionsFoundException(DeployToolErrorCode.DeploymentBundleDefinitionNotFound, "Failed to find a deployment bundle definition"); } throw new NoDeploymentBundleDefinitionsFoundException(DeployToolErrorCode.DeploymentBundleDefinitionNotFound, "Failed to find a deployment bundle definition"); } /// <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> /// <param name="projectDefinition">The <see cref="ProjectDefinition"/> of the application to be deployed.</param> /// <returns>A <see cref="HashSet{String}"/> containing absolute paths of directories inside which the custom recipe snapshot is stored</returns> public async Task<HashSet<string>> LocateCustomRecipePaths(ProjectDefinition projectDefinition) { var targetApplicationFullPath = new DirectoryInfo(projectDefinition.ProjectPath).FullName; var solutionDirectoryPath = !string.IsNullOrEmpty(projectDefinition.ProjectSolutionPath) ? new DirectoryInfo(projectDefinition.ProjectSolutionPath).Parent?.FullName ?? string.Empty : string.Empty; return await LocateCustomRecipePaths(targetApplicationFullPath, solutionDirectoryPath); } /// <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> /// <param name="targetApplicationFullPath">The absolute path to the csproj or fsproj file of the target application</param> /// <param name="solutionDirectoryPath">The absolute path of the directory which contains the solution file for the target application</param> /// <returns>A <see cref="HashSet{String}"/> containing absolute paths of directories inside which the custom recipe snapshot is stored</returns> public async Task<HashSet<string>> LocateCustomRecipePaths(string targetApplicationFullPath, string solutionDirectoryPath) { var customRecipePaths = new HashSet<string>(); foreach (var recipePath in await LocateRecipePathsFromManifestFile(targetApplicationFullPath)) { if (ContainsRecipeFile(recipePath)) { _orchestratorInteractiveService.LogInfoMessage($"Found custom recipe file at: {recipePath}"); customRecipePaths.Add(recipePath); } } foreach (var recipePath in LocateAlternateRecipePaths(targetApplicationFullPath, solutionDirectoryPath)) { if (ContainsRecipeFile(recipePath)) { _orchestratorInteractiveService.LogInfoMessage($"Found custom recipe file at: {recipePath}"); customRecipePaths.Add(recipePath); } } return customRecipePaths; } /// <summary> /// Runs the recipe level validators and returns a list of failed validations /// </summary> public List<ValidationResult> RunRecipeValidators(Recommendation recommendation, IDeployToolValidationContext deployToolValidationContext) { var validatorFailedResults = _validatorFactory.BuildValidators(recommendation.Recipe) .Select(async validator => await validator.Validate(recommendation, deployToolValidationContext)) .Select(x => x.Result) .Where(x => !x.IsValid) .ToList(); return validatorFailedResults; } /// <summary> /// Fetches recipe definition paths by parsing the deployment-manifest file that is associated with the target application. /// </summary> /// <param name="targetApplicationFullPath">The absolute path to the target application csproj or fsproj file</param> /// <returns>A list containing absolute paths to the saved CDK deployment projects</returns> private async Task<List<string>> LocateRecipePathsFromManifestFile(string targetApplicationFullPath) { try { return await _deploymentManifestEngine.GetRecipeDefinitionPaths(targetApplicationFullPath); } catch { _orchestratorInteractiveService.LogErrorMessage(Environment.NewLine); _orchestratorInteractiveService.LogErrorMessage("Failed to load custom deployment recommendations " + "from the deployment-manifest file due to an error while trying to deserialze the file."); return await Task.FromResult(new List<string>()); } } /// <summary> /// Fetches custom recipe paths from other locations that are monitored by the same source control root as the target application that needs to be deployed. /// If the target application is not under source control, then it scans the sub-directories of the solution folder for custom recipes. /// If source control root directory is equal to the file system root, then it scans the sub-directories of the solution folder for custom recipes. /// </summary> /// <param name="targetApplicationFullPath">The absolute path to the target application csproj or fsproj file</param> /// <param name="solutionDirectoryPath">The absolute path of the directory which contains the solution file for the target application</param> /// <returns>A list of recipe definition paths.</returns> private List<string> LocateAlternateRecipePaths(string targetApplicationFullPath, string solutionDirectoryPath) { var targetApplicationDirectoryPath = _directoryManager.GetDirectoryInfo(targetApplicationFullPath).Parent?.FullName ?? string.Empty; var fileSystemRootPath = _directoryManager.GetDirectoryInfo(targetApplicationDirectoryPath).Root.FullName; var rootDirectoryPath = GetSourceControlRootDirectory(targetApplicationDirectoryPath); if (string.IsNullOrEmpty(rootDirectoryPath) || string.Equals(rootDirectoryPath, fileSystemRootPath)) rootDirectoryPath = solutionDirectoryPath; return GetRecipePathsFromRootDirectory(rootDirectoryPath); } /// <summary> /// This method takes a root directory path and recursively searches all its sub-directories for custom recipe paths. /// However, it ignores any recipe file located inside a "bin" folder. /// </summary> /// <param name="rootDirectoryPath">The absolute path of the root directory.</param> /// <returns>A list of recipe definition paths.</returns> private List<string> GetRecipePathsFromRootDirectory(string? rootDirectoryPath) { var recipePaths = new List<string>(); if (!string.IsNullOrEmpty(rootDirectoryPath) && _directoryManager.Exists(rootDirectoryPath)) { var recipePathList = new List<string>(); try { recipePathList = _directoryManager.GetFiles(rootDirectoryPath, "*.recipe", SearchOption.AllDirectories).ToList(); } catch (Exception e) { _orchestratorInteractiveService.LogInfoMessage($"Failed to find custom recipe paths starting from {rootDirectoryPath}. Encountered the following exception: {e.GetType()}"); } foreach (var recipeFilePath in recipePathList) { if (recipeFilePath.Contains(_ignorePathSubstring)) continue; var directoryParent = _directoryManager.GetDirectoryInfo(recipeFilePath).Parent?.FullName; if (string.IsNullOrEmpty(directoryParent)) continue; recipePaths.Add(directoryParent); } } return recipePaths; } /// <summary> /// Helper method to find the source control root directory of the current directory path. /// If the current directory is not monitored by any source control system, then it returns string.Empty /// </summary> /// <param name="directoryPath">An absolute directory path.</param> /// <returns> First parent directory path that contains a ".git" folder or string.Empty if cannot find any</returns> private string GetSourceControlRootDirectory(string? directoryPath) { var currentDir = directoryPath; while (currentDir != null) { if (_directoryManager.GetDirectories(currentDir, ".git").Any()) { var sourceControlRootDirectory = _directoryManager.GetDirectoryInfo(currentDir).FullName; _orchestratorInteractiveService.LogDebugMessage($"Source control root directory found at: {sourceControlRootDirectory}"); return sourceControlRootDirectory; } currentDir = _directoryManager.GetDirectoryInfo(currentDir).Parent?.FullName; } _orchestratorInteractiveService.LogDebugMessage($"Could not find any source control root directory"); return string.Empty; } /// <summary> /// This method determines if the given directory contains any recipe files /// </summary> /// <param name="directoryPath">The path of the directory that needs to be validated</param> /// <returns>A bool indicating the presence of a recipe file inside the directory.</returns> private bool ContainsRecipeFile(string directoryPath) { var directoryName = _directoryManager.GetDirectoryInfo(directoryPath).Name; var recipeFilePaths = _directoryManager.GetFiles(directoryPath, "*.recipe"); if (!recipeFilePaths.Any()) { return false; } return recipeFilePaths.All(filePath => Path.GetFileNameWithoutExtension(filePath).Equals(directoryName, StringComparison.Ordinal)); } /// Creates an option setting item dependency tree that indicates /// which option setting items need to be validated if a value update occurs. /// The function recursively goes through all the settings and their children to build this tree. /// This method also creates a Fully Qualified Id which will help reference <see cref="OptionSettingItem"/>. /// </summary> private void BuildDependencyTree(RecipeDefinition recipe, List<OptionSettingItem> optionSettingItems, Dictionary<string, List<string>> dependencyTree, string parentFullyQualifiedId = "") { foreach (var optionSettingItem in optionSettingItems) { optionSettingItem.FullyQualifiedId = string.IsNullOrEmpty(parentFullyQualifiedId) ? optionSettingItem.Id : $"{parentFullyQualifiedId}.{optionSettingItem.Id}"; optionSettingItem.ParentId = parentFullyQualifiedId; foreach (var dependency in optionSettingItem.DependsOn) { if (dependencyTree.ContainsKey(dependency.Id)) { dependencyTree[dependency.Id].Add(optionSettingItem.FullyQualifiedId); } else { dependencyTree[dependency.Id] = new List<string> { optionSettingItem.FullyQualifiedId }; } } BuildDependencyTree(recipe, optionSettingItem.ChildOptionSettings, dependencyTree, optionSettingItem.FullyQualifiedId); } } } }
336
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; namespace AWS.Deploy.Orchestration { /// <summary> /// This enum controls which settings are persisted when <see cref="DeploymentSettingsHandler.SaveSettings(SaveSettingsConfiguration, Recommendation, CloudApplication, OrchestratorSession)"/> is invoked /// </summary> public enum SaveSettingsType { None, Modified, All } public class SaveSettingsConfiguration { /// <summary> /// Specifies which settings are persisted when <see cref="DeploymentSettingsHandler.SaveSettings(SaveSettingsConfiguration, Recommendation, CloudApplication, OrchestratorSession)"/> is invoked /// </summary> public readonly SaveSettingsType SettingsType; /// <summary> /// The absolute file path where deployment settings will be persisted /// </summary> public readonly string FilePath; public SaveSettingsConfiguration(SaveSettingsType settingsType, string filePath) { SettingsType = settingsType; FilePath = filePath; } } }
37
aws-dotnet-deploy
aws
C#
using System; namespace AWS.Deploy.Orchestration { public class SystemCapabilities { public Version? NodeJsVersion { get; set; } public DockerInfo DockerInfo { get; set; } public SystemCapabilities( Version? nodeJsVersion, DockerInfo dockerInfo) { NodeJsVersion = nodeJsVersion; DockerInfo = dockerInfo; } } public class DockerInfo { public bool DockerInstalled { get; set; } public string DockerContainerType { get; set; } public DockerInfo( bool dockerInstalled, string dockerContainerType) { DockerInstalled = dockerInstalled; DockerContainerType = dockerContainerType.Trim(); } } public class SystemCapability { public readonly string Name; public readonly string Message; public readonly string? InstallationUrl; public SystemCapability(string name, string message, string? installationUrl = null) { Name = name; Message = message; InstallationUrl = installationUrl; } public string GetMessage() { return string.IsNullOrEmpty(InstallationUrl) ? Message : $"{Message}{Environment.NewLine}You can install the missing {Name} dependency from: {InstallationUrl}"; } } }
54
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.Runtime.InteropServices; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Orchestration.Utilities; namespace AWS.Deploy.Orchestration { public interface ISystemCapabilityEvaluator { Task<List<SystemCapability>> EvaluateSystemCapabilities(Recommendation selectedRecommendation); } public class SystemCapabilityEvaluator : ISystemCapabilityEvaluator { private const string NODEJS_DEPENDENCY_NAME = "Node.js"; private const string NODEJS_INSTALLATION_URL = "https://nodejs.org/en/download/"; private const string DOCKER_DEPENDENCY_NAME = "Docker"; private const string DOCKER_INSTALLATION_URL = "https://docs.docker.com/engine/install/"; private readonly ICommandLineWrapper _commandLineWrapper; private static readonly Version MinimumNodeJSVersion = new Version(14,17,0); public SystemCapabilityEvaluator(ICommandLineWrapper commandLineWrapper) { _commandLineWrapper = commandLineWrapper; } public async Task<SystemCapabilities> Evaluate() { var dockerTask = HasDockerInstalledAndRunning(); var nodeTask = GetNodeJsVersion(); var capabilities = new SystemCapabilities(await nodeTask, await dockerTask); return capabilities; } private async Task<DockerInfo> HasDockerInstalledAndRunning() { var processExitCode = -1; var containerType = ""; var command = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "docker info -f \"{{.OSType}}\"" : "docker info"; await _commandLineWrapper.Run( command, streamOutputToInteractiveService: false, onComplete: proc => { processExitCode = proc.ExitCode; containerType = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? proc.StandardOut?.TrimEnd('\n') ?? throw new DockerInfoException(DeployToolErrorCode.FailedToCheckDockerInfo, "Failed to check if Docker is running in Windows or Linux container mode.") : "linux"; }); var dockerInfo = new DockerInfo(processExitCode == 0, containerType); return dockerInfo; } /// <summary> /// From https://docs.aws.amazon.com/cdk/latest/guide/work-with.html#work-with-prerequisites, /// min version is 10.3 /// </summary> private async Task<Version?> GetNodeJsVersion() { // run node --version to get the version var result = await _commandLineWrapper.TryRunWithResult("node --version"); var versionString = result.StandardOut ?? ""; if (versionString.StartsWith("v", StringComparison.OrdinalIgnoreCase)) versionString = versionString.Substring(1, versionString.Length - 1); if (!result.Success || !Version.TryParse(versionString, out var version)) return null; return version; } /// <summary> /// Checks if the system meets all the necessary requirements for deployment. /// </summary> public async Task<List<SystemCapability>> EvaluateSystemCapabilities(Recommendation selectedRecommendation) { var capabilities = new List<SystemCapability>(); var systemCapabilities = await Evaluate(); string? message; if (selectedRecommendation.Recipe.DeploymentType == DeploymentTypes.CdkProject) { if (systemCapabilities.NodeJsVersion == null) { message = $"Install Node.js {MinimumNodeJSVersion} or later and restart your IDE/Shell. The latest Node.js LTS version is recommended. This deployment option uses the AWS CDK, which requires Node.js."; capabilities.Add(new SystemCapability(NODEJS_DEPENDENCY_NAME, message, NODEJS_INSTALLATION_URL)); } else if (systemCapabilities.NodeJsVersion < MinimumNodeJSVersion) { message = $"Install Node.js {MinimumNodeJSVersion} or later and restart your IDE/Shell. The latest Node.js LTS version is recommended. This deployment option uses the AWS CDK, which requires Node.js version higher than your current installation ({systemCapabilities.NodeJsVersion}). "; capabilities.Add(new SystemCapability(NODEJS_DEPENDENCY_NAME, message, NODEJS_INSTALLATION_URL)); } } if (selectedRecommendation.Recipe.DeploymentBundle == DeploymentBundleTypes.Container) { if (!systemCapabilities.DockerInfo.DockerInstalled) { message = "Install and start Docker version appropriate for your OS. This deployment option requires Docker, which was not detected."; capabilities.Add(new SystemCapability(DOCKER_DEPENDENCY_NAME, message, DOCKER_INSTALLATION_URL)); } else if (!systemCapabilities.DockerInfo.DockerContainerType.Equals("linux", StringComparison.OrdinalIgnoreCase)) { message = "This is Linux-based deployment. Switch your Docker from Windows to Linux container mode."; capabilities.Add(new SystemCapability(DOCKER_DEPENDENCY_NAME, message)); } } return capabilities; } } }
132
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.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using AWS.Deploy.Common; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Edge; using Microsoft.TemplateEngine.Edge.Template; using Microsoft.TemplateEngine.IDE; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects; using Microsoft.TemplateEngine.Utils; namespace AWS.Deploy.Orchestration { public class TemplateEngine { private const string HostIdentifier = "aws-net-deploy-template-generator"; private const string HostVersion = "v1.0.0"; private readonly Bootstrapper _bootstrapper; private static readonly object s_locker = new(); public TemplateEngine() { _bootstrapper = new Bootstrapper(CreateHost(), null, virtualizeConfiguration: true); } public void GenerateCDKProjectFromTemplate(Recommendation recommendation, OrchestratorSession session, string outputDirectory, string assemblyName) { if (string.IsNullOrEmpty(recommendation.Recipe.CdkProjectTemplate)) { throw new InvalidOperationException($"{nameof(recommendation.Recipe.CdkProjectTemplate)} cannot be null or an empty string"); } if (string.IsNullOrEmpty(recommendation.Recipe.CdkProjectTemplateId)) { throw new InvalidOperationException($"{nameof(recommendation.Recipe.CdkProjectTemplateId)} cannot be null or an empty string"); } //The location of the base template that will be installed into the templating engine var cdkProjectTemplateDirectory = Path.Combine( Path.GetDirectoryName(recommendation.Recipe.RecipePath) ?? throw new InvalidRecipePathException(DeployToolErrorCode.BaseTemplatesInvalidPath, $"The following RecipePath is invalid as we could not retrieve the parent directory: {recommendation.Recipe.RecipePath}"), recommendation.Recipe.CdkProjectTemplate); //Installing the base template into the templating engine to make it available for generation InstallTemplates(cdkProjectTemplateDirectory); //Looking up the installed template in the templating engine var template = _bootstrapper .ListTemplates( true, WellKnownSearchFilters.NameFilter(recommendation.Recipe.CdkProjectTemplateId)) .FirstOrDefault() ?.Info; //If the template is not found, throw an exception if (template == null) throw new Exception($"Failed to find a Template for [{recommendation.Recipe.CdkProjectTemplateId}]"); var templateParameters = new Dictionary<string, string> { // CDK Template projects can parameterize the version number of the AWS.Deploy.Recipes.CDK.Common package. This avoid // projects having to be modified every time the package version is bumped. { "AWSDeployRecipesCDKCommonVersion", FileVersionInfo.GetVersionInfo(typeof(Constants.CloudFormationIdentifier).Assembly.Location).ProductVersion ?? throw new InvalidAWSDeployRecipesCDKCommonVersionException(DeployToolErrorCode.InvalidAWSDeployRecipesCDKCommonVersion, "The version number of the AWS.Deploy.Recipes.CDK.Common package is invalid.") } }; try { lock (s_locker) { //Generate the CDK project using the installed template into the output directory _bootstrapper.CreateAsync(template, assemblyName, outputDirectory, templateParameters, false, "").GetAwaiter().GetResult(); } } catch { throw new TemplateGenerationFailedException(DeployToolErrorCode.FailedToGenerateCDKProjectFromTemplate, "Failed to generate CDK project from template"); } } private void InstallTemplates(string folderLocation) { try { lock (s_locker) { _bootstrapper.Install(folderLocation); } } catch(Exception e) { throw new DefaultTemplateInstallationFailedException(DeployToolErrorCode.FailedToInstallProjectTemplates, "Failed to install the default template that is required to the generate the CDK project", e); } } private ITemplateEngineHost CreateHost() { var preferences = new Dictionary<string, string> { { "prefs:language", "C#" } }; var builtIns = new AssemblyComponentCatalog(new[] { typeof(RunnableProjectGenerator).GetTypeInfo().Assembly, // for assembly: Microsoft.TemplateEngine.Orchestrator.RunnableProjects typeof(AssemblyComponentCatalog).GetTypeInfo().Assembly, // for assembly: Microsoft.TemplateEngine.Edge }); ITemplateEngineHost host = new DefaultTemplateEngineHost(HostIdentifier, HostVersion, CultureInfo.CurrentCulture.Name, preferences, builtIns, null); return host; } } }
122
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.Linq; using System.Text; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using AWS.Deploy.Orchestration.Utilities; namespace AWS.Deploy.Orchestration.CDK { /// <summary> /// Abstracts low level node package manager commands to list and install CDK CLI /// in high level APIs. /// </summary> public interface ICDKInstaller { /// <summary> /// Gets CDK CLI version installed <see cref="workingDirectory"/> using npx command. /// It checks for local as well as global version /// </summary> /// <param name="workingDirectory">Directory for local node app.</param> /// <returns><see cref="Version"/> object wrapped in <see cref="TryGetResult{TResult}"/></returns> Task<TryGetResult<Version>> GetVersion(string workingDirectory); /// <summary> /// Installs local version of the AWS SDK CLI in the given working directory /// </summary> /// <param name="workingDirectory">Directory for local node app.</param> /// <param name="version">CDK CLI version to update</param> Task Install(string workingDirectory, Version version); } public class CDKInstaller : ICDKInstaller { private readonly ICommandLineWrapper _commandLineWrapper; private readonly IDirectoryManager _directoryManager; public CDKInstaller(ICommandLineWrapper commandLineWrapper, IDirectoryManager directoryManager) { _commandLineWrapper = commandLineWrapper; _directoryManager = directoryManager; } public async Task<TryGetResult<Version>> GetVersion(string workingDirectory) { const string command = "npx --no-install cdk --version"; if (!_directoryManager.Exists(workingDirectory)) _directoryManager.CreateDirectory(workingDirectory); TryRunResult result; try { result = await _commandLineWrapper.TryRunWithResult(command, workingDirectory, false); } catch (Exception exception) { throw new NPMCommandFailedException(DeployToolErrorCode.FailedToGetCDKVersion, $"Failed to execute {command}", exception); } var standardOut = result.StandardOut ?? ""; var lines = standardOut.Split(Environment.NewLine).Where(line => !string.IsNullOrWhiteSpace(line)).ToArray(); if (lines.Length < 1) { return TryGetResult.Failure<Version>(); } var versionLine = lines.Last(); /* * Split the last line which has the version * typical version line: 1.127.0 (build 0ea309a) * * part 0: 1.127.0 * part 1: build * part 2: 0ea309a * * It could be possible we have more than 3 parts with more information but they can be ignored. */ var parts = versionLine.Split(' ', '(', ')').Where(part => !string.IsNullOrWhiteSpace(part)).ToArray(); if (parts.Length < 3) { return TryGetResult.Failure<Version>(); } if (Version.TryParse(parts[0], out var version)) { return TryGetResult.FromResult(version); } return TryGetResult.Failure<Version>(); } public async Task Install(string workingDirectory, Version version) { await _commandLineWrapper.Run($"npm install aws-cdk@{version}", workingDirectory, false); } } }
104
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.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using AWS.Deploy.Common.Extensions; using AWS.Deploy.Orchestration.Utilities; namespace AWS.Deploy.Orchestration.CDK { /// <summary> /// Makes sure that a compatible version of CDK CLI is installed either in the global node_modules /// or local node_modules. /// </summary> public interface ICDKManager { /// <summary> /// Detects whether CDK CLI is installed or not in global node_modules. /// If global node_modules don't contain, it checks in local node_modules /// If local npm package isn't initialized, it initializes a npm package at <see cref="workingDirectory"/>. /// If local node_modules don't contain, it installs CDK CLI version <see cref="cdkVersion"/> in local modules. /// </summary> /// <param name="workingDirectory">Directory used for local node app</param> /// <param name="cdkVersion">Version of CDK CLI</param> Task EnsureCompatibleCDKExists(string workingDirectory, Version cdkVersion); } public class CDKManager : ICDKManager { private static readonly SemaphoreSlim s_cdkManagerSemaphoreSlim = new(1,1); private readonly ICDKInstaller _cdkInstaller; private readonly INPMPackageInitializer _npmPackageInitializer; private readonly IOrchestratorInteractiveService _interactiveService; public CDKManager(ICDKInstaller cdkInstaller, INPMPackageInitializer npmPackageInitializer, IOrchestratorInteractiveService interactiveService) { _cdkInstaller = cdkInstaller; _npmPackageInitializer = npmPackageInitializer; _interactiveService = interactiveService; } public async Task EnsureCompatibleCDKExists(string workingDirectory, Version cdkVersion) { await s_cdkManagerSemaphoreSlim.WaitAsync(); try { var installedCdkVersion = await _cdkInstaller.GetVersion(workingDirectory); if (installedCdkVersion.Success && installedCdkVersion.Result?.CompareTo(cdkVersion) >= 0) { _interactiveService.LogDebugMessage($"CDK version {installedCdkVersion.Result} found in global node_modules."); return; } var isNPMPackageInitialized = _npmPackageInitializer.IsInitialized(workingDirectory); if (!isNPMPackageInitialized) { await _npmPackageInitializer.Initialize(workingDirectory, cdkVersion); return; // There is no need to install CDK CLI explicitly, npm install takes care of first time bootstrap. } await _cdkInstaller.Install(workingDirectory, cdkVersion); } finally { s_cdkManagerSemaphoreSlim.Release(); } } } }
75
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.IO; using System.Linq; using System.Xml.Linq; namespace AWS.Deploy.Orchestration.CDK { /// <summary> /// Detects the CDK version by parsing the csproj files /// </summary> public interface ICDKVersionDetector { /// <summary> /// Parses the given csproj file and returns the highest version among Amazon.CDK.* dependencies. /// </summary> /// <param name="csprojPath">C# project file path.</param> /// <returns>Highest version among Amazon.CDK.* dependencies.</returns> Version Detect(string csprojPath); /// <summary> /// This is convenience method that uses <see cref="Detect(string)"/> method to detect highest version among Amazon.CDK.* dependencies /// in all the csproj files /// </summary> /// <param name="csprojPaths">C# project file paths.</param> /// <returns>Highest version among Amazon.CDK.* dependencies in all <param name="csprojPaths"></param>.</returns> Version Detect(IEnumerable<string> csprojPaths); } public class CDKVersionDetector : ICDKVersionDetector { private const string AMAZON_CDK_PACKAGE_REFERENCE_PREFIX = "Amazon.CDK"; public Version Detect(string csprojPath) { var content = File.ReadAllText(csprojPath); var document = XDocument.Parse(content); var cdkVersion = Constants.CDK.DefaultCDKVersion; foreach (var node in document.DescendantNodes()) { if (node is not XElement element || element.Name.ToString() != "PackageReference") { continue; } var includeAttribute = element.Attribute("Include"); if (includeAttribute == null) { continue; } if (!includeAttribute.Value.Equals(AMAZON_CDK_PACKAGE_REFERENCE_PREFIX) && !includeAttribute.Value.StartsWith($"{AMAZON_CDK_PACKAGE_REFERENCE_PREFIX}.")) { continue; } var versionAttribute = element.Attribute("Version"); if (versionAttribute == null) { continue; } var version = new Version(versionAttribute.Value); if (version > cdkVersion) { cdkVersion = version; } } return cdkVersion; } public Version Detect(IEnumerable<string> csprojPaths) { var cdkVersion = Constants.CDK.DefaultCDKVersion; foreach (var csprojPath in csprojPaths) { var version = Detect(csprojPath); if (version > cdkVersion) { cdkVersion = version; } } return cdkVersion; } } }
95
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.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using AWS.Deploy.Orchestration.Utilities; namespace AWS.Deploy.Orchestration.CDK { /// <summary> /// Orchestrates local node app. /// It makes sure that a local node application is initialized in order to be able to /// install CDK CLI in local node_modules. /// </summary> /// <remarks> /// When npm package is initialized, a specified version of CDK CLI is installed along with initialization. /// </remarks> public interface INPMPackageInitializer { /// <summary> /// Checks whether package.json file exists at given working directory or not. /// If there exists a package.json file, it is assumed to have node initialized. /// </summary> /// <param name="workingDirectory">Directory for local node app.</param> /// <returns>True, if package.json exists at <see cref="workingDirectory"/></returns> bool IsInitialized(string workingDirectory); /// <summary> /// Initializes npm package at <see cref="workingDirectory"/> /// </summary> /// <remarks> /// When npm package is initialized, a specified version of CDK CLI is installed along with installation. /// </remarks>w /// <param name="workingDirectory">Directory for local node app.</param> /// <param name="cdkVersion">Version of CDK CLI.</param> /// <exception cref="PackageJsonFileException">Thrown when package.json IO fails.</exception> /// <exception cref="NPMCommandFailedException">Thrown when a npm command fails to execute.</exception> Task Initialize(string workingDirectory, Version cdkVersion); } public class NPMPackageInitializer : INPMPackageInitializer { private readonly ICommandLineWrapper _commandLineWrapper; private readonly IPackageJsonGenerator _packageJsonGenerator; private readonly IFileManager _fileManager; private readonly IDirectoryManager _directoryManager; private readonly IOrchestratorInteractiveService _interactiveService; private const string _packageJsonFileName = "package.json"; public NPMPackageInitializer(ICommandLineWrapper commandLineWrapper, IPackageJsonGenerator packageJsonGenerator, IFileManager fileManager, IDirectoryManager directoryManager, IOrchestratorInteractiveService interactiveService) { _commandLineWrapper = commandLineWrapper; _packageJsonGenerator = packageJsonGenerator; _fileManager = fileManager; _directoryManager = directoryManager; _interactiveService = interactiveService; } public bool IsInitialized(string workingDirectory) { var packageFilePath = Path.Combine(workingDirectory, _packageJsonFileName); return _fileManager.Exists(packageFilePath); } public async Task Initialize(string workingDirectory, Version cdkVersion) { _interactiveService.LogDebugMessage($"Creating package.json at {workingDirectory}."); var packageJsonFileContent = _packageJsonGenerator.Generate(cdkVersion); var packageJsonFilePath = Path.Combine(workingDirectory, _packageJsonFileName); try { if (!_directoryManager.Exists(workingDirectory)) { _directoryManager.CreateDirectory(workingDirectory); } await _fileManager.WriteAllTextAsync(packageJsonFilePath, packageJsonFileContent); } catch (Exception exception) { throw new PackageJsonFileException(DeployToolErrorCode.FailedToWritePackageJsonFile, $"Failed to write {_packageJsonFileName} at {packageJsonFilePath}", exception); } try { // Install node packages specified in package.json file await _commandLineWrapper.Run("npm install", workingDirectory, false); } catch (Exception exception) { throw new NPMCommandFailedException(DeployToolErrorCode.FailedToInstallNpmPackages, $"Failed to install npm packages at {workingDirectory}", exception); } } } }
104
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.Reflection; namespace AWS.Deploy.Orchestration.CDK { /// <summary> /// Generates package.json file from the given template. /// </summary> public interface IPackageJsonGenerator { /// <summary> /// Generates an npm package.json file from the given template. /// This is meant to be used with an 'npm install' command to install the aws-cdk npm package /// in a specific directory. /// </summary> public string Generate(Version cdkVersion); } public class PackageJsonGenerator : IPackageJsonGenerator { private readonly string _template; public const string TemplateIdentifier = "AWS.Deploy.Orchestration.CDK.package.json.template"; public PackageJsonGenerator(string template) { _template = template; } public string Generate(Version cdkVersion) { var assembly = Assembly.GetExecutingAssembly(); var assemblyVersion = assembly.GetName().Version; var replacementTokens = new Dictionary<string, string> { { "{aws-cdk-version}", cdkVersion.ToString() }, { "{version}", $"{assemblyVersion?.Major}.{assemblyVersion?.Minor}.{assemblyVersion?.Build}" } }; var content = _template; foreach (var (key, value) in replacementTokens) { content = content.Replace(key, value); } return content; } } }
54
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Orchestration.CDK { /// <summary> /// Wrapper to return result for methods that follows TryGet pattern. /// <para> /// Especially handy for async methods that don't support out parameters. /// </para> /// </summary> /// <typeparam name="TResult">Type of the encapsulated <see cref="Result"/> object</typeparam> public class TryGetResult<TResult> { public bool Success { get; } public TResult? Result { get; } public TryGetResult(TResult? result, bool success) { Result = result; Success = success; } } /// <summary> /// Convenience static class to build <see cref="TryGetResult{TResult}"/> instance /// </summary> public static class TryGetResult { public static TryGetResult<T> Failure<T>() => new(default, false); public static TryGetResult<T> FromResult<T>(T result) => new(result, true); } }
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.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon; using Amazon.AppRunner.Model; using Amazon.CloudControlApi; using Amazon.CloudControlApi.Model; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.CloudFront; using Amazon.CloudFront.Model; using Amazon.CloudWatchEvents; using Amazon.CloudWatchEvents.Model; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using Amazon.EC2; using Amazon.EC2.Model; using Amazon.ECR; using Amazon.ECR.Model; using Amazon.ECS; using Amazon.ECS.Model; using Amazon.ElasticBeanstalk; using Amazon.ElasticBeanstalk.Model; using Amazon.ElasticLoadBalancingV2; using Amazon.ElasticLoadBalancingV2.Model; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using Amazon.Runtime; using Amazon.S3; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; using Amazon.SimpleSystemsManagement; using Amazon.SimpleSystemsManagement.Model; using Amazon.SQS; using Amazon.SQS.Model; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; namespace AWS.Deploy.Orchestration.Data { public class AWSResourceQueryer : IAWSResourceQueryer { private readonly IAWSClientFactory _awsClientFactory; public AWSResourceQueryer(IAWSClientFactory awsClientFactory) { _awsClientFactory = awsClientFactory; } public async Task<ResourceDescription> GetCloudControlApiResource(string type, string identifier) { var cloudControlApiClient = _awsClientFactory.GetAWSClient<IAmazonCloudControlApi>(); var request = new GetResourceRequest { TypeName = type, Identifier = identifier }; return await HandleException(async () => { var resource = await cloudControlApiClient.GetResourceAsync(request); return resource.ResourceDescription; }, $"Error attempting to retrieve Cloud Control API resource '{identifier}'"); } /// <summary> /// List the available subnets /// If <see cref="vpcID"/> is specified, the list of subnets is filtered by the VPC. /// </summary> public async Task<List<Subnet>> DescribeSubnets(string? vpcID = null) { var ec2Client = _awsClientFactory.GetAWSClient<IAmazonEC2>(); var request = new DescribeSubnetsRequest(); if (vpcID != null) { if (string.IsNullOrEmpty(vpcID)) return new List<Subnet>(); request.Filters = new List<Filter>() { new Filter() { Name = "vpc-id", Values = new List<string> { vpcID } } }; } return await HandleException(async () => await ec2Client.Paginators .DescribeSubnets(request) .Subnets .ToListAsync(), "Error attempting to describe available subnets"); } /// <summary> /// List the available security groups /// If <see cref="vpcID"/> is specified, the list of security groups is filtered by the VPC. /// </summary> public async Task<List<SecurityGroup>> DescribeSecurityGroups(string? vpcID = null) { var ec2Client = _awsClientFactory.GetAWSClient<IAmazonEC2>(); var request = new DescribeSecurityGroupsRequest(); // If a subnets IDs list is not specified, all security groups wil be returned. if (vpcID != null) { if (string.IsNullOrEmpty(vpcID)) return new List<SecurityGroup>(); request.Filters = new List<Filter>() { new Filter() { Name = "vpc-id", Values = new List<string> { vpcID } } }; } return await HandleException(async () => await ec2Client.Paginators .DescribeSecurityGroups(request) .SecurityGroups .ToListAsync(), "Error attempting to describe available security groups"); } public async Task<List<StackEvent>> GetCloudFormationStackEvents(string stackName) { var cfClient = _awsClientFactory.GetAWSClient<IAmazonCloudFormation>(); var request = new DescribeStackEventsRequest { StackName = stackName }; return await HandleException(async () => await cfClient.Paginators .DescribeStackEvents(request) .StackEvents .ToListAsync(), $"Error attempting to describe available CloudFormation stack events of '{stackName}'"); } public async Task<List<InstanceTypeInfo>> ListOfAvailableInstanceTypes() { var ec2Client = _awsClientFactory.GetAWSClient<IAmazonEC2>(); var instanceTypes = new List<InstanceTypeInfo>(); var listInstanceTypesPaginator = ec2Client.Paginators.DescribeInstanceTypes(new DescribeInstanceTypesRequest()); return await HandleException(async () => { await foreach (var response in listInstanceTypesPaginator.Responses) { instanceTypes.AddRange(response.InstanceTypes); } return instanceTypes; }, "Error attempting to describe available instance types"); } public async Task<InstanceTypeInfo?> DescribeInstanceType(string instanceType) { var ec2Client = _awsClientFactory.GetAWSClient<IAmazonEC2>(); var request = new DescribeInstanceTypesRequest { InstanceTypes = new List<string> { instanceType } }; return await HandleException(async () => { var response = await ec2Client.DescribeInstanceTypesAsync(request); return response.InstanceTypes.FirstOrDefault(); }, $"Error attempting to describe instance type '{instanceType}'"); } public async Task<List<VpcConnector>> DescribeAppRunnerVpcConnectors() { var appRunnerClient = _awsClientFactory.GetAWSClient<Amazon.AppRunner.IAmazonAppRunner>(); return await HandleException(async () => { var connections = await appRunnerClient.ListVpcConnectorsAsync(new ListVpcConnectorsRequest()); return connections.VpcConnectors; }, "Error attempting to describe available App Runner VPC connectors"); } public async Task<Amazon.AppRunner.Model.Service> DescribeAppRunnerService(string serviceArn) { var appRunnerClient = _awsClientFactory.GetAWSClient<Amazon.AppRunner.IAmazonAppRunner>(); return await HandleException(async () => { var service = (await appRunnerClient.DescribeServiceAsync(new DescribeServiceRequest { ServiceArn = serviceArn })).Service; if (service == null) { throw new AWSResourceNotFoundException(DeployToolErrorCode.AppRunnerServiceDoesNotExist, $"The AppRunner service '{serviceArn}' does not exist."); } return service; }, $"Error attempting to describe App Runner service '{serviceArn}'"); } public async Task<List<StackResource>> DescribeCloudFormationResources(string stackName) { var cfClient = _awsClientFactory.GetAWSClient<IAmazonCloudFormation>(); return await HandleException(async () => { var resources = await cfClient.DescribeStackResourcesAsync(new DescribeStackResourcesRequest { StackName = stackName }); return resources.StackResources; }, $"Error attempting to describe CloudFormation resources of '{stackName}'"); } public async Task<EnvironmentDescription> DescribeElasticBeanstalkEnvironment(string environmentName) { var beanstalkClient = _awsClientFactory.GetAWSClient<IAmazonElasticBeanstalk>(); return await HandleException(async () => { var environment = await beanstalkClient.DescribeEnvironmentsAsync(new DescribeEnvironmentsRequest { EnvironmentNames = new List<string> { environmentName } }); if (!environment.Environments.Any()) { throw new AWSResourceNotFoundException(DeployToolErrorCode.BeanstalkEnvironmentDoesNotExist, $"The elastic beanstalk environment '{environmentName}' does not exist."); } return environment.Environments.First(); }, $"Error attempting to describe Elastic Beanstalk environment '{environmentName}'"); } public async Task<Amazon.ElasticLoadBalancingV2.Model.LoadBalancer> DescribeElasticLoadBalancer(string loadBalancerArn) { var elasticLoadBalancingClient = _awsClientFactory.GetAWSClient<IAmazonElasticLoadBalancingV2>(); return await HandleException(async () => { var loadBalancers = await elasticLoadBalancingClient.DescribeLoadBalancersAsync(new DescribeLoadBalancersRequest { LoadBalancerArns = new List<string> { loadBalancerArn } }); if (!loadBalancers.LoadBalancers.Any()) { throw new AWSResourceNotFoundException(DeployToolErrorCode.LoadBalancerDoesNotExist, $"The load balancer '{loadBalancerArn}' does not exist."); } return loadBalancers.LoadBalancers.First(); }, $"Error attempting to describe Elastic Load Balancer '{loadBalancerArn}'"); } public async Task<List<Amazon.ElasticLoadBalancingV2.Model.Listener>> DescribeElasticLoadBalancerListeners(string loadBalancerArn) { var elasticLoadBalancingClient = _awsClientFactory.GetAWSClient<IAmazonElasticLoadBalancingV2>(); return await HandleException(async () => { var listeners = await elasticLoadBalancingClient.DescribeListenersAsync(new DescribeListenersRequest { LoadBalancerArn = loadBalancerArn }); if (!listeners.Listeners.Any()) { throw new AWSResourceNotFoundException(DeployToolErrorCode.LoadBalancerListenerDoesNotExist, $"The load balancer '{loadBalancerArn}' does not have any listeners."); } return listeners.Listeners; }, $"Error attempting to describe Elastic Load Balancer listeners of '{loadBalancerArn}'"); } public async Task<DescribeRuleResponse> DescribeCloudWatchRule(string ruleName) { var cloudWatchEventsClient = _awsClientFactory.GetAWSClient<IAmazonCloudWatchEvents>(); return await HandleException(async () => { var rule = await cloudWatchEventsClient.DescribeRuleAsync(new DescribeRuleRequest { Name = ruleName }); if (rule == null) { throw new AWSResourceNotFoundException(DeployToolErrorCode.CloudWatchRuleDoesNotExist, $"The CloudWatch rule'{ruleName}' does not exist."); } return rule; }, $"Error attempting to describe CloudWatch rule '{ruleName}'"); } public async Task<string> GetS3BucketLocation(string bucketName) { if (string.IsNullOrEmpty(bucketName)) { throw new ArgumentNullException($"The bucket name is null or empty."); } var s3Client = _awsClientFactory.GetAWSClient<IAmazonS3>(); var location = await HandleException(async () => await s3Client.GetBucketLocationAsync(bucketName), $"Error attempting to retrieve S3 bucket location of '{bucketName}'"); var region = ""; if (location.Location.Equals(S3Region.USEast1)) region = "us-east-1"; else if (location.Location.Equals(S3Region.EUWest1)) region = "eu-west-1"; else region = location.Location; return region; } public async Task<Amazon.S3.Model.WebsiteConfiguration> GetS3BucketWebSiteConfiguration(string bucketName) { var s3Client = _awsClientFactory.GetAWSClient<IAmazonS3>(); var response = await HandleException(async () => await s3Client.GetBucketWebsiteAsync(bucketName), $"Error attempting to retrieve S3 bucket website configuration of '{bucketName}'"); return response.WebsiteConfiguration; } public async Task<List<Cluster>> ListOfECSClusters(string? ecsClusterName = null) { var ecsClient = _awsClientFactory.GetAWSClient<IAmazonECS>(); var clusters = await HandleException(async () => { var request = new DescribeClustersRequest(); if (string.IsNullOrEmpty(ecsClusterName)) { var clusterArns = await ecsClient.Paginators .ListClusters(new ListClustersRequest()) .ClusterArns .ToListAsync(); request.Clusters = clusterArns; } else { request.Clusters = new List<string> { ecsClusterName }; } return await ecsClient.DescribeClustersAsync(request); }, "Error attempting to list available ECS clusters"); return clusters.Clusters; } public async Task<List<ApplicationDescription>> ListOfElasticBeanstalkApplications(string? applicationName = null) { var beanstalkClient = _awsClientFactory.GetAWSClient<IAmazonElasticBeanstalk>(); var request = new DescribeApplicationsRequest(); if (!string.IsNullOrEmpty(applicationName)) request.ApplicationNames = new List<string> { applicationName }; var applications = await HandleException(async () => await beanstalkClient.DescribeApplicationsAsync(request), "Error attempting to list available Elastic Beanstalk applications"); return applications.Applications; } public async Task<List<EnvironmentDescription>> ListOfElasticBeanstalkEnvironments(string? applicationName = null, string? environmentName = null) { var beanstalkClient = _awsClientFactory.GetAWSClient<IAmazonElasticBeanstalk>(); var request = new DescribeEnvironmentsRequest { ApplicationName = applicationName }; if (!string.IsNullOrEmpty(environmentName)) request.EnvironmentNames = new List<string> { environmentName }; return await HandleException(async () => { var environments = new List<EnvironmentDescription>(); do { var response = await beanstalkClient.DescribeEnvironmentsAsync(request); request.NextToken = response.NextToken; environments.AddRange(response.Environments); } while (!string.IsNullOrEmpty(request.NextToken)); return environments; }, "Error attempting to list available Elastic Beanstalk environments"); } public async Task<List<Amazon.ElasticBeanstalk.Model.Tag>> ListElasticBeanstalkResourceTags(string resourceArn) { var beanstalkClient = _awsClientFactory.GetAWSClient<IAmazonElasticBeanstalk>(); var response = await HandleException(async () => await beanstalkClient.ListTagsForResourceAsync(new Amazon.ElasticBeanstalk.Model.ListTagsForResourceRequest { ResourceArn = resourceArn }), $"Error attempting to list available Elastic Beanstalk resource tags of '{resourceArn}'"); return response.ResourceTags; } public async Task<List<KeyPairInfo>> ListOfEC2KeyPairs() { var ec2Client = _awsClientFactory.GetAWSClient<IAmazonEC2>(); var response = await HandleException(async () => await ec2Client.DescribeKeyPairsAsync(), "Error attempting to list available EC2 key pairs"); return response.KeyPairs; } public async Task<string> CreateEC2KeyPair(string keyName, string saveLocation) { var ec2Client = _awsClientFactory.GetAWSClient<IAmazonEC2>(); var request = new CreateKeyPairRequest { KeyName = keyName }; var response = await HandleException(async () => await ec2Client.CreateKeyPairAsync(request), "Error attempting to create EC2 key pair"); // We're creating the key pair at a user-defined location, and want to support relative paths // nosemgrep: csharp.lang.security.filesystem.unsafe-path-combine.unsafe-path-combine await File.WriteAllTextAsync(Path.Combine(saveLocation, $"{keyName}.pem"), response.KeyPair.KeyMaterial); return response.KeyPair.KeyName; } public async Task<List<Role>> ListOfIAMRoles(string? servicePrincipal) { var identityManagementServiceClient = _awsClientFactory.GetAWSClient<IAmazonIdentityManagementService>(); var listRolesRequest = new ListRolesRequest(); var listStacksPaginator = identityManagementServiceClient.Paginators.ListRoles(listRolesRequest); return await HandleException(async () => { var roles = new List<Role>(); await foreach (var response in listStacksPaginator.Responses) { var filteredRoles = response.Roles.Where(role => AssumeRoleServicePrincipalSelector(role, servicePrincipal)); roles.AddRange(filteredRoles); } return roles; }, "Error attempting to list available IAM roles"); } private static bool AssumeRoleServicePrincipalSelector(Role role, string? servicePrincipal) { return !string.IsNullOrEmpty(role.AssumeRolePolicyDocument) && !string.IsNullOrEmpty(servicePrincipal) && role.AssumeRolePolicyDocument.Contains(servicePrincipal); } public async Task<List<Vpc>> GetListOfVpcs() { var vpcClient = _awsClientFactory.GetAWSClient<IAmazonEC2>(); return await HandleException(async () => await vpcClient.Paginators .DescribeVpcs(new DescribeVpcsRequest()) .Vpcs .OrderByDescending(x => x.IsDefault) .ThenBy(x => x.VpcId) .ToListAsync(), "Error attempting to describe available VPCs"); } public async Task<Vpc> GetDefaultVpc() { var vpcClient = _awsClientFactory.GetAWSClient<IAmazonEC2>(); return await HandleException(async () => await vpcClient.Paginators .DescribeVpcs( new DescribeVpcsRequest { Filters = new List<Filter> { new Filter { Name = "is-default", Values = new List<string> { "true" } } } }) .Vpcs.FirstOrDefaultAsync(), "Error attempting to retrieve the default VPC"); } public async Task<List<PlatformSummary>> GetElasticBeanstalkPlatformArns(params BeanstalkPlatformType[]? platformTypes) { if(platformTypes == null || platformTypes.Length == 0) { platformTypes = new BeanstalkPlatformType[] { BeanstalkPlatformType.Linux, BeanstalkPlatformType.Windows }; } var beanstalkClient = _awsClientFactory.GetAWSClient<IAmazonElasticBeanstalk>(); Func<string, Task<List<PlatformSummary>>> fetchPlatforms = async (platformName) => { var request = new ListPlatformVersionsRequest { Filters = new List<PlatformFilter> { new PlatformFilter { Operator = "=", Type = "PlatformStatus", Values = { "Ready" } }, new PlatformFilter { Operator = "contains", Type = "PlatformName", Values = { platformName } } } }; var platforms = await HandleException(async () => (await beanstalkClient.Paginators.ListPlatformVersions(request).PlatformSummaryList.ToListAsync()), "Error attempting to list available Elastic Beanstalk platform versions"); // Filter out old test platforms that only internal accounts would be able to see. platforms = platforms.Where(x => !string.IsNullOrEmpty(x.PlatformBranchName)).ToList(); return platforms; }; var allPlatformSummaries = new List<PlatformSummary>(); if (platformTypes.Contains(BeanstalkPlatformType.Linux)) { allPlatformSummaries.AddRange(await fetchPlatforms(Constants.ElasticBeanstalk.LinuxPlatformType)); } if (platformTypes.Contains(BeanstalkPlatformType.Windows)) { var windowsPlatforms = await fetchPlatforms(Constants.ElasticBeanstalk.WindowsPlatformType); SortElasticBeanstalkWindowsPlatforms(windowsPlatforms); allPlatformSummaries.AddRange(windowsPlatforms); } var platformVersions = new List<PlatformSummary>(); foreach (var version in allPlatformSummaries) { if (string.IsNullOrEmpty(version.PlatformCategory) || string.IsNullOrEmpty(version.PlatformBranchLifecycleState)) continue; if (!version.PlatformBranchLifecycleState.Equals("Supported")) continue; platformVersions.Add(version); } return platformVersions; } public async Task<PlatformSummary> GetLatestElasticBeanstalkPlatformArn(BeanstalkPlatformType platformType) { var platforms = await GetElasticBeanstalkPlatformArns(platformType); if (!platforms.Any()) { throw new FailedToFindElasticBeanstalkSolutionStackException(DeployToolErrorCode.FailedToFindElasticBeanstalkSolutionStack, "Cannot use Elastic Beanstalk deployments because we cannot find a .NET Core Solution Stack to use. " + "Possible reasons could be that Elastic Beanstalk is not enabled in your region if you are using a non-default region, " + "or that the configured credentials lack permission to call ListPlatformVersions."); } return platforms.First(); } /// <summary> /// For Windows beanstalk platforms the describe calls return a collection of Windows Server Code and Windows Server based platforms. /// The order return will be sorted by platform versions but not OS. So for example we could get a result like the following /// /// IIS 10.0 running on 64bit Windows Server 2016 (1.1.0) /// IIS 10.0 running on 64bit Windows Server 2016 (1.0.0) /// IIS 10.0 running on 64bit Windows Server Core 2016 (1.1.0) /// IIS 10.0 running on 64bit Windows Server Core 2016 (1.0.0) /// IIS 10.0 running on 64bit Windows Server 2019 (1.1.0) /// IIS 10.0 running on 64bit Windows Server 2019 (1.0.0) /// IIS 10.0 running on 64bit Windows Server Core 2019 (1.1.0) /// IIS 10.0 running on 64bit Windows Server Core 2019 (1.0.0) /// /// We want the user to use the latest version of each OS first as well as the latest version of Windows first. Also Windows Server should come before Windows Server Core. /// This matches the behavior of the existing VS toolkit picker. The above example will be sorted into the following. /// /// IIS 10.0 running on 64bit Windows Server 2019 (1.1.0) /// IIS 10.0 running on 64bit Windows Server Core 2019 (1.1.0) /// IIS 10.0 running on 64bit Windows Server 2016 (1.1.0) /// IIS 10.0 running on 64bit Windows Server Core 2016 (1.1.0) /// IIS 10.0 running on 64bit Windows Server 2019 (1.0.0) /// IIS 10.0 running on 64bit Windows Server Core 2019 (1.0.0) /// IIS 10.0 running on 64bit Windows Server 2016 (1.0.0) /// IIS 10.0 running on 64bit Windows Server Core 2016 (1.0.0) /// </summary> /// <param name="windowsPlatforms"></param> public static void SortElasticBeanstalkWindowsPlatforms(List<PlatformSummary> windowsPlatforms) { var parseYear = (string name) => { var tokens = name.Split(' '); int year; if (int.TryParse(tokens[tokens.Length - 1], out year)) return year; if (int.TryParse(tokens[tokens.Length - 2], out year)) return year; return 0; }; var parseOSLevel = (string name) => { if (name.Contains("Windows Server Core")) return 1; if (name.Contains("Windows Server")) return 2; return 10; }; windowsPlatforms.Sort((x, y) => { if (!Version.TryParse(x.PlatformVersion, out var xVersion)) xVersion = Version.Parse("0.0.0"); if (!Version.TryParse(y.PlatformVersion, out var yVersion)) yVersion = Version.Parse("0.0.0"); if (yVersion != xVersion) { return yVersion.CompareTo(xVersion); } var xYear = parseYear(x.PlatformBranchName); var yYear = parseYear(y.PlatformBranchName); var xOSLevel = parseOSLevel(x.PlatformBranchName); var yOSLevel = parseOSLevel(y.PlatformBranchName); if (yYear == xYear) { if (yOSLevel == xOSLevel) { return 0; } return yOSLevel < xOSLevel ? -1 : 1; } return yYear < xYear ? -1 : 1; }); } public async Task<List<AuthorizationData>> GetECRAuthorizationToken() { var ecrClient = _awsClientFactory.GetAWSClient<IAmazonECR>(); var response = await HandleException(async () => await ecrClient.GetAuthorizationTokenAsync(new GetAuthorizationTokenRequest()), "Error attempting to retrieve ECR authorization token"); return response.AuthorizationData; } public async Task<List<Repository>> GetECRRepositories(List<string>? repositoryNames = null) { var ecrClient = _awsClientFactory.GetAWSClient<IAmazonECR>(); var request = new DescribeRepositoriesRequest { RepositoryNames = repositoryNames }; return await HandleException(async () => { try { return (await ecrClient.Paginators.DescribeRepositories(request).Repositories.ToListAsync()) .OrderByDescending(x => x.CreatedAt) .ToList(); } catch (RepositoryNotFoundException) { return new List<Repository>(); } }, "Error attempting to list available ECR repositories"); } public async Task<Repository> CreateECRRepository(string repositoryName) { var ecrClient = _awsClientFactory.GetAWSClient<IAmazonECR>(); var request = new CreateRepositoryRequest { RepositoryName = repositoryName }; var response = await HandleException(async () => await ecrClient.CreateRepositoryAsync(request), "Error attempting to create an ECR repository"); return response.Repository; } public async Task<List<Stack>> GetCloudFormationStacks() { using var cloudFormationClient = _awsClientFactory.GetAWSClient<IAmazonCloudFormation>(); return await HandleException(async () => await cloudFormationClient.Paginators .DescribeStacks(new DescribeStacksRequest()) .Stacks.ToListAsync(), "Error attempting to describe available CloudFormation stacks"); } public async Task<Stack?> GetCloudFormationStack(string stackName) { using var cloudFormationClient = _awsClientFactory.GetAWSClient<IAmazonCloudFormation>(); return await HandleException(async () => { try { var request = new DescribeStacksRequest { StackName = stackName }; var response = await cloudFormationClient.DescribeStacksAsync(request); return response.Stacks.FirstOrDefault(); } // CloudFormation throws a BadRequest exception if the stack does not exist catch (AmazonCloudFormationException e) when (e.StatusCode == System.Net.HttpStatusCode.BadRequest) { return null; } }, $"Error attempting to retrieve the CloudFormation stack '{stackName}'"); } public async Task<GetCallerIdentityResponse> GetCallerIdentity(string awsRegion) { var request = new GetCallerIdentityRequest(); using var stsClient = _awsClientFactory.GetAWSClient<IAmazonSecurityTokenService>(awsRegion); return await HandleException(async () => { try { return await stsClient.GetCallerIdentityAsync(request); } catch (Exception ex) { var regionEndpointPartition = RegionEndpoint.GetBySystemName(awsRegion).PartitionName ?? String.Empty; if (regionEndpointPartition.Equals("aws") && !awsRegion.Equals(Constants.CLI.DEFAULT_STS_AWS_REGION)) { try { using var defaultRegionStsClient = _awsClientFactory.GetAWSClient<IAmazonSecurityTokenService>(Constants.CLI.DEFAULT_STS_AWS_REGION); await defaultRegionStsClient.GetCallerIdentityAsync(request); } catch (Exception e) { throw new UnableToAccessAWSRegionException( DeployToolErrorCode.UnableToAccessAWSRegion, $"We were unable to access the AWS region '{awsRegion}'. Make sure you have correct permissions for that region and the region is accessible.", e); } throw new UnableToAccessAWSRegionException( DeployToolErrorCode.OptInRegionDisabled, $"We were unable to access the Opt-In region '{awsRegion}'. Please enable the AWS Region '{awsRegion}' and try again. Additional details could be found at https://docs.aws.amazon.com/general/latest/gr/rande-manage.html", ex); } throw new UnableToAccessAWSRegionException( DeployToolErrorCode.UnableToAccessAWSRegion, $"We were unable to access the AWS region '{awsRegion}'. Make sure you have correct permissions for that region and the region is accessible.", ex); } }, "Error attempting to retrieve the STS caller identity"); } public async Task<List<Amazon.ElasticLoadBalancingV2.Model.LoadBalancer>> ListOfLoadBalancers(Amazon.ElasticLoadBalancingV2.LoadBalancerTypeEnum loadBalancerType) { var client = _awsClientFactory.GetAWSClient<IAmazonElasticLoadBalancingV2>(); return await HandleException(async () => { return await client.Paginators.DescribeLoadBalancers(new DescribeLoadBalancersRequest()) .LoadBalancers.Where(loadBalancer => loadBalancer.Type == loadBalancerType) .ToListAsync(); }, "Error attempting to list available Elastic load balancers"); } public async Task<Distribution> GetCloudFrontDistribution(string distributionId) { var client = _awsClientFactory.GetAWSClient<IAmazonCloudFront>(); return await HandleException(async () => { var response = await client.GetDistributionAsync(new GetDistributionRequest { Id = distributionId }); return response.Distribution; }, $"Error attempting to retrieve the CloudFront distribution '{distributionId}'"); } public async Task<List<string>> ListOfDyanmoDBTables() { var client = _awsClientFactory.GetAWSClient<IAmazonDynamoDB>(); return await HandleException(async () => await client.Paginators.ListTables(new ListTablesRequest()).TableNames.ToListAsync(), "Error attempting to list available DynamoDB tables"); } public async Task<List<string>> ListOfSQSQueuesUrls() { var client = _awsClientFactory.GetAWSClient<IAmazonSQS>(); return await HandleException(async () => await client.Paginators.ListQueues(new ListQueuesRequest()).QueueUrls.ToListAsync(), "Error attempting to list available SQS queue URLs"); } public async Task<List<string>> ListOfSNSTopicArns() { var client = _awsClientFactory.GetAWSClient<IAmazonSimpleNotificationService>(); return await HandleException(async () => { return await client.Paginators.ListTopics(new ListTopicsRequest()).Topics.Select(topic => topic.TopicArn).ToListAsync(); }, "Error attempting to list available SNS topics"); } public async Task<List<Amazon.S3.Model.S3Bucket>> ListOfS3Buckets() { var client = _awsClientFactory.GetAWSClient<IAmazonS3>(); return await HandleException(async () => (await client.ListBucketsAsync()).Buckets.ToList(), "Error attempting to list available S3 buckets"); } public async Task<List<ConfigurationOptionSetting>> GetBeanstalkEnvironmentConfigurationSettings(string environmentName) { var optionSetting = new List<ConfigurationOptionSetting>(); var environmentDescription = await DescribeElasticBeanstalkEnvironment(environmentName); var client = _awsClientFactory.GetAWSClient<IAmazonElasticBeanstalk>(); return await HandleException(async () => { var response = await client.DescribeConfigurationSettingsAsync(new DescribeConfigurationSettingsRequest { ApplicationName = environmentDescription.ApplicationName, EnvironmentName = environmentName }); optionSetting.AddRange(response.ConfigurationSettings.SelectMany(settingDescription => settingDescription.OptionSettings)); return optionSetting; }, $"Error attempting to retrieve Elastic Beanstalk environment configuration settings for '{environmentName}'"); } public async Task<Repository> DescribeECRRepository(string respositoryName) { var client = _awsClientFactory.GetAWSClient<IAmazonECR>(); return await HandleException(async () => { DescribeRepositoriesResponse response; try { response = await client.DescribeRepositoriesAsync(new DescribeRepositoriesRequest { RepositoryNames = new List<string> { respositoryName } }); } catch (RepositoryNotFoundException ex) { throw new AWSResourceNotFoundException(DeployToolErrorCode.ECRRepositoryDoesNotExist, $"The ECR repository {respositoryName} does not exist.", ex); } return response.Repositories.First(); }, $"Error attempting to describe ECR repository '{respositoryName}'"); } public async Task<string?> GetParameterStoreTextValue(string parameterName) { var client = _awsClientFactory.GetAWSClient<IAmazonSimpleSystemsManagement>(); return await HandleException(async () => { try { var request = new GetParameterRequest { Name = parameterName }; var response = await client.GetParameterAsync(request); return response.Parameter.Value; } catch (ParameterNotFoundException) { return null; } }, $"Error attempting to retrieve SSM parameter store value of '{parameterName}'"); } private async Task<T> HandleException<T>(Func<Task<T>> action, string exceptionMessage) { try { return await action(); } catch (AmazonServiceException e) { var messageBuilder = new StringBuilder(); var userMessage = string.Empty; if (!string.IsNullOrEmpty(exceptionMessage)) { if (!string.IsNullOrEmpty(e.ErrorCode)) { userMessage += $"{exceptionMessage} ({e.ErrorCode})."; } else { userMessage += $"{exceptionMessage}."; } } else { if (!string.IsNullOrEmpty(e.ErrorCode)) { userMessage += e.ErrorCode; } } if (!string.IsNullOrEmpty(userMessage)) { messageBuilder.AppendLine(userMessage); } if (!string.IsNullOrEmpty(e.Message)) { messageBuilder.AppendLine(e.Message); } if (messageBuilder.Length == 0) { messageBuilder.Append($"An unknown error occurred while communicating with AWS.{Environment.NewLine}"); } throw new ResourceQueryException(DeployToolErrorCode.ResourceQuery, messageBuilder.ToString(), e); } } } }
978
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; using AWS.Deploy.Orchestration.DisplayedResources; namespace AWS.Deploy.Orchestration.DeploymentCommands { public class BeanstalkEnvironmentDeploymentCommand : IDeploymentCommand { public async Task ExecuteAsync(Orchestrator orchestrator, CloudApplication cloudApplication, Recommendation recommendation) { if (orchestrator._interactiveService == null) throw new InvalidOperationException($"{nameof(orchestrator._interactiveService)} is null as part of the orchestartor object"); if (orchestrator._awsResourceQueryer == null) throw new InvalidOperationException($"{nameof(orchestrator._awsResourceQueryer)} is null as part of the orchestartor object"); if (orchestrator._awsServiceHandler == null) throw new InvalidOperationException($"{nameof(orchestrator._awsServiceHandler)} is null as part of the orchestartor object"); var deploymentPackage = recommendation.DeploymentBundle.DotnetPublishZipPath; var environmentName = cloudApplication.Name; var applicationName = (await orchestrator._awsResourceQueryer.ListOfElasticBeanstalkEnvironments()) .Where(x => string.Equals(x.EnvironmentId, cloudApplication.UniqueIdentifier)) .FirstOrDefault()? .ApplicationName; var s3Handler = orchestrator._awsServiceHandler.S3Handler; var elasticBeanstalkHandler = orchestrator._awsServiceHandler.ElasticBeanstalkHandler; if (string.IsNullOrEmpty(applicationName)) { var message = $"Could not find any Elastic Beanstalk application that contains the following environment: {environmentName}"; throw new AWSResourceNotFoundException(DeployToolErrorCode.FailedToFindElasticBeanstalkApplication, message); } orchestrator._interactiveService.LogSectionStart($"Creating application version", "Uploading deployment bundle to S3 and create an Elastic Beanstalk application version"); // This step is only required for Elastic Beanstalk Windows deployments since a manifest file needs to be created for that deployment. if (recommendation.Recipe.Id.Equals(Constants.RecipeIdentifier.EXISTING_BEANSTALK_WINDOWS_ENVIRONMENT_RECIPE_ID)) { elasticBeanstalkHandler.SetupWindowsDeploymentManifest(recommendation, deploymentPackage); } else if (recommendation.Recipe.Id.Equals(Constants.RecipeIdentifier.EXISTING_BEANSTALK_ENVIRONMENT_RECIPE_ID)) { elasticBeanstalkHandler.SetupProcfileForSelfContained(deploymentPackage); } var versionLabel = $"v-{DateTime.Now.Ticks}"; var s3location = await elasticBeanstalkHandler.CreateApplicationStorageLocationAsync(applicationName, versionLabel, deploymentPackage); await s3Handler.UploadToS3Async(s3location.S3Bucket, s3location.S3Key, deploymentPackage); await elasticBeanstalkHandler.CreateApplicationVersionAsync(applicationName, versionLabel, s3location); var environmentConfigurationSettings = elasticBeanstalkHandler.GetEnvironmentConfigurationSettings(recommendation); orchestrator._interactiveService.LogSectionStart($"Deploying application version", $"Deploy new application version to Elastic Beanstalk environment {environmentName}."); var success = await elasticBeanstalkHandler.UpdateEnvironmentAsync(applicationName, environmentName, versionLabel, environmentConfigurationSettings); if (success) { orchestrator._interactiveService.LogInfoMessage($"The Elastic Beanstalk Environment {environmentName} has been successfully updated to the application version {versionLabel}" + Environment.NewLine); } else { throw new ElasticBeanstalkException(DeployToolErrorCode.FailedToUpdateElasticBeanstalkEnvironment, "Failed to update the Elastic Beanstalk environment"); } } public async Task<List<DisplayedResourceItem>> GetDeploymentOutputsAsync(IDisplayedResourcesHandler displayedResourcesHandler, CloudApplication cloudApplication, Recommendation recommendation) { var displayedResources = new List<DisplayedResourceItem>(); var environment = await displayedResourcesHandler.AwsResourceQueryer.DescribeElasticBeanstalkEnvironment(cloudApplication.Name); var data = new Dictionary<string, string>() {{ "Endpoint", $"http://{environment.CNAME}/" }}; var resourceDescription = "An AWS Elastic Beanstalk environment is a collection of AWS resources running an application version."; var resourceType = "Elastic Beanstalk Environment"; displayedResources.Add(new DisplayedResourceItem(environment.EnvironmentName, resourceDescription, resourceType, data)); return displayedResources; } } }
84
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.Text; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Orchestration.DisplayedResources; namespace AWS.Deploy.Orchestration.DeploymentCommands { public class CdkDeploymentCommand : IDeploymentCommand { public async Task ExecuteAsync(Orchestrator orchestrator, CloudApplication cloudApplication, Recommendation recommendation) { if (orchestrator._interactiveService == null) throw new InvalidOperationException($"{nameof(orchestrator._interactiveService)} is null as part of the orchestartor object"); if (orchestrator._cdkManager == null) throw new InvalidOperationException($"{nameof(orchestrator._cdkManager)} is null as part of the orchestartor object"); if (orchestrator._cdkProjectHandler == null) throw new InvalidOperationException($"{nameof(CdkProjectHandler)} is null as part of the orchestartor object"); if (orchestrator._localUserSettingsEngine == null) throw new InvalidOperationException($"{nameof(orchestrator._localUserSettingsEngine)} is null as part of the orchestartor object"); if (orchestrator._session == null) throw new InvalidOperationException($"{nameof(orchestrator._session)} is null as part of the orchestartor object"); if (orchestrator._cdkVersionDetector == null) throw new InvalidOperationException($"{nameof(orchestrator._cdkVersionDetector)} must not be null."); if (orchestrator._directoryManager == null) throw new InvalidOperationException($"{nameof(orchestrator._directoryManager)} must not be null."); if (orchestrator._workspaceMetadata == null) throw new InvalidOperationException($"{nameof(orchestrator._workspaceMetadata)} must not be null."); orchestrator._interactiveService.LogSectionStart("Configuring AWS Cloud Development Kit (CDK)", "Ensure a compatible CDK version is installed and the CDK bootstrap CloudFormation stack has been created. A CDK project to perform the deployment is generated unless an existing deployment project was selected."); var cdkProject = await orchestrator._cdkProjectHandler.ConfigureCdkProject(orchestrator._session, cloudApplication, recommendation); var projFiles = orchestrator._directoryManager.GetProjFiles(cdkProject); var cdkVersion = orchestrator._cdkVersionDetector.Detect(projFiles); await orchestrator._cdkManager.EnsureCompatibleCDKExists(recommendation.Recipe.PersistedDeploymentProject ? cdkProject : orchestrator._workspaceMetadata.DeployToolWorkspaceDirectoryRoot, cdkVersion); try { await orchestrator._cdkProjectHandler.DeployCdkProject(orchestrator._session, cloudApplication, cdkProject, recommendation); } finally { orchestrator._cdkProjectHandler.DeleteTemporaryCdkProject(cdkProject); } await orchestrator._localUserSettingsEngine.UpdateLastDeployedStack(cloudApplication.Name, orchestrator._session.ProjectDefinition.ProjectName, orchestrator._session.AWSAccountId, orchestrator._session.AWSRegion); } public async Task<List<DisplayedResourceItem>> GetDeploymentOutputsAsync(IDisplayedResourcesHandler displayedResourcesHandler, CloudApplication cloudApplication, Recommendation recommendation) { var displayedResources = new List<DisplayedResourceItem>(); if (recommendation.Recipe.DisplayedResources == null) return displayedResources; var resources = await displayedResourcesHandler.AwsResourceQueryer.DescribeCloudFormationResources(cloudApplication.Name); foreach (var displayedResource in recommendation.Recipe.DisplayedResources) { var resource = resources.FirstOrDefault(x => x.LogicalResourceId.Equals(displayedResource.LogicalId)); if (resource == null) continue; var data = new Dictionary<string, string>(); if (!string.IsNullOrEmpty(resource.ResourceType) && displayedResourcesHandler.DisplayedResourcesFactory.GetResource(resource.ResourceType) is var displayedResourceCommand && displayedResourceCommand != null) { data = await displayedResourceCommand.Execute(resource.PhysicalResourceId); } displayedResources.Add(new DisplayedResourceItem(resource.PhysicalResourceId, displayedResource.Description, resource.ResourceType, data)); } return displayedResources; } } }
83
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.Common; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.Orchestration.DeploymentCommands { public static class DeploymentCommandFactory { private static readonly Dictionary<DeploymentTypes, Type> _deploymentCommandTypeMapping = new() { { DeploymentTypes.CdkProject, typeof(CdkDeploymentCommand) }, { DeploymentTypes.BeanstalkEnvironment, typeof(BeanstalkEnvironmentDeploymentCommand) }, { DeploymentTypes.ElasticContainerRegistryImage, typeof(ElasticContainerRegistryPushCommand) } }; public static IDeploymentCommand BuildDeploymentCommand(DeploymentTypes deploymentType) { if (!_deploymentCommandTypeMapping.ContainsKey(deploymentType)) { var message = $"Failed to create an instance of type {nameof(IDeploymentCommand)}. {deploymentType} does not exist as a key in {_deploymentCommandTypeMapping}."; throw new FailedToCreateDeploymentCommandInstanceException(DeployToolErrorCode.FailedToCreateDeploymentCommandInstance, message); } var deploymentCommandInstance = Activator.CreateInstance(_deploymentCommandTypeMapping[deploymentType]); if (deploymentCommandInstance == null || deploymentCommandInstance is not IDeploymentCommand) { var message = $"Failed to create an instance of type {_deploymentCommandTypeMapping[deploymentType]}."; throw new FailedToCreateDeploymentCommandInstanceException(DeployToolErrorCode.FailedToCreateDeploymentCommandInstance, message); } return (IDeploymentCommand)deploymentCommandInstance; } } }
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 System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Orchestration.DisplayedResources; namespace AWS.Deploy.Orchestration.DeploymentCommands { public class ElasticContainerRegistryPushCommand : IDeploymentCommand { // This method does not have a body because an actual deployment is not being performed. // The container images are already pushed to ECR in the orchestrator.CreateContainerDeploymentBundle(..) method. public Task ExecuteAsync(Orchestrator orchestrator, CloudApplication cloudApplication, Recommendation recommendation) { return Task.CompletedTask; } public async Task<List<DisplayedResourceItem>> GetDeploymentOutputsAsync(IDisplayedResourcesHandler displayedResourcesHandler, CloudApplication cloudApplication, Recommendation recommendation) { var displayedResources = new List<DisplayedResourceItem>(); var repositoryName = recommendation.DeploymentBundle.ECRRepositoryName; var imageTag = recommendation.DeploymentBundle.ECRImageTag; var repository = await displayedResourcesHandler.AwsResourceQueryer.DescribeECRRepository(repositoryName); var data = new Dictionary<string, string>() { { "Repository URI", repository.RepositoryUri }, { "Image URI", $"{repository.RepositoryUri}:{imageTag}"} }; var resourceDescription = "Amazon Elastic Container Registry is a collection of repositories that can store tagged container images"; var resourceType = "Elastic Container Registry Repository"; displayedResources.Add(new DisplayedResourceItem(repository.RepositoryName, resourceDescription, resourceType, data)); return displayedResources; } } }
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.Text; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Orchestration.DisplayedResources; namespace AWS.Deploy.Orchestration.DeploymentCommands { public interface IDeploymentCommand { Task ExecuteAsync(Orchestrator orchestrator, CloudApplication cloudApplication, Recommendation recommendation); Task<List<DisplayedResourceItem>> GetDeploymentOutputsAsync(IDisplayedResourcesHandler displayedResourcesHandler, CloudApplication cloudApplication, Recommendation recommendation); } }
19
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.Data; using AWS.Deploy.Orchestration.Data; namespace AWS.Deploy.Orchestration.DisplayedResources { public class AppRunnerServiceResource : IDisplayedResourceCommand { private readonly IAWSResourceQueryer _awsResourceQueryer; public AppRunnerServiceResource(IAWSResourceQueryer awsResourceQueryer) { _awsResourceQueryer = awsResourceQueryer; } public async Task<Dictionary<string, string>> Execute(string resourceId) { var service = await _awsResourceQueryer.DescribeAppRunnerService(resourceId); return new Dictionary<string, string>() { { "Endpoint", $"https://{service.ServiceUrl}/" } }; } } }
30
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.Orchestration.Data; using Amazon.CloudFront.Model; using AWS.Deploy.Common.Data; namespace AWS.Deploy.Orchestration.DisplayedResources { public class CloudFrontDistributionResource : IDisplayedResourceCommand { private readonly IAWSResourceQueryer _awsResourceQueryer; public CloudFrontDistributionResource(IAWSResourceQueryer awsResourceQueryer) { _awsResourceQueryer = awsResourceQueryer; } public async Task<Dictionary<string, string>> Execute(string resourceId) { var distribution = await _awsResourceQueryer.GetCloudFrontDistribution(resourceId); var endpoint = $"https://{distribution.DomainName}/"; return new Dictionary<string, string>() { { "Endpoint", endpoint } }; } } }
36
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.Data; using AWS.Deploy.Orchestration.Data; namespace AWS.Deploy.Orchestration.DisplayedResources { public class CloudWatchEventResource : IDisplayedResourceCommand { private const string DATA_TITLE_EVENT_SCHEDULE = "Event Schedule"; private readonly IAWSResourceQueryer _awsResourceQueryer; public CloudWatchEventResource(IAWSResourceQueryer awsResourceQueryer) { _awsResourceQueryer = awsResourceQueryer; } public async Task<Dictionary<string, string>> Execute(string resourceId) { var rule = await _awsResourceQueryer.DescribeCloudWatchRule(resourceId); return new Dictionary<string, string>() { { DATA_TITLE_EVENT_SCHEDULE, rule.ScheduleExpression } }; } } }
31
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.Data; using AWS.Deploy.Orchestration.Data; namespace AWS.Deploy.Orchestration.DisplayedResources { /// <summary> /// Interface for displayed resources such as <see cref="ElasticBeanstalkEnvironmentResource"/> /// </summary> public interface IDisplayedResourceCommand { Task<Dictionary<string, string>> Execute(string resourceId); } public interface IDisplayedResourceCommandFactory { IDisplayedResourceCommand? GetResource(string resourceType); } /// <summary> /// Factory class responsible to build and get the displayed resources. /// </summary> public class DisplayedResourceCommandFactory : IDisplayedResourceCommandFactory { private const string RESOURCE_TYPE_APPRUNNER_SERVICE = "AWS::AppRunner::Service"; private const string RESOURCE_TYPE_ELASTICBEANSTALK_ENVIRONMENT = "AWS::ElasticBeanstalk::Environment"; private const string RESOURCE_TYPE_ELASTICLOADBALANCINGV2_LOADBALANCER = "AWS::ElasticLoadBalancingV2::LoadBalancer"; private const string RESOURCE_TYPE_S3_BUCKET = "AWS::S3::Bucket"; private const string RESOURCE_TYPE_CLOUDFRONT_DISTRIBUTION = "AWS::CloudFront::Distribution"; private const string RESOURCE_TYPE_EVENTS_RULE = "AWS::Events::Rule"; private readonly Dictionary<string, IDisplayedResourceCommand> _resources; public DisplayedResourceCommandFactory(IAWSResourceQueryer awsResourceQueryer) { _resources = new Dictionary<string, IDisplayedResourceCommand> { { RESOURCE_TYPE_APPRUNNER_SERVICE, new AppRunnerServiceResource(awsResourceQueryer) }, { RESOURCE_TYPE_ELASTICBEANSTALK_ENVIRONMENT, new ElasticBeanstalkEnvironmentResource(awsResourceQueryer) }, { RESOURCE_TYPE_ELASTICLOADBALANCINGV2_LOADBALANCER, new ElasticLoadBalancerResource(awsResourceQueryer) }, { RESOURCE_TYPE_S3_BUCKET, new S3BucketResource(awsResourceQueryer) }, { RESOURCE_TYPE_CLOUDFRONT_DISTRIBUTION, new CloudFrontDistributionResource(awsResourceQueryer) }, { RESOURCE_TYPE_EVENTS_RULE, new CloudWatchEventResource(awsResourceQueryer) } }; } public IDisplayedResourceCommand? GetResource(string resourceType) { if (!_resources.ContainsKey(resourceType)) { return null; } return _resources[resourceType]; } } }
62
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.Orchestration.DisplayedResources { public class DisplayedResourceItem { /// <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 DisplayedResourceItem(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.Collections.Generic; using AWS.Deploy.Common; using System.Threading.Tasks; using AWS.Deploy.Orchestration.Data; using System.Linq; using AWS.Deploy.Orchestration.DeploymentCommands; using AWS.Deploy.Common.Data; namespace AWS.Deploy.Orchestration.DisplayedResources { public interface IDisplayedResourcesHandler { IAWSResourceQueryer AwsResourceQueryer { get; } IDisplayedResourceCommandFactory DisplayedResourcesFactory { get; } Task<List<DisplayedResourceItem>> GetDeploymentOutputs(CloudApplication cloudApplication, Recommendation recommendation); } public class DisplayedResourcesHandler : IDisplayedResourcesHandler { public IAWSResourceQueryer AwsResourceQueryer { get; } public IDisplayedResourceCommandFactory DisplayedResourcesFactory { get; } public DisplayedResourcesHandler(IAWSResourceQueryer awsResourceQueryer, IDisplayedResourceCommandFactory displayedResourcesFactory) { AwsResourceQueryer = awsResourceQueryer; DisplayedResourcesFactory = displayedResourcesFactory; } /// <summary> /// Retrieves the displayed resource data for known resource types by executing specific resource commands. /// For unknown resource types, this returns the physical resource ID and type. /// </summary> public async Task<List<DisplayedResourceItem>> GetDeploymentOutputs(CloudApplication cloudApplication, Recommendation recommendation) { var deploymentCommand = DeploymentCommandFactory.BuildDeploymentCommand(recommendation.Recipe.DeploymentType); return await deploymentCommand.GetDeploymentOutputsAsync(this, cloudApplication, recommendation); } } }
43
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.Data; using AWS.Deploy.Orchestration.Data; namespace AWS.Deploy.Orchestration.DisplayedResources { public class ElasticBeanstalkEnvironmentResource : IDisplayedResourceCommand { private readonly IAWSResourceQueryer _awsResourceQueryer; public ElasticBeanstalkEnvironmentResource(IAWSResourceQueryer awsResourceQueryer) { _awsResourceQueryer = awsResourceQueryer; } public async Task<Dictionary<string, string>> Execute(string resourceId) { var environment = await _awsResourceQueryer.DescribeElasticBeanstalkEnvironment(resourceId); return new Dictionary<string, string>() { { "Endpoint", $"http://{environment.CNAME}/" } }; } } }
29
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.Linq; using System.Threading.Tasks; using Amazon.ElasticLoadBalancingV2; using AWS.Deploy.Common.Data; using AWS.Deploy.Orchestration.Data; namespace AWS.Deploy.Orchestration.DisplayedResources { public class ElasticLoadBalancerResource : IDisplayedResourceCommand { private readonly IAWSResourceQueryer _awsResourceQueryer; public ElasticLoadBalancerResource(IAWSResourceQueryer awsResourceQueryer) { _awsResourceQueryer = awsResourceQueryer; } public async Task<Dictionary<string, string>> Execute(string resourceId) { var loadBalancer = await _awsResourceQueryer.DescribeElasticLoadBalancer(resourceId); var listeners = await _awsResourceQueryer.DescribeElasticLoadBalancerListeners(resourceId); var protocol = "http"; var httpsListeners = listeners.Where(x => x.Protocol.Equals(ProtocolEnum.HTTPS)).ToList(); if (httpsListeners.Any()) protocol = "https"; return new Dictionary<string, string>() { { "Endpoint", $"{protocol}://{loadBalancer.DNSName}/" } }; } } }
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.Text; using System.Threading.Tasks; using AWS.Deploy.Common.Data; using AWS.Deploy.Orchestration.Data; namespace AWS.Deploy.Orchestration.DisplayedResources { public class S3BucketResource : IDisplayedResourceCommand { private readonly IAWSResourceQueryer _awsResourceQueryer; public S3BucketResource(IAWSResourceQueryer awsResourceQueryer) { _awsResourceQueryer = awsResourceQueryer; } public async Task<Dictionary<string, string>> Execute(string resourceId) { var metadata = new Dictionary<string, string> { { "Bucket Name", resourceId } }; var webSiteConfiguration = await _awsResourceQueryer.GetS3BucketWebSiteConfiguration(resourceId); // Only add an endpoint if the S3 bucket has been configured to have a website configuration. if(webSiteConfiguration != null && !string.IsNullOrEmpty(webSiteConfiguration.IndexDocumentSuffix)) { string region = await _awsResourceQueryer.GetS3BucketLocation(resourceId); string regionSeparator = "."; if (string.Equals("us-east-1", region) || string.Equals("us-west-1", region) || string.Equals("us-west-2", region) || string.Equals("ap-southeast-1", region) || string.Equals("ap-southeast-2", region) || string.Equals("ap-northeast-1", region) || string.Equals("eu-west-1", region) || string.Equals("sa-east-1", region)) { regionSeparator = "-"; } var endpoint = $"http://{resourceId}.s3-website{regionSeparator}{region}.amazonaws.com/"; metadata["Endpoint"] = endpoint; } return metadata; } } }
52
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.Orchestration.LocalUserSettings { public class LastDeployedStack { public string AWSAccountId { get; set; } public string AWSRegion { get; set; } public string ProjectName { get; set; } public List<string> Stacks { get; set; } public LastDeployedStack(string awsAccountId, string awsRegion, string projectName, List<string> stacks) { AWSAccountId = awsAccountId; AWSRegion = awsRegion; ProjectName = projectName; Stacks = stacks; } public bool Exists(string? awsAccountId, string? awsRegion, string? projectName) { if (string.IsNullOrEmpty(AWSAccountId) || string.IsNullOrEmpty(AWSRegion) || string.IsNullOrEmpty(ProjectName)) return false; if (string.IsNullOrEmpty(awsAccountId) || string.IsNullOrEmpty(awsRegion) || string.IsNullOrEmpty(projectName)) return false; if (AWSAccountId.Equals(awsAccountId) && AWSRegion.Equals(awsRegion) && ProjectName.Equals(projectName)) return true; return false; } } }
47
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.Orchestration.LocalUserSettings { public class LocalUserSettings { public List<LastDeployedStack> LastDeployedStacks = new List<LastDeployedStack>(); } }
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.IO; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using Newtonsoft.Json; namespace AWS.Deploy.Orchestration.LocalUserSettings { public interface ILocalUserSettingsEngine { Task UpdateLastDeployedStack(string stackName, string projectName, string? awsAccountId, string? awsRegion); Task DeleteLastDeployedStack(string stackName, string projectName, string? awsAccountId, string? awsRegion); Task CleanOrphanStacks(List<string> deployedStacks, string projectName, string? awsAccountId, string? awsRegion); Task<LocalUserSettings?> GetLocalUserSettings(); } public class LocalUserSettingsEngine : ILocalUserSettingsEngine { private readonly IFileManager _fileManager; private readonly IDirectoryManager _directoryManager; private readonly IDeployToolWorkspaceMetadata _workspaceMetadata; private const string LOCAL_USER_SETTINGS_FILE_NAME = "local-user-settings.json"; public LocalUserSettingsEngine(IFileManager fileManager, IDirectoryManager directoryManager, IDeployToolWorkspaceMetadata workspaceMetadata) { _fileManager = fileManager; _directoryManager = directoryManager; _workspaceMetadata = workspaceMetadata; } /// <summary> /// This method updates the local user settings json file by adding the name of the stack that was most recently used. /// If the file does not exists then a new file is generated. /// </summary> public async Task UpdateLastDeployedStack(string stackName, string projectName, string? awsAccountId, string? awsRegion) { try { if (string.IsNullOrEmpty(projectName)) throw new FailedToUpdateLocalUserSettingsFileException(DeployToolErrorCode.FailedToUpdateLocalUserSettingsFile, "The Project Name is not defined."); if (string.IsNullOrEmpty(awsAccountId) || string.IsNullOrEmpty(awsRegion)) throw new FailedToUpdateLocalUserSettingsFileException(DeployToolErrorCode.FailedToUpdateLocalUserSettingsFile, "The AWS Account Id or Region is not defined."); var localUserSettings = await GetLocalUserSettings(); var lastDeployedStack = localUserSettings?.LastDeployedStacks? .FirstOrDefault(x => x.Exists(awsAccountId, awsRegion, projectName)); if (localUserSettings != null) { if (lastDeployedStack != null) { if (lastDeployedStack.Stacks == null) { lastDeployedStack.Stacks = new List<string> { stackName }; } else { if (!lastDeployedStack.Stacks.Contains(stackName)) lastDeployedStack.Stacks.Add(stackName); lastDeployedStack.Stacks.Sort(); } } else { var currentStack = new LastDeployedStack( awsAccountId, awsRegion, projectName, new List<string>() { stackName }); if (localUserSettings.LastDeployedStacks == null) { localUserSettings.LastDeployedStacks = new List<LastDeployedStack>() { currentStack }; } else { localUserSettings.LastDeployedStacks.Add(currentStack); } } } else { var lastDeployedStacks = new List<LastDeployedStack> { new LastDeployedStack( awsAccountId, awsRegion, projectName, new List<string>() { stackName }) }; localUserSettings = new LocalUserSettings { LastDeployedStacks = lastDeployedStacks }; } await WriteLocalUserSettingsFile(localUserSettings); } catch (Exception ex) { throw new FailedToUpdateLocalUserSettingsFileException(DeployToolErrorCode.FailedToUpdateLocalUserSettingsFile, $"Failed to update the local user settings file " + $"to include the last deployed to stack '{stackName}'.", ex); } } /// <summary> /// This method updates the local user settings json file by deleting the stack that was most recently used. /// </summary> public async Task DeleteLastDeployedStack(string stackName, string projectName, string? awsAccountId, string? awsRegion) { try { if (string.IsNullOrEmpty(projectName)) throw new FailedToUpdateLocalUserSettingsFileException(DeployToolErrorCode.FailedToUpdateLocalUserSettingsFile, "The Project Name is not defined."); if (string.IsNullOrEmpty(awsAccountId) || string.IsNullOrEmpty(awsRegion)) throw new FailedToUpdateLocalUserSettingsFileException(DeployToolErrorCode.FailedToUpdateLocalUserSettingsFile, "The AWS Account Id or Region is not defined."); var localUserSettings = await GetLocalUserSettings(); var lastDeployedStack = localUserSettings?.LastDeployedStacks? .FirstOrDefault(x => x.Exists(awsAccountId, awsRegion, projectName)); if (localUserSettings == null || lastDeployedStack == null) return; lastDeployedStack.Stacks.Remove(stackName); await WriteLocalUserSettingsFile(localUserSettings); } catch (Exception ex) { throw new FailedToUpdateLocalUserSettingsFileException(DeployToolErrorCode.FailedToUpdateLocalUserSettingsFile, $"Failed to update the local user settings file " + $"to delete the stack '{stackName}'.", ex); } } /// <summary> /// This method updates the local user settings json file by deleting orphan stacks. /// </summary> public async Task CleanOrphanStacks(List<string> deployedStacks, string projectName, string? awsAccountId, string? awsRegion) { try { if (string.IsNullOrEmpty(projectName)) throw new FailedToUpdateLocalUserSettingsFileException(DeployToolErrorCode.FailedToUpdateLocalUserSettingsFile, "The Project Name is not defined."); if (string.IsNullOrEmpty(awsAccountId) || string.IsNullOrEmpty(awsRegion)) throw new FailedToUpdateLocalUserSettingsFileException(DeployToolErrorCode.FailedToUpdateLocalUserSettingsFile, "The AWS Account Id or Region is not defined."); var localUserSettings = await GetLocalUserSettings(); var localStacks = localUserSettings?.LastDeployedStacks? .FirstOrDefault(x => x.Exists(awsAccountId, awsRegion, projectName)); if (localUserSettings == null || localStacks == null || localStacks.Stacks == null) return; var validStacks = deployedStacks.Intersect(localStacks.Stacks); localStacks.Stacks = validStacks.ToList(); await WriteLocalUserSettingsFile(localUserSettings); } catch (Exception ex) { throw new FailedToUpdateLocalUserSettingsFileException(DeployToolErrorCode.FailedToUpdateLocalUserSettingsFile, $"Failed to update the local user settings file " + $"to delete orphan stacks.", ex); } } /// <summary> /// This method parses the <see cref="LocalUserSettings"/> into a string and writes it to disk. /// </summary> private async Task<string> WriteLocalUserSettingsFile(LocalUserSettings deploymentManifestModel) { var localUserSettingsFilePath = GetLocalUserSettingsFilePath(); var settingsFilejsonString = JsonConvert.SerializeObject(deploymentManifestModel, new JsonSerializerSettings { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore }); await _fileManager.WriteAllTextAsync(localUserSettingsFilePath, settingsFilejsonString); return localUserSettingsFilePath; } /// <summary> /// This method parses the local user settings file into a <see cref="LocalUserSettings"/> /// </summary> public async Task<LocalUserSettings?> GetLocalUserSettings() { try { var localUserSettingsFilePath = GetLocalUserSettingsFilePath(); if (!_fileManager.Exists(localUserSettingsFilePath)) return null; var settingsFilejsonString = await _fileManager.ReadAllTextAsync(localUserSettingsFilePath); return JsonConvert.DeserializeObject<LocalUserSettings>(settingsFilejsonString); } catch (Exception ex) { throw new InvalidLocalUserSettingsFileException(DeployToolErrorCode.InvalidLocalUserSettingsFile, "The Local User Settings file is invalid.", ex); } } /// <summary> /// This method returns the path at which the local user settings file will be stored. /// </summary> private string GetLocalUserSettingsFilePath() { var deployToolWorkspace = _directoryManager.GetDirectoryInfo(_workspaceMetadata.DeployToolWorkspaceDirectoryRoot).FullName; var localUserSettingsFileFullPath = Path.Combine(deployToolWorkspace, LOCAL_USER_SETTINGS_FILE_NAME); return localUserSettingsFileFullPath; } } }
224
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; namespace AWS.Deploy.Orchestration.RecommendationEngine { /// <summary> /// The base class for all recommendation tests used to run the logic for a model test to see if a recipe is valid for a given project. /// The RecommendationEngine will load up all types that extends from this base class and register them by their Name. /// </summary> public abstract class BaseRecommendationTest { /// <summary> /// The name of the test. This will match the value used in recipes when defining the test they want to perform. /// </summary> public abstract string Name { get; } /// <summary> /// Executes the test /// </summary> /// <param name="input"></param> /// <returns>True for successful test pass, otherwise false.</returns> public abstract Task<bool> Execute(RecommendationTestInput input); } }
27
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.Threading.Tasks; namespace AWS.Deploy.Orchestration.RecommendationEngine { /// <summary> /// This test checks to see if a file exists within the project directory. /// </summary> public class FileExistsTest : BaseRecommendationTest { public override string Name => "FileExists"; public override Task<bool> Execute(RecommendationTestInput input) { var directory = Path.GetDirectoryName(input.ProjectDefinition.ProjectPath); if (directory == null || input.Test.Condition.FileName == null) return Task.FromResult(false); var result = (Directory.GetFiles(directory, input.Test.Condition.FileName).Length == 1); return Task.FromResult(result); } } }
29
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.Threading.Tasks; namespace AWS.Deploy.Orchestration.RecommendationEngine { /// <summary> /// This test checks the value of the Sdk attribute of the root Project node of a .NET project file. /// </summary> public class MSProjectSdkAttributeTest : BaseRecommendationTest { public override string Name => "MSProjectSdkAttribute"; public override Task<bool> Execute(RecommendationTestInput input) { bool result = false; if(!string.IsNullOrEmpty(input.Test.Condition.Value)) { result = string.Equals(input.ProjectDefinition.SdkType, input.Test.Condition.Value, StringComparison.InvariantCultureIgnoreCase); } else if(input.Test.Condition.AllowedValues?.Count > 0) { result = input.Test.Condition.AllowedValues.Contains(input.ProjectDefinition.SdkType); } return Task.FromResult(result); } } }
32
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; namespace AWS.Deploy.Orchestration.RecommendationEngine { /// <summary> /// This test checks to see if a property in a PropertyGroup of the .NET project exists. /// </summary> public class MSPropertyExistsTest : BaseRecommendationTest { public override string Name => "MSPropertyExists"; public override Task<bool> Execute(RecommendationTestInput input) { var result = !string.IsNullOrEmpty(input.ProjectDefinition.GetMSPropertyValue(input.Test.Condition.PropertyName)); return Task.FromResult(result); } } }
22
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; namespace AWS.Deploy.Orchestration.RecommendationEngine { /// <summary> /// This test checks to see if the value of a property in a PropertyGroup of the .NET project exists. /// </summary> public class MSPropertyTest : BaseRecommendationTest { public override string Name => "MSProperty"; public override Task<bool> Execute(RecommendationTestInput input) { var propertyValue = input.ProjectDefinition.GetMSPropertyValue(input.Test.Condition.PropertyName); var result = (propertyValue != null && input.Test.Condition.AllowedValues.Contains(propertyValue)); return Task.FromResult(result); } } }
23