repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Threading.Tasks; namespace AWS.Deploy.Orchestration.RecommendationEngine { public class NuGetPackageReferenceTest : BaseRecommendationTest { public override string Name => "NuGetPackageReference"; public override Task<bool> Execute(RecommendationTestInput input) { var result = !string.IsNullOrEmpty(input.ProjectDefinition.GetPackageReferenceVersion(input.Test.Condition.NuGetPackageName)); return Task.FromResult(result); } } }
19
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Recipes; using Newtonsoft.Json; namespace AWS.Deploy.Orchestration.RecommendationEngine { public class RecommendationEngine { private readonly OrchestratorSession _orchestratorSession; private readonly IRecipeHandler _recipeHandler; public RecommendationEngine(OrchestratorSession orchestratorSession, IRecipeHandler recipeHandler) { _orchestratorSession = orchestratorSession; _recipeHandler = recipeHandler; } public async Task<List<Recommendation>> ComputeRecommendations(List<string>? recipeDefinitionPaths = null, Dictionary<string, object>? additionalReplacements = null) { additionalReplacements ??= new Dictionary<string, object>(); var recommendations = new List<Recommendation>(); var availableRecommendations = await _recipeHandler.GetRecipeDefinitions(recipeDefinitionPaths); foreach (var potentialRecipe in availableRecommendations) { var results = await EvaluateRules(potentialRecipe.RecommendationRules); if(!results.Include) { continue; } var priority = potentialRecipe.RecipePriority + results.PriorityAdjustment; // Recipes with a negative priority are ignored. if (priority < 0) { continue; } recommendations.Add(new Recommendation(potentialRecipe, _orchestratorSession.ProjectDefinition, priority, additionalReplacements)); } recommendations = recommendations.OrderByDescending(recommendation => recommendation.ComputedPriority).ThenBy(recommendation => recommendation.Name).ToList(); return recommendations; } public async Task<RulesResult> EvaluateRules(IList<RecommendationRuleItem> rules) { // If there are no rules the recipe must be invalid so don't include it. if (false == rules?.Any()) { return new RulesResult { Include = false }; } var availableTests = RecommendationTestFactory.LoadAvailableTests(); var results = new RulesResult {Include = true }; foreach (var rule in rules!) { var allTestPass = true; foreach (var test in rule.Tests) { if(!availableTests.TryGetValue(test.Type, out var testInstance)) { throw new InvalidRecipeDefinitionException(DeployToolErrorCode.RuleHasInvalidTestType, $"Invalid test type [{test.Type}] found in rule."); } var input = new RecommendationTestInput( test, _orchestratorSession.ProjectDefinition, _orchestratorSession); allTestPass &= await testInstance.Execute(input); if (!allTestPass) break; } results.Include &= ShouldInclude(rule.Effect, allTestPass); var effectOptions = GetEffectOptions(rule.Effect, allTestPass); if(effectOptions != null) { if(effectOptions.PriorityAdjustment.HasValue) { results.PriorityAdjustment += effectOptions.PriorityAdjustment.Value; } } } return results; } public bool ShouldInclude(RuleEffect? effect, bool testPass) { // Get either the pass or fail effect options. var effectOptions = GetEffectOptions(effect, testPass); if (effectOptions != null) { if (effectOptions.Include.HasValue) { return effectOptions.Include.Value; } else { return true; } } return testPass; } private EffectOptions? GetEffectOptions(RuleEffect? effect, bool testPass) { if (effect == null) { return null; } return testPass ? effect.Pass : effect.Fail; } public class RulesResult { public bool Include { get; set; } public int PriorityAdjustment { get; set; } } } }
140
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; namespace AWS.Deploy.Orchestration.RecommendationEngine { public class RecommendationTestFactory { public static IDictionary<string, BaseRecommendationTest> LoadAvailableTests() { return typeof(BaseRecommendationTest) .Assembly .GetTypes() .Where(x => !x.IsAbstract && x.IsSubclassOf(typeof(BaseRecommendationTest))) .Select(x => Activator.CreateInstance(x) as BaseRecommendationTest) .Where(x => x != null) .Select(x => x!) .ToDictionary(x => x.Name); } } }
26
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; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.Orchestration.RecommendationEngine { /// <summary> /// The input fields passed into recommendation tests. /// </summary> public class RecommendationTestInput { /// <summary> /// The modeled test and its conditions from the recipe. /// </summary> public RuleTest Test { get; set; } /// <summary> /// The definition of the project which provides access to project metadata. /// </summary> public ProjectDefinition ProjectDefinition { get; set; } /// <summary> /// The session that provides access to the AWS credentials and region configured. This allows /// potential tests to check for AWS resources in the account being deployed to. /// </summary> public OrchestratorSession Session { get; set; } public RecommendationTestInput( RuleTest test, ProjectDefinition projectDefinition, OrchestratorSession session) { Test = test; ProjectDefinition = projectDefinition; Session = session; } } }
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.IO.Compression; using System.IO; using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Amazon.ElasticBeanstalk; using Amazon.ElasticBeanstalk.Model; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using System.Text.Json.Serialization; namespace AWS.Deploy.Orchestration.ServiceHandlers { public interface IElasticBeanstalkHandler { /// <summary> /// Deployments to Windows Elastic Beanstalk envvironments require a manifest file to be included with the binaries. /// This method creates the manifest file if it doesn't exist, or it creates a new one. /// The two main settings that are updated are IIS Website and IIS App Path. /// </summary> void SetupWindowsDeploymentManifest(Recommendation recommendation, string dotnetZipFilePath); /// <summary> /// When deploying a self contained deployment bundle, Beanstalk needs a Procfile to tell the environment what process to start up. /// Check out the AWS Elastic Beanstalk developer guide for more information on Procfiles /// https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/dotnet-linux-procfile.html /// </summary> void SetupProcfileForSelfContained(string dotnetZipFilePath); Task<S3Location> CreateApplicationStorageLocationAsync(string applicationName, string versionLabel, string deploymentPackage); Task<CreateApplicationVersionResponse> CreateApplicationVersionAsync(string applicationName, string versionLabel, S3Location sourceBundle); Task<bool> UpdateEnvironmentAsync(string applicationName, string environmentName, string versionLabel, List<ConfigurationOptionSetting> optionSettings); List<ConfigurationOptionSetting> GetEnvironmentConfigurationSettings(Recommendation recommendation); } /// <summary> /// This class represents the structure of the Windows manifest file to be included with Windows Elastic Beanstalk deployments. /// </summary> public class ElasticBeanstalkWindowsManifest { [JsonPropertyName("manifestVersion")] public int ManifestVersion { get; set; } = 1; [JsonPropertyName("deployments")] public ManifestDeployments Deployments { get; set; } = new(); public class ManifestDeployments { [JsonPropertyName("aspNetCoreWeb")] public List<AspNetCoreWebDeployments> AspNetCoreWeb { get; set; } = new(); public class AspNetCoreWebDeployments { [JsonPropertyName("name")] public string Name { get; set; } = "app"; [JsonPropertyName("parameters")] public AspNetCoreWebParameters Parameters { get; set; } = new(); public class AspNetCoreWebParameters { [JsonPropertyName("appBundle")] public string AppBundle { get; set; } = "."; [JsonPropertyName("iisPath")] public string IISPath { get; set; } = "/"; [JsonPropertyName("iisWebSite")] public string IISWebSite { get; set; } = "Default Web Site"; } } } } public class AWSElasticBeanstalkHandler : IElasticBeanstalkHandler { private readonly IAWSClientFactory _awsClientFactory; private readonly IOrchestratorInteractiveService _interactiveService; private readonly IFileManager _fileManager; private readonly IOptionSettingHandler _optionSettingHandler; public AWSElasticBeanstalkHandler(IAWSClientFactory awsClientFactory, IOrchestratorInteractiveService interactiveService, IFileManager fileManager, IOptionSettingHandler optionSettingHandler) { _awsClientFactory = awsClientFactory; _interactiveService = interactiveService; _fileManager = fileManager; _optionSettingHandler = optionSettingHandler; } private T GetOrCreateNode<T>(object? json) where T : new() { try { return JsonSerializer.Deserialize<T>(json?.ToString() ?? string.Empty, new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip }) ?? new T(); } catch { return new T(); } } /// <summary> /// Deployments to Windows Elastic Beanstalk envvironments require a manifest file to be included with the binaries. /// This method creates the manifest file if it doesn't exist, or it creates a new one. /// The two main settings that are updated are IIS Website and IIS App Path. /// </summary> public void SetupWindowsDeploymentManifest(Recommendation recommendation, string dotnetZipFilePath) { var iisWebSiteOptionSetting = _optionSettingHandler.GetOptionSetting(recommendation, Constants.ElasticBeanstalk.IISWebSiteOptionId); var iisAppPathOptionSetting = _optionSettingHandler.GetOptionSetting(recommendation, Constants.ElasticBeanstalk.IISAppPathOptionId); var iisWebSiteValue = _optionSettingHandler.GetOptionSettingValue<string>(recommendation, iisWebSiteOptionSetting); var iisAppPathValue = _optionSettingHandler.GetOptionSettingValue<string>(recommendation, iisAppPathOptionSetting); var iisWebSite = !string.IsNullOrEmpty(iisWebSiteValue) ? iisWebSiteValue : "Default Web Site"; var iisAppPath = !string.IsNullOrEmpty(iisAppPathValue) ? iisAppPathValue : "/"; var newManifestFile = new ElasticBeanstalkWindowsManifest(); newManifestFile.Deployments.AspNetCoreWeb.Add(new ElasticBeanstalkWindowsManifest.ManifestDeployments.AspNetCoreWebDeployments { Parameters = new ElasticBeanstalkWindowsManifest.ManifestDeployments.AspNetCoreWebDeployments.AspNetCoreWebParameters { IISPath = iisAppPath, IISWebSite = iisWebSite } }); using (var zipArchive = ZipFile.Open(dotnetZipFilePath, ZipArchiveMode.Update)) { var zipEntry = zipArchive.GetEntry(Constants.ElasticBeanstalk.WindowsManifestName); var serializedManifest = JsonSerializer.Serialize(new Dictionary<string, object>()); if (zipEntry != null) { using (var streamReader = new StreamReader(zipEntry.Open())) { serializedManifest = streamReader.ReadToEnd(); } } var jsonDoc = GetOrCreateNode<Dictionary<string, object>>(serializedManifest); if (!jsonDoc.ContainsKey("manifestVersion")) { jsonDoc["manifestVersion"] = newManifestFile.ManifestVersion; } if (jsonDoc.ContainsKey("deployments")) { var deploymentNode = GetOrCreateNode<Dictionary<string, object>>(jsonDoc["deployments"]); if (deploymentNode.ContainsKey("aspNetCoreWeb")) { var aspNetCoreWebNode = GetOrCreateNode<List<object>>(deploymentNode["aspNetCoreWeb"]); if (aspNetCoreWebNode.Count == 0) { aspNetCoreWebNode.Add(newManifestFile.Deployments.AspNetCoreWeb[0]); } else { // We only need 1 entry in the 'aspNetCoreWeb' node that defines the parameters we are interested in. Typically, only 1 entry exists. var aspNetCoreWebEntry = GetOrCreateNode<Dictionary<string, object>>(JsonSerializer.Serialize(aspNetCoreWebNode[0])); var nameValue = aspNetCoreWebEntry.ContainsKey("name") ? aspNetCoreWebEntry["name"].ToString() : string.Empty; aspNetCoreWebEntry["name"] = !string.IsNullOrEmpty(nameValue) ? nameValue : newManifestFile.Deployments.AspNetCoreWeb[0].Name; if (aspNetCoreWebEntry.ContainsKey("parameters")) { var parametersNode = GetOrCreateNode<Dictionary<string, object>>(aspNetCoreWebEntry["parameters"]); parametersNode["appBundle"] = "."; parametersNode["iisPath"] = iisAppPath; parametersNode["iisWebSite"] = iisWebSite; aspNetCoreWebEntry["parameters"] = parametersNode; } else { aspNetCoreWebEntry["parameters"] = newManifestFile.Deployments.AspNetCoreWeb[0].Parameters; } aspNetCoreWebNode[0] = aspNetCoreWebEntry; } deploymentNode["aspNetCoreWeb"] = aspNetCoreWebNode; } else { deploymentNode["aspNetCoreWeb"] = newManifestFile.Deployments.AspNetCoreWeb; } jsonDoc["deployments"] = deploymentNode; } else { jsonDoc["deployments"] = newManifestFile.Deployments; } using (var jsonStream = new MemoryStream(JsonSerializer.SerializeToUtf8Bytes(jsonDoc, new JsonSerializerOptions { WriteIndented = true }))) { zipEntry ??= zipArchive.CreateEntry(Constants.ElasticBeanstalk.WindowsManifestName); using var zipEntryStream = zipEntry.Open(); jsonStream.Position = 0; jsonStream.CopyTo(zipEntryStream); } } } /// <summary> /// When deploying a self contained deployment bundle, Beanstalk needs a Procfile to tell the environment what process to start up. /// Check out the AWS Elastic Beanstalk developer guide for more information on Procfiles /// https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/dotnet-linux-procfile.html /// /// This code is a copy of the code in the AspNetAppElasticBeanstalkLinux CDK recipe definition. Any changes to this method /// should be made into that version as well. /// </summary> /// <param name="dotnetZipFilePath"></param> public void SetupProcfileForSelfContained(string dotnetZipFilePath) { const string RUNTIME_CONFIG_SUFFIX = ".runtimeconfig.json"; const string PROCFILE_NAME = "Procfile"; string runtimeConfigFilename; string runtimeConfigJson; using (var zipArchive = ZipFile.Open(dotnetZipFilePath, ZipArchiveMode.Read)) { // Skip Procfile setup if one already exists. if (zipArchive.GetEntry(PROCFILE_NAME) != null) { return; } var runtimeConfigEntry = zipArchive.Entries.FirstOrDefault(x => x.Name.EndsWith(RUNTIME_CONFIG_SUFFIX)); if (runtimeConfigEntry == null) { return; } runtimeConfigFilename = runtimeConfigEntry.Name; using var stream = runtimeConfigEntry.Open(); runtimeConfigJson = new StreamReader(stream).ReadToEnd(); } var runtimeConfigDoc = JsonDocument.Parse(runtimeConfigJson); if (!runtimeConfigDoc.RootElement.TryGetProperty("runtimeOptions", out var runtimeOptionsNode)) { return; } // If there are includedFrameworks then the zip file is a self contained deployment bundle. if (!runtimeOptionsNode.TryGetProperty("includedFrameworks", out _)) { return; } var executableName = runtimeConfigFilename.Substring(0, runtimeConfigFilename.Length - RUNTIME_CONFIG_SUFFIX.Length); var procCommand = $"web: ./{executableName}"; using (var zipArchive = ZipFile.Open(dotnetZipFilePath, ZipArchiveMode.Update)) { var procfileEntry = zipArchive.CreateEntry(PROCFILE_NAME); using var zipEntryStream = procfileEntry.Open(); zipEntryStream.Write(System.Text.UTF8Encoding.UTF8.GetBytes(procCommand)); } } public async Task<S3Location> CreateApplicationStorageLocationAsync(string applicationName, string versionLabel, string deploymentPackage) { string bucketName; try { var ebClient = _awsClientFactory.GetAWSClient<IAmazonElasticBeanstalk>(); bucketName = (await ebClient.CreateStorageLocationAsync()).S3Bucket; } catch (Exception e) { throw new ElasticBeanstalkException(DeployToolErrorCode.FailedToCreateElasticBeanstalkStorageLocation, "An error occured while creating the Elastic Beanstalk storage location", e); } var key = string.Format("{0}/AWSDeploymentArchive_{0}_{1}{2}", applicationName.Replace(' ', '-'), versionLabel.Replace(' ', '-'), _fileManager.GetExtension(deploymentPackage)); return new S3Location { S3Bucket = bucketName, S3Key = key }; } public async Task<CreateApplicationVersionResponse> CreateApplicationVersionAsync(string applicationName, string versionLabel, S3Location sourceBundle) { _interactiveService.LogInfoMessage("Creating new application version: " + versionLabel); try { var ebClient = _awsClientFactory.GetAWSClient<IAmazonElasticBeanstalk>(); var response = await ebClient.CreateApplicationVersionAsync(new CreateApplicationVersionRequest { ApplicationName = applicationName, VersionLabel = versionLabel, SourceBundle = sourceBundle }); return response; } catch (Exception e) { throw new ElasticBeanstalkException(DeployToolErrorCode.FailedToCreateElasticBeanstalkApplicationVersion, "An error occured while creating the Elastic Beanstalk application version", e); } } public List<ConfigurationOptionSetting> GetEnvironmentConfigurationSettings(Recommendation recommendation) { var additionalSettings = new List<ConfigurationOptionSetting>(); List<(string OptionSettingId, string OptionSettingNameSpace, string OptionSettingName)> tupleList; switch (recommendation.Recipe.Id) { case Constants.RecipeIdentifier.EXISTING_BEANSTALK_ENVIRONMENT_RECIPE_ID: tupleList = Constants.ElasticBeanstalk.OptionSettingQueryList; break; case Constants.RecipeIdentifier.EXISTING_BEANSTALK_WINDOWS_ENVIRONMENT_RECIPE_ID: tupleList = Constants.ElasticBeanstalk.WindowsOptionSettingQueryList; break; default: throw new InvalidOperationException($"The recipe '{recommendation.Recipe.Id}' is not supported."); }; foreach (var tuple in tupleList) { var optionSetting = _optionSettingHandler.GetOptionSetting(recommendation, tuple.OptionSettingId); if (!optionSetting.Updatable) continue; var optionSettingValue = optionSetting.GetValue<string>(new Dictionary<string, object>()); additionalSettings.Add(new ConfigurationOptionSetting { Namespace = tuple.OptionSettingNameSpace, OptionName = tuple.OptionSettingName, Value = optionSettingValue }); } return additionalSettings; } public async Task<bool> UpdateEnvironmentAsync(string applicationName, string environmentName, string versionLabel, List<ConfigurationOptionSetting> optionSettings) { _interactiveService.LogInfoMessage("Getting latest environment event date before update"); var startingEventDate = await GetLatestEventDateAsync(applicationName, environmentName); _interactiveService.LogInfoMessage($"Updating environment {environmentName} to new application version {versionLabel}"); var updateRequest = new UpdateEnvironmentRequest { ApplicationName = applicationName, EnvironmentName = environmentName, VersionLabel = versionLabel, OptionSettings = optionSettings }; try { var ebClient = _awsClientFactory.GetAWSClient<IAmazonElasticBeanstalk>(); var updateEnvironmentResponse = await ebClient.UpdateEnvironmentAsync(updateRequest); return await WaitForEnvironmentUpdateCompletion(applicationName, environmentName, startingEventDate); } catch (Exception e) { throw new ElasticBeanstalkException(DeployToolErrorCode.FailedToUpdateElasticBeanstalkEnvironment, "An error occured while updating the Elastic Beanstalk environment", e); } } private async Task<DateTime> GetLatestEventDateAsync(string applicationName, string environmentName) { var request = new DescribeEventsRequest { ApplicationName = applicationName, EnvironmentName = environmentName }; var ebClient = _awsClientFactory.GetAWSClient<IAmazonElasticBeanstalk>(); var response = await ebClient.DescribeEventsAsync(request); if (response.Events.Count == 0) return DateTime.Now; return response.Events.First().EventDate; } private async Task<bool> WaitForEnvironmentUpdateCompletion(string applicationName, string environmentName, DateTime startingEventDate) { _interactiveService.LogInfoMessage("Waiting for environment update to complete"); var success = true; var environment = new EnvironmentDescription(); var lastPrintedEventDate = startingEventDate; var requestEvents = new DescribeEventsRequest { ApplicationName = applicationName, EnvironmentName = environmentName }; var requestEnvironment = new DescribeEnvironmentsRequest { ApplicationName = applicationName, EnvironmentNames = new List<string> { environmentName } }; var ebClient = _awsClientFactory.GetAWSClient<IAmazonElasticBeanstalk>(); do { Thread.Sleep(5000); var responseEnvironments = await ebClient.DescribeEnvironmentsAsync(requestEnvironment); if (responseEnvironments.Environments.Count == 0) throw new AWSResourceNotFoundException(DeployToolErrorCode.BeanstalkEnvironmentDoesNotExist, $"Failed to find environment {environmentName} belonging to application {applicationName}"); environment = responseEnvironments.Environments[0]; requestEvents.StartTimeUtc = lastPrintedEventDate; var responseEvents = await ebClient.DescribeEventsAsync(requestEvents); if (responseEvents.Events.Any()) { for (var i = responseEvents.Events.Count - 1; i >= 0; i--) { var evnt = responseEvents.Events[i]; if (evnt.EventDate <= lastPrintedEventDate) continue; _interactiveService.LogInfoMessage(evnt.EventDate.ToLocalTime() + " " + evnt.Severity + " " + evnt.Message); if (evnt.Severity == EventSeverity.ERROR || evnt.Severity == EventSeverity.FATAL) { success = false; } } lastPrintedEventDate = responseEvents.Events[0].EventDate; } } while (environment.Status == EnvironmentStatus.Launching || environment.Status == EnvironmentStatus.Updating); return success; } } }
452
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 Amazon.S3; using Amazon.S3.Transfer; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; namespace AWS.Deploy.Orchestration.ServiceHandlers { public interface IS3Handler { Task UploadToS3Async(string bucket, string key, string filePath); } public class AWSS3Handler : IS3Handler { private readonly IAWSClientFactory _awsClientFactory; private readonly IOrchestratorInteractiveService _interactiveService; private readonly IFileManager _fileManager; private const int UPLOAD_PROGRESS_INCREMENT = 10; public AWSS3Handler(IAWSClientFactory awsClientFactory, IOrchestratorInteractiveService interactiveService, IFileManager fileManager) { _awsClientFactory = awsClientFactory; _interactiveService = interactiveService; _fileManager = fileManager; } public async Task UploadToS3Async(string bucket, string key, string filePath) { using (var stream = _fileManager.OpenRead(filePath)) { _interactiveService.LogInfoMessage($"Uploading to S3. (Bucket: {bucket} Key: {key} Size: {_fileManager.GetSizeInBytes(filePath)} bytes)"); var request = new TransferUtilityUploadRequest() { BucketName = bucket, Key = key, InputStream = stream }; request.UploadProgressEvent += CreateTransferUtilityProgressHandler(); try { var s3Client = _awsClientFactory.GetAWSClient<IAmazonS3>(); await new TransferUtility(s3Client).UploadAsync(request); } catch (Exception e) { throw new S3Exception(DeployToolErrorCode.FailedS3Upload, $"Error uploading to {key} in bucket {bucket}", innerException: e); } } } private EventHandler<UploadProgressArgs> CreateTransferUtilityProgressHandler() { var percentToUpdateOn = UPLOAD_PROGRESS_INCREMENT; EventHandler<UploadProgressArgs> handler = ((s, e) => { if (e.PercentDone != percentToUpdateOn && e.PercentDone <= percentToUpdateOn) return; var increment = e.PercentDone % UPLOAD_PROGRESS_INCREMENT; if (increment == 0) increment = UPLOAD_PROGRESS_INCREMENT; percentToUpdateOn = e.PercentDone + increment; _interactiveService.LogInfoMessage($"... Progress: {e.PercentDone}%"); }); return handler; } } }
81
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.Orchestration.ServiceHandlers { public interface IAWSServiceHandler { IS3Handler S3Handler { get; } IElasticBeanstalkHandler ElasticBeanstalkHandler { get; } } public class AWSServiceHandler : IAWSServiceHandler { public IS3Handler S3Handler { get; } public IElasticBeanstalkHandler ElasticBeanstalkHandler { get; } public AWSServiceHandler(IS3Handler s3Handler, IElasticBeanstalkHandler elasticBeanstalkHandler) { S3Handler = s3Handler; ElasticBeanstalkHandler = elasticBeanstalkHandler; } } }
28
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.Text.RegularExpressions; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.Orchestration.Utilities { public interface ICloudApplicationNameGenerator { /// <summary> /// Generates a valid candidate for <see cref="CloudApplication.Name"/> based on <paramref name="target"/>. /// Name is checked to ensure it is unique, ie <paramref name="existingApplications"/> doesn't already have it. /// </summary> /// <exception cref="ArgumentException"> /// Thrown if can't generate a valid name from <paramref name="target"/>. /// </exception> string GenerateValidName(ProjectDefinition target, List<CloudApplication> existingApplications, DeploymentTypes? deploymentType = null); /// <summary> /// Validates the cloud application name /// </summary> /// <param name="name">User provided cloud application name</param> /// <param name="deploymentType">The deployment type of the selected recommendation</param> /// <param name="existingApplications">List of existing deployed applications</param> /// <returns><see cref="CloudApplicationNameValidationResult"/></returns> CloudApplicationNameValidationResult IsValidName(string name, IList<CloudApplication> existingApplications, DeploymentTypes? deploymentType = null); } /// <summary> /// Stores the result from validating the cloud application name. /// </summary> public class CloudApplicationNameValidationResult { public readonly bool IsValid; public readonly string ErrorMessage; public CloudApplicationNameValidationResult(bool isValid, string errorMessage) { IsValid = isValid; ErrorMessage = errorMessage; } } public class CloudApplicationNameGenerator : ICloudApplicationNameGenerator { private readonly IFileManager _fileManager; private readonly IDirectoryManager _directoryManager; /// <summary> /// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-using-console-create-stack-parameters.html /// </summary> private readonly Regex _validatorRegex = new ("^[a-zA-Z][a-zA-Z0-9-]{0,127}$", RegexOptions.Compiled); public CloudApplicationNameGenerator(IFileManager fileManager, IDirectoryManager directoryManager) { _fileManager = fileManager; _directoryManager = directoryManager; } public string GenerateValidName(ProjectDefinition target, List<CloudApplication> existingApplications, DeploymentTypes? deploymentType = null) { // generate recommendation var recommendedPrefix = "deployment"; if (_fileManager.Exists(target.ProjectPath)) recommendedPrefix = Path.GetFileNameWithoutExtension(target.ProjectPath) ?? ""; else if (_directoryManager.Exists(target.ProjectPath)) recommendedPrefix = Path.GetDirectoryName(target.ProjectPath) ?? ""; // sanitize recommendation recommendedPrefix = new string( recommendedPrefix .ToCharArray() .SkipWhile(c => !char.IsLetter(c) && ((int)c) < 127) .Where(c => char.IsNumber(c) || char.IsLetter(c) && ((int)c) < 127 || c == '-') .ToArray()); // make sure the recommendation doesn't exist already in existingApplications var recommendation = recommendedPrefix; var suffixString = ""; var recommendationCharArray = recommendation.ToCharArray(); for (var i = recommendationCharArray.Length - 1; i >= 0; i--) { if (char.IsDigit(recommendationCharArray[i])) suffixString = $"{recommendationCharArray[i]}{suffixString}"; else break; } var prefix = !string.IsNullOrEmpty(suffixString) ? recommendation[..^suffixString.Length] : recommendedPrefix; var suffix = !string.IsNullOrEmpty(suffixString) ? int.Parse(suffixString): 0; while (suffix < int.MaxValue) { var validationResult = IsValidName(recommendation, existingApplications, deploymentType); if (validationResult.IsValid) return recommendation; recommendation = $"{prefix}{++suffix}"; } throw new ArgumentException("Failed to generate a valid and unique name."); } public CloudApplicationNameValidationResult IsValidName(string name, IList<CloudApplication> existingApplications, DeploymentTypes? deploymentType = null) { var errorMessage = string.Empty; if (!SatisfiesRegex(name)) { errorMessage += $"The application name can contain only alphanumeric characters (case-sensitive) and hyphens. " + $"It must start with an alphabetic character and can't be longer than 128 characters.{Environment.NewLine}"; } if (MatchesExistingDeployment(name, existingApplications, deploymentType)) { errorMessage += "A cloud application already exists with this name."; } if (string.IsNullOrEmpty(errorMessage)) return new CloudApplicationNameValidationResult(true, string.Empty); return new CloudApplicationNameValidationResult(false, $"Invalid cloud application name: {name}{Environment.NewLine}{errorMessage}"); } /// <summary> /// This method first filters the existing applications by the current deploymentType if the deploymentType is not null /// It will then check if the current name matches the filtered list of existing applications /// </summary> /// <param name="name">User provided cloud application name</param> /// <param name="deploymentType">The deployment type of the selected recommendation</param> /// <param name="existingApplications">List of existing deployed applications</param> /// <returns>true if found a match. false otherwise</returns> private bool MatchesExistingDeployment(string name, IList<CloudApplication> existingApplications, DeploymentTypes? deploymentType = null) { if (!existingApplications.Any()) return false; if (deploymentType != null) existingApplications = existingApplications.Where(x => x.DeploymentType == deploymentType).ToList(); return existingApplications.Any(x => x.Name == name); } /// <summary> /// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-using-console-create-stack-parameters.html /// </summary> private bool SatisfiesRegex(string name) { return _validatorRegex.IsMatch(name); } } }
165
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.Text.Json; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.ElasticBeanstalk; using Amazon.ElasticBeanstalk.Model; using AWS.Deploy.Common; using AWS.Deploy.Common.Data; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Orchestration.Data; using AWS.Deploy.Orchestration.LocalUserSettings; using AWS.Deploy.Orchestration.ServiceHandlers; namespace AWS.Deploy.Orchestration.Utilities { public interface IDeployedApplicationQueryer { /// <summary> /// Get the list of existing deployed <see cref="CloudApplication"/> based on the deploymentTypes filter. /// </summary> Task<List<CloudApplication>> GetExistingDeployedApplications(List<DeploymentTypes> deploymentTypes); /// <summary> /// Get the list of compatible applications by matching elements of the CloudApplication RecipeId and the recommendation RecipeId. /// </summary> Task<List<CloudApplication>> GetCompatibleApplications(List<Recommendation> recommendations, List<CloudApplication>? allDeployedApplications = null, OrchestratorSession? session = null); /// <summary> /// Checks if the given recommendation can be used for a redeployment to an existing cloudformation stack. /// </summary> bool IsCompatible(CloudApplication application, Recommendation recommendation); /// <summary> /// Gets the current option settings associated with the cloud application. This method is only used for non-CloudFormation based cloud applications. /// </summary> Task<IDictionary<string, object>> GetPreviousSettings(CloudApplication application, Recommendation recommendation); } public class DeployedApplicationQueryer : IDeployedApplicationQueryer { private readonly IAWSResourceQueryer _awsResourceQueryer; private readonly ILocalUserSettingsEngine _localUserSettingsEngine; private readonly IOrchestratorInteractiveService _orchestratorInteractiveService; private readonly IFileManager _fileManager; public DeployedApplicationQueryer( IAWSResourceQueryer awsResourceQueryer, ILocalUserSettingsEngine localUserSettingsEngine, IOrchestratorInteractiveService orchestratorInteractiveService, IFileManager fileManager) { _awsResourceQueryer = awsResourceQueryer; _localUserSettingsEngine = localUserSettingsEngine; _orchestratorInteractiveService = orchestratorInteractiveService; _fileManager = fileManager; } public async Task<List<CloudApplication>> GetExistingDeployedApplications(List<DeploymentTypes> deploymentTypes) { var existingApplications = new List<CloudApplication>(); if (deploymentTypes.Contains(DeploymentTypes.CdkProject)) existingApplications.AddRange(await GetExistingCloudFormationStacks()); if (deploymentTypes.Contains(DeploymentTypes.BeanstalkEnvironment)) existingApplications.AddRange(await GetExistingBeanstalkEnvironments()); return existingApplications; } /// <summary> /// Filters the applications that can be re-deployed using the current set of available recommendations. /// </summary> /// <returns>A list of <see cref="CloudApplication"/> that are compatible for a re-deployment</returns> public async Task<List<CloudApplication>> GetCompatibleApplications(List<Recommendation> recommendations, List<CloudApplication>? allDeployedApplications = null, OrchestratorSession? session = null) { var compatibleApplications = new List<CloudApplication>(); if (allDeployedApplications == null) allDeployedApplications = await GetExistingDeployedApplications(recommendations.Select(x => x.Recipe.DeploymentType).ToList()); foreach (var application in allDeployedApplications) { if (recommendations.Any(rec => IsCompatible(application, rec))) { compatibleApplications.Add(application); } } if (session != null) { try { await _localUserSettingsEngine.CleanOrphanStacks(allDeployedApplications.Select(x => x.Name).ToList(), session.ProjectDefinition.ProjectName, session.AWSAccountId, session.AWSRegion); var deploymentManifest = await _localUserSettingsEngine.GetLocalUserSettings(); var lastDeployedStack = deploymentManifest?.LastDeployedStacks? .FirstOrDefault(x => x.Exists(session.AWSAccountId, session.AWSRegion, session.ProjectDefinition.ProjectName)); return compatibleApplications .Select(x => { x.UpdatedByCurrentUser = lastDeployedStack?.Stacks?.Contains(x.Name) ?? false; return x; }) .OrderByDescending(x => x.UpdatedByCurrentUser) .ThenByDescending(x => x.LastUpdatedTime) .ToList(); } catch (FailedToUpdateLocalUserSettingsFileException ex) { _orchestratorInteractiveService.LogErrorMessage(ex.Message); _orchestratorInteractiveService.LogDebugMessage(ex.PrettyPrint()); } catch (InvalidLocalUserSettingsFileException ex) { _orchestratorInteractiveService.LogErrorMessage(ex.Message); _orchestratorInteractiveService.LogDebugMessage(ex.PrettyPrint()); } } return compatibleApplications .OrderByDescending(x => x.LastUpdatedTime) .ToList(); } /// <summary> /// Checks if the given recommendation can be used for a redeployment to an existing cloudformation stack. /// </summary> public bool IsCompatible(CloudApplication application, Recommendation recommendation) { // For persisted projects check both the recipe id and the base recipe id for compatibility. The base recipe id check is for stacks that // were first created by a system recipe and then later moved to a persisted deployment project. if (recommendation.Recipe.PersistedDeploymentProject) { return string.Equals(recommendation.Recipe.Id, application.RecipeId, StringComparison.Ordinal) || string.Equals(recommendation.Recipe.BaseRecipeId, application.RecipeId, StringComparison.Ordinal); } return string.Equals(recommendation.Recipe.Id, application.RecipeId, StringComparison.Ordinal); } /// <summary> /// Gets the current option settings associated with the cloud application.This method is only used for non-CloudFormation based cloud applications. /// </summary> public async Task<IDictionary<string, object>> GetPreviousSettings(CloudApplication application, Recommendation recommendation) { IDictionary<string, object> previousSettings; switch (application.ResourceType) { case CloudApplicationResourceType.BeanstalkEnvironment: previousSettings = await GetBeanstalkEnvironmentConfigurationSettings(application.Name, recommendation.Recipe.Id, recommendation.ProjectPath); break; default: throw new InvalidOperationException($"Cannot fetch existing option settings for the following {nameof(CloudApplicationResourceType)}: {application.ResourceType}"); } return previousSettings; } /// <summary> /// Fetches existing CloudFormation stacks created by the AWS .NET deployment tool /// </summary> /// <returns>A list of <see cref="CloudApplication"/></returns> private async Task<List<CloudApplication>> GetExistingCloudFormationStacks() { var stacks = await _awsResourceQueryer.GetCloudFormationStacks(); var apps = new List<CloudApplication>(); foreach (var stack in stacks) { // Check to see if stack has AWS .NET deployment tool tag and the stack is not deleted or in the process of being deleted. var deployTag = stack.Tags.FirstOrDefault(tags => string.Equals(tags.Key, Constants.CloudFormationIdentifier.STACK_TAG)); // Skip stacks that don't have AWS .NET deployment tool tag if (deployTag == null || // Skip stacks does not have AWS .NET deployment tool description prefix. (This is filter out stacks that have the tag propagated to it like the Beanstalk stack) (stack.Description == null || !stack.Description.StartsWith(Constants.CloudFormationIdentifier.STACK_DESCRIPTION_PREFIX)) || // Skip tags that are deleted or in the process of being deleted stack.StackStatus.ToString().StartsWith("DELETE")) { continue; } // ROLLBACK_COMPLETE occurs when a stack creation fails and successfully rollbacks with cleaning partially created resources. // In this state, only a delete operation can be performed. (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html) // We don't want to include ROLLBACK_COMPLETE because it never succeeded to deploy. // However, a customer can give name of new application same as ROLLBACK_COMPLETE stack, which will trigger the re-deployment flow on the ROLLBACK_COMPLETE stack. if (stack.StackStatus == StackStatus.ROLLBACK_COMPLETE) { continue; } // If a list of compatible recommendations was given then skip existing applications that were used with a // recipe that is not compatible. var recipeId = deployTag.Value; apps.Add(new CloudApplication(stack.StackName, stack.StackId, CloudApplicationResourceType.CloudFormationStack, recipeId, stack.LastUpdatedTime)); } return apps; } /// <summary> /// Fetches existing Elastic Beanstalk environments that can serve as a deployment target. /// These environments must have a valid dotnet specific platform arn. /// Any environment that was created via the AWS .NET deployment tool as part of a CloudFormation stack is not included. /// </summary> /// <returns>A list of <see cref="CloudApplication"/></returns> private async Task<List<CloudApplication>> GetExistingBeanstalkEnvironments() { var validEnvironments = new List<CloudApplication>(); var environments = await _awsResourceQueryer.ListOfElasticBeanstalkEnvironments(); if (!environments.Any()) return validEnvironments; var dotnetPlatforms = await _awsResourceQueryer.GetElasticBeanstalkPlatformArns(); var dotnetPlatformArns = dotnetPlatforms.Select(x => x.PlatformArn).ToList(); // only select environments that have a dotnet specific platform ARN. environments = environments.Where(x => x.Status == EnvironmentStatus.Ready && dotnetPlatformArns.Contains(x.PlatformArn)).ToList(); foreach (var env in environments) { var tags = await _awsResourceQueryer.ListElasticBeanstalkResourceTags(env.EnvironmentArn); // skips all environments that were created via the deploy tool. if (tags.Any(x => string.Equals(x.Key, Constants.CloudFormationIdentifier.STACK_TAG))) continue; var recipeId = env.PlatformArn.Contains(Constants.ElasticBeanstalk.LinuxPlatformType) ? Constants.RecipeIdentifier.EXISTING_BEANSTALK_ENVIRONMENT_RECIPE_ID : Constants.RecipeIdentifier.EXISTING_BEANSTALK_WINDOWS_ENVIRONMENT_RECIPE_ID; validEnvironments.Add(new CloudApplication(env.EnvironmentName, env.EnvironmentId, CloudApplicationResourceType.BeanstalkEnvironment, recipeId, env.DateUpdated)); } return validEnvironments; } private async Task<IDictionary<string, object>> GetBeanstalkEnvironmentConfigurationSettings(string environmentName, string recipeId, string projectPath) { IDictionary<string, object> optionSettings = new Dictionary<string, object>(); var configurationSettings = await _awsResourceQueryer.GetBeanstalkEnvironmentConfigurationSettings(environmentName); List<(string OptionSettingId, string OptionSettingNameSpace, string OptionSettingName)> tupleList; switch (recipeId) { case Constants.RecipeIdentifier.EXISTING_BEANSTALK_ENVIRONMENT_RECIPE_ID: tupleList = Constants.ElasticBeanstalk.OptionSettingQueryList; break; case Constants.RecipeIdentifier.EXISTING_BEANSTALK_WINDOWS_ENVIRONMENT_RECIPE_ID: tupleList = Constants.ElasticBeanstalk.WindowsOptionSettingQueryList; break; default: throw new InvalidOperationException($"The recipe '{recipeId}' is not supported."); } foreach (var tuple in tupleList) { var configurationSetting = GetBeanstalkEnvironmentConfigurationSetting(configurationSettings, tuple.OptionSettingNameSpace, tuple.OptionSettingName); if (string.IsNullOrEmpty(configurationSetting?.Value)) continue; optionSettings[tuple.OptionSettingId] = configurationSetting.Value; } if (recipeId.Equals(Constants.RecipeIdentifier.EXISTING_BEANSTALK_WINDOWS_ENVIRONMENT_RECIPE_ID)) { var windowsManifest = await GetBeanstalkWindowsManifest(projectPath); if (windowsManifest != null && windowsManifest.Deployments.AspNetCoreWeb.Count != 0) { optionSettings[Constants.ElasticBeanstalk.IISWebSiteOptionId] = windowsManifest.Deployments.AspNetCoreWeb[0].Parameters.IISWebSite; optionSettings[Constants.ElasticBeanstalk.IISAppPathOptionId] = windowsManifest.Deployments.AspNetCoreWeb[0].Parameters.IISPath; } } return optionSettings; } private async Task<ElasticBeanstalkWindowsManifest?> GetBeanstalkWindowsManifest(string projectPath) { try { var manifestPath = Path.Combine(Path.GetDirectoryName(projectPath) ?? string.Empty, Constants.ElasticBeanstalk.WindowsManifestName); if (_fileManager.Exists(manifestPath)) { var manifest = JsonSerializer.Deserialize<ElasticBeanstalkWindowsManifest>(await _fileManager.ReadAllTextAsync(manifestPath), new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip }); return manifest; } return null; } catch (Exception ex) { throw new InvalidWindowsManifestFileException( DeployToolErrorCode.InvalidWindowsManifestFile, $"We detected a malformed Elastic Beanstalk Windows manifest file '{Constants.ElasticBeanstalk.WindowsManifestName}' in your project and were not able to load the previous settings from that file.", ex); } } private ConfigurationOptionSetting? GetBeanstalkEnvironmentConfigurationSetting(List<ConfigurationOptionSetting> configurationSettings, string optionNameSpace, string optionName) { var configurationSetting = configurationSettings .FirstOrDefault(x => string.Equals(optionNameSpace, x.Namespace) && string.Equals(optionName, x.OptionName)); return configurationSetting; } } }
320
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.Orchestration.Utilities { public interface IEnvironmentVariableManager { /// <summary> /// Retrieves the environment variable /// </summary> string? GetEnvironmentVariable(string variable); /// <summary> /// Stores the environment variable with the specified value. The variable is scoped to the current process /// </summary> void SetEnvironmentVariable(string variable, string? value); } public class EnvironmentVariableManager : IEnvironmentVariableManager { public string? GetEnvironmentVariable(string variable) { return Environment.GetEnvironmentVariable(variable); } public void SetEnvironmentVariable(string variable, string? value) { Environment.SetEnvironmentVariable(variable, value); } } }
35
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; namespace AWS.Deploy.Orchestration.Utilities { /// <summary> /// This class holds static helper methods /// </summary> public static class Helpers { /// <summary> /// Wait for <see cref="timeout"/> TimeSpan until <see cref="Predicate{T}"/> isn't satisfied /// </summary> /// <param name="predicate">Termination condition for breaking the wait loop</param> /// <param name="frequency">Interval between the two executions of the task</param> /// <param name="timeout">Interval for timeout, if timeout passes, methods throws <see cref="TimeoutException"/></param> /// <exception cref="TimeoutException">Throws when timeout passes</exception> public static async Task WaitUntil(Func<Task<bool>> predicate, TimeSpan frequency, TimeSpan timeout, CancellationToken cancellationToken = default) { var waitTask = Task.Run(async () => { while (!cancellationToken.IsCancellationRequested && !await predicate()) { await Task.Delay(frequency); } }); if (waitTask != await Task.WhenAny(waitTask, Task.Delay(timeout))) { throw new TimeoutException(); } } /// <summary> /// This method returns the deployment tool workspace directory to create the CDK app during deployment. /// It will first look for AWS_DOTNET_DEPLOYTOOL_WORKSPACE environment variable set by the user. It will be used as the deploy tool workspace if it points to a valid directory whithout whitespace characters in its path. /// If the environment variable is set, it will also create a temp directory inside the workspace and set process scoped TEMP and TMP environment variables that point to the temp directory. /// This additional configuration is required due to a known issue in the CDK - https://github.com/aws/aws-cdk/issues/2532 /// If the override is not present, then it defaults to USERPROFILE/.aws-dotnet-deploy. /// It will throw an exception if the USERPROFILE contains a whitespace character. /// </summary> public static string GetDeployToolWorkspaceDirectoryRoot(string userProfilePath, IDirectoryManager directoryManager, IEnvironmentVariableManager environmentVariableManager) { var overridenWorkspace = environmentVariableManager.GetEnvironmentVariable(Constants.CLI.WORKSPACE_ENV_VARIABLE); var defaultWorkSpace = Path.Combine(userProfilePath, ".aws-dotnet-deploy"); if (overridenWorkspace == null) { return !defaultWorkSpace.Contains(" ") ? defaultWorkSpace : throw new InvalidDeployToolWorkspaceException(DeployToolErrorCode.InvalidDeployToolWorkspace, $"The USERPROFILE path ({userProfilePath}) contains a whitespace character and cannot be used as a workspace by the deployment tool. " + $"Please refer to the troubleshooting guide for setting the {Constants.CLI.WORKSPACE_ENV_VARIABLE} that specifies an alternative workspace directory."); } if (!directoryManager.Exists(overridenWorkspace)) { throw new InvalidDeployToolWorkspaceException(DeployToolErrorCode.InvalidDeployToolWorkspace, $"The {Constants.CLI.WORKSPACE_ENV_VARIABLE} environment variable has been set to \"{overridenWorkspace}\" but it does not point to a valid directory."); } if (overridenWorkspace.Contains(" ")) { throw new InvalidDeployToolWorkspaceException(DeployToolErrorCode.InvalidDeployToolWorkspace, $"The {Constants.CLI.WORKSPACE_ENV_VARIABLE} environment variable ({overridenWorkspace}) contains a whitespace character and cannot be used as a workspace by the deployment tool."); } var tempDir = Path.Combine(overridenWorkspace, "temp"); if (!directoryManager.Exists(tempDir)) { directoryManager.CreateDirectory(tempDir); } // This is done to override the C:\Users\<username>\AppData\Local\Temp directory. // There is a known issue with CDK where it cannot access the Temp directory if the username contains a whitespace. environmentVariableManager.SetEnvironmentVariable("TMP", tempDir); environmentVariableManager.SetEnvironmentVariable("TEMP", tempDir); return overridenWorkspace; } /// <summary> /// Creates a <see cref="SaveSettingsConfiguration"/> /// </summary> /// <param name="saveSettingsPath">Absolute or relative JSON file path where the deployment settings will be saved. Only the settings modified by the user are persisted.</param> /// <param name="saveAllSettingsPath">Absolute or relative JSON file path where the deployment settings will be saved. All deployment settings are persisted.</param> /// <param name="projectDirectoryPath">Absolute path to the user's .NET project directory</param> /// <param name="fileManager"><see cref="IFileManager"/></param> /// <returns><see cref="SaveSettingsConfiguration"/></returns> public static SaveSettingsConfiguration GetSaveSettingsConfiguration(string? saveSettingsPath, string? saveAllSettingsPath, string projectDirectoryPath, IFileManager fileManager) { if (!string.IsNullOrEmpty(saveSettingsPath) && !string.IsNullOrEmpty(saveAllSettingsPath)) { throw new FailedToSaveDeploymentSettingsException(DeployToolErrorCode.FailedToSaveDeploymentSettings, "Cannot save deployment settings because invalid arguments were provided. Cannot use --save-settings along with --save-all-settings"); } var filePath = string.Empty; var saveSettingsType = SaveSettingsType.None; if (!string.IsNullOrEmpty(saveSettingsPath)) { filePath = saveSettingsPath; saveSettingsType = SaveSettingsType.Modified; } else if (!string.IsNullOrEmpty(saveAllSettingsPath)) { filePath = saveAllSettingsPath; saveSettingsType = SaveSettingsType.All; } if (!string.IsNullOrEmpty(filePath)) { filePath = Path.GetFullPath(filePath, projectDirectoryPath); if (!fileManager.IsFileValidPath(filePath)) { var message = $"Failed to save deployment settings because {filePath} is invalid or its parent directory does not exist on disk."; throw new FailedToSaveDeploymentSettingsException(DeployToolErrorCode.FailedToSaveDeploymentSettings, message); } } return new SaveSettingsConfiguration(saveSettingsType, filePath); } } }
136
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; namespace AWS.Deploy.Orchestration.Utilities { public interface ICommandLineWrapper { /// <summary> /// Forks a new shell process and executes <paramref name="command"/>. /// </summary> /// <param name="command"> /// Shell script to execute /// </param> /// <param name="workingDirectory"> /// Default directory for the shell. This needs to have the correct pathing for /// the current OS /// </param> /// <param name="streamOutputToInteractiveService"> /// By default standard out/error will be piped to a <see cref="IOrchestratorInteractiveService"/>. /// Set this to false to disable sending output. /// </param> /// <param name="onComplete"> /// Async callback to inspect/manipulate the completed <see cref="Process"/>. Useful /// if you need to get an exit code or <see cref="Process.StandardOutput"/>. /// </param> /// <param name="redirectIO"> /// By default, <see cref="Process.StandardInput"/>, <see cref="Process.StandardOutput"/> and <see cref="Process.StandardError"/> will be redirected. /// Set this to false to avoid redirection. /// </param> /// <param name="environmentVariables"> /// <see cref="command"/> is executed as a child process of running process which inherits the parent process's environment variables. /// <see cref="environmentVariables"/> allows to add (replace if exists) extra environment variables to the child process. /// <remarks> /// AWS Execution Environment string to append in AWS_EXECUTION_ENV env var. /// AWS SDK calls made while executing <see cref="command"/> will have User-Agent string containing /// </remarks> /// </param> /// <param name="cancelToken"> /// <see cref="CancellationToken"/> /// </param> public Task Run( string command, string workingDirectory = "", bool streamOutputToInteractiveService = true, Action<TryRunResult>? onComplete = null, bool redirectIO = true, string? stdin = null, IDictionary<string, string>? environmentVariables = null, CancellationToken cancelToken = default, bool needAwsCredentials = false); /// <summary> /// Configure the child process that executes the command passed as parameter in <see cref="Run"/> method. /// </summary> /// <param name="processStartInfoAction">Child process <see cref="Action{T}"/> that executes the command</param> void ConfigureProcess(Action<ProcessStartInfo> processStartInfoAction); } public static class CommandLineWrapperExtensions { /// <summary> /// Convenience extension to <see cref="ICommandLineWrapper.Run"/> /// that returns a <see cref="TryRunWithResult"/> with the full contents /// of <see cref="Process.StandardError"/> and <see cref="Process.StandardOutput"/> /// </summary> /// <param name="commandLineWrapper"> /// See <see cref="ICommandLineWrapper"/> /// </param> /// <param name="command"> /// Shell script to execute /// </param> /// <param name="workingDirectory"> /// Default directory for the shell. This needs to have the correct pathing for /// the current OS /// </param> /// <param name="streamOutputToInteractiveService"> /// By default standard out/error will be piped to a <see cref="IOrchestratorInteractiveService"/>. /// Set this to false to disable sending output. /// </param> /// <param name="redirectIO"> /// By default, <see cref="Process.StandardInput"/>, <see cref="Process.StandardOutput"/> and <see cref="Process.StandardError"/> will be redirected. /// Set this to false to avoid redirection. /// </param> /// <param name="stdin"> /// Text to pass into the process through standard input. /// </param> /// <param name="environmentVariables"> /// <see cref="command"/> is executed as a child process of running process which inherits the parent process's environment variables. /// <see cref="environmentVariables"/> allows to add (replace if exists) extra environment variables to the child process. /// <remarks> /// AWS Execution Environment string to append in AWS_EXECUTION_ENV env var. /// AWS SDK calls made while executing <see cref="command"/> will have User-Agent string containing /// </remarks> /// </param> /// <param name="cancelToken"> /// <see cref="CancellationToken"/> /// </param> public static async Task<TryRunResult> TryRunWithResult( this ICommandLineWrapper commandLineWrapper, string command, string workingDirectory = "", bool streamOutputToInteractiveService = false, bool redirectIO = true, string? stdin = null, IDictionary<string, string>? environmentVariables = null, CancellationToken cancelToken = default, bool needAwsCredentials = false) { var result = new TryRunResult(); await commandLineWrapper.Run( command, workingDirectory, streamOutputToInteractiveService, onComplete: runResult => result = runResult, redirectIO: redirectIO, stdin: stdin, environmentVariables: environmentVariables, cancelToken: cancelToken, needAwsCredentials: needAwsCredentials); return result; } } public class TryRunResult { /// <summary> /// Indicates if this command was run successfully. This checks that /// <see cref="StandardError"/> is empty. /// </summary> public bool Success => string.IsNullOrWhiteSpace(StandardError); /// <summary> /// Fully read <see cref="Process.StandardOutput"/> /// </summary> public string? StandardOut { get; set; } /// <summary> /// Fully read <see cref="Process.StandardError"/> /// </summary> public string? StandardError { get; set; } /// <summary> /// Fully read <see cref="Process.ExitCode"/> /// </summary> public int ExitCode { get; set; } } }
157
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 Amazon.CloudFormation.Model; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using Newtonsoft.Json; using YamlDotNet.RepresentationModel; namespace AWS.Deploy.Orchestration.Utilities { public interface ICloudFormationTemplateReader { /// <summary> /// For a given Cloud Application loads the metadata for it. This includes the settings used to deploy and the recipe information. /// </summary> Task<CloudApplicationMetadata> LoadCloudApplicationMetadata(string cloudApplication); /// <summary> /// Parses the CDK Bootstrap template that is used by the tool and retrieves the template version. /// </summary> Task<int> ReadCDKTemplateVersion(); } /// <summary> /// A class for reading the metadata section of an CloudFormation template to pull out the AWS .NET deployment tool settings. /// </summary> public class CloudFormationTemplateReader : ICloudFormationTemplateReader { private readonly IAWSClientFactory _awsClientFactory; private readonly IDeployToolWorkspaceMetadata _deployToolWorkspaceMetadata; private readonly IFileManager _fileManager; public CloudFormationTemplateReader(IAWSClientFactory awsClientFactory, IDeployToolWorkspaceMetadata deployToolWorkspaceMetadata, IFileManager fileManager) { _awsClientFactory = awsClientFactory; _deployToolWorkspaceMetadata = deployToolWorkspaceMetadata; _fileManager = fileManager; } public async Task<CloudApplicationMetadata> LoadCloudApplicationMetadata(string cloudApplication) { using var client = _awsClientFactory.GetAWSClient<Amazon.CloudFormation.IAmazonCloudFormation>(); var request = new GetTemplateRequest { StackName = cloudApplication }; var response = await client.GetTemplateAsync(request); if(IsJsonCFTemplate(response.TemplateBody)) return ReadSettingsFromJSONCFTemplate(response.TemplateBody); else return ReadSettingsFromYAMLCFTemplate(response.TemplateBody); } private async Task<string> LoadCDKBootstrapTemplate() { return await _fileManager.ReadAllTextAsync(_deployToolWorkspaceMetadata.CDKBootstrapTemplatePath); } /// <summary> /// Parses the CDK Bootstrap template that is used by the tool and retrieves the template version. /// </summary> public async Task<int> ReadCDKTemplateVersion() { try { var template = await LoadCDKBootstrapTemplate(); var yamlMetadata = new YamlStream(); using var reader = new StringReader(template); yamlMetadata.Load(reader); var root = (YamlMappingNode)yamlMetadata.Documents[0].RootNode; // The YAML path to the version is: .Resources.CdkBootstrapVersion.Properties.Value var resourcesNode = (YamlMappingNode)root.Children[new YamlScalarNode("Resources")]; var cdkBootstrapVersionNode = (YamlMappingNode)resourcesNode.Children[new YamlScalarNode("CdkBootstrapVersion")]; var propertiesNode = (YamlMappingNode)cdkBootstrapVersionNode.Children[new YamlScalarNode("Properties")]; var valueNode = (YamlScalarNode)propertiesNode.Children[new YamlScalarNode("Value")]; var cdkBootstrapVersion = valueNode.Value ?? String.Empty; return int.Parse(cdkBootstrapVersion); } catch(Exception ex) { throw new FailedToReadCdkBootstrapVersionException(DeployToolErrorCode.FailedToReadCdkBootstrapVersion, "Failed to read the CDK Bootstrap version from the Template file.", ex); } } /// <summary> /// Read the AWS .NET deployment tool metadata from the CloudFormation template which is in JSON format. /// </summary> /// <returns></returns> private static CloudApplicationMetadata ReadSettingsFromJSONCFTemplate(string templateBody) { try { var cfTemplate = JsonConvert.DeserializeObject<CFTemplate>(templateBody); var cloudApplicationMetadata = new CloudApplicationMetadata( cfTemplate?.Metadata?[Constants.CloudFormationIdentifier.STACK_METADATA_RECIPE_ID] ?? throw new Exception("Error parsing existing application's metadata to retrieve Recipe ID."), cfTemplate?.Metadata?[Constants.CloudFormationIdentifier.STACK_METADATA_RECIPE_VERSION] ?? throw new Exception("Error parsing existing application's metadata to retrieve Recipe Version.") ); var jsonString = cfTemplate.Metadata[Constants.CloudFormationIdentifier.STACK_METADATA_SETTINGS]; cloudApplicationMetadata.Settings = JsonConvert.DeserializeObject<IDictionary<string, object>>(jsonString ?? "") ?? new Dictionary<string, object>(); if (cfTemplate.Metadata.ContainsKey(Constants.CloudFormationIdentifier.STACK_METADATA_DEPLOYMENT_BUNDLE_SETTINGS)) { jsonString = cfTemplate.Metadata[Constants.CloudFormationIdentifier.STACK_METADATA_DEPLOYMENT_BUNDLE_SETTINGS]; cloudApplicationMetadata.DeploymentBundleSettings = JsonConvert.DeserializeObject<IDictionary<string, object>>(jsonString ?? "") ?? new Dictionary<string, object>(); } return cloudApplicationMetadata; } catch (Exception e) { throw new ParsingExistingCloudApplicationMetadataException(DeployToolErrorCode.ErrorParsingApplicationMetadata, "Error parsing existing application's metadata", e); } } /// <summary> /// Read the AWS .NET deployment tool metadata from the CloudFormation template which is in YAML format. /// </summary> /// <returns></returns> private static CloudApplicationMetadata ReadSettingsFromYAMLCFTemplate(string templateBody) { try { var metadataSection = ExtractMetadataSection(templateBody); var yamlMetadata = new YamlStream(); using var reader = new StringReader(metadataSection); yamlMetadata.Load(reader); var root = (YamlMappingNode)yamlMetadata.Documents[0].RootNode; var metadataNode = (YamlMappingNode)root.Children[new YamlScalarNode("Metadata")]; var cloudApplicationMetadata = new CloudApplicationMetadata( ((YamlScalarNode)metadataNode.Children[new YamlScalarNode(Constants.CloudFormationIdentifier.STACK_METADATA_RECIPE_ID)]).Value ?? throw new Exception("Error parsing existing application's metadata to retrieve Recipe ID."), ((YamlScalarNode)metadataNode.Children[new YamlScalarNode(Constants.CloudFormationIdentifier.STACK_METADATA_RECIPE_VERSION)]).Value ?? throw new Exception("Error parsing existing application's metadata to retrieve Recipe Version.") ); var jsonString = ((YamlScalarNode)metadataNode.Children[new YamlScalarNode(Constants.CloudFormationIdentifier.STACK_METADATA_SETTINGS)]).Value; cloudApplicationMetadata.Settings = JsonConvert.DeserializeObject<IDictionary<string, object>>(jsonString ?? "") ?? new Dictionary<string, object>(); if (metadataNode.Children.ContainsKey(Constants.CloudFormationIdentifier.STACK_METADATA_DEPLOYMENT_BUNDLE_SETTINGS)) { jsonString = ((YamlScalarNode)metadataNode.Children[new YamlScalarNode(Constants.CloudFormationIdentifier.STACK_METADATA_DEPLOYMENT_BUNDLE_SETTINGS)]).Value; cloudApplicationMetadata.DeploymentBundleSettings = JsonConvert.DeserializeObject<IDictionary<string, object>>(jsonString ?? "") ?? new Dictionary<string, object>(); } return cloudApplicationMetadata; } catch(Exception e) { throw new ParsingExistingCloudApplicationMetadataException(DeployToolErrorCode.ErrorParsingApplicationMetadata, "Error parsing existing application's metadata", e); } } /// <summary> /// YamlDotNet does not like CloudFormation short hand notation. To avoid getting any parse failures due to use of the short hand notation /// using string parsing to extract just the Metadata section from the template. /// </summary> /// <returns></returns> private static string ExtractMetadataSection(string templateBody) { var builder = new StringBuilder(); bool inMetadata = false; using var reader = new StringReader(templateBody); string? line; while((line = reader.ReadLine()) != null) { if(!inMetadata) { // See if we found the start of the Metadata section if(line.StartsWith("Metadata:")) { builder.AppendLine(line); inMetadata = true; } } else { // See if we have found the next top level node signaling the end of the Metadata section if (line.Length > 0 && char.IsLetterOrDigit(line[0])) { break; } builder.AppendLine(line); } } return builder.ToString(); } private bool IsJsonCFTemplate(string templateBody) { try { JsonConvert.DeserializeObject(templateBody); return true; } catch { return false; } } } public class CFTemplate { public Dictionary<string, string>? Metadata { get; set; } } }
227
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.IO.Compression; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; namespace AWS.Deploy.Orchestration.Utilities { public interface IZipFileManager { Task CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName); } public class ZipFileManager : IZipFileManager { private readonly ICommandLineWrapper _commandLineWrapper; private readonly IFileManager _fileManager; public ZipFileManager(ICommandLineWrapper commandLineWrapper, IFileManager fileManager) { _commandLineWrapper = commandLineWrapper; _fileManager = fileManager; } public async Task CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName); } else { await BuildZipForLinux(sourceDirectoryName, destinationArchiveFileName); } } /// <summary> /// Use the native zip utility if it exist which will maintain linux/osx file permissions. /// </summary> private async Task BuildZipForLinux(string sourceDirectoryName, string destinationArchiveFileName) { var zipCLI = FindExecutableInPath("zip"); if (string.IsNullOrEmpty(zipCLI)) throw new FailedToCreateZipFileException(DeployToolErrorCode.FailedToFindZipUtility, "Failed to find the \"zip\" utility program in path. This program is required to maintain Linux file permissions in the zip archive.", null); var args = new StringBuilder($"\"{destinationArchiveFileName}\""); var allFiles = GetFilesToIncludeInArchive(sourceDirectoryName); foreach (var kvp in allFiles) { args.AppendFormat(" \"{0}\"", kvp.Key); } var command = $"{zipCLI} {args}"; var result = await _commandLineWrapper.TryRunWithResult(command, sourceDirectoryName); if (result.ExitCode != 0) { var errorMessage = "We were unable to create a zip archive of the packaged application."; if (!string.IsNullOrEmpty(result.StandardError)) errorMessage = $"We were unable to create a zip archive of the packaged application due to the following reason:{Environment.NewLine}{result.StandardError}"; errorMessage += $"{Environment.NewLine}Normally this indicates a problem running the \"zip\" utility. Make sure that application is installed and available in your PATH."; throw new FailedToCreateZipFileException(DeployToolErrorCode.ZipUtilityFailedToZip, errorMessage, result.ExitCode); } } /// <summary> /// Get the list of files from the publish folder that should be added to the zip archive. /// This will skip all files in the runtimes folder because they have already been flatten to the root. /// </summary> private IDictionary<string, string> GetFilesToIncludeInArchive(string publishLocation) { var includedFiles = new Dictionary<string, string>(); var allFiles = Directory.GetFiles(publishLocation, "*.*", SearchOption.AllDirectories); foreach (var file in allFiles) { var relativePath = Path.GetRelativePath(publishLocation, file); includedFiles[relativePath] = file; } return includedFiles; } /// <summary> /// A collection of known paths for common utilities that are usually not found in the path /// </summary> private readonly IDictionary<string, string> KNOWN_LOCATIONS = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { {"zip", @"/usr/bin/zip" } }; /// <summary> /// Search the path environment variable for the command given. /// </summary> /// <param name="command">The command to search for in the path</param> /// <returns>The full path to the command if found otherwise it will return null</returns> private string? FindExecutableInPath(string command) { if (_fileManager.Exists(command)) return Path.GetFullPath(command); Func<string, string> quoteRemover = x => { if (x.StartsWith("\"")) x = x.Substring(1); if (x.EndsWith("\"")) x = x.Substring(0, x.Length - 1); return x; }; var envPath = Environment.GetEnvironmentVariable("PATH") ?? ""; foreach (var path in envPath.Split(Path.PathSeparator)) { try { var fullPath = Path.Combine(quoteRemover(path), command); if (_fileManager.Exists(fullPath)) return fullPath; } catch (Exception) { // Catch exceptions and continue if there are invalid characters in the user's path. } } if (KNOWN_LOCATIONS.ContainsKey(command) && _fileManager.Exists(KNOWN_LOCATIONS[command])) return KNOWN_LOCATIONS[command]; return null; } } }
142
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.IO; namespace AWS.Deploy.Recipes { public class DeploymentBundleDefinitionLocator { public static string FindDeploymentBundleDefinitionPath() { var assemblyPath = typeof(DeploymentBundleDefinitionLocator).Assembly.Location; var deploymentBundleDefinitionPath = Path.Combine(Directory.GetParent(assemblyPath)!.FullName, "DeploymentBundleDefinitions"); return deploymentBundleDefinitionPath; } } }
18
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.IO; namespace AWS.Deploy.Recipes { public class RecipeLocator { public static string FindRecipeDefinitionsPath() { var assemblyPath = typeof(RecipeLocator).Assembly.Location; var recipePath = Path.Combine(Directory.GetParent(assemblyPath)!.FullName, "RecipeDefinitions"); return recipePath; } } }
18
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using Amazon.CDK; using Amazon.CDK.AWS.AppRunner; using Amazon.CDK.AWS.IAM; using AWS.Deploy.Recipes.CDK.Common; using AspNetAppAppRunner.Configurations; using Amazon.CDK.AWS.ECR; using Amazon.CDK.AWS.ECS; using CfnService = Amazon.CDK.AWS.AppRunner.CfnService; using CfnServiceProps = Amazon.CDK.AWS.AppRunner.CfnServiceProps; using Constructs; namespace AspNetAppAppRunner { public class AppStack : Stack { private readonly Configuration _configuration; internal AppStack(Construct scope, IDeployToolStackProps<Configuration> props) : base(scope, props.StackName, props) { _configuration = props.RecipeProps.Settings; // Setup callback for generated construct to provide access to customize CDK properties before creating constructs. CDKRecipeCustomizer<Recipe>.CustomizeCDKProps += CustomizeCDKProps; // Create custom CDK constructs here that might need to be referenced in the CustomizeCDKProps. For example if // creating a DynamoDB table construct and then later using the CDK construct reference in CustomizeCDKProps to // pass the table name as an environment variable to the container image. // Create the recipe defined CDK construct with all of its sub constructs. var generatedRecipe = new Recipe(this, props.RecipeProps); // Create additional CDK constructs here. The recipe's constructs can be accessed as properties on // the generatedRecipe variable. } /// <summary> /// This method can be used to customize the properties for CDK constructs before creating the constructs. /// /// The pattern used in this method is to check to evnt.ResourceLogicalName to see if the CDK construct about to be created is one /// you want to customize. If so cast the evnt.Props object to the CDK properties object and make the appropriate settings. /// </summary> /// <param name="evnt"></param> private void CustomizeCDKProps(CustomizePropsEventArgs<Recipe> evnt) { // Example of how to customize the container image definition to include environment variables to the running applications. // //if (string.Equals(evnt.ResourceLogicalName, nameof(evnt.Construct.AppRunnerService))) //{ // if (evnt.Props is CfnServiceProps props) // { // Console.WriteLine("Customizing AppRunner Service"); // } //} } } }
64
aws-dotnet-deploy
aws
C#
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Potential Code Quality Issues", "RECS0026:Possible unassigned object created by 'new'", Justification = "Constructs add themselves to the scope in which they are created")]
2
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.CDK; using AWS.Deploy.Recipes.CDK.Common; using AspNetAppAppRunner.Configurations; using Microsoft.Extensions.Configuration; namespace AspNetAppAppRunner { sealed class Program { public static void Main(string[] args) { var app = new App(); var builder = new ConfigurationBuilder().AddAWSDeployToolConfiguration(app); var recipeProps = builder.Build().Get<RecipeProps<Configuration>>(); var appStackProps = new DeployToolStackProps<Configuration>(recipeProps) { Env = new Environment { Account = recipeProps.AWSAccountId, Region = recipeProps.AWSRegion } }; // The RegisterStack method is used to set identifying information on the stack // for the recipe used to deploy the application and preserve the settings used in the recipe // to allow redeployment. The information is stored as CloudFormation tags and metadata inside // the generated CloudFormation template. CDKRecipeSetup.RegisterStack<Configuration>(new AppStack(app, appStackProps), appStackProps.RecipeProps); app.Synth(); } } }
38
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AspNetAppAppRunner.Configurations { /// <summary> /// The configuration settings that are passed in from the deploy tool to the CDK project. If /// custom settings are defined in the recipe definition then corresponding properties should be added here. /// /// This is a partial class with all of the settings defined by default in the recipe declared in the /// Generated directory's version of this file. /// </summary> public partial class Configuration { } }
18
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Linq; using Amazon.CDK; using Amazon.CDK.AWS.AppRunner; using Amazon.CDK.AWS.IAM; using Amazon.CDK.AWS.ECR; using Amazon.CDK.AWS.ECS; using AWS.Deploy.Recipes.CDK.Common; using AspNetAppAppRunner.Configurations; using CfnService = Amazon.CDK.AWS.AppRunner.CfnService; using CfnServiceProps = Amazon.CDK.AWS.AppRunner.CfnServiceProps; using Constructs; using System.Collections.Generic; using Amazon.CDK.AWS.EC2; // This is a generated file from the original deployment recipe. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // To customize the CDK constructs created in this file you should use the AppStack.CustomizeCDKProps() method. namespace AspNetAppAppRunner { using static AWS.Deploy.Recipes.CDK.Common.CDKRecipeCustomizer<Recipe>; public class Recipe : Construct { public CfnService? AppRunnerService { get; private set; } public IRole? ServiceAccessRole { get; private set; } public IRole? TaskRole { get; private set; } public CfnVpcConnector? VPCConnector { get; private set; } public Vpc? AppVpc { get; private set; } public Recipe(Construct scope, IRecipeProps<Configuration> props) // The "Recipe" construct ID will be used as part of the CloudFormation logical ID. If the value is changed this will // change the expected values for the "DisplayedResources" in the corresponding recipe file. : base(scope, "Recipe") { ConfigureVPCConnector(props.Settings); ConfigureIAMRoles(props.Settings); ConfigureAppRunnerService(props); } private void ConfigureVpc(Configuration settings) { if (settings.VPCConnector.UseVPCConnector) { if (settings.VPCConnector.CreateNew) { if (settings.VPCConnector.CreateNewVpc) { AppVpc = new Vpc(this, nameof(AppVpc), InvokeCustomizeCDKPropsEvent(nameof(AppVpc), this, new VpcProps { MaxAzs = 2 })); } } } } private void ConfigureVPCConnector(Configuration settings) { if (settings.VPCConnector.CreateNew) { if (settings.VPCConnector.CreateNewVpc) { ConfigureVpc(settings); if (AppVpc == null) throw new InvalidOperationException($"{nameof(AppVpc)} has not been set."); VPCConnector = new CfnVpcConnector(this, nameof(VPCConnector), InvokeCustomizeCDKPropsEvent(nameof(VPCConnector), this, new CfnVpcConnectorProps { Subnets = AppVpc.PrivateSubnets.Select(x => x.SubnetId).ToArray(), // the properties below are optional SecurityGroups = new string[] { AppVpc.VpcDefaultSecurityGroup } })); VPCConnector.Node.AddDependency(AppVpc); } else { if (settings.VPCConnector.Subnets.Count == 0) throw new InvalidOrMissingConfigurationException("The provided list of Subnets is null or empty."); VPCConnector = new CfnVpcConnector(this, nameof(VPCConnector), InvokeCustomizeCDKPropsEvent(nameof(VPCConnector), this, new CfnVpcConnectorProps { Subnets = settings.VPCConnector.Subnets.ToArray(), // the properties below are optional SecurityGroups = settings.VPCConnector.SecurityGroups.ToArray() })); } } } private void ConfigureIAMRoles(Configuration settings) { if (settings.ServiceAccessIAMRole.CreateNew) { ServiceAccessRole = new Role(this, nameof(ServiceAccessRole), InvokeCustomizeCDKPropsEvent(nameof(ServiceAccessRole), this, new RoleProps { AssumedBy = new ServicePrincipal("build.apprunner.amazonaws.com") })); ServiceAccessRole.AddManagedPolicy(ManagedPolicy.FromManagedPolicyArn(this, "ServiceAccessRoleManagedPolicy", "arn:aws:iam::aws:policy/service-role/AWSAppRunnerServicePolicyForECRAccess")); } else { if (string.IsNullOrEmpty(settings.ServiceAccessIAMRole.RoleArn)) throw new InvalidOrMissingConfigurationException("The provided Application IAM Role ARN is null or empty."); ServiceAccessRole = Role.FromRoleArn(this, nameof(ServiceAccessRole), settings.ServiceAccessIAMRole.RoleArn, new FromRoleArnOptions { Mutable = false }); } if (settings.ApplicationIAMRole.CreateNew) { TaskRole = new Role(this, nameof(TaskRole), InvokeCustomizeCDKPropsEvent(nameof(TaskRole), this, new RoleProps { AssumedBy = new ServicePrincipal("tasks.apprunner.amazonaws.com") })); } else { if (string.IsNullOrEmpty(settings.ApplicationIAMRole.RoleArn)) throw new InvalidOrMissingConfigurationException("The provided Application IAM Role ARN is null or empty."); TaskRole = Role.FromRoleArn(this, nameof(TaskRole), settings.ApplicationIAMRole.RoleArn, new FromRoleArnOptions { Mutable = false }); } } private void ConfigureAppRunnerService(IRecipeProps<Configuration> props) { if (ServiceAccessRole == null) throw new InvalidOperationException($"{nameof(ServiceAccessRole)} has not been set. The {nameof(ConfigureIAMRoles)} method should be called before {nameof(ConfigureAppRunnerService)}"); if (TaskRole == null) throw new InvalidOperationException($"{nameof(TaskRole)} has not been set. The {nameof(ConfigureIAMRoles)} method should be called before {nameof(ConfigureAppRunnerService)}"); if (string.IsNullOrEmpty(props.ECRRepositoryName)) throw new InvalidOrMissingConfigurationException("The provided ECR Repository Name is null or empty."); var ecrRepository = Repository.FromRepositoryName(this, "ECRRepository", props.ECRRepositoryName); Configuration settings = props.Settings; var runtimeEnvironmentVariables = new List<CfnService.IKeyValuePairProperty>(); foreach (var variable in settings.AppRunnerEnvironmentVariables) { runtimeEnvironmentVariables.Add(new CfnService.KeyValuePairProperty { Name = variable.Key, Value = variable.Value }); } var appRunnerServiceProp = new CfnServiceProps { ServiceName = settings.ServiceName, SourceConfiguration = new CfnService.SourceConfigurationProperty { AuthenticationConfiguration = new CfnService.AuthenticationConfigurationProperty { AccessRoleArn = ServiceAccessRole.RoleArn }, ImageRepository = new CfnService.ImageRepositoryProperty { ImageRepositoryType = "ECR", ImageIdentifier = ContainerImage.FromEcrRepository(ecrRepository, props.ECRImageTag).ImageName, ImageConfiguration = new CfnService.ImageConfigurationProperty { Port = settings.Port.ToString(), StartCommand = !string.IsNullOrWhiteSpace(settings.StartCommand) ? settings.StartCommand : null, RuntimeEnvironmentVariables = runtimeEnvironmentVariables.ToArray() } } } }; if (settings.VPCConnector.UseVPCConnector) { appRunnerServiceProp.NetworkConfiguration = new CfnService.NetworkConfigurationProperty { EgressConfiguration = new CfnService.EgressConfigurationProperty { EgressType = "VPC", VpcConnectorArn = VPCConnector != null ? VPCConnector.AttrVpcConnectorArn : settings.VPCConnector.VpcConnectorId } }; } if (!string.IsNullOrEmpty(settings.EncryptionKmsKey)) { var encryptionConfig = new CfnService.EncryptionConfigurationProperty(); appRunnerServiceProp.EncryptionConfiguration = encryptionConfig; encryptionConfig.KmsKey = settings.EncryptionKmsKey; } var healthCheckConfig = new CfnService.HealthCheckConfigurationProperty(); appRunnerServiceProp.HealthCheckConfiguration = healthCheckConfig; healthCheckConfig.HealthyThreshold = settings.HealthCheckHealthyThreshold; healthCheckConfig.Interval = settings.HealthCheckInterval; healthCheckConfig.Protocol = settings.HealthCheckProtocol; healthCheckConfig.Timeout = settings.HealthCheckTimeout; healthCheckConfig.UnhealthyThreshold = settings.HealthCheckUnhealthyThreshold; if (string.Equals(healthCheckConfig.Protocol, "HTTP")) { healthCheckConfig.Path = string.IsNullOrEmpty(settings.HealthCheckPath) ? "/" : settings.HealthCheckPath; } var instanceConfig = new CfnService.InstanceConfigurationProperty(); appRunnerServiceProp.InstanceConfiguration = instanceConfig; instanceConfig.InstanceRoleArn = TaskRole.RoleArn; instanceConfig.Cpu = settings.Cpu; instanceConfig.Memory = settings.Memory; AppRunnerService = new CfnService(this, nameof(AppRunnerService), InvokeCustomizeCDKPropsEvent(nameof(AppRunnerService), this, appRunnerServiceProp)); var output = new CfnOutput(this, "EndpointURL", new CfnOutputProps { Value = $"https://{AppRunnerService.AttrServiceUrl}/" }); } } }
243
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. using System.Collections.Generic; namespace AspNetAppAppRunner.Configurations { public partial class Configuration { /// <summary> /// The Identity and Access Management Role that provides AWS credentials to the application to access AWS services /// </summary> public IAMRoleConfiguration ApplicationIAMRole { get; set; } /// <summary> /// App Runner requires this resource when you want to associate your App Runner service to a custom Amazon Virtual Private Cloud (Amazon VPC). /// </summary> public VPCConnectorConfiguration VPCConnector { get; set; } /// <summary> /// The Identity and Access Management (IAM) role that provides the AWS App Runner service access to pull the container image from ECR. /// </summary> public IAMRoleConfiguration ServiceAccessIAMRole { get; set; } /// <summary> /// The name of the AppRunner service. /// </summary> public string ServiceName { get; set; } /// <summary> /// The port that your application listens to in the container. Defaults to port 80. /// </summary> public int Port { get; set; } = 80; /// <summary> /// An optional command that App Runner runs to start the application in the source image. If specified, this command overrides the Docker image’s default start command. /// </summary> public string? StartCommand { get; set; } /// <summary> /// The ARN of the KMS key that's used for encryption. /// </summary> public string? EncryptionKmsKey { get; set; } /// <summary> /// The number of consecutive checks that must succeed before App Runner decides that the service is healthy. /// </summary> public double? HealthCheckHealthyThreshold { get; set; } /// <summary> /// The time interval, in seconds, between health checks. /// </summary> public int? HealthCheckInterval { get; set; } /// <summary> /// The URL that health check requests are sent to. /// </summary> public string? HealthCheckPath { get; set; } /// <summary> /// The IP protocol that App Runner uses to perform health checks for your service. /// </summary> public string HealthCheckProtocol { get; set; } = "TCP"; /// <summary> /// The time, in seconds, to wait for a health check response before deciding it failed. /// </summary> public int? HealthCheckTimeout { get; set; } /// <summary> /// The number of consecutive checks that must fail before App Runner decides that the service is unhealthy. /// </summary> public int? HealthCheckUnhealthyThreshold { get; set; } /// <summary> /// The number of CPU units reserved for each instance of your App Runner service. /// </summary> public string Cpu { get; set; } /// <summary> /// The amount of memory, in MB or GB, reserved for each instance of your App Runner service. /// </summary> public string Memory { get; set; } /// <summary> /// The environment variables that are set for the AppRunner environment. /// </summary> public Dictionary<string, string> AppRunnerEnvironmentVariables { get; set; } = new Dictionary<string, string> { }; /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public Configuration() { } #nullable restore warnings public Configuration( IAMRoleConfiguration applicationIAMRole, VPCConnectorConfiguration vpcConnector, IAMRoleConfiguration serviceAccessIAMRole, string serviceName, int? port, string healthCheckProtocol, string cpu, string memory, Dictionary<string, string> appRunnerEnvironmentVariables) { ApplicationIAMRole = applicationIAMRole; VPCConnector = vpcConnector; ServiceAccessIAMRole = serviceAccessIAMRole; ServiceName = serviceName; Port = port ?? 80; HealthCheckProtocol = healthCheckProtocol; Cpu = cpu; Memory = memory; AppRunnerEnvironmentVariables = appRunnerEnvironmentVariables; } } }
129
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppAppRunner.Configurations { public partial class IAMRoleConfiguration { /// <summary> /// If set, create a new anonymously named IAM role. /// </summary> public bool CreateNew { get; set; } /// <summary> /// If <see cref="CreateNew"/> is false, /// then use an existing IAM role by referencing through <see cref="RoleArn"/> /// </summary> public string? RoleArn { get; set; } } }
26
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. using System.Collections.Generic; namespace AspNetAppAppRunner.Configurations { public partial class VPCConnectorConfiguration { /// <summary> /// If set, the deployment will use a VPC Connector to connect to the AppRunner service. /// </summary> public bool UseVPCConnector { get; set; } /// <summary> /// If set, creates a new VPC Connector to connect to the AppRunner service. /// </summary> public bool CreateNew { get; set; } /// <summary> /// The VPC Connector to use for the App Runner service. /// </summary> public string? VpcConnectorId { get; set; } /// <summary> /// If set, creates a new VPC whose Subnets and Security Groups will be used to create a new VPC Connector. /// </summary> public bool CreateNewVpc { get; set; } /// <summary> /// The VPC ID to use for the App Runner service. /// </summary> public string? VpcId { get; set; } /// <summary> /// A list of IDs of subnets that App Runner should use when it associates your service with a custom Amazon VPC. /// Specify IDs of subnets of a single Amazon VPC. App Runner determines the Amazon VPC from the subnets you specify. /// </summary> public SortedSet<string> Subnets { get; set; } = new SortedSet<string>(); /// <summary> /// A list of IDs of security groups that App Runner should use for access to AWS resources under the specified subnets. /// If not specified, App Runner uses the default security group of the Amazon VPC. /// The default security group allows all outbound traffic. /// </summary> public SortedSet<string> SecurityGroups { get; set; } = new SortedSet<string>(); } }
55
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 Amazon.CDK; using Amazon.CDK.AWS.ECS; using AWS.Deploy.Recipes.CDK.Common; using AspNetAppEcsFargate.Configurations; using Constructs; namespace AspNetAppEcsFargate { public class AppStack : Stack { private readonly Configuration _configuration; internal AppStack(Construct scope, IDeployToolStackProps<Configuration> props) : base(scope, props.StackName, props) { _configuration = props.RecipeProps.Settings; // Setup callback for generated construct to provide access to customize CDK properties before creating constructs. CDKRecipeCustomizer<Recipe>.CustomizeCDKProps += CustomizeCDKProps; // Create custom CDK constructs here that might need to be referenced in the CustomizeCDKProps. For example if // creating a DynamoDB table construct and then later using the CDK construct reference in CustomizeCDKProps to // pass the table name as an environment variable to the container image. // Create the recipe defined CDK construct with all of its sub constructs. var generatedRecipe = new Recipe(this, props.RecipeProps); // Create additional CDK constructs here. The recipe's constructs can be accessed as properties on // the generatedRecipe variable. } /// <summary> /// This method can be used to customize the properties for CDK constructs before creating the constructs. /// /// The pattern used in this method is to check to evnt.ResourceLogicalName to see if the CDK construct about to be created is one /// you want to customize. If so cast the evnt.Props object to the CDK properties object and make the appropriate settings. /// </summary> /// <param name="evnt"></param> private void CustomizeCDKProps(CustomizePropsEventArgs<Recipe> evnt) { // Example of how to customize the container image definition to include environment variables to the running applications. // //if (string.Equals(evnt.ResourceLogicalName, nameof(evnt.Construct.AppContainerDefinition))) //{ // if(evnt.Props is ContainerDefinitionOptions props) // { // Console.WriteLine("Customizing AppContainerDefinition"); // if (props.Environment == null) // props.Environment = new Dictionary<string, string>(); // props.Environment["EXAMPLE_ENV1"] = "EXAMPLE_VALUE1"; // } //} } } }
63
aws-dotnet-deploy
aws
C#
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Potential Code Quality Issues", "RECS0026:Possible unassigned object created by 'new'", Justification = "Constructs add themselves to the scope in which they are created")]
2
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using Amazon.CDK; using AWS.Deploy.Recipes.CDK.Common; using AspNetAppEcsFargate.Configurations; using Microsoft.Extensions.Configuration; using Environment = Amazon.CDK.Environment; namespace AspNetAppEcsFargate { sealed class Program { public static void Main(string[] args) { var app = new App(); var builder = new ConfigurationBuilder().AddAWSDeployToolConfiguration(app); var recipeProps = builder.Build().Get<RecipeProps<Configuration>>(); var appStackProps = new DeployToolStackProps<Configuration>(recipeProps) { Env = new Environment { Account = recipeProps.AWSAccountId, Region = recipeProps.AWSRegion } }; // The RegisterStack method is used to set identifying information on the stack // for the recipe used to deploy the application and preserve the settings used in the recipe // to allow redeployment. The information is stored as CloudFormation tags and metadata inside // the generated CloudFormation template. CDKRecipeSetup.RegisterStack<Configuration>(new AppStack(app, appStackProps), appStackProps.RecipeProps); app.Synth(); } } }
40
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 namespace AspNetAppEcsFargate.Configurations { /// <summary> /// The configuration settings that are passed in from the deploy tool to the CDK project. If /// custom settings are defined in the recipe definition then corresponding properties should be added here. /// /// This is a partial class with all of the settings defined by default in the recipe declared in the /// Generated directory's version of this file. /// </summary> public partial class Configuration { } }
18
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using Amazon.CDK; using Amazon.CDK.AWS.ApplicationAutoScaling; using Amazon.CDK.AWS.EC2; using Amazon.CDK.AWS.ECS; using Amazon.CDK.AWS.ElasticLoadBalancingV2; using Amazon.CDK.AWS.IAM; using AWS.Deploy.Recipes.CDK.Common; using AspNetAppEcsFargate.Configurations; using Amazon.CDK.AWS.ECR; using System.Linq; using Constructs; // This is a generated file from the original deployment recipe. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // To customize the CDK constructs created in this file you should use the AppStack.CustomizeCDKProps() method. namespace AspNetAppEcsFargate { using static AWS.Deploy.Recipes.CDK.Common.CDKRecipeCustomizer<Recipe>; public class Recipe : Construct { public IVpc? AppVpc { get; private set; } public ICluster? EcsCluster { get; private set; } public IRole? AppIAMTaskRole { get; private set; } public TaskDefinition? AppTaskDefinition { get; private set; } public IRepository? EcrRepository { get; private set; } public ContainerDefinition? AppContainerDefinition { get; private set; } public SecurityGroup? WebAccessSecurityGroup { get; private set; } public IList<ISecurityGroup>? EcsServiceSecurityGroups { get; private set; } public FargateService? AppFargateService { get; private set; } public IApplicationLoadBalancer? ServiceLoadBalancer { get; private set; } public IApplicationListener? LoadBalancerListener { get; private set; } public ApplicationTargetGroup? ServiceTargetGroup { get; private set; } public AwsLogDriver? AppLogging { get; private set; } public ScalableTaskCount? AutoScalingConfiguration { get; private set; } public string AutoScaleTypeCpuType { get; } = "AutoScaleTypeCpuType"; public string AutoScaleTypeRequestType { get; } = "AutoScaleTypeRequestType"; public string AutoScaleTypeMemoryType { get; } = "AutoScaleTypeMemoryType"; public string AddTargetGroup { get; } = "AddTargetGroup"; public Recipe(Construct scope, IRecipeProps<Configuration> props) // The "Recipe" construct ID will be used as part of the CloudFormation logical ID. If the value is changed this will // change the expected values for the "DisplayedResources" in the corresponding recipe file. : base(scope, "Recipe") { var settings = props.Settings; ConfigureVpc(settings); ConfigureApplicationIAMRole(settings); ConfigureECSClusterAndService(props); ConfigureLoadBalancer(settings); ConfigureAutoScaling(settings); } private void ConfigureVpc(Configuration settings) { if (settings.Vpc.IsDefault) { AppVpc = Vpc.FromLookup(this, nameof(AppVpc), InvokeCustomizeCDKPropsEvent(nameof(AppVpc), this, new VpcLookupOptions { IsDefault = true })); } else if (settings.Vpc.CreateNew) { AppVpc = new Vpc(this, nameof(AppVpc), InvokeCustomizeCDKPropsEvent(nameof(AppVpc), this, new VpcProps { MaxAzs = 2 })); } else { AppVpc = Vpc.FromLookup(this, nameof(AppVpc), InvokeCustomizeCDKPropsEvent(nameof(AppVpc), this, new VpcLookupOptions { VpcId = settings.Vpc.VpcId })); } } private void ConfigureApplicationIAMRole(Configuration settings) { if (settings.ApplicationIAMRole.CreateNew) { AppIAMTaskRole = new Role(this, nameof(AppIAMTaskRole), InvokeCustomizeCDKPropsEvent(nameof(AppIAMTaskRole), this, new RoleProps { AssumedBy = new ServicePrincipal("ecs-tasks.amazonaws.com") })); } else { if (string.IsNullOrEmpty(settings.ApplicationIAMRole.RoleArn)) throw new InvalidOrMissingConfigurationException("The provided Application IAM Role ARN is null or empty."); AppIAMTaskRole = Role.FromRoleArn(this, nameof(AppIAMTaskRole), settings.ApplicationIAMRole.RoleArn, InvokeCustomizeCDKPropsEvent(nameof(AppIAMTaskRole), this, new FromRoleArnOptions { Mutable = false })); } } private void ConfigureECSClusterAndService(IRecipeProps<Configuration> recipeConfiguration) { if (AppVpc == null) throw new InvalidOperationException($"{nameof(AppVpc)} has not been set. The {nameof(ConfigureVpc)} method should be called before {nameof(ConfigureECSClusterAndService)}"); var settings = recipeConfiguration.Settings; if (settings.ECSCluster.CreateNew) { EcsCluster = new Cluster(this, nameof(EcsCluster), InvokeCustomizeCDKPropsEvent(nameof(EcsCluster), this, new ClusterProps { Vpc = AppVpc, ClusterName = settings.ECSCluster.NewClusterName })); } else { EcsCluster = Cluster.FromClusterAttributes(this, nameof(EcsCluster), InvokeCustomizeCDKPropsEvent(nameof(EcsCluster), this, new ClusterAttributes { ClusterArn = settings.ECSCluster.ClusterArn, ClusterName = ECSFargateUtilities.GetClusterNameFromArn(settings.ECSCluster.ClusterArn), SecurityGroups = new ISecurityGroup[0], Vpc = AppVpc })); } AppTaskDefinition = new FargateTaskDefinition(this, nameof(AppTaskDefinition), InvokeCustomizeCDKPropsEvent(nameof(AppTaskDefinition), this, new FargateTaskDefinitionProps { TaskRole = AppIAMTaskRole, Cpu = settings.TaskCpu, MemoryLimitMiB = settings.TaskMemory })); AppLogging = new AwsLogDriver(InvokeCustomizeCDKPropsEvent(nameof(AppLogging), this, new AwsLogDriverProps { StreamPrefix = recipeConfiguration.StackName })); if (string.IsNullOrEmpty(recipeConfiguration.ECRRepositoryName)) throw new InvalidOrMissingConfigurationException("The provided ECR Repository Name is null or empty."); EcrRepository = Repository.FromRepositoryName(this, nameof(EcrRepository), recipeConfiguration.ECRRepositoryName); AppContainerDefinition = AppTaskDefinition.AddContainer(nameof(AppContainerDefinition), InvokeCustomizeCDKPropsEvent(nameof(AppContainerDefinition), this, new ContainerDefinitionOptions { Image = ContainerImage.FromEcrRepository(EcrRepository, recipeConfiguration.ECRImageTag), Logging = AppLogging, Environment = settings.ECSEnvironmentVariables, MemoryLimitMiB = settings.TaskMemory })); AppContainerDefinition.AddPortMappings(new PortMapping { ContainerPort = 80, Protocol = Amazon.CDK.AWS.ECS.Protocol.TCP }); WebAccessSecurityGroup = new SecurityGroup(this, nameof(WebAccessSecurityGroup), InvokeCustomizeCDKPropsEvent(nameof(WebAccessSecurityGroup), this, new SecurityGroupProps { Vpc = AppVpc, SecurityGroupName = $"{recipeConfiguration.StackName}-ECSService" })); EcsServiceSecurityGroups = new List<ISecurityGroup>(); EcsServiceSecurityGroups.Add(WebAccessSecurityGroup); if (settings.AdditionalECSServiceSecurityGroups.Any()) { var count = 1; foreach (var securityGroupId in settings.AdditionalECSServiceSecurityGroups) { EcsServiceSecurityGroups.Add(SecurityGroup.FromSecurityGroupId(this, $"AdditionalGroup-{count++}", securityGroupId.Trim(), new SecurityGroupImportOptions { Mutable = false })); } } AppFargateService = new FargateService(this, nameof(AppFargateService), InvokeCustomizeCDKPropsEvent(nameof(AppFargateService), this, new FargateServiceProps { Cluster = EcsCluster, TaskDefinition = AppTaskDefinition, DesiredCount = settings.DesiredCount, ServiceName = settings.ECSServiceName, AssignPublicIp = settings.Vpc.IsDefault, SecurityGroups = EcsServiceSecurityGroups.ToArray() })); } private void ConfigureLoadBalancer(Configuration settings) { if (AppVpc == null) throw new InvalidOperationException($"{nameof(AppVpc)} has not been set. The {nameof(ConfigureVpc)} method should be called before {nameof(ConfigureLoadBalancer)}"); if (EcsCluster == null) throw new InvalidOperationException($"{nameof(EcsCluster)} has not been set. The {nameof(ConfigureECSClusterAndService)} method should be called before {nameof(ConfigureLoadBalancer)}"); if (AppFargateService == null) throw new InvalidOperationException($"{nameof(AppFargateService)} has not been set. The {nameof(ConfigureECSClusterAndService)} method should be called before {nameof(ConfigureLoadBalancer)}"); if (settings.LoadBalancer.CreateNew) { ServiceLoadBalancer = new ApplicationLoadBalancer(this, nameof(ServiceLoadBalancer), InvokeCustomizeCDKPropsEvent(nameof(ServiceLoadBalancer), this, new ApplicationLoadBalancerProps { Vpc = AppVpc, InternetFacing = settings.LoadBalancer.InternetFacing })); LoadBalancerListener = ServiceLoadBalancer.AddListener(nameof(LoadBalancerListener), InvokeCustomizeCDKPropsEvent(nameof(LoadBalancerListener), this, new ApplicationListenerProps { Protocol = ApplicationProtocol.HTTP, Port = 80, Open = true })); ServiceTargetGroup = LoadBalancerListener.AddTargets(nameof(ServiceTargetGroup), InvokeCustomizeCDKPropsEvent(nameof(ServiceTargetGroup), this, new AddApplicationTargetsProps { Protocol = ApplicationProtocol.HTTP, DeregistrationDelay = Duration.Seconds(settings.LoadBalancer.DeregistrationDelayInSeconds) })); } else { ServiceLoadBalancer = ApplicationLoadBalancer.FromLookup(this, nameof(ServiceLoadBalancer), InvokeCustomizeCDKPropsEvent(nameof(ServiceLoadBalancer), this, new ApplicationLoadBalancerLookupOptions { LoadBalancerArn = settings.LoadBalancer.ExistingLoadBalancerArn })); LoadBalancerListener = ApplicationListener.FromLookup(this, nameof(LoadBalancerListener), InvokeCustomizeCDKPropsEvent(nameof(LoadBalancerListener), this, new ApplicationListenerLookupOptions { LoadBalancerArn = settings.LoadBalancer.ExistingLoadBalancerArn, ListenerPort = 80 })); ServiceTargetGroup = new ApplicationTargetGroup(this, nameof(ServiceTargetGroup), InvokeCustomizeCDKPropsEvent(nameof(ServiceTargetGroup), this, new ApplicationTargetGroupProps { Port = 80, Vpc = EcsCluster.Vpc, })); var addApplicationTargetGroupsProps = new AddApplicationTargetGroupsProps { TargetGroups = new[] { ServiceTargetGroup } }; if(settings.LoadBalancer.ListenerConditionType != LoadBalancerConfiguration.ListenerConditionTypeEnum.None) { addApplicationTargetGroupsProps.Priority = settings.LoadBalancer.ListenerConditionPriority; } if (settings.LoadBalancer.ListenerConditionType == LoadBalancerConfiguration.ListenerConditionTypeEnum.Path) { if(settings.LoadBalancer.ListenerConditionPathPattern == null) { throw new ArgumentNullException("Listener condition type was set to \"Path\" but no value was set for the \"TargetPathPattern\""); } addApplicationTargetGroupsProps.Conditions = new ListenerCondition[] { ListenerCondition.PathPatterns(new []{ settings.LoadBalancer.ListenerConditionPathPattern }) }; } LoadBalancerListener.AddTargetGroups("AddTargetGroup", InvokeCustomizeCDKPropsEvent("AddTargetGroup", this, addApplicationTargetGroupsProps)); } // Configure health check for ALB Target Group var healthCheck = new Amazon.CDK.AWS.ElasticLoadBalancingV2.HealthCheck(); if(settings.LoadBalancer.HealthCheckPath != null) { var path = settings.LoadBalancer.HealthCheckPath; if (!path.StartsWith("/")) path = "/" + path; healthCheck.Path = path; } if(settings.LoadBalancer.HealthCheckInternval.HasValue) { healthCheck.Interval = Duration.Seconds(settings.LoadBalancer.HealthCheckInternval.Value); } if (settings.LoadBalancer.HealthyThresholdCount.HasValue) { healthCheck.HealthyThresholdCount = settings.LoadBalancer.HealthyThresholdCount.Value; } if (settings.LoadBalancer.UnhealthyThresholdCount.HasValue) { healthCheck.UnhealthyThresholdCount = settings.LoadBalancer.UnhealthyThresholdCount.Value; } if (settings.LoadBalancer.HealthCheckTimeout.HasValue) { healthCheck.Timeout = Duration.Seconds(settings.LoadBalancer.HealthCheckTimeout.Value); } ServiceTargetGroup.ConfigureHealthCheck(healthCheck); ServiceTargetGroup.AddTarget(AppFargateService); } private void ConfigureAutoScaling(Configuration settings) { if (AppFargateService == null) throw new InvalidOperationException($"{nameof(AppFargateService)} has not been set. The {nameof(ConfigureECSClusterAndService)} method should be called before {nameof(ConfigureAutoScaling)}"); if (ServiceTargetGroup == null) throw new InvalidOperationException($"{nameof(ServiceTargetGroup)} has not been set. The {nameof(ConfigureLoadBalancer)} method should be called before {nameof(ConfigureAutoScaling)}"); if (settings.AutoScaling.Enabled) { AutoScalingConfiguration = AppFargateService.AutoScaleTaskCount(InvokeCustomizeCDKPropsEvent(nameof(AutoScalingConfiguration), this, new EnableScalingProps { MinCapacity = settings.AutoScaling.MinCapacity, MaxCapacity = settings.AutoScaling.MaxCapacity })); switch (settings.AutoScaling.ScalingType) { case AspNetAppEcsFargate.Configurations.AutoScalingConfiguration.ScalingTypeEnum.Cpu: AutoScalingConfiguration.ScaleOnCpuUtilization(AutoScaleTypeCpuType, InvokeCustomizeCDKPropsEvent(AutoScaleTypeCpuType, this, new CpuUtilizationScalingProps { TargetUtilizationPercent = settings.AutoScaling.CpuTypeTargetUtilizationPercent, ScaleOutCooldown = Duration.Seconds(settings.AutoScaling.CpuTypeScaleOutCooldownSeconds), ScaleInCooldown = Duration.Seconds(settings.AutoScaling.CpuTypeScaleInCooldownSeconds) })); break; case AspNetAppEcsFargate.Configurations.AutoScalingConfiguration.ScalingTypeEnum.Memory: AutoScalingConfiguration.ScaleOnMemoryUtilization(AutoScaleTypeMemoryType, InvokeCustomizeCDKPropsEvent(AutoScaleTypeMemoryType, this, new MemoryUtilizationScalingProps { TargetUtilizationPercent = settings.AutoScaling.MemoryTypeTargetUtilizationPercent, ScaleOutCooldown = Duration.Seconds(settings.AutoScaling.MemoryTypeScaleOutCooldownSeconds), ScaleInCooldown = Duration.Seconds(settings.AutoScaling.MemoryTypeScaleInCooldownSeconds) })); break; case AspNetAppEcsFargate.Configurations.AutoScalingConfiguration.ScalingTypeEnum.Request: AutoScalingConfiguration.ScaleOnRequestCount(AutoScaleTypeRequestType, InvokeCustomizeCDKPropsEvent(AutoScaleTypeRequestType, this, new RequestCountScalingProps { TargetGroup = ServiceTargetGroup, RequestsPerTarget = settings.AutoScaling.RequestTypeRequestsPerTarget, ScaleOutCooldown = Duration.Seconds(settings.AutoScaling.RequestTypeScaleOutCooldownSeconds), ScaleInCooldown = Duration.Seconds(settings.AutoScaling.RequestTypeScaleInCooldownSeconds) })); break; default: throw new ArgumentException($"Invalid AutoScaling type {settings.AutoScaling.ScalingType}"); } } } } }
351
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; // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppEcsFargate.Configurations { public partial class AutoScalingConfiguration { const int defaultCooldown = 300; public bool Enabled { get; set; } public int MinCapacity { get; set; } = 3; public int MaxCapacity { get; set; } = 6; public enum ScalingTypeEnum { Cpu, Memory, Request } public ScalingTypeEnum? ScalingType { get; set; } public double CpuTypeTargetUtilizationPercent { get; set; } = 70; public int CpuTypeScaleInCooldownSeconds { get; set; } = defaultCooldown; public int CpuTypeScaleOutCooldownSeconds { get; set; } = defaultCooldown; public int RequestTypeRequestsPerTarget { get; set; } = 10000; public int RequestTypeScaleInCooldownSeconds { get; set; } = defaultCooldown; public int RequestTypeScaleOutCooldownSeconds { get; set; } = defaultCooldown; public double MemoryTypeTargetUtilizationPercent { get; set; } = 70; public int MemoryTypeScaleInCooldownSeconds { get; set; } = defaultCooldown; public int MemoryTypeScaleOutCooldownSeconds { get; set; } = defaultCooldown; } }
55
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. using System.Collections.Generic; namespace AspNetAppEcsFargate.Configurations { public partial class Configuration { /// <summary> /// The Identity and Access Management Role that provides AWS credentials to the application to access AWS services. /// </summary> public IAMRoleConfiguration ApplicationIAMRole { get; set; } /// <summary> /// The desired number of ECS tasks to run for the service. /// </summary> public double DesiredCount { get; set; } /// <summary> /// The name of the ECS service running in the cluster. /// </summary> public string ECSServiceName { get; set; } /// <summary> /// The ECS cluster that will host the deployed application. /// </summary> public ECSClusterConfiguration ECSCluster { get; set; } /// <summary> /// Virtual Private Cloud to launch container instance into a virtual network. /// </summary> public VpcConfiguration Vpc { get; set; } /// <summary> /// List of security groups assigned to the ECS service. /// </summary> public SortedSet<string> AdditionalECSServiceSecurityGroups { get; set; } = new SortedSet<string>(); /// <summary> /// The amount of CPU to allocate to the Fargate task /// </summary> public double? TaskCpu { get; set; } /// <summary> /// The amount of memory to allocate to the Fargate task /// </summary> public double? TaskMemory { get; set; } public LoadBalancerConfiguration LoadBalancer { get; set; } public AutoScalingConfiguration AutoScaling { get; set; } /// <summary> /// The environment variables that are set for the ECS environment. /// </summary> public Dictionary<string, string> ECSEnvironmentVariables { get; set; } = new Dictionary<string, string> { }; /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public Configuration() { } #nullable restore warnings public Configuration( IAMRoleConfiguration applicationIAMRole, string ecsServiceName, ECSClusterConfiguration ecsCluster, VpcConfiguration vpc, SortedSet<string> additionalECSServiceSecurityGroups, LoadBalancerConfiguration loadBalancer, AutoScalingConfiguration autoScaling, Dictionary<string, string> ecsEnvironmentVariables ) { ApplicationIAMRole = applicationIAMRole; ECSServiceName = ecsServiceName; ECSCluster = ecsCluster; Vpc = vpc; AdditionalECSServiceSecurityGroups = additionalECSServiceSecurityGroups; LoadBalancer = loadBalancer; AutoScaling = autoScaling; ECSEnvironmentVariables = ecsEnvironmentVariables; } } }
97
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppEcsFargate.Configurations { public partial class ECSClusterConfiguration { /// <summary> /// Indicates whether to create a new ECS Cluster or use and existing one /// </summary> public bool CreateNew { get; set; } /// <summary> /// If <see cref="CreateNew" /> is false, /// then use an existing ECS Cluster by referencing through <see cref="ClusterArn"/> /// </summary> public string ClusterArn { get; set; } /// <summary> /// If <see cref="CreateNew" /> is true, /// then create a new ECS Cluster with the name <see cref="NewClusterName"/> /// </summary> public string NewClusterName { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public ECSClusterConfiguration() { } #nullable restore warnings public ECSClusterConfiguration( bool createNew, string clusterArn, string newClusterName) { CreateNew = createNew; ClusterArn = clusterArn; NewClusterName = newClusterName; } } }
52
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppEcsFargate.Configurations { public partial class IAMRoleConfiguration { /// <summary> /// If set, create a new anonymously named IAM role. /// </summary> public bool CreateNew { get; set; } /// <summary> /// If <see cref="CreateNew"/> is false, /// then use an existing IAM role by referencing through <see cref="RoleArn"/> /// </summary> public string? RoleArn { get; set; } } }
26
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Text; // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppEcsFargate.Configurations { public partial class LoadBalancerConfiguration { /// <summary> /// If set and <see cref="CreateNew"/> is false, create a new LoadBalancer /// </summary> public bool CreateNew { get; set; } /// <summary> /// If not creating a new Load Balancer then this is set to an existing load balancer arn. /// </summary> public string ExistingLoadBalancerArn { get; set; } /// <summary> /// How much time to allow currently executing request in ECS tasks to finish before deregistering tasks. /// </summary> public int DeregistrationDelayInSeconds { get; set; } = 60; /// <summary> /// The ping path destination where Elastic Load Balancing sends health check requests. /// </summary> public string? HealthCheckPath { get; set; } /// <summary> /// The approximate number of seconds between health checks. /// </summary> public int? HealthCheckInternval { get; set; } /// <summary> /// The amount of time, in seconds, during which no response from a target means a failed health check. /// </summary> public int? HealthCheckTimeout { get; set; } /// <summary> /// The number of consecutive health check successes required before considering an unhealthy target healthy. /// </summary> public int? HealthyThresholdCount { get; set; } /// <summary> /// The number of consecutive health check successes required before considering an unhealthy target unhealthy. /// </summary> public int? UnhealthyThresholdCount { get; set; } public enum ListenerConditionTypeEnum { None, Path} /// <summary> /// The type of listener condition to create. Current valid values are "None" and "Path" /// </summary> public ListenerConditionTypeEnum? ListenerConditionType { get; set; } /// <summary> /// The resource path pattern to use with ListenerConditionType is set to "Path" /// </summary> public string? ListenerConditionPathPattern { get; set; } /// <summary> /// The priority of the listener condition rule. /// </summary> public double ListenerConditionPriority { get; set; } = 100; /// <summary> /// Whether the load balancer has an internet-routable address. /// </summary> public bool InternetFacing { get; set; } = true; /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public LoadBalancerConfiguration() { } #nullable restore warnings public LoadBalancerConfiguration( bool createNew, string loadBalancerId) { CreateNew = createNew; ExistingLoadBalancerArn = loadBalancerId; } } }
95
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppEcsFargate.Configurations { public partial class VpcConfiguration { /// <summary> /// If set, use default VPC /// </summary> public bool IsDefault { get; set; } /// <summary> /// If set and <see cref="CreateNew"/> is false, create a new VPC /// </summary> public bool CreateNew { get; set; } /// <summary> /// If <see cref="IsDefault" /> is false and <see cref="CreateNew" /> is false, /// then use an existing VPC by referencing through <see cref="VpcId"/> /// </summary> public string VpcId { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public VpcConfiguration() { } #nullable restore warnings public VpcConfiguration( bool isDefault, bool createNew, string vpcId) { IsDefault = isDefault; CreateNew = createNew; VpcId = vpcId; } } }
51
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using Amazon.CDK; using Amazon.CDK.AWS.ElasticBeanstalk; using AWS.Deploy.Recipes.CDK.Common; using AspNetAppElasticBeanstalkLinux.Configurations; using Constructs; namespace AspNetAppElasticBeanstalkLinux { public class AppStack : Stack { private readonly Configuration _configuration; internal AppStack(Construct scope, IDeployToolStackProps<Configuration> props) : base(scope, props.StackName, props) { _configuration = props.RecipeProps.Settings; // Setup callback for generated construct to provide access to customize CDK properties before creating constructs. CDKRecipeCustomizer<Recipe>.CustomizeCDKProps += CustomizeCDKProps; // Create custom CDK constructs here that might need to be referenced in the CustomizeCDKProps. For example if // creating a DynamoDB table construct and then later using the CDK construct reference in CustomizeCDKProps to // pass the table name as an environment variable to the container image. // Create the recipe defined CDK construct with all of its sub constructs. var generatedRecipe = new Recipe(this, props.RecipeProps); // Create additional CDK constructs here. The recipe's constructs can be accessed as properties on // the generatedRecipe variable. } /// <summary> /// This method can be used to customize the properties for CDK constructs before creating the constructs. /// /// The pattern used in this method is to check to evnt.ResourceLogicalName to see if the CDK construct about to be created is one /// you want to customize. If so cast the evnt.Props object to the CDK properties object and make the appropriate settings. /// </summary> /// <param name="evnt"></param> private void CustomizeCDKProps(CustomizePropsEventArgs<Recipe> evnt) { // Example of how to customize the Beanstalk Environment. // //if (string.Equals(evnt.ResourceLogicalName, nameof(evnt.Construct.BeanstalkEnvironment))) //{ // if (evnt.Props is CfnEnvironmentProps props) // { // Console.WriteLine("Customizing Beanstalk Environment"); // } //} } } }
59
aws-dotnet-deploy
aws
C#
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Potential Code Quality Issues", "RECS0026:Possible unassigned object created by 'new'", Justification = "Constructs add themselves to the scope in which they are created")]
2
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.CDK; using AWS.Deploy.Recipes.CDK.Common; using AspNetAppElasticBeanstalkLinux.Configurations; using Microsoft.Extensions.Configuration; namespace AspNetAppElasticBeanstalkLinux { sealed class Program { public static void Main(string[] args) { var app = new App(); var builder = new ConfigurationBuilder().AddAWSDeployToolConfiguration(app); var recipeProps = builder.Build().Get<RecipeProps<Configuration>>(); var appStackProps = new DeployToolStackProps<Configuration>(recipeProps) { Env = new Environment { Account = recipeProps.AWSAccountId, Region = recipeProps.AWSRegion } }; // The RegisterStack method is used to set identifying information on the stack // for the recipe used to deploy the application and preserve the settings used in the recipe // to allow redeployment. The information is stored as CloudFormation tags and metadata inside // the generated CloudFormation template. CDKRecipeSetup.RegisterStack<Configuration>(new AppStack(app, appStackProps), appStackProps.RecipeProps); app.Synth(); } } }
38
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AspNetAppElasticBeanstalkLinux.Configurations { /// <summary> /// The configuration settings that are passed in from the deploy tool to the CDK project. If /// custom settings are defined in the recipe definition then corresponding properties should be added here. /// /// This is a partial class with all of the settings defined by default in the recipe declared in the /// Generated directory's version of this file. /// </summary> public partial class Configuration { } }
18
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO.Compression; using System.Text.Json; using Amazon.CDK; using Amazon.CDK.AWS.ElasticBeanstalk; using Amazon.CDK.AWS.IAM; using Amazon.CDK.AWS.S3.Assets; using AWS.Deploy.Recipes.CDK.Common; using AspNetAppElasticBeanstalkLinux.Configurations; using Constructs; using System.Linq; using Amazon.CDK.AWS.EC2; using System.IO; // This is a generated file from the original deployment recipe. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // To customize the CDK constructs created in this file you should use the AppStack.CustomizeCDKProps() method. namespace AspNetAppElasticBeanstalkLinux { using static AWS.Deploy.Recipes.CDK.Common.CDKRecipeCustomizer<Recipe>; public class Recipe : Construct { public const string ENVIRONMENTTYPE_SINGLEINSTANCE = "SingleInstance"; public const string ENVIRONMENTTYPE_LOADBALANCED = "LoadBalanced"; public const string LOADBALANCERTYPE_APPLICATION = "application"; public const string REVERSEPROXY_NGINX = "nginx"; public const string ENHANCED_HEALTH_REPORTING = "enhanced"; public Vpc? AppVpc { get; private set; } public IRole? AppIAMRole { get; private set; } public IRole? BeanstalkServiceRole { get; private set; } public Asset? ApplicationAsset { get; private set; } public CfnInstanceProfile? Ec2InstanceProfile { get; private set; } public CfnApplicationVersion? ApplicationVersion { get; private set; } public CfnApplication? BeanstalkApplication { get; private set; } public CfnEnvironment? BeanstalkEnvironment { get; private set; } public Recipe(Construct scope, IRecipeProps<Configuration> props) // The "Recipe" construct ID will be used as part of the CloudFormation logical ID. If the value is changed this will // change the expected values for the "DisplayedResources" in the corresponding recipe file. : base(scope, "Recipe") { var settings = props.Settings; if (string.IsNullOrEmpty(props.DotnetPublishZipPath)) throw new InvalidOrMissingConfigurationException("The provided path containing the dotnet publish zip file is null or empty."); // Self contained deployment bundles need a Procfile to tell Beanstalk what process to start. SetupProcfileForSelfContained(props.DotnetPublishZipPath); ApplicationAsset = new Asset(this, "Asset", new AssetProps { Path = props.DotnetPublishZipPath }); ConfigureVpc(settings); ConfigureIAM(settings); var beanstalkApplicationName = ConfigureApplication(settings); ConfigureBeanstalkEnvironment(settings, beanstalkApplicationName); } private void ConfigureVpc(Configuration settings) { if (settings.VPC.UseVPC) { if (settings.VPC.CreateNew) { AppVpc = new Vpc(this, nameof(AppVpc), InvokeCustomizeCDKPropsEvent(nameof(AppVpc), this, new VpcProps { MaxAzs = 2 })); } } } private void ConfigureIAM(Configuration settings) { if (settings.ApplicationIAMRole.CreateNew) { AppIAMRole = new Role(this, nameof(AppIAMRole), InvokeCustomizeCDKPropsEvent(nameof(AppIAMRole), this, new RoleProps { AssumedBy = new ServicePrincipal("ec2.amazonaws.com"), // https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-instanceprofile.html ManagedPolicies = new[] { ManagedPolicy.FromAwsManagedPolicyName("AWSElasticBeanstalkWebTier"), ManagedPolicy.FromAwsManagedPolicyName("AWSElasticBeanstalkWorkerTier") } })); } else { if (string.IsNullOrEmpty(settings.ApplicationIAMRole.RoleArn)) throw new InvalidOrMissingConfigurationException("The provided Application IAM Role ARN is null or empty."); AppIAMRole = Role.FromRoleArn(this, nameof(AppIAMRole), settings.ApplicationIAMRole.RoleArn); } Ec2InstanceProfile = new CfnInstanceProfile(this, nameof(Ec2InstanceProfile), InvokeCustomizeCDKPropsEvent(nameof(Ec2InstanceProfile), this, new CfnInstanceProfileProps { Roles = new[] { AppIAMRole.RoleName } })); if (settings.ServiceIAMRole.CreateNew) { BeanstalkServiceRole = new Role(this, nameof(BeanstalkServiceRole), InvokeCustomizeCDKPropsEvent(nameof(BeanstalkServiceRole), this, new RoleProps { AssumedBy = new ServicePrincipal("elasticbeanstalk.amazonaws.com"), ManagedPolicies = new[] { ManagedPolicy.FromAwsManagedPolicyName("AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy"), ManagedPolicy.FromAwsManagedPolicyName("service-role/AWSElasticBeanstalkEnhancedHealth") } })); } else { if (string.IsNullOrEmpty(settings.ServiceIAMRole.RoleArn)) throw new InvalidOrMissingConfigurationException("The provided Service IAM Role ARN is null or empty."); BeanstalkServiceRole = Role.FromRoleArn(this, nameof(BeanstalkServiceRole), settings.ServiceIAMRole.RoleArn); } } private string ConfigureApplication(Configuration settings) { if (ApplicationAsset == null) throw new InvalidOperationException($"{nameof(ApplicationAsset)} has not been set."); string beanstalkApplicationName; if(settings.BeanstalkApplication.CreateNew) { if (settings.BeanstalkApplication.ApplicationName == null) throw new InvalidOperationException($"{nameof(settings.BeanstalkApplication.ApplicationName)} has not been set."); beanstalkApplicationName = settings.BeanstalkApplication.ApplicationName; } else { // This check is here for deployments that were initially done with an older version of the project. // In those deployments the existing application name was persisted in the ApplicationName property. if (settings.BeanstalkApplication.ExistingApplicationName == null && settings.BeanstalkApplication.ApplicationName != null) { beanstalkApplicationName = settings.BeanstalkApplication.ApplicationName; } else { if (settings.BeanstalkApplication.ExistingApplicationName == null) throw new InvalidOperationException($"{nameof(settings.BeanstalkApplication.ExistingApplicationName)} has not been set."); beanstalkApplicationName = settings.BeanstalkApplication.ExistingApplicationName; } } // Create an app version from the S3 asset defined above // The S3 "putObject" will occur first before CF generates the template ApplicationVersion = new CfnApplicationVersion(this, nameof(ApplicationVersion), InvokeCustomizeCDKPropsEvent(nameof(ApplicationVersion), this, new CfnApplicationVersionProps { ApplicationName = beanstalkApplicationName, SourceBundle = new CfnApplicationVersion.SourceBundleProperty { S3Bucket = ApplicationAsset.S3BucketName, S3Key = ApplicationAsset.S3ObjectKey } })); if (settings.BeanstalkApplication.CreateNew) { BeanstalkApplication = new CfnApplication(this, nameof(BeanstalkApplication), InvokeCustomizeCDKPropsEvent(nameof(BeanstalkApplication), this, new CfnApplicationProps { ApplicationName = beanstalkApplicationName })); ApplicationVersion.AddDependsOn(BeanstalkApplication); } return beanstalkApplicationName; } private void ConfigureBeanstalkEnvironment(Configuration settings, string beanstalkApplicationName) { if (Ec2InstanceProfile == null) throw new InvalidOperationException($"{nameof(Ec2InstanceProfile)} has not been set. The {nameof(ConfigureIAM)} method should be called before {nameof(ConfigureBeanstalkEnvironment)}"); if (ApplicationVersion == null) throw new InvalidOperationException($"{nameof(ApplicationVersion)} has not been set. The {nameof(ConfigureApplication)} method should be called before {nameof(ConfigureBeanstalkEnvironment)}"); var optionSettingProperties = new List<CfnEnvironment.OptionSettingProperty> { new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:launchconfiguration", OptionName = "IamInstanceProfile", Value = Ec2InstanceProfile.AttrArn }, new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:environment", OptionName = "EnvironmentType", Value = settings.EnvironmentType }, new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:managedactions", OptionName = "ManagedActionsEnabled", Value = settings.ElasticBeanstalkManagedPlatformUpdates.ManagedActionsEnabled.ToString().ToLower() }, new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:xray", OptionName = "XRayEnabled", Value = settings.XRayTracingSupportEnabled.ToString().ToLower() }, new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:healthreporting:system", OptionName = "SystemType", Value = settings.EnhancedHealthReporting } }; if (!string.IsNullOrEmpty(settings.InstanceType)) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:launchconfiguration", OptionName = "InstanceType", Value = settings.InstanceType }); } if (settings.EnvironmentType.Equals(ENVIRONMENTTYPE_LOADBALANCED)) { optionSettingProperties.Add( new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:environment", OptionName = "LoadBalancerType", Value = settings.LoadBalancerType } ); if (!string.IsNullOrEmpty(settings.HealthCheckURL)) { optionSettingProperties.Add( new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:application", OptionName = "Application Healthcheck URL", Value = settings.HealthCheckURL } ); optionSettingProperties.Add( new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:environment:process:default", OptionName = "HealthCheckPath", Value = settings.HealthCheckURL } ); } } if (!string.IsNullOrEmpty(settings.EC2KeyPair)) { optionSettingProperties.Add( new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:launchconfiguration", OptionName = "EC2KeyName", Value = settings.EC2KeyPair } ); } if (settings.ElasticBeanstalkManagedPlatformUpdates.ManagedActionsEnabled) { if (BeanstalkServiceRole == null) throw new InvalidOrMissingConfigurationException("The Elastic Beanstalk service role cannot be null"); optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:environment", OptionName = "ServiceRole", Value = BeanstalkServiceRole.RoleArn }); optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:managedactions", OptionName = "PreferredStartTime", Value = settings.ElasticBeanstalkManagedPlatformUpdates.PreferredStartTime }); optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:managedactions:platformupdate", OptionName = "UpdateLevel", Value = settings.ElasticBeanstalkManagedPlatformUpdates.UpdateLevel }); } if (!string.IsNullOrEmpty(settings.ReverseProxy)) { optionSettingProperties.Add( new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:environment:proxy", OptionName = "ProxyServer", Value = settings.ReverseProxy } ); } if (settings.ElasticBeanstalkRollingUpdates.RollingUpdatesEnabled) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:updatepolicy:rollingupdate", OptionName = "RollingUpdateEnabled", Value = settings.ElasticBeanstalkRollingUpdates.RollingUpdatesEnabled.ToString().ToLower() }); optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:updatepolicy:rollingupdate", OptionName = "RollingUpdateType", Value = settings.ElasticBeanstalkRollingUpdates.RollingUpdateType }); optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:updatepolicy:rollingupdate", OptionName = "Timeout", Value = settings.ElasticBeanstalkRollingUpdates.Timeout }); if (settings.ElasticBeanstalkRollingUpdates.MaxBatchSize != null) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:updatepolicy:rollingupdate", OptionName = "MaxBatchSize", Value = settings.ElasticBeanstalkRollingUpdates.MaxBatchSize.ToString() }); } if (settings.ElasticBeanstalkRollingUpdates.MinInstancesInService != null) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:updatepolicy:rollingupdate", OptionName = "MinInstancesInService", Value = settings.ElasticBeanstalkRollingUpdates.MinInstancesInService.ToString() }); } if (settings.ElasticBeanstalkRollingUpdates.PauseTime != null) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:updatepolicy:rollingupdate", OptionName = "PauseTime", Value = settings.ElasticBeanstalkRollingUpdates.PauseTime }); } } if (settings.ElasticBeanstalkEnvironmentVariables != null) { foreach (var (key, value) in settings.ElasticBeanstalkEnvironmentVariables) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:application:environment", OptionName = key, Value = value }); } } if (settings.VPC.UseVPC) { if (settings.VPC.CreateNew) { if (AppVpc == null) throw new InvalidOperationException($"{nameof(AppVpc)} has not been set. The {nameof(ConfigureVpc)} method should be called before {nameof(ConfigureBeanstalkEnvironment)}"); optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:ec2:vpc", OptionName = "VPCId", Value = AppVpc.VpcId }); if (settings.EnvironmentType.Equals(ENVIRONMENTTYPE_SINGLEINSTANCE)) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:ec2:vpc", OptionName = "Subnets", Value = string.Join(",", AppVpc.PublicSubnets.Select(x => x.SubnetId)) }); } else if (settings.EnvironmentType.Equals(ENVIRONMENTTYPE_LOADBALANCED)) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:ec2:vpc", OptionName = "Subnets", Value = string.Join(",", AppVpc.PrivateSubnets.Select(x => x.SubnetId)) }); optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:ec2:vpc", OptionName = "ELBSubnets", Value = string.Join(",", AppVpc.PublicSubnets.Select(x => x.SubnetId)) }); } optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:launchconfiguration", OptionName = "SecurityGroups", Value = AppVpc.VpcDefaultSecurityGroup }); } else { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:ec2:vpc", OptionName = "VPCId", Value = settings.VPC.VpcId }); if (settings.VPC.Subnets.Any()) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:ec2:vpc", OptionName = "Subnets", Value = string.Join(",", settings.VPC.Subnets) }); if (settings.VPC.SecurityGroups.Any()) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:launchconfiguration", OptionName = "SecurityGroups", Value = string.Join(",", settings.VPC.SecurityGroups) }); } } } } BeanstalkEnvironment = new CfnEnvironment(this, nameof(BeanstalkEnvironment), InvokeCustomizeCDKPropsEvent(nameof(BeanstalkEnvironment), this, new CfnEnvironmentProps { EnvironmentName = settings.BeanstalkEnvironment.EnvironmentName, ApplicationName = beanstalkApplicationName, PlatformArn = settings.ElasticBeanstalkPlatformArn, OptionSettings = optionSettingProperties.ToArray(), CnamePrefix = !string.IsNullOrEmpty(settings.CNamePrefix) ? settings.CNamePrefix : null, // This line is critical - reference the label created in this same stack VersionLabel = ApplicationVersion.Ref, })); } /// <summary> /// When deploying a self contained deployment bundle, Beanstalk needs a Procfile to tell the environment what process to start up. /// Check out the AWS Elastic Beanstalk developer guide for more information on Procfiles /// https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/dotnet-linux-procfile.html /// </summary> /// <param name="dotnetZipFilePath"></param> static void SetupProcfileForSelfContained(string dotnetZipFilePath) { const string RUNTIME_CONFIG_SUFFIX = ".runtimeconfig.json"; const string PROCFILE_NAME = "Procfile"; string runtimeConfigFilename; string runtimeConfigJson; using (var zipArchive = ZipFile.Open(dotnetZipFilePath, ZipArchiveMode.Read)) { // Skip Procfile setup if one already exists. if (zipArchive.GetEntry(PROCFILE_NAME) != null) { return; } var runtimeConfigEntry = zipArchive.Entries.FirstOrDefault(x => x.Name.EndsWith(RUNTIME_CONFIG_SUFFIX)); if (runtimeConfigEntry == null) { return; } runtimeConfigFilename = runtimeConfigEntry.Name; using var stream = runtimeConfigEntry.Open(); runtimeConfigJson = new StreamReader(stream).ReadToEnd(); } var runtimeConfigDoc = JsonDocument.Parse(runtimeConfigJson); if (!runtimeConfigDoc.RootElement.TryGetProperty("runtimeOptions", out var runtimeOptionsNode)) { return; } // If there are includedFrameworks then the zip file is a self contained deployment bundle. if (!runtimeOptionsNode.TryGetProperty("includedFrameworks", out _)) { return; } var executableName = runtimeConfigFilename.Substring(0, runtimeConfigFilename.Length - RUNTIME_CONFIG_SUFFIX.Length); var procCommand = $"web: ./{executableName}"; using (var zipArchive = ZipFile.Open(dotnetZipFilePath, ZipArchiveMode.Update)) { var procfileEntry = zipArchive.CreateEntry(PROCFILE_NAME); using var zipEntryStream = procfileEntry.Open(); zipEntryStream.Write(System.Text.UTF8Encoding.UTF8.GetBytes(procCommand)); } } } }
547
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppElasticBeanstalkLinux.Configurations { public partial class BeanstalkApplicationConfiguration { public bool CreateNew { get; set; } public string? ApplicationName { get; set; } public string? ExistingApplicationName { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public BeanstalkApplicationConfiguration() { } #nullable restore warnings public BeanstalkApplicationConfiguration( bool createNew) { CreateNew = createNew; } } }
35
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppElasticBeanstalkLinux.Configurations { public partial class BeanstalkEnvironmentConfiguration { public string EnvironmentName { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public BeanstalkEnvironmentConfiguration() { } #nullable restore warnings public BeanstalkEnvironmentConfiguration( string environmentName) { EnvironmentName = environmentName; } } }
33
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. using System.Collections.Generic; namespace AspNetAppElasticBeanstalkLinux.Configurations { public partial class Configuration { /// <summary> /// The Identity and Access Management Role that provides AWS credentials to the application to access AWS services /// </summary> public IAMRoleConfiguration ApplicationIAMRole { get; set; } /// <summary> /// A service role is the IAM role that Elastic Beanstalk assumes when calling other services on your behalf /// </summary> public IAMRoleConfiguration ServiceIAMRole { get; set; } /// <summary> /// The type of environment for the Elastic Beanstalk application. /// </summary> public string EnvironmentType { get; set; } = Recipe.ENVIRONMENTTYPE_SINGLEINSTANCE; /// <summary> /// The EC2 instance type used for the EC2 instances created for the environment. /// </summary> public string InstanceType { get; set; } /// <summary> /// The Elastic Beanstalk environment. /// </summary> public BeanstalkEnvironmentConfiguration BeanstalkEnvironment { get; set; } /// <summary> /// The Elastic Beanstalk application. /// </summary> public BeanstalkApplicationConfiguration BeanstalkApplication { get; set; } /// <summary> /// The name of an Elastic Beanstalk solution stack (platform version) to use with the environment. /// </summary> public string ElasticBeanstalkPlatformArn { get; set; } /// <summary> /// The type of load balancer for your environment. /// </summary> public string LoadBalancerType { get; set; } = Recipe.LOADBALANCERTYPE_APPLICATION; /// <summary> /// The EC2 Key Pair used for the Beanstalk Application. /// </summary> public string EC2KeyPair { get; set; } /// <summary> /// Specifies whether to enable or disable Managed Platform Updates. /// </summary> public ElasticBeanstalkManagedPlatformUpdatesConfiguration ElasticBeanstalkManagedPlatformUpdates { get; set; } /// <summary> /// Specifies whether to enable or disable AWS X-Ray tracing support. /// </summary> public bool XRayTracingSupportEnabled { get; set; } = false; /// <summary> /// The reverse proxy to use. /// </summary> public string ReverseProxy { get; set; } = Recipe.REVERSEPROXY_NGINX; /// <summary> /// Specifies whether to enable or disable enhanced health reporting. /// </summary> public string EnhancedHealthReporting { get; set; } = Recipe.ENHANCED_HEALTH_REPORTING; /// <summary> /// The health check URL to use. /// </summary> public string HealthCheckURL { get; set; } /// <summary> /// Specifies whether to enable or disable Rolling Updates. /// </summary> public ElasticBeanstalkRollingUpdatesConfiguration ElasticBeanstalkRollingUpdates { get; set; } /// <summary> /// The CName Prefix used for the Beanstalk Environment. /// </summary> public string CNamePrefix { get; set; } /// <summary> /// The environment variables that are set for the beanstalk environment. /// </summary> public Dictionary<string, string> ElasticBeanstalkEnvironmentVariables { get; set; } = new Dictionary<string, string> { }; /// <summary> /// Virtual Private Cloud to launch container instance into a virtual network. /// </summary> public VPCConfiguration VPC { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public Configuration() { } #nullable restore warnings public Configuration( IAMRoleConfiguration applicationIAMRole, IAMRoleConfiguration serviceIAMRole, string instanceType, BeanstalkEnvironmentConfiguration beanstalkEnvironment, BeanstalkApplicationConfiguration beanstalkApplication, string elasticBeanstalkPlatformArn, string ec2KeyPair, ElasticBeanstalkManagedPlatformUpdatesConfiguration elasticBeanstalkManagedPlatformUpdates, string healthCheckURL, ElasticBeanstalkRollingUpdatesConfiguration elasticBeanstalkRollingUpdates, string cnamePrefix, Dictionary<string, string> elasticBeanstalkEnvironmentVariables, VPCConfiguration vpc, string environmentType = Recipe.ENVIRONMENTTYPE_SINGLEINSTANCE, string loadBalancerType = Recipe.LOADBALANCERTYPE_APPLICATION, string reverseProxy = Recipe.REVERSEPROXY_NGINX, bool xrayTracingSupportEnabled = false, string enhancedHealthReporting = Recipe.ENHANCED_HEALTH_REPORTING) { ApplicationIAMRole = applicationIAMRole; ServiceIAMRole = serviceIAMRole; InstanceType = instanceType; BeanstalkEnvironment = beanstalkEnvironment; BeanstalkApplication = beanstalkApplication; ElasticBeanstalkPlatformArn = elasticBeanstalkPlatformArn; EC2KeyPair = ec2KeyPair; ElasticBeanstalkManagedPlatformUpdates = elasticBeanstalkManagedPlatformUpdates; ElasticBeanstalkRollingUpdates = elasticBeanstalkRollingUpdates; ElasticBeanstalkEnvironmentVariables = elasticBeanstalkEnvironmentVariables; VPC = vpc; EnvironmentType = environmentType; LoadBalancerType = loadBalancerType; XRayTracingSupportEnabled = xrayTracingSupportEnabled; ReverseProxy = reverseProxy; EnhancedHealthReporting = enhancedHealthReporting; HealthCheckURL = healthCheckURL; CNamePrefix = cnamePrefix; } } }
157
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppElasticBeanstalkLinux.Configurations { public partial class ElasticBeanstalkManagedPlatformUpdatesConfiguration { public bool ManagedActionsEnabled { get; set; } = true; public string PreferredStartTime { get; set; } = "Sun:00:00"; public string UpdateLevel { get; set; } = "minor"; } }
19
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppElasticBeanstalkLinux.Configurations { public partial class ElasticBeanstalkRollingUpdatesConfiguration { public bool RollingUpdatesEnabled { get; set; } = false; public string RollingUpdateType { get; set; } = "Time"; public int? MaxBatchSize { get; set; } public int? MinInstancesInService { get; set; } public string? PauseTime { get; set; } public string Timeout { get; set; } = "PT30M"; } }
22
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppElasticBeanstalkLinux.Configurations { public partial class IAMRoleConfiguration { /// <summary> /// If set, create a new anonymously named IAM role. /// </summary> public bool CreateNew { get; set; } /// <summary> /// If <see cref="CreateNew"/> is false, /// then use an existing IAM role by referencing through <see cref="RoleArn"/> /// </summary> public string? RoleArn { get; set; } } }
26
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AspNetAppElasticBeanstalkLinux.Configurations { public partial class VPCConfiguration { /// <summary> /// If set, the deployment will use a VPC to connect to the Elastic Beanstalk service. /// </summary> public bool UseVPC { get; set; } /// <summary> /// Creates a new VPC if set to true. /// </summary> public bool CreateNew { get; set; } /// <summary> /// The VPC ID to use for the Elastic Beanstalk service. /// </summary> public string? VpcId { get; set; } /// <summary> /// A list of IDs of subnets that Elastic Beanstalk should use when it associates your environment with a custom Amazon VPC. /// Specify IDs of subnets of a single Amazon VPC. /// </summary> public SortedSet<string> Subnets { get; set; } = new SortedSet<string>(); /// <summary> /// Lists the Amazon EC2 security groups to assign to the EC2 instances in the Auto Scaling group to define firewall rules for the instances. /// </summary> public SortedSet<string> SecurityGroups { get; set; } = new SortedSet<string>(); } }
39
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using Amazon.CDK; using Amazon.CDK.AWS.ElasticBeanstalk; using AWS.Deploy.Recipes.CDK.Common; using AspNetAppElasticBeanstalkWindows.Configurations; using Constructs; namespace AspNetAppElasticBeanstalkWindows { public class AppStack : Stack { private readonly Configuration _configuration; internal AppStack(Construct scope, IDeployToolStackProps<Configuration> props) : base(scope, props.StackName, props) { _configuration = props.RecipeProps.Settings; // Setup callback for generated construct to provide access to customize CDK properties before creating constructs. CDKRecipeCustomizer<Recipe>.CustomizeCDKProps += CustomizeCDKProps; // Create custom CDK constructs here that might need to be referenced in the CustomizeCDKProps. For example if // creating a DynamoDB table construct and then later using the CDK construct reference in CustomizeCDKProps to // pass the table name as an environment variable to the container image. // Create the recipe defined CDK construct with all of its sub constructs. var generatedRecipe = new Recipe(this, props.RecipeProps); // Create additional CDK constructs here. The recipe's constructs can be accessed as properties on // the generatedRecipe variable. } /// <summary> /// This method can be used to customize the properties for CDK constructs before creating the constructs. /// /// The pattern used in this method is to check to evnt.ResourceLogicalName to see if the CDK construct about to be created is one /// you want to customize. If so cast the evnt.Props object to the CDK properties object and make the appropriate settings. /// </summary> /// <param name="evnt"></param> private void CustomizeCDKProps(CustomizePropsEventArgs<Recipe> evnt) { // Example of how to customize the Beanstalk Environment. // //if (string.Equals(evnt.ResourceLogicalName, nameof(evnt.Construct.BeanstalkEnvironment))) //{ // if (evnt.Props is CfnEnvironmentProps props) // { // Console.WriteLine("Customizing Beanstalk Environment"); // } //} } } }
59
aws-dotnet-deploy
aws
C#
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Potential Code Quality Issues", "RECS0026:Possible unassigned object created by 'new'", Justification = "Constructs add themselves to the scope in which they are created")]
2
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.CDK; using AWS.Deploy.Recipes.CDK.Common; using AspNetAppElasticBeanstalkWindows.Configurations; using Microsoft.Extensions.Configuration; namespace AspNetAppElasticBeanstalkWindows { sealed class Program { public static void Main(string[] args) { var app = new App(); var builder = new ConfigurationBuilder().AddAWSDeployToolConfiguration(app); var recipeProps = builder.Build().Get<RecipeProps<Configuration>>(); var appStackProps = new DeployToolStackProps<Configuration>(recipeProps) { Env = new Environment { Account = recipeProps.AWSAccountId, Region = recipeProps.AWSRegion } }; // The RegisterStack method is used to set identifying information on the stack // for the recipe used to deploy the application and preserve the settings used in the recipe // to allow redeployment. The information is stored as CloudFormation tags and metadata inside // the generated CloudFormation template. CDKRecipeSetup.RegisterStack<Configuration>(new AppStack(app, appStackProps), appStackProps.RecipeProps); app.Synth(); } } }
38
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AspNetAppElasticBeanstalkWindows.Configurations { /// <summary> /// The configuration settings that are passed in from the deploy tool to the CDK project. If /// custom settings are defined in the recipe definition then corresponding properties should be added here. /// /// This is a partial class with all of the settings defined by default in the recipe declared in the /// Generated directory's version of this file. /// </summary> public partial class Configuration { } }
18
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO.Compression; using System.IO; using System.Linq; using System.Text.Json; using Amazon.CDK; using Amazon.CDK.AWS.EC2; using Amazon.CDK.AWS.ElasticBeanstalk; using Amazon.CDK.AWS.IAM; using Amazon.CDK.AWS.S3.Assets; using AWS.Deploy.Recipes.CDK.Common; using AspNetAppElasticBeanstalkWindows.Configurations; using Constructs; // This is a generated file from the original deployment recipe. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // To customize the CDK constructs created in this file you should use the AppStack.CustomizeCDKProps() method. namespace AspNetAppElasticBeanstalkWindows { using static AWS.Deploy.Recipes.CDK.Common.CDKRecipeCustomizer<Recipe>; public class Recipe : Construct { public const string ENVIRONMENTTYPE_SINGLEINSTANCE = "SingleInstance"; public const string ENVIRONMENTTYPE_LOADBALANCED = "LoadBalanced"; public const string LOADBALANCERTYPE_APPLICATION = "application"; public const string REVERSEPROXY_NGINX = "nginx"; public const string ENHANCED_HEALTH_REPORTING = "enhanced"; public Vpc? AppVpc { get; private set; } public IRole? AppIAMRole { get; private set; } public IRole? BeanstalkServiceRole { get; private set; } public Asset? ApplicationAsset { get; private set; } public CfnInstanceProfile? Ec2InstanceProfile { get; private set; } public CfnApplicationVersion? ApplicationVersion { get; private set; } public CfnApplication? BeanstalkApplication { get; private set; } public CfnEnvironment? BeanstalkEnvironment { get; private set; } public Recipe(Construct scope, IRecipeProps<Configuration> props) // The "Recipe" construct ID will be used as part of the CloudFormation logical ID. If the value is changed this will // change the expected values for the "DisplayedResources" in the corresponding recipe file. : base(scope, "Recipe") { var settings = props.Settings; if (string.IsNullOrEmpty(props.DotnetPublishZipPath)) throw new InvalidOrMissingConfigurationException("The provided path containing the dotnet publish zip file is null or empty."); // Write the Beanstalk manifest file to the .NET Zip bundle. SetupAWSDeploymentManifest(settings, props.DotnetPublishZipPath); ApplicationAsset = new Asset(this, "Asset", new AssetProps { Path = props.DotnetPublishZipPath }); ConfigureVpc(settings); ConfigureIAM(settings); var beanstalkApplicationName = ConfigureApplication(settings); ConfigureBeanstalkEnvironment(settings, beanstalkApplicationName); } private void ConfigureVpc(Configuration settings) { if (settings.VPC.UseVPC) { if (settings.VPC.CreateNew) { AppVpc = new Vpc(this, nameof(AppVpc), InvokeCustomizeCDKPropsEvent(nameof(AppVpc), this, new VpcProps { MaxAzs = 2 })); } } } private void ConfigureIAM(Configuration settings) { if (settings.ApplicationIAMRole.CreateNew) { AppIAMRole = new Role(this, nameof(AppIAMRole), InvokeCustomizeCDKPropsEvent(nameof(AppIAMRole), this, new RoleProps { AssumedBy = new ServicePrincipal("ec2.amazonaws.com"), // https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-instanceprofile.html ManagedPolicies = new[] { ManagedPolicy.FromAwsManagedPolicyName("AWSElasticBeanstalkWebTier"), ManagedPolicy.FromAwsManagedPolicyName("AWSElasticBeanstalkWorkerTier") } })); } else { if (string.IsNullOrEmpty(settings.ApplicationIAMRole.RoleArn)) throw new InvalidOrMissingConfigurationException("The provided Application IAM Role ARN is null or empty."); AppIAMRole = Role.FromRoleArn(this, nameof(AppIAMRole), settings.ApplicationIAMRole.RoleArn); } Ec2InstanceProfile = new CfnInstanceProfile(this, nameof(Ec2InstanceProfile), InvokeCustomizeCDKPropsEvent(nameof(Ec2InstanceProfile), this, new CfnInstanceProfileProps { Roles = new[] { AppIAMRole.RoleName } })); if (settings.ServiceIAMRole.CreateNew) { BeanstalkServiceRole = new Role(this, nameof(BeanstalkServiceRole), InvokeCustomizeCDKPropsEvent(nameof(BeanstalkServiceRole), this, new RoleProps { AssumedBy = new ServicePrincipal("elasticbeanstalk.amazonaws.com"), ManagedPolicies = new[] { ManagedPolicy.FromAwsManagedPolicyName("AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy"), ManagedPolicy.FromAwsManagedPolicyName("service-role/AWSElasticBeanstalkEnhancedHealth") } })); } else { if (string.IsNullOrEmpty(settings.ServiceIAMRole.RoleArn)) throw new InvalidOrMissingConfigurationException("The provided Service IAM Role ARN is null or empty."); BeanstalkServiceRole = Role.FromRoleArn(this, nameof(BeanstalkServiceRole), settings.ServiceIAMRole.RoleArn); } } private string ConfigureApplication(Configuration settings) { if (ApplicationAsset == null) throw new InvalidOperationException($"{nameof(ApplicationAsset)} has not been set."); string beanstalkApplicationName; if(settings.BeanstalkApplication.CreateNew) { if (settings.BeanstalkApplication.ApplicationName == null) throw new InvalidOperationException($"{nameof(settings.BeanstalkApplication.ApplicationName)} has not been set."); beanstalkApplicationName = settings.BeanstalkApplication.ApplicationName; } else { // This check is here for deployments that were initially done with an older version of the project. // In those deployments the existing application name was persisted in the ApplicationName property. if (settings.BeanstalkApplication.ExistingApplicationName == null && settings.BeanstalkApplication.ApplicationName != null) { beanstalkApplicationName = settings.BeanstalkApplication.ApplicationName; } else { if (settings.BeanstalkApplication.ExistingApplicationName == null) throw new InvalidOperationException($"{nameof(settings.BeanstalkApplication.ExistingApplicationName)} has not been set."); beanstalkApplicationName = settings.BeanstalkApplication.ExistingApplicationName; } } // Create an app version from the S3 asset defined above // The S3 "putObject" will occur first before CF generates the template ApplicationVersion = new CfnApplicationVersion(this, nameof(ApplicationVersion), InvokeCustomizeCDKPropsEvent(nameof(ApplicationVersion), this, new CfnApplicationVersionProps { ApplicationName = beanstalkApplicationName, SourceBundle = new CfnApplicationVersion.SourceBundleProperty { S3Bucket = ApplicationAsset.S3BucketName, S3Key = ApplicationAsset.S3ObjectKey } })); if (settings.BeanstalkApplication.CreateNew) { BeanstalkApplication = new CfnApplication(this, nameof(BeanstalkApplication), InvokeCustomizeCDKPropsEvent(nameof(BeanstalkApplication), this, new CfnApplicationProps { ApplicationName = beanstalkApplicationName })); ApplicationVersion.AddDependsOn(BeanstalkApplication); } return beanstalkApplicationName; } private void ConfigureBeanstalkEnvironment(Configuration settings, string beanstalkApplicationName) { if (Ec2InstanceProfile == null) throw new InvalidOperationException($"{nameof(Ec2InstanceProfile)} has not been set. The {nameof(ConfigureIAM)} method should be called before {nameof(ConfigureBeanstalkEnvironment)}"); if (ApplicationVersion == null) throw new InvalidOperationException($"{nameof(ApplicationVersion)} has not been set. The {nameof(ConfigureApplication)} method should be called before {nameof(ConfigureBeanstalkEnvironment)}"); var optionSettingProperties = new List<CfnEnvironment.OptionSettingProperty> { new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:launchconfiguration", OptionName = "IamInstanceProfile", Value = Ec2InstanceProfile.AttrArn }, new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:environment", OptionName = "EnvironmentType", Value = settings.EnvironmentType }, new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:managedactions", OptionName = "ManagedActionsEnabled", Value = settings.ElasticBeanstalkManagedPlatformUpdates.ManagedActionsEnabled.ToString().ToLower() }, new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:xray", OptionName = "XRayEnabled", Value = settings.XRayTracingSupportEnabled.ToString().ToLower() }, new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:healthreporting:system", OptionName = "SystemType", Value = settings.EnhancedHealthReporting } }; if (!string.IsNullOrEmpty(settings.InstanceType)) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:launchconfiguration", OptionName = "InstanceType", Value = settings.InstanceType }); } if (settings.EnvironmentType.Equals(ENVIRONMENTTYPE_LOADBALANCED)) { optionSettingProperties.Add( new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:environment", OptionName = "LoadBalancerType", Value = settings.LoadBalancerType } ); if (!string.IsNullOrEmpty(settings.HealthCheckURL)) { optionSettingProperties.Add( new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:application", OptionName = "Application Healthcheck URL", Value = settings.HealthCheckURL } ); optionSettingProperties.Add( new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:environment:process:default", OptionName = "HealthCheckPath", Value = settings.HealthCheckURL } ); } } if (!string.IsNullOrEmpty(settings.EC2KeyPair)) { optionSettingProperties.Add( new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:launchconfiguration", OptionName = "EC2KeyName", Value = settings.EC2KeyPair } ); } if (settings.ElasticBeanstalkManagedPlatformUpdates.ManagedActionsEnabled) { if (BeanstalkServiceRole == null) throw new InvalidOrMissingConfigurationException("The Elastic Beanstalk service role cannot be null"); optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:environment", OptionName = "ServiceRole", Value = BeanstalkServiceRole.RoleArn }); optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:managedactions", OptionName = "PreferredStartTime", Value = settings.ElasticBeanstalkManagedPlatformUpdates.PreferredStartTime }); optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:managedactions:platformupdate", OptionName = "UpdateLevel", Value = settings.ElasticBeanstalkManagedPlatformUpdates.UpdateLevel }); } if (settings.ElasticBeanstalkRollingUpdates.RollingUpdatesEnabled) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:updatepolicy:rollingupdate", OptionName = "RollingUpdateEnabled", Value = settings.ElasticBeanstalkRollingUpdates.RollingUpdatesEnabled.ToString().ToLower() }); optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:updatepolicy:rollingupdate", OptionName = "RollingUpdateType", Value = settings.ElasticBeanstalkRollingUpdates.RollingUpdateType }); optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:updatepolicy:rollingupdate", OptionName = "Timeout", Value = settings.ElasticBeanstalkRollingUpdates.Timeout }); if (settings.ElasticBeanstalkRollingUpdates.MaxBatchSize != null) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:updatepolicy:rollingupdate", OptionName = "MaxBatchSize", Value = settings.ElasticBeanstalkRollingUpdates.MaxBatchSize.ToString() }); } if (settings.ElasticBeanstalkRollingUpdates.MinInstancesInService != null) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:updatepolicy:rollingupdate", OptionName = "MinInstancesInService", Value = settings.ElasticBeanstalkRollingUpdates.MinInstancesInService.ToString() }); } if (settings.ElasticBeanstalkRollingUpdates.PauseTime != null) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:updatepolicy:rollingupdate", OptionName = "PauseTime", Value = settings.ElasticBeanstalkRollingUpdates.PauseTime }); } } if (settings.ElasticBeanstalkEnvironmentVariables != null) { foreach (var (key, value) in settings.ElasticBeanstalkEnvironmentVariables) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:elasticbeanstalk:application:environment", OptionName = key, Value = value }); } } if (settings.VPC.UseVPC) { if (settings.VPC.CreateNew) { if (AppVpc == null) throw new InvalidOperationException($"{nameof(AppVpc)} has not been set. The {nameof(ConfigureVpc)} method should be called before {nameof(ConfigureBeanstalkEnvironment)}"); optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:ec2:vpc", OptionName = "VPCId", Value = AppVpc.VpcId }); if (settings.EnvironmentType.Equals(ENVIRONMENTTYPE_SINGLEINSTANCE)) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:ec2:vpc", OptionName = "Subnets", Value = string.Join(",", AppVpc.PublicSubnets.Select(x => x.SubnetId)) }); } else if (settings.EnvironmentType.Equals(ENVIRONMENTTYPE_LOADBALANCED)) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:ec2:vpc", OptionName = "Subnets", Value = string.Join(",", AppVpc.PrivateSubnets.Select(x => x.SubnetId)) }); optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:ec2:vpc", OptionName = "ELBSubnets", Value = string.Join(",", AppVpc.PublicSubnets.Select(x => x.SubnetId)) }); } optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:launchconfiguration", OptionName = "SecurityGroups", Value = AppVpc.VpcDefaultSecurityGroup }); } else { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:ec2:vpc", OptionName = "VPCId", Value = settings.VPC.VpcId }); if (settings.VPC.Subnets.Any()) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:ec2:vpc", OptionName = "Subnets", Value = string.Join(",", settings.VPC.Subnets) }); if (settings.VPC.SecurityGroups.Any()) { optionSettingProperties.Add(new CfnEnvironment.OptionSettingProperty { Namespace = "aws:autoscaling:launchconfiguration", OptionName = "SecurityGroups", Value = string.Join(",", settings.VPC.SecurityGroups) }); } } } } BeanstalkEnvironment = new CfnEnvironment(this, nameof(BeanstalkEnvironment), InvokeCustomizeCDKPropsEvent(nameof(BeanstalkEnvironment), this, new CfnEnvironmentProps { EnvironmentName = settings.EnvironmentName, ApplicationName = beanstalkApplicationName, PlatformArn = settings.ElasticBeanstalkPlatformArn, OptionSettings = optionSettingProperties.ToArray(), CnamePrefix = !string.IsNullOrEmpty(settings.CNamePrefix) ? settings.CNamePrefix : null, // This line is critical - reference the label created in this same stack VersionLabel = ApplicationVersion.Ref, })); } public void SetupAWSDeploymentManifest(Configuration settings, string dotnetZipFilePath) { const string MANIFEST_FILENAME = "aws-windows-deployment-manifest.json"; var iisWebSite = !string.IsNullOrEmpty(settings.IISWebSite) ? settings.IISWebSite : "Default Web Site"; var iisAppPath = !string.IsNullOrEmpty(settings.IISAppPath) ? settings.IISAppPath : "/"; var jsonStream = new MemoryStream(); using (var jsonWriter = new Utf8JsonWriter(jsonStream)) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("manifestVersion"); jsonWriter.WriteNumberValue(1); jsonWriter.WriteStartObject("deployments"); jsonWriter.WriteStartArray("aspNetCoreWeb"); jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("name"); jsonWriter.WriteStringValue("MainApp"); jsonWriter.WriteStartObject("parameters"); jsonWriter.WritePropertyName("appBundle"); jsonWriter.WriteStringValue("."); jsonWriter.WritePropertyName("iisWebSite"); jsonWriter.WriteStringValue(iisWebSite); jsonWriter.WritePropertyName("iisPath"); jsonWriter.WriteStringValue(iisAppPath); jsonWriter.WriteEndObject(); jsonWriter.WriteEndObject(); jsonWriter.WriteEndArray(); jsonWriter.WriteEndObject(); jsonWriter.WriteEndObject(); } using (var zipArchive = ZipFile.Open(dotnetZipFilePath, ZipArchiveMode.Update)) { var zipEntry = zipArchive.CreateEntry(MANIFEST_FILENAME); using var zipEntryStream = zipEntry.Open(); jsonStream.Position = 0; jsonStream.CopyTo(zipEntryStream); } } } }
526
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppElasticBeanstalkWindows.Configurations { public partial class BeanstalkApplicationConfiguration { public bool CreateNew { get; set; } public string? ApplicationName { get; set; } public string? ExistingApplicationName { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public BeanstalkApplicationConfiguration() { } #nullable restore warnings public BeanstalkApplicationConfiguration( bool createNew) { CreateNew = createNew; } } }
35
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. using System.Collections.Generic; namespace AspNetAppElasticBeanstalkWindows.Configurations { public partial class Configuration { /// <summary> /// The Identity and Access Management Role that provides AWS credentials to the application to access AWS services /// </summary> public IAMRoleConfiguration ApplicationIAMRole { get; set; } /// <summary> /// A service role is the IAM role that Elastic Beanstalk assumes when calling other services on your behalf /// </summary> public IAMRoleConfiguration ServiceIAMRole { get; set; } /// <summary> /// The type of environment for the Elastic Beanstalk application. /// </summary> public string EnvironmentType { get; set; } = Recipe.ENVIRONMENTTYPE_SINGLEINSTANCE; /// <summary> /// The EC2 instance type used for the EC2 instances created for the environment. /// </summary> public string InstanceType { get; set; } /// <summary> /// The Elastic Beanstalk environment. /// </summary> public string EnvironmentName { get; set; } /// <summary> /// The Elastic Beanstalk application. /// </summary> public BeanstalkApplicationConfiguration BeanstalkApplication { get; set; } /// <summary> /// The name of an Elastic Beanstalk solution stack (platform version) to use with the environment. /// </summary> public string ElasticBeanstalkPlatformArn { get; set; } /// <summary> /// The type of load balancer for your environment. /// </summary> public string LoadBalancerType { get; set; } = Recipe.LOADBALANCERTYPE_APPLICATION; /// <summary> /// The EC2 Key Pair used for the Beanstalk Application. /// </summary> public string EC2KeyPair { get; set; } /// <summary> /// Specifies whether to enable or disable Managed Platform Updates. /// </summary> public ElasticBeanstalkManagedPlatformUpdatesConfiguration ElasticBeanstalkManagedPlatformUpdates { get; set; } /// <summary> /// Specifies whether to enable or disable AWS X-Ray tracing support. /// </summary> public bool XRayTracingSupportEnabled { get; set; } = false; /// <summary> /// Specifies the IIS WebSite. /// </summary> public string IISWebSite { get; set; } = "Default Web Site"; /// <summary> /// Specifies the IIS application path. /// </summary> public string IISAppPath { get; set; } = "/"; /// <summary> /// Specifies whether to enable or disable enhanced health reporting. /// </summary> public string EnhancedHealthReporting { get; set; } = Recipe.ENHANCED_HEALTH_REPORTING; /// <summary> /// The health check URL to use. /// </summary> public string HealthCheckURL { get; set; } /// <summary> /// Specifies whether to enable or disable Rolling Updates. /// </summary> public ElasticBeanstalkRollingUpdatesConfiguration ElasticBeanstalkRollingUpdates { get; set; } /// <summary> /// The CName Prefix used for the Beanstalk Environment. /// </summary> public string CNamePrefix { get; set; } /// <summary> /// The environment variables that are set for the beanstalk environment. /// </summary> public Dictionary<string, string> ElasticBeanstalkEnvironmentVariables { get; set; } = new Dictionary<string, string> { }; /// <summary> /// Virtual Private Cloud to launch container instance into a virtual network. /// </summary> public VPCConfiguration VPC { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public Configuration() { } #nullable restore warnings public Configuration( IAMRoleConfiguration applicationIAMRole, IAMRoleConfiguration serviceIAMRole, string instanceType, string environmentName, BeanstalkApplicationConfiguration beanstalkApplication, string elasticBeanstalkPlatformArn, string ec2KeyPair, ElasticBeanstalkManagedPlatformUpdatesConfiguration elasticBeanstalkManagedPlatformUpdates, string healthCheckURL, ElasticBeanstalkRollingUpdatesConfiguration elasticBeanstalkRollingUpdates, string cnamePrefix, Dictionary<string, string> elasticBeanstalkEnvironmentVariables, VPCConfiguration vpc, string environmentType = Recipe.ENVIRONMENTTYPE_SINGLEINSTANCE, string loadBalancerType = Recipe.LOADBALANCERTYPE_APPLICATION, bool xrayTracingSupportEnabled = false, string enhancedHealthReporting = Recipe.ENHANCED_HEALTH_REPORTING) { ApplicationIAMRole = applicationIAMRole; ServiceIAMRole = serviceIAMRole; InstanceType = instanceType; EnvironmentName = environmentName; BeanstalkApplication = beanstalkApplication; ElasticBeanstalkPlatformArn = elasticBeanstalkPlatformArn; EC2KeyPair = ec2KeyPair; ElasticBeanstalkManagedPlatformUpdates = elasticBeanstalkManagedPlatformUpdates; ElasticBeanstalkRollingUpdates = elasticBeanstalkRollingUpdates; ElasticBeanstalkEnvironmentVariables = elasticBeanstalkEnvironmentVariables; VPC = vpc; EnvironmentType = environmentType; LoadBalancerType = loadBalancerType; XRayTracingSupportEnabled = xrayTracingSupportEnabled; EnhancedHealthReporting = enhancedHealthReporting; HealthCheckURL = healthCheckURL; CNamePrefix = cnamePrefix; } } }
160
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppElasticBeanstalkWindows.Configurations { public partial class ElasticBeanstalkManagedPlatformUpdatesConfiguration { public bool ManagedActionsEnabled { get; set; } = true; public string PreferredStartTime { get; set; } = "Sun:00:00"; public string UpdateLevel { get; set; } = "minor"; } }
19
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppElasticBeanstalkWindows.Configurations { public partial class ElasticBeanstalkRollingUpdatesConfiguration { public bool RollingUpdatesEnabled { get; set; } = false; public string RollingUpdateType { get; set; } = "Time"; public int? MaxBatchSize { get; set; } public int? MinInstancesInService { get; set; } public string? PauseTime { get; set; } public string Timeout { get; set; } = "PT30M"; } }
22
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace AspNetAppElasticBeanstalkWindows.Configurations { public partial class IAMRoleConfiguration { /// <summary> /// If set, create a new anonymously named IAM role. /// </summary> public bool CreateNew { get; set; } /// <summary> /// If <see cref="CreateNew"/> is false, /// then use an existing IAM role by referencing through <see cref="RoleArn"/> /// </summary> public string? RoleArn { get; set; } } }
26
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AspNetAppElasticBeanstalkWindows.Configurations { public partial class VPCConfiguration { /// <summary> /// If set, the deployment will use a VPC to connect to the Elastic Beanstalk service. /// </summary> public bool UseVPC { get; set; } /// <summary> /// Creates a new VPC if set to true. /// </summary> public bool CreateNew { get; set; } /// <summary> /// The VPC ID to use for the Elastic Beanstalk service. /// </summary> public string? VpcId { get; set; } /// <summary> /// A list of IDs of subnets that Elastic Beanstalk should use when it associates your environment with a custom Amazon VPC. /// Specify IDs of subnets of a single Amazon VPC. /// </summary> public SortedSet<string> Subnets { get; set; } = new SortedSet<string>(); /// <summary> /// Lists the Amazon EC2 security groups to assign to the EC2 instances in the Auto Scaling group to define firewall rules for the instances. /// </summary> public SortedSet<string> SecurityGroups { get; set; } = new SortedSet<string>(); } }
39
aws-dotnet-deploy
aws
C#
using System; using System.IO; using System.Collections.Generic; using Amazon.CDK; using Amazon.CDK.AWS.CloudFront; using AWS.Deploy.Recipes.CDK.Common; using BlazorWasm.Configurations; using Constructs; namespace BlazorWasm { public class AppStack : Stack { private readonly Configuration _configuration; internal AppStack(Construct scope, IDeployToolStackProps<Configuration> props) : base(scope, props.StackName, props) { _configuration = props.RecipeProps.Settings; // Setup callback for generated construct to provide access to customize CDK properties before creating constructs. CDKRecipeCustomizer<Recipe>.CustomizeCDKProps += CustomizeCDKProps; // Create custom CDK constructs here that might need to be referenced in the CustomizeCDKProps. For example if // creating a DynamoDB table construct and then later using the CDK construct reference in CustomizeCDKProps to // pass the table name as an environment variable to the container image. // Create the recipe defined CDK construct with all of its sub constructs. var generatedRecipe = new Recipe(this, props.RecipeProps); // Create additional CDK constructs here. The recipe's constructs can be accessed as properties on // the generatedRecipe variable. } /// <summary> /// This method can be used to customize the properties for CDK constructs before creating the constructs. /// /// The pattern used in this method is to check to evnt.ResourceLogicalName to see if the CDK construct about to be created is one /// you want to customize. If so cast the evnt.Props object to the CDK properties object and make the appropriate settings. /// </summary> /// <param name="evnt"></param> private void CustomizeCDKProps(CustomizePropsEventArgs<Recipe> evnt) { // Example of how to customize the container image definition to include environment variables to the running applications. // //if (string.Equals(evnt.ResourceLogicalName, nameof(evnt.Construct.CloudFrontDistribution))) //{ // if (evnt.Props is DistributionProps props) // { // Console.WriteLine("Customizing CloudFront Distribution"); // } //} } } }
58
aws-dotnet-deploy
aws
C#
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Potential Code Quality Issues", "RECS0026:Possible unassigned object created by 'new'", Justification = "Constructs add themselves to the scope in which they are created")]
2
aws-dotnet-deploy
aws
C#
using Amazon.CDK; using AWS.Deploy.Recipes.CDK.Common; using BlazorWasm.Configurations; using Microsoft.Extensions.Configuration; namespace BlazorWasm { sealed class Program { public static void Main(string[] args) { var app = new App(); var builder = new ConfigurationBuilder().AddAWSDeployToolConfiguration(app); var recipeProps = builder.Build().Get<RecipeProps<Configuration>>(); var appStackProps = new DeployToolStackProps<Configuration>(recipeProps) { Env = new Environment { Account = recipeProps.AWSAccountId, Region = recipeProps.AWSRegion } }; // The RegisterStack method is used to set identifying information on the stack // for the recipe used to deploy the application and preserve the settings used in the recipe // to allow redeployment. The information is stored as CloudFormation tags and metadata inside // the generated CloudFormation template. CDKRecipeSetup.RegisterStack<Configuration>(new AppStack(app, appStackProps), appStackProps.RecipeProps); app.Synth(); } } }
35
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 namespace BlazorWasm.Configurations { /// <summary> /// The configuration settings that are passed in from the deploy tool to the CDK project. If /// custom settings are defined in the recipe definition then corresponding properties should be added here. /// /// This is a partial class with all of the settings defined by default in the recipe declared in the /// Generated directory's version of this file. /// </summary> public partial class Configuration { } }
18
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Amazon.CDK; using Amazon.CDK.AWS.CloudFront; using Amazon.CDK.AWS.CloudFront.Origins; using Amazon.CDK.AWS.S3; using Amazon.CDK.AWS.S3.Deployment; using AWS.Deploy.Recipes.CDK.Common; using BlazorWasm.Configurations; using Constructs; // This is a generated file from the original deployment recipe. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // To customize the CDK constructs created in this file you should use the AppStack.CustomizeCDKProps() method. namespace BlazorWasm { using static AWS.Deploy.Recipes.CDK.Common.CDKRecipeCustomizer<Recipe>; public class Recipe : Construct { public Bucket? ContentS3Bucket { get; private set; } public BucketDeployment? ContentS3Deployment { get; private set; } public Distribution? CloudFrontDistribution { get; private set; } public string AccessLoggingBucket { get; } = "AccessLoggingBucket"; public string BackendRestApiHttpOrigin { get; } = "BackendRestApiHttpOrigin"; public string BackendRestApiCacheBehavior { get; } = "BackendRestApiCacheBehavior"; public Recipe(Construct scope, IRecipeProps<Configuration> props) // The "Recipe" construct ID will be used as part of the CloudFormation logical ID. If the value is changed this will // change the expected values for the "DisplayedResources" in the corresponding recipe file. : base(scope, "Recipe") { ConfigureS3ContentBucket(); ConfigureCloudFrontDistribution(props.Settings); ConfigureS3Deployment(props); } private void ConfigureS3ContentBucket() { var bucketProps = new BucketProps { // Turn on delete objects so deployed Blazor application is deleted when the stack is deleted. AutoDeleteObjects = true, RemovalPolicy = RemovalPolicy.DESTROY }; ContentS3Bucket = new Bucket(this, nameof(ContentS3Bucket), InvokeCustomizeCDKPropsEvent(nameof(ContentS3Bucket), this, bucketProps)); new CfnOutput(this, "S3ContentBucket", new CfnOutputProps { Description = "S3 bucket where Blazor application is uploaded to", Value = ContentS3Bucket.BucketName }); } private void ConfigureCloudFrontDistribution(Configuration settings) { if (ContentS3Bucket == null) throw new InvalidOperationException($"{nameof(ContentS3Bucket)} has not been set. The {nameof(ConfigureS3ContentBucket)} method should be called before {nameof(ConfigureCloudFrontDistribution)}"); var distributionProps = new DistributionProps { DefaultBehavior = new BehaviorOptions { Origin = new S3Origin(ContentS3Bucket, new S3OriginProps()) }, DefaultRootObject = settings.IndexDocument, EnableIpv6 = settings.EnableIpv6, HttpVersion = settings.MaxHttpVersion, PriceClass = settings.PriceClass }; var errorResponses = new List<ErrorResponse>(); if (!string.IsNullOrEmpty(settings.ErrorDocument)) { errorResponses.Add( new ErrorResponse { ResponsePagePath = settings.ErrorDocument } ); } if (settings.Redirect404ToRoot) { errorResponses.Add( new ErrorResponse { HttpStatus = 404, ResponseHttpStatus = 200, ResponsePagePath = "/" } ); // Since S3 returns back an access denied for objects that don't exist to CloudFront treat 403 as 404 not found. errorResponses.Add( new ErrorResponse { HttpStatus = 403, ResponseHttpStatus = 200, ResponsePagePath = "/" } ); } if (errorResponses.Any()) { distributionProps.ErrorResponses = errorResponses.ToArray(); } if(settings.AccessLogging?.Enable == true) { distributionProps.EnableLogging = true; if(settings.AccessLogging.CreateLoggingS3Bucket) { var loggingBucket = new Bucket(this, nameof(AccessLoggingBucket), InvokeCustomizeCDKPropsEvent(nameof(AccessLoggingBucket), this, new BucketProps { RemovalPolicy = RemovalPolicy.RETAIN, })); distributionProps.LogBucket = loggingBucket; new CfnOutput(this, "S3AccessLoggingBucket", new CfnOutputProps { Description = "S3 bucket storing access logs. Bucket and logs will be retained after deployment is deleted.", Value = distributionProps.LogBucket.BucketName }); } else if(!string.IsNullOrEmpty(settings.AccessLogging.ExistingS3LoggingBucket)) { distributionProps.LogBucket = Bucket.FromBucketName(this, nameof(AccessLoggingBucket), settings.AccessLogging.ExistingS3LoggingBucket); } if(!string.IsNullOrEmpty(settings.AccessLogging.LoggingS3KeyPrefix)) { distributionProps.LogFilePrefix = settings.AccessLogging.LoggingS3KeyPrefix; } distributionProps.LogIncludesCookies = settings.AccessLogging.LogIncludesCookies; } if(!string.IsNullOrEmpty(settings.WebAclId)) { distributionProps.WebAclId = settings.WebAclId; } CloudFrontDistribution = new Distribution(this, nameof(CloudFrontDistribution), InvokeCustomizeCDKPropsEvent(nameof(CloudFrontDistribution), this, distributionProps)); if (settings.BackendApi?.Enable == true) { var backendApiUri = new Uri(settings.BackendApi.Uri); var httpOriginProps = new HttpOriginProps { OriginPath = backendApiUri.PathAndQuery }; if (string.Equals("https", backendApiUri.Scheme, StringComparison.OrdinalIgnoreCase)) { httpOriginProps.ProtocolPolicy = OriginProtocolPolicy.HTTPS_ONLY; httpOriginProps.HttpsPort = backendApiUri.Port; } else { httpOriginProps.ProtocolPolicy = OriginProtocolPolicy.HTTP_ONLY; httpOriginProps.HttpPort = backendApiUri.Port; } var httpOrigin = new HttpOrigin(backendApiUri.Host, InvokeCustomizeCDKPropsEvent(nameof(BackendRestApiHttpOrigin), this, httpOriginProps)); // Since this is a backend API where the business logic for the Blazor app caching must be disabled. var addBehavorOptions = new AddBehaviorOptions { AllowedMethods = AllowedMethods.ALLOW_ALL, CachePolicy = CachePolicy.CACHING_DISABLED }; CloudFrontDistribution.AddBehavior(settings.BackendApi.ResourcePathPattern, httpOrigin, InvokeCustomizeCDKPropsEvent(nameof(BackendRestApiCacheBehavior), this, addBehavorOptions)); } new CfnOutput(this, "EndpointURL", new CfnOutputProps { Description = "Endpoint to access application", Value = $"https://{CloudFrontDistribution.DomainName}/" }); } private void ConfigureS3Deployment(IRecipeProps<Configuration> props) { if (ContentS3Bucket == null) throw new InvalidOperationException($"{nameof(ContentS3Bucket)} has not been set. The {nameof(ConfigureS3ContentBucket)} method should be called before {nameof(ContentS3Bucket)}"); if (string.IsNullOrEmpty(props.DotnetPublishOutputDirectory)) throw new InvalidOrMissingConfigurationException("The provided path containing the dotnet publish output is null or empty."); var bucketDeploymentProps = new BucketDeploymentProps { Sources = new ISource[] { Source.Asset(Path.Combine(props.DotnetPublishOutputDirectory, "wwwroot")) }, DestinationBucket = ContentS3Bucket, MemoryLimit = 3008, Distribution = CloudFrontDistribution, DistributionPaths = new string[] { "/*" } }; ContentS3Deployment = new BucketDeployment(this, nameof(ContentS3Deployment), InvokeCustomizeCDKPropsEvent(nameof(ContentS3Deployment), this, bucketDeploymentProps)); } } }
227
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; // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace BlazorWasm.Configurations { /// <summary> /// Configure if and how access logs are written for the CloudFront distribution. /// </summary> public partial class AccessLoggingConfiguration { /// <summary> /// Enable CloudFront Access Logging. /// </summary> public bool Enable { get; set; } = false; /// <summary> /// Include cookies in access logs. /// </summary> public bool LogIncludesCookies { get; set; } = false; /// <summary> /// Create new S3 bucket for access logs to be stored. /// </summary> public bool CreateLoggingS3Bucket { get; set; } = true; /// <summary> /// S3 bucket to use for storing access logs. /// </summary> public string? ExistingS3LoggingBucket { get; set; } /// <summary> /// Optional S3 key prefix to store access logs (e.g. app-name/). /// </summary> public string? LoggingS3KeyPrefix { get; set; } } }
47
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.Text; // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace BlazorWasm.Configurations { public partial class BackendRestApiConfiguration { /// <summary> /// Enable Backend rest api /// </summary> public bool Enable { get; set; } /// <summary> /// Uri to the backend rest api /// </summary> public string Uri { get; set; } /// <summary> /// The resource path pattern to determine which request to go to backend rest api. (i.e. "/api/*") /// </summary> public string ResourcePathPattern { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public BackendRestApiConfiguration() { } #nullable restore warnings public BackendRestApiConfiguration( string uri, string resourcePathPattern ) { Uri = uri; ResourcePathPattern = resourcePathPattern; } } }
50
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace BlazorWasm.Configurations { public partial class Configuration { /// <summary> /// The default page to use when endpoint accessed with no resource path. /// </summary> public string IndexDocument { get; set; } /// <summary> /// The error page to use when an error occurred accessing the resource path. /// </summary> public string? ErrorDocument { get; set; } /// <summary> /// Redirect any 404 and 403 requests to the index document. This is useful in Blazor applications that modify the resource path in the browser. /// If the modified resource path is reused in a new browser it will result in a 403 from Amazon CloudFront since no S3 object /// exists at that resource path. /// </summary> public bool Redirect404ToRoot { get; set; } = true; /// <summary> /// Configure if and how access logs are written for the CloudFront distribution. /// </summary> public AccessLoggingConfiguration? AccessLogging { get; set; } /// <summary> /// Configure the edge locations that will respond to request for the CloudFront distribution /// </summary> public Amazon.CDK.AWS.CloudFront.PriceClass PriceClass { get; set; } = Amazon.CDK.AWS.CloudFront.PriceClass.PRICE_CLASS_ALL; /// <summary> /// The AWS WAF (web application firewall) ACL arn /// </summary> public string? WebAclId { get; set; } /// <summary> /// Control if IPv6 should be enabled for the CloudFront distribution /// </summary> public bool EnableIpv6 { get; set; } = true; /// <summary> /// The maximum http version that users can use to communicate with the CloudFront distribution /// </summary> public Amazon.CDK.AWS.CloudFront.HttpVersion MaxHttpVersion { get; set; } = Amazon.CDK.AWS.CloudFront.HttpVersion.HTTP2; /// <summary> /// The backend rest api to be added as a origin to the CloudFront distribution /// </summary> public BackendRestApiConfiguration? BackendApi { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public Configuration() { } #nullable restore warnings public Configuration( string indexDocument ) { IndexDocument = indexDocument; } } }
79
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.CDK; using Amazon.CDK.AWS.EC2; using Amazon.CDK.AWS.ECS; using Amazon.CDK.AWS.ECR; using Amazon.CDK.AWS.ECS.Patterns; using Amazon.CDK.AWS.IAM; using AWS.Deploy.Recipes.CDK.Common; using System.IO; using System.Collections.Generic; using ConsoleAppECSFargateScheduleTask.Configurations; using Protocol = Amazon.CDK.AWS.ECS.Protocol; using Schedule = Amazon.CDK.AWS.ApplicationAutoScaling.Schedule; using Constructs; namespace ConsoleAppECSFargateScheduleTask { public class AppStack : Stack { private readonly Configuration _configuration; internal AppStack(Construct scope, IDeployToolStackProps<Configuration> props) : base(scope, props.StackName, props) { _configuration = props.RecipeProps.Settings; // Setup callback for generated construct to provide access to customize CDK properties before creating constructs. CDKRecipeCustomizer<Recipe>.CustomizeCDKProps += CustomizeCDKProps; // Create custom CDK constructs here that might need to be referenced in the CustomizeCDKProps. For example if // creating a DynamoDB table construct and then later using the CDK construct reference in CustomizeCDKProps to // pass the table name as an environment variable to the container image. // Create the recipe defined CDK construct with all of its sub constructs. var generatedRecipe = new Recipe(this, props.RecipeProps); // Create additional CDK constructs here. The recipe's constructs can be accessed as properties on // the generatedRecipe variable. } /// <summary> /// This method can be used to customize the properties for CDK constructs before creating the constructs. /// /// The pattern used in this method is to check to evnt.ResourceLogicalName to see if the CDK construct about to be created is one /// you want to customize. If so cast the evnt.Props object to the CDK properties object and make the appropriate settings. /// </summary> /// <param name="evnt"></param> private void CustomizeCDKProps(CustomizePropsEventArgs<Recipe> evnt) { // Example of how to customize the container image definition to include environment variables to the running applications. // //if (string.Equals(evnt.ResourceLogicalName, nameof(evnt.Construct.AppContainerDefinition))) //{ // if(evnt.Props is ContainerDefinitionOptions props) // { // Console.WriteLine("Customizing AppContainerDefinition"); // if (props.Environment == null) // props.Environment = new Dictionary<string, string>(); // props.Environment["EXAMPLE_ENV1"] = "EXAMPLE_VALUE1"; // } //} } } }
68
aws-dotnet-deploy
aws
C#
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Potential Code Quality Issues", "RECS0026:Possible unassigned object created by 'new'", Justification = "Constructs add themselves to the scope in which they are created")]
2
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.CDK; using AWS.Deploy.Recipes.CDK.Common; using ConsoleAppECSFargateScheduleTask.Configurations; using Microsoft.Extensions.Configuration; namespace ConsoleAppECSFargateScheduleTask { sealed class Program { public static void Main(string[] args) { var app = new App(); var builder = new ConfigurationBuilder().AddAWSDeployToolConfiguration(app); var recipeProps = builder.Build().Get<RecipeProps<Configuration>>(); var appStackProps = new DeployToolStackProps<Configuration>(recipeProps) { Env = new Environment { Account = recipeProps.AWSAccountId, Region = recipeProps.AWSRegion } }; // The RegisterStack method is used to set identifying information on the stack // for the recipe used to deploy the application and preserve the settings used in the recipe // to allow redeployment. The information is stored as CloudFormation tags and metadata inside // the generated CloudFormation template. CDKRecipeSetup.RegisterStack<Configuration>(new AppStack(app, appStackProps), appStackProps.RecipeProps); app.Synth(); } } }
38
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 namespace ConsoleAppECSFargateScheduleTask.Configurations { /// <summary> /// The configuration settings that are passed in from the deploy tool to the CDK project. If /// custom settings are defined in the recipe definition then corresponding properties should be added here. /// /// This is a partial class with all of the settings defined by default in the recipe declared in the /// Generated directory's version of this file. /// </summary> public partial class Configuration { } }
18
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using Amazon.CDK; using Amazon.CDK.AWS.EC2; using Amazon.CDK.AWS.ECS; using Amazon.CDK.AWS.ECR; using Amazon.CDK.AWS.ECS.Patterns; using Amazon.CDK.AWS.IAM; using AWS.Deploy.Recipes.CDK.Common; using ConsoleAppECSFargateScheduleTask.Configurations; using Protocol = Amazon.CDK.AWS.ECS.Protocol; using Schedule = Amazon.CDK.AWS.ApplicationAutoScaling.Schedule; using Constructs; // This is a generated file from the original deployment recipe. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // To customize the CDK constructs created in this file you should use the AppStack.CustomizeCDKProps() method. namespace ConsoleAppECSFargateScheduleTask { using static AWS.Deploy.Recipes.CDK.Common.CDKRecipeCustomizer<Recipe>; public class Recipe : Construct { public IRole? AppIAMTaskRole { get; private set; } public IVpc? AppVpc { get; private set; } public ICluster? EcsCluster { get; private set; } public ContainerDefinitionOptions? AppContainerDefinition { get; private set; } public AwsLogDriver? AppLogging { get; private set; } public FargateTaskDefinition? AppTaskDefinition { get; private set; } public ScheduledFargateTask? ScheduleTask { get; private set; } public Recipe(Construct scope, IRecipeProps<Configuration> props) // The "Recipe" construct ID will be used as part of the CloudFormation logical ID. If the value is changed this will // change the expected values for the "DisplayedResources" in the corresponding recipe file. : base(scope, "Recipe") { var settings = props.Settings; ConfigureIAM(settings); ConfigureVpc(settings); ConfigureTaskDefinition(props); ConfigureCluster(settings); ConfigureScheduledTask(settings); } private void ConfigureIAM(Configuration settings) { if (settings.ApplicationIAMRole.CreateNew) { AppIAMTaskRole = new Role(this, nameof(AppIAMTaskRole), InvokeCustomizeCDKPropsEvent(nameof(AppIAMTaskRole), this, new RoleProps { AssumedBy = new ServicePrincipal("ecs-tasks.amazonaws.com") })); } else { if (string.IsNullOrEmpty(settings.ApplicationIAMRole.RoleArn)) throw new InvalidOrMissingConfigurationException("The provided Application IAM Role ARN is null or empty."); AppIAMTaskRole = Role.FromRoleArn(this, nameof(AppIAMTaskRole), settings.ApplicationIAMRole.RoleArn, new FromRoleArnOptions { Mutable = false }); } } private void ConfigureVpc(Configuration settings) { if (settings.Vpc.IsDefault) { AppVpc = Vpc.FromLookup(this, nameof(AppVpc), new VpcLookupOptions { IsDefault = true }); } else if (settings.Vpc.CreateNew) { AppVpc = new Vpc(this, nameof(AppVpc), InvokeCustomizeCDKPropsEvent(nameof(AppVpc), this, new VpcProps { MaxAzs = 2 })); } else { AppVpc = Vpc.FromLookup(this, nameof(AppVpc), new VpcLookupOptions { VpcId = settings.Vpc.VpcId }); } } private void ConfigureTaskDefinition(IRecipeProps<Configuration> props) { var settings = props.Settings; AppTaskDefinition = new FargateTaskDefinition(this, nameof(AppTaskDefinition), InvokeCustomizeCDKPropsEvent(nameof(AppTaskDefinition), this, new FargateTaskDefinitionProps { TaskRole = AppIAMTaskRole, Cpu = settings.TaskCpu, MemoryLimitMiB = settings.TaskMemory })); AppLogging = new AwsLogDriver(InvokeCustomizeCDKPropsEvent(nameof(AppLogging), this, new AwsLogDriverProps { StreamPrefix = props.StackName })); if (string.IsNullOrEmpty(props.ECRRepositoryName)) throw new InvalidOrMissingConfigurationException("The provided ECR Repository Name is null or empty."); var ecrRepository = Repository.FromRepositoryName(this, "ECRRepository", props.ECRRepositoryName); AppContainerDefinition = new ContainerDefinitionOptions { Image = ContainerImage.FromEcrRepository(ecrRepository, props.ECRImageTag), Logging = AppLogging, Environment = settings.ECSEnvironmentVariables, MemoryLimitMiB = settings.TaskMemory }; AppTaskDefinition.AddContainer(nameof(AppContainerDefinition), InvokeCustomizeCDKPropsEvent(nameof(AppContainerDefinition), this, AppContainerDefinition)); } private void ConfigureCluster(Configuration settings) { if (AppVpc == null) throw new InvalidOperationException($"{nameof(AppVpc)} has not been set. The {nameof(ConfigureVpc)} method should be called before {nameof(ConfigureCluster)}"); if (settings.ECSCluster.CreateNew) { EcsCluster = new Cluster(this, nameof(EcsCluster), InvokeCustomizeCDKPropsEvent(nameof(EcsCluster), this, new ClusterProps { Vpc = AppVpc, ClusterName = settings.ECSCluster.NewClusterName })); } else { EcsCluster = Cluster.FromClusterAttributes(this, nameof(EcsCluster), new ClusterAttributes { ClusterArn = settings.ECSCluster.ClusterArn, ClusterName = ECSFargateUtilities.GetClusterNameFromArn(settings.ECSCluster.ClusterArn), SecurityGroups = new ISecurityGroup[0], Vpc = AppVpc }); } } private void ConfigureScheduledTask(Configuration settings) { if (AppTaskDefinition == null) throw new InvalidOperationException($"{nameof(AppTaskDefinition)} has not been set. The {nameof(ConfigureTaskDefinition)} method should be called before {nameof(ConfigureScheduledTask)}"); SubnetSelection? subnetSelection = null; if (settings.Vpc.IsDefault) { subnetSelection = new SubnetSelection { SubnetType = SubnetType.PUBLIC }; } ScheduleTask = new ScheduledFargateTask(this, nameof(ScheduleTask), InvokeCustomizeCDKPropsEvent(nameof(ScheduleTask), this, new ScheduledFargateTaskProps { Cluster = EcsCluster, Schedule = Schedule.Expression(settings.Schedule), Vpc = AppVpc, ScheduledFargateTaskDefinitionOptions = new ScheduledFargateTaskDefinitionOptions { TaskDefinition = AppTaskDefinition }, SubnetSelection = subnetSelection })); } } }
189
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. using System.Collections.Generic; namespace ConsoleAppECSFargateScheduleTask.Configurations { public partial class Configuration { /// <summary> /// The Identity and Access Management Role that provides AWS credentials to the application to access AWS services. /// </summary> public IAMRoleConfiguration ApplicationIAMRole { get; set; } /// <summary> /// The schedule or rate (frequency) that determines when CloudWatch Events runs the rule. /// </summary> public string Schedule { get; set; } /// <summary> /// The ECS cluster that will host the deployed application. /// </summary> public ECSClusterConfiguration ECSCluster { get; set; } /// <summary> /// Virtual Private Cloud to launch container instance into a virtual network. /// </summary> public VpcConfiguration Vpc { get; set; } /// <inheritdoc cref="FargateTaskDefinitionProps.Cpu"/> public double? TaskCpu { get; set; } /// <inheritdoc cref="FargateTaskDefinitionProps.MemoryLimitMiB"/> public double? TaskMemory { get; set; } /// <summary> /// The environment variables that are set for the ECS environment. /// </summary> public Dictionary<string, string> ECSEnvironmentVariables { get; set; } = new Dictionary<string, string> { }; /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public Configuration() { } #nullable restore warnings public Configuration( IAMRoleConfiguration applicationIAMRole, string schedule, ECSClusterConfiguration ecsCluster, VpcConfiguration vpc, Dictionary<string, string> ecsEnvironmentVariables ) { ApplicationIAMRole = applicationIAMRole; Schedule = schedule; ECSCluster = ecsCluster; Vpc = vpc; ECSEnvironmentVariables = ecsEnvironmentVariables; } } }
73
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace ConsoleAppECSFargateScheduleTask.Configurations { public partial class ECSClusterConfiguration { /// <summary> /// Indicates whether to create a new ECS Cluster or use and existing one /// </summary> public bool CreateNew { get; set; } /// <summary> /// If <see cref="CreateNew" /> is false, /// then use an existing ECS Cluster by referencing through <see cref="ClusterArn"/> /// </summary> public string ClusterArn { get; set; } /// <summary> /// If <see cref="CreateNew" /> is true, /// then create a new ECS Cluster with the name <see cref="NewClusterName"/> /// </summary> public string NewClusterName { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public ECSClusterConfiguration() { } #nullable restore warnings public ECSClusterConfiguration( bool createNew, string clusterArn, string newClusterName) { CreateNew = createNew; ClusterArn = clusterArn; NewClusterName = newClusterName; } } }
52
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace ConsoleAppECSFargateScheduleTask.Configurations { public partial class IAMRoleConfiguration { /// <summary> /// If set, create a new anonymously named IAM role. /// </summary> public bool CreateNew { get; set; } /// <summary> /// If <see cref="CreateNew"/> is false, /// then use an existing IAM role by referencing through <see cref="RoleArn"/> /// </summary> public string? RoleArn { get; set; } } }
26
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace ConsoleAppECSFargateScheduleTask.Configurations { public partial class VpcConfiguration { /// <summary> /// If set, use default VPC /// </summary> public bool IsDefault { get; set; } /// <summary> /// If set and <see cref="CreateNew"/> is false, create a new VPC /// </summary> public bool CreateNew { get; set; } /// <summary> /// If <see cref="IsDefault" /> is false and <see cref="CreateNew" /> is false, /// then use an existing VPC by referencing through <see cref="VpcId"/> /// </summary> public string VpcId { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public VpcConfiguration() { } #nullable restore warnings public VpcConfiguration( bool isDefault, bool createNew, string vpcId) { IsDefault = isDefault; CreateNew = createNew; VpcId = vpcId; } } }
51
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using Amazon.CDK; using AWS.Deploy.Recipes.CDK.Common; using ConsoleAppEcsFargateService.Configurations; using Constructs; namespace ConsoleAppEcsFargateService { public class AppStack : Stack { private readonly Configuration _configuration; internal AppStack(Construct scope, IDeployToolStackProps<Configuration> props) : base(scope, props.StackName, props) { _configuration = props.RecipeProps.Settings; // Setup callback for generated construct to provide access to customize CDK properties before creating constructs. CDKRecipeCustomizer<Recipe>.CustomizeCDKProps += CustomizeCDKProps; // Create custom CDK constructs here that might need to be referenced in the CustomizeCDKProps. For example if // creating a DynamoDB table construct and then later using the CDK construct reference in CustomizeCDKProps to // pass the table name as an environment variable to the container image. // Create the recipe defined CDK construct with all of its sub constructs. var generatedRecipe = new Recipe(this, props.RecipeProps); // Create additional CDK constructs here. The recipe's constructs can be accessed as properties on // the generatedRecipe variable. } /// <summary> /// This method can be used to customize the properties for CDK constructs before creating the constructs. /// /// The pattern used in this method is to check to evnt.ResourceLogicalName to see if the CDK construct about to be created is one /// you want to customize. If so cast the evnt.Props object to the CDK properties object and make the appropriate settings. /// </summary> /// <param name="evnt"></param> private void CustomizeCDKProps(CustomizePropsEventArgs<Recipe> evnt) { // Example of how to customize the container image definition to include environment variables to the running applications. // //if (string.Equals(evnt.ResourceLogicalName, nameof(evnt.Construct.AppContainerDefinition))) //{ // if(evnt.Props is ContainerDefinitionOptions props) // { // Console.WriteLine("Customizing AppContainerDefinition"); // if (props.Environment == null) // props.Environment = new Dictionary<string, string>(); // props.Environment["EXAMPLE_ENV1"] = "EXAMPLE_VALUE1"; // } //} } } }
62
aws-dotnet-deploy
aws
C#
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Potential Code Quality Issues", "RECS0026:Possible unassigned object created by 'new'", Justification = "Constructs add themselves to the scope in which they are created")]
2
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.CDK; using AWS.Deploy.Recipes.CDK.Common; using ConsoleAppEcsFargateService.Configurations; using Microsoft.Extensions.Configuration; namespace ConsoleAppEcsFargateService { sealed class Program { public static void Main(string[] args) { var app = new App(); var builder = new ConfigurationBuilder().AddAWSDeployToolConfiguration(app); var recipeProps = builder.Build().Get<RecipeProps<Configuration>>(); var appStackProps = new DeployToolStackProps<Configuration>(recipeProps) { Env = new Environment { Account = recipeProps.AWSAccountId, Region = recipeProps.AWSRegion } }; // The RegisterStack method is used to set identifying information on the stack // for the recipe used to deploy the application and preserve the settings used in the recipe // to allow redeployment. The information is stored as CloudFormation tags and metadata inside // the generated CloudFormation template. CDKRecipeSetup.RegisterStack<Configuration>(new AppStack(app, appStackProps), appStackProps.RecipeProps); app.Synth(); } } }
38
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 namespace ConsoleAppEcsFargateService.Configurations { /// <summary> /// The configuration settings that are passed in from the deploy tool to the CDK project. If /// custom settings are defined in the recipe definition then corresponding properties should be added here. /// /// This is a partial class with all of the settings defined by default in the recipe declared in the /// Generated directory's version of this file. /// </summary> public partial class Configuration { } }
18
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using Amazon.CDK; using Amazon.CDK.AWS.EC2; using Amazon.CDK.AWS.ECS; using Amazon.CDK.AWS.IAM; using Amazon.CDK.AWS.ECR; using AWS.Deploy.Recipes.CDK.Common; using ConsoleAppEcsFargateService.Configurations; using Amazon.CDK.AWS.ApplicationAutoScaling; using Constructs; // This is a generated file from the original deployment recipe. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // To customize the CDK constructs created in this file you should use the AppStack.CustomizeCDKProps() method. namespace ConsoleAppEcsFargateService { using static AWS.Deploy.Recipes.CDK.Common.CDKRecipeCustomizer<Recipe>; public class Recipe : Construct { public IRole? AppIAMTaskRole { get; private set; } public IVpc? AppVpc { get; private set; } public ICluster? EcsCluster { get; private set; } public ContainerDefinitionOptions? AppContainerDefinition { get; private set; } public AwsLogDriver? AppLogging { get; private set; } public FargateTaskDefinition? AppTaskDefinition { get; private set; } public FargateService? AppFargateService { get; private set; } public ScalableTaskCount? AutoScalingConfiguration { get; private set; } public string AutoScaleTypeCpuType { get; } = "AutoScaleTypeCpuType"; public string AutoScaleTypeMemoryType { get; } = "AutoScaleTypeMemoryType"; public Recipe(Construct scope, IRecipeProps<Configuration> props) // The "Recipe" construct ID will be used as part of the CloudFormation logical ID. If the value is changed this will // change the expected values for the "DisplayedResources" in the corresponding recipe file. : base(scope, "Recipe") { var settings = props.Settings; ConfigureIAM(settings); ConfigureVpc(settings); ConfigureTaskDefinition(props); ConfigureCluster(settings); ConfigureService(settings); ConfigureAutoScaling(settings); } private void ConfigureIAM(Configuration settings) { if (settings.ApplicationIAMRole.CreateNew) { AppIAMTaskRole = new Role(this, nameof(AppIAMTaskRole), InvokeCustomizeCDKPropsEvent(nameof(AppIAMTaskRole), this, new RoleProps { AssumedBy = new ServicePrincipal("ecs-tasks.amazonaws.com") })); } else { if (string.IsNullOrEmpty(settings.ApplicationIAMRole.RoleArn)) throw new InvalidOrMissingConfigurationException("The provided Application IAM Role ARN is null or empty."); AppIAMTaskRole = Role.FromRoleArn(this, nameof(AppIAMTaskRole), settings.ApplicationIAMRole.RoleArn, new FromRoleArnOptions { Mutable = false }); } } private void ConfigureVpc(Configuration settings) { if (settings.Vpc.IsDefault) { AppVpc = Vpc.FromLookup(this, nameof(AppVpc), new VpcLookupOptions { IsDefault = true }); } else if (settings.Vpc.CreateNew) { AppVpc = new Vpc(this, nameof(AppVpc), InvokeCustomizeCDKPropsEvent(nameof(AppVpc), this, new VpcProps { MaxAzs = 2 })); } else { AppVpc = Vpc.FromLookup(this, nameof(AppVpc), new VpcLookupOptions { VpcId = settings.Vpc.VpcId }); } } private void ConfigureTaskDefinition(IRecipeProps<Configuration> props) { var settings = props.Settings; AppTaskDefinition = new FargateTaskDefinition(this, nameof(AppTaskDefinition), InvokeCustomizeCDKPropsEvent(nameof(AppTaskDefinition), this, new FargateTaskDefinitionProps { TaskRole = AppIAMTaskRole, Cpu = settings.TaskCpu, MemoryLimitMiB = settings.TaskMemory })); AppLogging = new AwsLogDriver(InvokeCustomizeCDKPropsEvent(nameof(AppLogging), this, new AwsLogDriverProps { StreamPrefix = props.StackName })); if (string.IsNullOrEmpty(props.ECRRepositoryName)) throw new InvalidOrMissingConfigurationException("The provided ECR Repository Name is null or empty."); var ecrRepository = Repository.FromRepositoryName(this, "ECRRepository", props.ECRRepositoryName); AppContainerDefinition = new ContainerDefinitionOptions { Image = ContainerImage.FromEcrRepository(ecrRepository, props.ECRImageTag), Logging = AppLogging, Environment = settings.ECSEnvironmentVariables, MemoryLimitMiB = settings.TaskMemory }; AppTaskDefinition.AddContainer(nameof(AppContainerDefinition), InvokeCustomizeCDKPropsEvent(nameof(AppContainerDefinition), this, AppContainerDefinition)); } private void ConfigureCluster(Configuration settings) { if (AppVpc == null) throw new InvalidOperationException($"{nameof(AppVpc)} has not been set. The {nameof(ConfigureVpc)} method should be called before {nameof(ConfigureCluster)}"); if (settings.ECSCluster.CreateNew) { EcsCluster = new Cluster(this, nameof(EcsCluster), InvokeCustomizeCDKPropsEvent(nameof(EcsCluster), this, new ClusterProps { Vpc = AppVpc, ClusterName = settings.ECSCluster.NewClusterName })); } else { EcsCluster = Cluster.FromClusterAttributes(this, nameof(EcsCluster), new ClusterAttributes { ClusterArn = settings.ECSCluster.ClusterArn, ClusterName = ECSFargateUtilities.GetClusterNameFromArn(settings.ECSCluster.ClusterArn), SecurityGroups = new ISecurityGroup[0], Vpc = AppVpc }); } } private void ConfigureService(Configuration settings) { if (EcsCluster == null) throw new InvalidOperationException($"{nameof(EcsCluster)} has not been set. The {nameof(ConfigureCluster)} method should be called before {nameof(ConfigureService)}"); if (AppTaskDefinition == null) throw new InvalidOperationException($"{nameof(AppTaskDefinition)} has not been set. The {nameof(ConfigureTaskDefinition)} method should be called before {nameof(ConfigureService)}"); var fargateServiceProps = new FargateServiceProps { Cluster = EcsCluster, TaskDefinition = AppTaskDefinition, AssignPublicIp = settings.Vpc.IsDefault, DesiredCount = settings.DesiredCount }; if (!string.IsNullOrEmpty(settings.ECSServiceSecurityGroups)) { var ecsServiceSecurityGroups = new List<ISecurityGroup>(); var count = 1; foreach (var securityGroupId in settings.ECSServiceSecurityGroups.Split(',')) { ecsServiceSecurityGroups.Add(SecurityGroup.FromSecurityGroupId(this, $"AdditionalGroup-{count++}", securityGroupId.Trim(), new SecurityGroupImportOptions { Mutable = false })); } fargateServiceProps.SecurityGroups = ecsServiceSecurityGroups.ToArray(); } AppFargateService = new FargateService(this, nameof(AppFargateService), InvokeCustomizeCDKPropsEvent(nameof(AppFargateService), this, fargateServiceProps)); } private void ConfigureAutoScaling(Configuration settings) { if (AppFargateService == null) throw new InvalidOperationException($"{nameof(AppFargateService)} has not been set. The {nameof(ConfigureService)} method should be called before {nameof(ConfigureAutoScaling)}"); if (settings.AutoScaling.Enabled) { AutoScalingConfiguration = AppFargateService.AutoScaleTaskCount(InvokeCustomizeCDKPropsEvent(nameof(AutoScalingConfiguration), this, new EnableScalingProps { MinCapacity = settings.AutoScaling.MinCapacity, MaxCapacity = settings.AutoScaling.MaxCapacity })); switch (settings.AutoScaling.ScalingType) { case ConsoleAppEcsFargateService.Configurations.AutoScalingConfiguration.ScalingTypeEnum.Cpu: AutoScalingConfiguration.ScaleOnCpuUtilization(AutoScaleTypeCpuType, InvokeCustomizeCDKPropsEvent(AutoScaleTypeCpuType, this, new CpuUtilizationScalingProps { TargetUtilizationPercent = settings.AutoScaling.CpuTypeTargetUtilizationPercent, ScaleOutCooldown = Duration.Seconds(settings.AutoScaling.CpuTypeScaleOutCooldownSeconds), ScaleInCooldown = Duration.Seconds(settings.AutoScaling.CpuTypeScaleInCooldownSeconds) })); break; case ConsoleAppEcsFargateService.Configurations.AutoScalingConfiguration.ScalingTypeEnum.Memory: AutoScalingConfiguration.ScaleOnMemoryUtilization(AutoScaleTypeMemoryType, InvokeCustomizeCDKPropsEvent(AutoScaleTypeMemoryType, this, new MemoryUtilizationScalingProps { TargetUtilizationPercent = settings.AutoScaling.MemoryTypeTargetUtilizationPercent, ScaleOutCooldown = Duration.Seconds(settings.AutoScaling.MemoryTypeScaleOutCooldownSeconds), ScaleInCooldown = Duration.Seconds(settings.AutoScaling.MemoryTypeScaleInCooldownSeconds) })); break; default: throw new System.ArgumentException($"Invalid AutoScaling type {settings.AutoScaling.ScalingType}"); } } } } }
241
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; // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace ConsoleAppEcsFargateService.Configurations { public partial class AutoScalingConfiguration { const int defaultCooldown = 300; public bool Enabled { get; set; } public int MinCapacity { get; set; } = 1; public int MaxCapacity { get; set; } = 3; public enum ScalingTypeEnum { Cpu, Memory } public ScalingTypeEnum? ScalingType { get; set; } public double CpuTypeTargetUtilizationPercent { get; set; } = 70; public int CpuTypeScaleInCooldownSeconds { get; set; } = defaultCooldown; public int CpuTypeScaleOutCooldownSeconds { get; set; } = defaultCooldown; public int MemoryTypeTargetUtilizationPercent { get; set; } = 70; public int MemoryTypeScaleInCooldownSeconds { get; set; } = defaultCooldown; public int MemoryTypeScaleOutCooldownSeconds { get; set; } = defaultCooldown; /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public AutoScalingConfiguration() { } #nullable restore warnings public AutoScalingConfiguration( int minCapacity, int maxCapacity, int cpuTypeTargetUtilizationPercent, int cpuTypeScaleInCooldownSeconds, int cpuTypeScaleOutCooldownSeconds, int memoryTypeTargetUtilizationPercent, int memoryTypeScaleInCooldownSeconds, int memoryTypeScaleOutCooldownSeconds ) { MinCapacity = minCapacity; MaxCapacity = maxCapacity; CpuTypeTargetUtilizationPercent = cpuTypeTargetUtilizationPercent; CpuTypeScaleInCooldownSeconds = cpuTypeScaleInCooldownSeconds; CpuTypeScaleOutCooldownSeconds = cpuTypeScaleOutCooldownSeconds; MemoryTypeTargetUtilizationPercent = memoryTypeTargetUtilizationPercent; MemoryTypeScaleInCooldownSeconds = memoryTypeScaleInCooldownSeconds; MemoryTypeScaleOutCooldownSeconds = memoryTypeScaleOutCooldownSeconds; } } }
78
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. using System.Collections.Generic; namespace ConsoleAppEcsFargateService.Configurations { public partial class Configuration { /// <summary> /// The desired number of ECS tasks to run for the service. /// </summary> public double DesiredCount { get; set; } /// <summary> /// The Identity and Access Management Role that provides AWS credentials to the application to access AWS services. /// </summary> public IAMRoleConfiguration ApplicationIAMRole { get; set; } /// <summary> /// The ECS cluster that will host the deployed application. /// </summary> public ECSClusterConfiguration ECSCluster { get; set; } /// <summary> /// Virtual Private Cloud to launch container instance into a virtual network. /// </summary> public VpcConfiguration Vpc { get; set; } /// <summary> /// Comma-delimited list of security groups assigned to the ECS service. /// </summary> public string ECSServiceSecurityGroups { get; set; } /// <inheritdoc cref="FargateTaskDefinitionProps.Cpu"/> public double? TaskCpu { get; set; } /// <inheritdoc cref="FargateTaskDefinitionProps.MemoryLimitMiB"/> public double? TaskMemory { get; set; } public AutoScalingConfiguration AutoScaling { get; set; } /// <summary> /// The environment variables that are set for the ECS environment. /// </summary> public Dictionary<string, string> ECSEnvironmentVariables { get; set; } = new Dictionary<string, string> { }; /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public Configuration() { } #nullable restore warnings public Configuration( IAMRoleConfiguration applicationIAMRole, ECSClusterConfiguration ecsCluster, VpcConfiguration vpc, string ecsServiceSecurityGroups, AutoScalingConfiguration autoScaling, Dictionary<string, string> ecsEnvironmentVariables ) { ApplicationIAMRole = applicationIAMRole; ECSCluster = ecsCluster; Vpc = vpc; ECSServiceSecurityGroups = ecsServiceSecurityGroups; AutoScaling = autoScaling; ECSEnvironmentVariables = ecsEnvironmentVariables; } } }
82
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace ConsoleAppEcsFargateService.Configurations { public partial class ECSClusterConfiguration { /// <summary> /// Indicates whether to create a new ECS Cluster or use and existing one /// </summary> public bool CreateNew { get; set; } /// <summary> /// If <see cref="CreateNew" /> is false, /// then use an existing ECS Cluster by referencing through <see cref="ClusterArn"/> /// </summary> public string ClusterArn { get; set; } /// <summary> /// If <see cref="CreateNew" /> is true, /// then create a new ECS Cluster with the name <see cref="NewClusterName"/> /// </summary> public string NewClusterName { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public ECSClusterConfiguration() { } #nullable restore warnings public ECSClusterConfiguration( bool createNew, string clusterArn, string newClusterName) { CreateNew = createNew; ClusterArn = clusterArn; NewClusterName = newClusterName; } } }
52
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace ConsoleAppEcsFargateService.Configurations { public partial class IAMRoleConfiguration { /// <summary> /// If set, create a new anonymously named IAM role. /// </summary> public bool CreateNew { get; set; } /// <summary> /// If <see cref="CreateNew"/> is false, /// then use an existing IAM role by referencing through <see cref="RoleArn"/> /// </summary> public string? RoleArn { get; set; } } }
26
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 // This is a generated file from the original deployment recipe. It contains properties for // all of the settings defined in the recipe file. It is recommended to not modify this file in order // to allow easy updates to the file when the original recipe that this project was created from has updates. // This class is marked as a partial class. If you add new settings to the recipe file, those settings should be // added to partial versions of this class outside of the Generated folder for example in the Configuration folder. namespace ConsoleAppEcsFargateService.Configurations { public partial class VpcConfiguration { /// <summary> /// If set, use default VPC /// </summary> public bool IsDefault { get; set; } /// <summary> /// If set and <see cref="CreateNew"/> is false, create a new VPC /// </summary> public bool CreateNew { get; set; } /// <summary> /// If <see cref="IsDefault" /> is false and <see cref="CreateNew" /> is false, /// then use an existing VPC by referencing through <see cref="VpcId"/> /// </summary> public string VpcId { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public VpcConfiguration() { } #nullable restore warnings public VpcConfiguration( bool isDefault, bool createNew, string vpcId) { IsDefault = isDefault; CreateNew = createNew; VpcId = vpcId; } } }
51
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.IO; using System.Text; using Amazon.CDK; using Microsoft.Extensions.Configuration; namespace AWS.Deploy.Recipes.CDK.Common { public static class AWSDeployToolConfigurationExtensions { /// <summary> /// Add the AWS .NET deployment tool configuration as a source to the IConfigurationBuilder. /// </summary> /// <param name="builder"></param> /// <param name="app"></param> /// <returns></returns> public static IConfigurationBuilder AddAWSDeployToolConfiguration(this IConfigurationBuilder builder, App app) { builder.AddJsonFile(DetermineAWSDeployToolSettingsFile(app), false, false); return builder; } /// <summary> /// Determine the location of the JSON config file written by the AWS .NET deployment tool. /// /// Currently only the appsettings.json is used which is created by the AWS .NET deployment tool. The "args" parameter /// is passed in so in the future the file could be customized by the AWS .NET deployment tool. /// </summary> /// <param name="app"></param> /// <returns></returns> private static string DetermineAWSDeployToolSettingsFile(App app) { var settingsPath = app.Node.TryGetContext(Constants.CloudFormationIdentifier.SETTINGS_PATH_CDK_CONTEXT_PARAMETER)?.ToString(); if (string.IsNullOrEmpty(settingsPath)) { throw new InvalidAWSDeployToolSettingsException("Missing CDK context parameter specifying the AWS .NET deployment tool settings file."); } if (!File.Exists(settingsPath)) { throw new InvalidAWSDeployToolSettingsException($"AWS .NET deployment tool settings file {settingsPath} can not be found."); } return settingsPath; } } }
52
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 Constructs; namespace AWS.Deploy.Recipes.CDK.Common { public delegate void CustomizePropsDelegate<GeneratedConstruct>(CustomizePropsEventArgs<GeneratedConstruct> evnt) where GeneratedConstruct : Construct; /// <summary> /// Event object created after each CDK constructor properties object is created in the recipe's container construct. /// The CDK properties object can be further customized before the property object is passed into the CDK construct /// making the properties immutable. /// </summary> /// <typeparam name="GeneratedConstruct"></typeparam> public class CustomizePropsEventArgs<GeneratedConstruct> where GeneratedConstruct : Construct { /// <summary> /// The CDK props object about to be used to create the CDK construct /// </summary> public object Props { get; } /// <summary> /// The CDK logical name of the CDK construct about to be created. /// </summary> public string ResourceLogicalName { get; } /// <summary> /// The container construct for all of the CDK constructs that are part of the generated CDK project. /// </summary> public GeneratedConstruct Construct { get; } public CustomizePropsEventArgs(object props, string resourceLogicalName, GeneratedConstruct construct) { Props = props; ResourceLogicalName = resourceLogicalName; Construct = construct; } } public class CDKRecipeCustomizer<GeneratedConstruct> where GeneratedConstruct : Construct { /// <summary> /// Event called whenever a CDK construct property object is created. Subscribers to the event can customize /// the property object before it is passed into the CDK construct /// making the properties immutable. /// </summary> public static event CustomizePropsDelegate<GeneratedConstruct>? CustomizeCDKProps; /// <summary> /// Utility method used in recipes to trigger the CustomizeCDKProps event. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="resourceLogicalName"></param> /// <param name="construct"></param> /// <param name="props"></param> /// <returns></returns> public static T InvokeCustomizeCDKPropsEvent<T>(string resourceLogicalName, GeneratedConstruct construct, T props) where T : class { var handler = CustomizeCDKProps; handler?.Invoke(new CustomizePropsEventArgs<GeneratedConstruct>(props, resourceLogicalName, construct)); return props; } } }
71
aws-dotnet-deploy
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Text.Json; using Microsoft.Extensions.Configuration; using Amazon.CDK; using System.Text.Json.Serialization; namespace AWS.Deploy.Recipes.CDK.Common { /// <summary> /// This class contains methods for setting up a CDK stack to be managed by the AWS .NET deployment tool. /// </summary> public static class CDKRecipeSetup { /// <summary> /// Tags the stack to identify it as an AWS .NET deployment tool Clould Application. Appropriate metadata as also applied to the generated /// template to identify the recipe used as well as the last AWS .NET deployment tool settings. This is required to support the /// AWS .NET deployment tool to be able to redeploy new versions of the application to AWS. /// </summary> /// <typeparam name="C">The configuration type defined as part of the recipe that contains all of the recipe specific settings.</typeparam> /// <param name="stack"></param> /// <param name="recipeConfiguration"></param> public static void RegisterStack<C>(Stack stack, IRecipeProps<C> recipeConfiguration) { // Set the AWS .NET deployment tool tag which also identifies the recipe used. stack.Tags.SetTag(Constants.CloudFormationIdentifier.STACK_TAG, $"{recipeConfiguration.RecipeId}"); // Serializes all AWS .NET deployment tool settings. var recipeSettingsJson = JsonSerializer.Serialize( recipeConfiguration.Settings, new JsonSerializerOptions { WriteIndented = false, Converters = { new JsonStringEnumConverter() } }); Dictionary<string, object> metadata; if(stack.TemplateOptions.Metadata?.Count > 0) { metadata = new Dictionary<string, object>(stack.TemplateOptions.Metadata); } else { metadata = new Dictionary<string, object>(); } // Save the settings, recipe id and version as metadata to the CloudFormation template. metadata[Constants.CloudFormationIdentifier.STACK_METADATA_SETTINGS] = recipeSettingsJson; metadata[Constants.CloudFormationIdentifier.STACK_METADATA_RECIPE_ID] = recipeConfiguration.RecipeId; metadata[Constants.CloudFormationIdentifier.STACK_METADATA_RECIPE_VERSION] = recipeConfiguration.RecipeVersion; // Save the deployment bundle settings. if (!string.IsNullOrEmpty(recipeConfiguration.DeploymentBundleSettings)) { metadata[Constants.CloudFormationIdentifier.STACK_METADATA_DEPLOYMENT_BUNDLE_SETTINGS] = recipeConfiguration.DeploymentBundleSettings; } // For the CDK to pick up the changes to the metadata .NET Dictionary you have to reassign the Metadata property. stack.TemplateOptions.Metadata = metadata; // CloudFormation tags are propagated to resources created by the stack. In case of Beanstalk deployment a second CloudFormation stack is // launched which will also have the AWS .NET deployment tool tag. To differentiate these additional stacks a special AWS .NET deployment tool prefix // is added to the description. if (string.IsNullOrEmpty(stack.TemplateOptions.Description)) { stack.TemplateOptions.Description = Constants.CloudFormationIdentifier.STACK_DESCRIPTION_PREFIX; } else { stack.TemplateOptions.Description = $"{Constants.CloudFormationIdentifier.STACK_DESCRIPTION_PREFIX}: {stack.TemplateOptions.Description}"; } } } }
77
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.Recipes.CDK.Common { /// <summary> /// Properties to be passed into a CDK stack used by the deploy tool. This object contains all of the configuration properties specified by the /// deploy tool recipe. /// </summary> /// <typeparam name="T"></typeparam> public interface IDeployToolStackProps<T> : Amazon.CDK.IStackProps { /// <summary> /// The user specified settings that are defined as part of the deploy tool recipe. /// </summary> IRecipeProps<T> RecipeProps { get; set; } } /// <summary> /// Properties to be passed into a CDK stack used by the deploy tool. This object contains all of the configuration properties specified by the /// deploy tool recipe. /// </summary> /// <typeparam name="T"></typeparam> public class DeployToolStackProps<T> : Amazon.CDK.StackProps, IDeployToolStackProps<T> { public IRecipeProps<T> RecipeProps { get; set; } public DeployToolStackProps(IRecipeProps<T> props) { RecipeProps = props; StackName = props.StackName; } } }
39
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 namespace AWS.Deploy.Recipes.CDK.Common { public static class ECSFargateUtilities { public static string GetClusterNameFromArn(string clusterArn) { if (string.IsNullOrEmpty(clusterArn)) return string.Empty; var arnSplit = clusterArn.Split("/"); if (arnSplit.Length == 2) return arnSplit[1]; return string.Empty; } } }
21
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Text; namespace AWS.Deploy.Recipes.CDK.Common { public class InvalidAWSDeployToolSettingsException : Exception { public InvalidAWSDeployToolSettingsException(string message) : base(message) { } } /// <summary> /// The exception is thrown if an invalid configuration setting is passed to the CDK template project. /// </summary> public class InvalidOrMissingConfigurationException : Exception { public InvalidOrMissingConfigurationException(string message) : base(message) { } } }
27
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System.Text.Json.Serialization; namespace AWS.Deploy.Recipes.CDK.Common { /// <summary> /// A representation of the settings transferred from the AWS .NET deployment tool to the CDK project. /// </summary> /// <typeparam name="T"></typeparam> public interface IRecipeProps<T> { /// <summary> /// The name of the CloudFormation stack /// </summary> string StackName { get; set; } /// <summary> /// The path to the .NET project to deploy to AWS. /// </summary> string ProjectPath { get; set; } /// <summary> /// The ECR Repository Name where the docker image will be pushed to. /// </summary> string? ECRRepositoryName { get; set; } /// <summary> /// The ECR Image Tag of the docker image. /// </summary> string? ECRImageTag { get; set; } /// <summary> /// The path of the zip file containing the assemblies produced by the dotnet publish command. /// </summary> string? DotnetPublishZipPath { get; set; } /// <summary> /// The directory containing the assemblies produced by the dotnet publish command. /// </summary> string? DotnetPublishOutputDirectory { get; set; } /// <summary> /// The ID of the recipe being used to deploy the application. /// </summary> string RecipeId { get; set; } /// <summary> /// The version of the recipe being used to deploy the application. /// </summary> string RecipeVersion { get; set; } /// <summary> /// The configured settings made by the frontend. These are recipe specific and defined in the recipe's definition. /// </summary> T Settings { get; set; } /// <summary> /// These option settings are part of the deployment bundle definition /// </summary> string? DeploymentBundleSettings { get; set; } /// <summary> /// The Region used during deployment. /// </summary> string? AWSRegion { get; set; } /// <summary> /// The account ID used during deployment. /// </summary> string? AWSAccountId { get; set; } } /// <summary> /// A representation of the settings transferred from the AWS .NET deployment tool to the CDK project. /// </summary> /// <typeparam name="T"></typeparam> public class RecipeProps<T> : IRecipeProps<T> { /// <summary> /// The name of the CloudFormation stack /// </summary> public string StackName { get; set; } /// <summary> /// The path to the .NET project to deploy to AWS. /// </summary> public string ProjectPath { get; set; } /// <summary> /// The ECR Repository Name where the docker image will be pushed to. /// </summary> public string? ECRRepositoryName { get; set; } /// <summary> /// The ECR Image Tag of the docker image. /// </summary> public string? ECRImageTag { get; set; } /// <summary> /// The path of the zip file containing the assemblies produced by the dotnet publish command. /// </summary> public string? DotnetPublishZipPath { get; set; } /// <summary> /// The directory containing the assemblies produced by the dotnet publish command. /// </summary> public string? DotnetPublishOutputDirectory { get; set; } /// <summary> /// The ID of the recipe being used to deploy the application. /// </summary> public string RecipeId { get; set; } /// <summary> /// The version of the recipe being used to deploy the application. /// </summary> public string RecipeVersion { get; set; } /// <summary> /// The configured settings made by the frontend. These are recipe specific and defined in the recipe's definition. /// </summary> public T Settings { get; set; } /// <summary> /// These option settings are part of the deployment bundle definition /// </summary> public string? DeploymentBundleSettings { get; set; } /// <summary> /// The Region used during deployment. /// </summary> public string? AWSRegion { get; set; } /// <summary> /// The account ID used during deployment. /// </summary> public string? AWSAccountId { get; set; } /// A parameterless constructor is needed for <see cref="Microsoft.Extensions.Configuration.ConfigurationBuilder"/> /// or the classes will fail to initialize. /// The warnings are disabled since a parameterless constructor will allow non-nullable properties to be initialized with null values. #nullable disable warnings public RecipeProps() { } #nullable restore warnings public RecipeProps(string stackName, string projectPath, string recipeId, string recipeVersion, string? awsAccountId, string? awsRegion, T settings) { StackName = stackName; ProjectPath = projectPath; RecipeId = recipeId; RecipeVersion = recipeVersion; AWSAccountId = awsAccountId; AWSRegion = awsRegion; Settings = settings; } } }
164
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System.Diagnostics; namespace AWS.Deploy.ServerMode.Client { /// <summary> /// This file provides a place to add annotations to partial classes that are auto-generated in RestAPI.cs. /// The annotations are intended for use by clients like the AWS Toolkit. /// </summary> [DebuggerDisplay(value: "{DeploymentType}: {RecipeId} | {Name}")] public partial class ExistingDeploymentSummary { } [DebuggerDisplay(value: "Recipe: {RecipeId}, Base: ({BaseRecipeId})")] public partial class RecommendationSummary { } }
23
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; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using AWS.Deploy.ServerMode.Client.Utilities; namespace AWS.Deploy.ServerMode.Client { public class CommandLineWrapper { private readonly bool _diagnosticLoggingEnabled; public CommandLineWrapper(bool diagnosticLoggingEnabled) { _diagnosticLoggingEnabled = diagnosticLoggingEnabled; } public virtual async Task<RunResult> Run(string command, params string[] stdIn) { var arguments = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"/c {command}" : $"-c \"{command}\""; var strOutput = new CappedStringBuilder(100); var strError = new CappedStringBuilder(50); var processStartInfo = new ProcessStartInfo { FileName = GetSystemShell(), Arguments = arguments, UseShellExecute = false, // UseShellExecute must be false in allow redirection of StdIn. RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = !_diagnosticLoggingEnabled, // It allows displaying stdout and stderr on the screen. }; var process = Process.Start(processStartInfo); if (process == null) { throw new InvalidOperationException(); } try { foreach (var line in stdIn) { await process.StandardInput.WriteLineAsync(line).ConfigureAwait(false); } } catch (Exception ex) { process.Kill(); return await Task.FromResult(new RunResult { ExitCode = -1, StandardError = ex.Message }).ConfigureAwait(false); } process.OutputDataReceived += (sender, e) => { strOutput.AppendLine(e.Data); }; process.ErrorDataReceived += (sender, e) => { strError.AppendLine(e.Data); }; process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(-1); var result = new RunResult { ExitCode = process.ExitCode, StandardError = strError.ToString(), StandardOut = strOutput.GetLastLines(5), }; return await Task.FromResult(result).ConfigureAwait(false); } private string GetSystemShell() { if (TryGetEnvironmentVariable("COMSPEC", out var comspec)) { return comspec!; } if (TryGetEnvironmentVariable("SHELL", out var shell)) { return shell!; } // fallback to defaults return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "cmd.exe" : "/bin/sh"; } private bool TryGetEnvironmentVariable(string variable, out string? value) { value = Environment.GetEnvironmentVariable(variable); return !string.IsNullOrEmpty(value); } } public class RunResult { /// <summary> /// Indicates if this command was run successfully. This checks that /// <see cref="StandardError"/> is empty. /// </summary> public bool Success => string.IsNullOrWhiteSpace(StandardError); /// <summary> /// Fully read <see cref="Process.StandardOutput"/> /// </summary> public string StandardOut { get; set; } = string.Empty; /// <summary> /// Fully read <see cref="Process.StandardError"/> /// </summary> public string StandardError { get; set; } = string.Empty; /// <summary> /// Fully read <see cref="Process.ExitCode"/> /// </summary> public int ExitCode { get; set; } } }
137
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 Microsoft.AspNetCore.SignalR.Client; using Microsoft.Extensions.Logging; namespace AWS.Deploy.ServerMode.Client { public interface IDeploymentCommunicationClient : IDisposable { Action<string>? ReceiveLogDebugMessage { get; set; } Action<string>? ReceiveLogErrorMessage { get; set; } Action<string>? ReceiveLogInfoMessage { get; set; } Action<string, string>? ReceiveLogSectionStart { get; set; } Task JoinSession(string sessionId); } public class DeploymentCommunicationClient : IDeploymentCommunicationClient { private bool _disposedValue; private bool _initialized = false; private readonly HubConnection _connection; public Action<string>? ReceiveLogDebugMessage { get; set; } public Action<string>? ReceiveLogErrorMessage { get; set; } public Action<string>? ReceiveLogInfoMessage { get; set; } public Action<string, string>? ReceiveLogSectionStart { get; set; } public DeploymentCommunicationClient(string baseUrl) { _connection = new HubConnectionBuilder() .WithUrl(new Uri(new Uri(baseUrl), "DeploymentCommunicationHub")) .WithAutomaticReconnect() .Build(); _connection.On<string>("OnLogDebugMessage", (message) => { ReceiveLogDebugMessage?.Invoke(message); }); _connection.On<string>("OnLogErrorMessage", (message) => { ReceiveLogErrorMessage?.Invoke(message); }); _connection.On<string>("OnLogInfoMessage", (message) => { ReceiveLogInfoMessage?.Invoke(message); }); _connection.On<string, string>("OnLogSectionStart", (message, description) => { ReceiveLogSectionStart?.Invoke(message, description); }); } public async Task JoinSession(string sessionId) { if(!_initialized) { _initialized = true; await _connection.StartAsync(); } await _connection.SendAsync("JoinSession", sessionId); } protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { _connection.DisposeAsync().GetAwaiter().GetResult(); } _disposedValue = true; } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } }
97
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; namespace AWS.Deploy.ServerMode.Client { /// <summary> /// Exception is thrown when deployment tool server failed to start for an unknown reason. /// </summary> public class InternalServerModeException : Exception { public InternalServerModeException(string message) : base(message) { } } /// <summary> /// Exception is thrown when deployment tool server failed to start due to unavailability of free ports. /// </summary> public class PortUnavailableException : Exception { public PortUnavailableException(string message) : base(message) { } } /// <summary> /// Exception is thrown when there is a mismatch between the deploy tool and the server mode client library certificate author. /// </summary> public class InvalidAssemblyReferenceException : Exception { public InvalidAssemblyReferenceException(string message) : base(message) { } } }
38
aws-dotnet-deploy
aws
C#
//---------------------- // <auto-generated> // Generated using the NSwag toolchain v13.10.9.0 (NJsonSchema v10.4.1.0 (Newtonsoft.Json v13.0.0.0)) (http://NSwag.org) // </auto-generated> //---------------------- #pragma warning disable 108 // Disable "CS0108 '{derivedDto}.ToJson()' hides inherited member '{dtoBase}.ToJson()'. Use the new keyword if hiding was intended." #pragma warning disable 114 // Disable "CS0114 '{derivedDto}.RaisePropertyChanged(String)' hides inherited member 'dtoBase.RaisePropertyChanged(String)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." #pragma warning disable 472 // Disable "CS0472 The result of the expression is always 'false' since a value of type 'Int32' is never equal to 'null' of type 'Int32?' #pragma warning disable 1573 // Disable "CS1573 Parameter '...' has no matching param tag in the XML comment for ... #pragma warning disable 1591 // Disable "CS1591 Missing XML comment for publicly visible type or member ..." #pragma warning disable 8073 // Disable "CS8073 The result of the expression is always 'false' since a value of type 'T' is never equal to 'null' of type 'T?'" namespace AWS.Deploy.ServerMode.Client { using System = global::System; [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.10.9.0 (NJsonSchema v10.4.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial interface IRestAPIClient { /// <summary>Start a deployment session. A session id will be generated. This session id needs to be passed in future API calls to configure and execute deployment.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<StartDeploymentSessionOutput> StartDeploymentSessionAsync(StartDeploymentSessionInput body); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Start a deployment session. A session id will be generated. This session id needs to be passed in future API calls to configure and execute deployment.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<StartDeploymentSessionOutput> StartDeploymentSessionAsync(StartDeploymentSessionInput body, System.Threading.CancellationToken cancellationToken); /// <summary>Closes the deployment session. This removes any session state for the session id.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task CloseDeploymentSessionAsync(string sessionId); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Closes the deployment session. This removes any session state for the session id.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task CloseDeploymentSessionAsync(string sessionId, System.Threading.CancellationToken cancellationToken); /// <summary>Set the target recipe and name for the deployment.</summary> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task SetDeploymentTargetAsync(string sessionId, SetDeploymentTargetInput body); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Set the target recipe and name for the deployment.</summary> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task SetDeploymentTargetAsync(string sessionId, SetDeploymentTargetInput body, System.Threading.CancellationToken cancellationToken); /// <summary>Gets the list of compatible deployments for the session's project. The list is ordered with the first recommendation in the list being the most compatible recommendation.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetRecommendationsOutput> GetRecommendationsAsync(string sessionId); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets the list of compatible deployments for the session's project. The list is ordered with the first recommendation in the list being the most compatible recommendation.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetRecommendationsOutput> GetRecommendationsAsync(string sessionId, System.Threading.CancellationToken cancellationToken); /// <summary>Gets the list of updatable option setting items for the selected recommendation.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetOptionSettingsOutput> GetConfigSettingsAsync(string sessionId); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets the list of updatable option setting items for the selected recommendation.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetOptionSettingsOutput> GetConfigSettingsAsync(string sessionId, System.Threading.CancellationToken cancellationToken); /// <summary>Applies a value for a list of option setting items on the selected recommendation. /// Option setting updates are provided as Key Value pairs with the Key being the JSON path to the leaf node. /// Only primitive data types are supported for Value updates. The Value is a string value which will be parsed as its corresponding data type.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<ApplyConfigSettingsOutput> ApplyConfigSettingsAsync(string sessionId, ApplyConfigSettingsInput body); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Applies a value for a list of option setting items on the selected recommendation. /// Option setting updates are provided as Key Value pairs with the Key being the JSON path to the leaf node. /// Only primitive data types are supported for Value updates. The Value is a string value which will be parsed as its corresponding data type.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<ApplyConfigSettingsOutput> ApplyConfigSettingsAsync(string sessionId, ApplyConfigSettingsInput body, System.Threading.CancellationToken cancellationToken); /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetConfigSettingResourcesOutput> GetConfigSettingResourcesAsync(string sessionId, string configSettingId); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetConfigSettingResourcesOutput> GetConfigSettingResourcesAsync(string sessionId, string configSettingId, System.Threading.CancellationToken cancellationToken); /// <summary>Gets the list of existing deployments that are compatible with the session's project.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetExistingDeploymentsOutput> GetExistingDeploymentsAsync(string sessionId); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets the list of existing deployments that are compatible with the session's project.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetExistingDeploymentsOutput> GetExistingDeploymentsAsync(string sessionId, System.Threading.CancellationToken cancellationToken); /// <summary>Checks the missing System Capabilities for a given session.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetCompatibilityOutput> GetCompatibilityAsync(string sessionId); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Checks the missing System Capabilities for a given session.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetCompatibilityOutput> GetCompatibilityAsync(string sessionId, System.Threading.CancellationToken cancellationToken); /// <summary>Creates the CloudFormation template that will be used by CDK for the deployment. /// This operation returns the CloudFormation template that is created for this deployment.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GenerateCloudFormationTemplateOutput> GenerateCloudFormationTemplateAsync(string sessionId); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Creates the CloudFormation template that will be used by CDK for the deployment. /// This operation returns the CloudFormation template that is created for this deployment.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GenerateCloudFormationTemplateOutput> GenerateCloudFormationTemplateAsync(string sessionId, System.Threading.CancellationToken cancellationToken); /// <summary>Begin execution of the deployment.</summary> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task StartDeploymentAsync(string sessionId); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Begin execution of the deployment.</summary> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task StartDeploymentAsync(string sessionId, System.Threading.CancellationToken cancellationToken); /// <summary>Gets the status of the deployment.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetDeploymentStatusOutput> GetDeploymentStatusAsync(string sessionId); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets the status of the deployment.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetDeploymentStatusOutput> GetDeploymentStatusAsync(string sessionId, System.Threading.CancellationToken cancellationToken); /// <summary>Gets information about the displayed resources defined in the recipe definition.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetDeploymentDetailsOutput> GetDeploymentDetailsAsync(string sessionId); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets information about the displayed resources defined in the recipe definition.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetDeploymentDetailsOutput> GetDeploymentDetailsAsync(string sessionId, System.Threading.CancellationToken cancellationToken); /// <summary>Gets the health of the deployment tool. Use this API after starting the command line to see if the tool is ready to handle requests.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<HealthStatusOutput> HealthAsync(); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets the health of the deployment tool. Use this API after starting the command line to see if the tool is ready to handle requests.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<HealthStatusOutput> HealthAsync(System.Threading.CancellationToken cancellationToken); /// <summary>Gets a list of available recipe IDs.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<ListAllRecipesOutput> ListAllRecipesAsync(string projectPath); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets a list of available recipe IDs.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<ListAllRecipesOutput> ListAllRecipesAsync(string projectPath, System.Threading.CancellationToken cancellationToken); /// <summary>Gets a summary of the specified Recipe.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<RecipeSummary> GetRecipeAsync(string recipeId, string projectPath); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets a summary of the specified Recipe.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<RecipeSummary> GetRecipeAsync(string recipeId, string projectPath, System.Threading.CancellationToken cancellationToken); /// <summary>Gets a summary of the specified recipe option settings.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<System.Collections.Generic.ICollection<RecipeOptionSettingSummary>> GetRecipeOptionSettingsAsync(string recipeId, string projectPath); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets a summary of the specified recipe option settings.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<System.Collections.Generic.ICollection<RecipeOptionSettingSummary>> GetRecipeOptionSettingsAsync(string recipeId, string projectPath, System.Threading.CancellationToken cancellationToken); /// <summary>Requests to stop the deployment tool. Any open sessions are implicitly closed. /// This may return Microsoft.AspNetCore.Mvc.OkResult prior to the server being stopped, /// clients may need to wait or check the health after requesting shutdown.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task ShutdownAsync(); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Requests to stop the deployment tool. Any open sessions are implicitly closed. /// This may return Microsoft.AspNetCore.Mvc.OkResult prior to the server being stopped, /// clients may need to wait or check the health after requesting shutdown.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task ShutdownAsync(System.Threading.CancellationToken cancellationToken); } [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.10.9.0 (NJsonSchema v10.4.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial class RestAPIClient : IRestAPIClient { private string _baseUrl = ""; private ServerModeHttpClient _httpClient; private System.Lazy<Newtonsoft.Json.JsonSerializerSettings> _settings; public RestAPIClient(string baseUrl, ServerModeHttpClient httpClient) { BaseUrl = baseUrl; _httpClient = httpClient; _settings = new System.Lazy<Newtonsoft.Json.JsonSerializerSettings>(CreateSerializerSettings); } private Newtonsoft.Json.JsonSerializerSettings CreateSerializerSettings() { var settings = new Newtonsoft.Json.JsonSerializerSettings(); UpdateJsonSerializerSettings(settings); return settings; } public string BaseUrl { get { return _baseUrl; } set { _baseUrl = value; } } protected Newtonsoft.Json.JsonSerializerSettings JsonSerializerSettings { get { return _settings.Value; } } partial void UpdateJsonSerializerSettings(Newtonsoft.Json.JsonSerializerSettings settings); partial void PrepareRequest(ServerModeHttpClient client, System.Net.Http.HttpRequestMessage request, string url); partial void PrepareRequest(ServerModeHttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder); partial void ProcessResponse(ServerModeHttpClient client, System.Net.Http.HttpResponseMessage response); /// <summary>Start a deployment session. A session id will be generated. This session id needs to be passed in future API calls to configure and execute deployment.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task<StartDeploymentSessionOutput> StartDeploymentSessionAsync(StartDeploymentSessionInput body) { return StartDeploymentSessionAsync(body, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Start a deployment session. A session id will be generated. This session id needs to be passed in future API calls to configure and execute deployment.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<StartDeploymentSessionOutput> StartDeploymentSessionAsync(StartDeploymentSessionInput body, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Deployment/session"); var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync<StartDeploymentSessionOutput>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Closes the deployment session. This removes any session state for the session id.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task CloseDeploymentSessionAsync(string sessionId) { return CloseDeploymentSessionAsync(sessionId, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Closes the deployment session. This removes any session state for the session id.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task CloseDeploymentSessionAsync(string sessionId, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Deployment/session/<sessionId>?"); if (sessionId != null) { urlBuilder_.Append(System.Uri.EscapeDataString("sessionId") + "=").Append(System.Uri.EscapeDataString(ConvertToString(sessionId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Method = new System.Net.Http.HttpMethod("DELETE"); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { return; } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Set the target recipe and name for the deployment.</summary> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task SetDeploymentTargetAsync(string sessionId, SetDeploymentTargetInput body) { return SetDeploymentTargetAsync(sessionId, body, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Set the target recipe and name for the deployment.</summary> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task SetDeploymentTargetAsync(string sessionId, SetDeploymentTargetInput body, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Deployment/session/<sessionId>?"); if (sessionId != null) { urlBuilder_.Append(System.Uri.EscapeDataString("sessionId") + "=").Append(System.Uri.EscapeDataString(ConvertToString(sessionId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 404) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Not Found", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else if (status_ == 400) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Bad Request", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else if (status_ == 200 || status_ == 204) { return; } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Gets the list of compatible deployments for the session's project. The list is ordered with the first recommendation in the list being the most compatible recommendation.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task<GetRecommendationsOutput> GetRecommendationsAsync(string sessionId) { return GetRecommendationsAsync(sessionId, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets the list of compatible deployments for the session's project. The list is ordered with the first recommendation in the list being the most compatible recommendation.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<GetRecommendationsOutput> GetRecommendationsAsync(string sessionId, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Deployment/session/<sessionId>/recommendations?"); if (sessionId != null) { urlBuilder_.Append(System.Uri.EscapeDataString("sessionId") + "=").Append(System.Uri.EscapeDataString(ConvertToString(sessionId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync<GetRecommendationsOutput>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else if (status_ == 404) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Not Found", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Gets the list of updatable option setting items for the selected recommendation.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task<GetOptionSettingsOutput> GetConfigSettingsAsync(string sessionId) { return GetConfigSettingsAsync(sessionId, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets the list of updatable option setting items for the selected recommendation.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<GetOptionSettingsOutput> GetConfigSettingsAsync(string sessionId, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Deployment/session/<sessionId>/settings?"); if (sessionId != null) { urlBuilder_.Append(System.Uri.EscapeDataString("sessionId") + "=").Append(System.Uri.EscapeDataString(ConvertToString(sessionId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync<GetOptionSettingsOutput>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else if (status_ == 404) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Not Found", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Applies a value for a list of option setting items on the selected recommendation. /// Option setting updates are provided as Key Value pairs with the Key being the JSON path to the leaf node. /// Only primitive data types are supported for Value updates. The Value is a string value which will be parsed as its corresponding data type.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task<ApplyConfigSettingsOutput> ApplyConfigSettingsAsync(string sessionId, ApplyConfigSettingsInput body) { return ApplyConfigSettingsAsync(sessionId, body, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Applies a value for a list of option setting items on the selected recommendation. /// Option setting updates are provided as Key Value pairs with the Key being the JSON path to the leaf node. /// Only primitive data types are supported for Value updates. The Value is a string value which will be parsed as its corresponding data type.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<ApplyConfigSettingsOutput> ApplyConfigSettingsAsync(string sessionId, ApplyConfigSettingsInput body, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Deployment/session/<sessionId>/settings?"); if (sessionId != null) { urlBuilder_.Append(System.Uri.EscapeDataString("sessionId") + "=").Append(System.Uri.EscapeDataString(ConvertToString(sessionId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value)); content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("PUT"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync<ApplyConfigSettingsOutput>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else if (status_ == 404) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Not Found", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else if (status_ == 400) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Bad Request", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task<GetConfigSettingResourcesOutput> GetConfigSettingResourcesAsync(string sessionId, string configSettingId) { return GetConfigSettingResourcesAsync(sessionId, configSettingId, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<GetConfigSettingResourcesOutput> GetConfigSettingResourcesAsync(string sessionId, string configSettingId, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Deployment/session/<sessionId>/settings/<configSettingId>/resources?"); if (sessionId != null) { urlBuilder_.Append(System.Uri.EscapeDataString("sessionId") + "=").Append(System.Uri.EscapeDataString(ConvertToString(sessionId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } if (configSettingId != null) { urlBuilder_.Append(System.Uri.EscapeDataString("configSettingId") + "=").Append(System.Uri.EscapeDataString(ConvertToString(configSettingId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync<GetConfigSettingResourcesOutput>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else if (status_ == 404) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Not Found", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Gets the list of existing deployments that are compatible with the session's project.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task<GetExistingDeploymentsOutput> GetExistingDeploymentsAsync(string sessionId) { return GetExistingDeploymentsAsync(sessionId, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets the list of existing deployments that are compatible with the session's project.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<GetExistingDeploymentsOutput> GetExistingDeploymentsAsync(string sessionId, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Deployment/session/<sessionId>/deployments?"); if (sessionId != null) { urlBuilder_.Append(System.Uri.EscapeDataString("sessionId") + "=").Append(System.Uri.EscapeDataString(ConvertToString(sessionId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync<GetExistingDeploymentsOutput>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else if (status_ == 404) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Not Found", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Checks the missing System Capabilities for a given session.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task<GetCompatibilityOutput> GetCompatibilityAsync(string sessionId) { return GetCompatibilityAsync(sessionId, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Checks the missing System Capabilities for a given session.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<GetCompatibilityOutput> GetCompatibilityAsync(string sessionId, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Deployment/session/<sessionId>/compatiblity?"); if (sessionId != null) { urlBuilder_.Append(System.Uri.EscapeDataString("sessionId") + "=").Append(System.Uri.EscapeDataString(ConvertToString(sessionId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Content = new System.Net.Http.StringContent(string.Empty, System.Text.Encoding.UTF8, "application/json"); request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync<GetCompatibilityOutput>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else if (status_ == 404) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Not Found", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Creates the CloudFormation template that will be used by CDK for the deployment. /// This operation returns the CloudFormation template that is created for this deployment.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task<GenerateCloudFormationTemplateOutput> GenerateCloudFormationTemplateAsync(string sessionId) { return GenerateCloudFormationTemplateAsync(sessionId, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Creates the CloudFormation template that will be used by CDK for the deployment. /// This operation returns the CloudFormation template that is created for this deployment.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<GenerateCloudFormationTemplateOutput> GenerateCloudFormationTemplateAsync(string sessionId, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Deployment/session/<sessionId>/cftemplate?"); if (sessionId != null) { urlBuilder_.Append(System.Uri.EscapeDataString("sessionId") + "=").Append(System.Uri.EscapeDataString(ConvertToString(sessionId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync<GenerateCloudFormationTemplateOutput>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else if (status_ == 404) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Not Found", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Begin execution of the deployment.</summary> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task StartDeploymentAsync(string sessionId) { return StartDeploymentAsync(sessionId, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Begin execution of the deployment.</summary> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task StartDeploymentAsync(string sessionId, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Deployment/session/<sessionId>/execute?"); if (sessionId != null) { urlBuilder_.Append(System.Uri.EscapeDataString("sessionId") + "=").Append(System.Uri.EscapeDataString(ConvertToString(sessionId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Content = new System.Net.Http.StringContent(string.Empty, System.Text.Encoding.UTF8, "application/json"); request_.Method = new System.Net.Http.HttpMethod("POST"); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 404) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Not Found", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else if (status_ == 424) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Client Error", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else if (status_ == 200 || status_ == 204) { return; } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Gets the status of the deployment.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task<GetDeploymentStatusOutput> GetDeploymentStatusAsync(string sessionId) { return GetDeploymentStatusAsync(sessionId, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets the status of the deployment.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<GetDeploymentStatusOutput> GetDeploymentStatusAsync(string sessionId, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Deployment/session/<sessionId>/execute?"); if (sessionId != null) { urlBuilder_.Append(System.Uri.EscapeDataString("sessionId") + "=").Append(System.Uri.EscapeDataString(ConvertToString(sessionId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync<GetDeploymentStatusOutput>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else if (status_ == 404) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Not Found", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Gets information about the displayed resources defined in the recipe definition.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task<GetDeploymentDetailsOutput> GetDeploymentDetailsAsync(string sessionId) { return GetDeploymentDetailsAsync(sessionId, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets information about the displayed resources defined in the recipe definition.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<GetDeploymentDetailsOutput> GetDeploymentDetailsAsync(string sessionId, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Deployment/session/<sessionId>/details?"); if (sessionId != null) { urlBuilder_.Append(System.Uri.EscapeDataString("sessionId") + "=").Append(System.Uri.EscapeDataString(ConvertToString(sessionId, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync<GetDeploymentDetailsOutput>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else if (status_ == 404) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Not Found", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Gets the health of the deployment tool. Use this API after starting the command line to see if the tool is ready to handle requests.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task<HealthStatusOutput> HealthAsync() { return HealthAsync(System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets the health of the deployment tool. Use this API after starting the command line to see if the tool is ready to handle requests.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<HealthStatusOutput> HealthAsync(System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Health"); var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync<HealthStatusOutput>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Gets a list of available recipe IDs.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task<ListAllRecipesOutput> ListAllRecipesAsync(string projectPath) { return ListAllRecipesAsync(projectPath, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets a list of available recipe IDs.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<ListAllRecipesOutput> ListAllRecipesAsync(string projectPath, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Recipe/recipes?"); if (projectPath != null) { urlBuilder_.Append(System.Uri.EscapeDataString("projectPath") + "=").Append(System.Uri.EscapeDataString(ConvertToString(projectPath, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync<ListAllRecipesOutput>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else if (status_ == 400) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Bad Request", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Gets a summary of the specified Recipe.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task<RecipeSummary> GetRecipeAsync(string recipeId, string projectPath) { return GetRecipeAsync(recipeId, projectPath, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets a summary of the specified Recipe.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<RecipeSummary> GetRecipeAsync(string recipeId, string projectPath, System.Threading.CancellationToken cancellationToken) { if (recipeId == null) throw new System.ArgumentNullException("recipeId"); var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Recipe/{recipeId}?"); urlBuilder_.Replace("{recipeId}", System.Uri.EscapeDataString(ConvertToString(recipeId, System.Globalization.CultureInfo.InvariantCulture))); if (projectPath != null) { urlBuilder_.Append(System.Uri.EscapeDataString("projectPath") + "=").Append(System.Uri.EscapeDataString(ConvertToString(projectPath, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync<RecipeSummary>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else if (status_ == 400) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Bad Request", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Gets a summary of the specified recipe option settings.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task<System.Collections.Generic.ICollection<RecipeOptionSettingSummary>> GetRecipeOptionSettingsAsync(string recipeId, string projectPath) { return GetRecipeOptionSettingsAsync(recipeId, projectPath, System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Gets a summary of the specified recipe option settings.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task<System.Collections.Generic.ICollection<RecipeOptionSettingSummary>> GetRecipeOptionSettingsAsync(string recipeId, string projectPath, System.Threading.CancellationToken cancellationToken) { if (recipeId == null) throw new System.ArgumentNullException("recipeId"); var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Recipe/{recipeId}/settings?"); urlBuilder_.Replace("{recipeId}", System.Uri.EscapeDataString(ConvertToString(recipeId, System.Globalization.CultureInfo.InvariantCulture))); if (projectPath != null) { urlBuilder_.Append(System.Uri.EscapeDataString("projectPath") + "=").Append(System.Uri.EscapeDataString(ConvertToString(projectPath, System.Globalization.CultureInfo.InvariantCulture))).Append("&"); } urlBuilder_.Length--; var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Method = new System.Net.Http.HttpMethod("GET"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { var objectResponse_ = await ReadObjectResponseAsync<System.Collections.Generic.ICollection<RecipeOptionSettingSummary>>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } return objectResponse_.Object; } else if (status_ == 400) { var objectResponse_ = await ReadObjectResponseAsync<ProblemDetails>(response_, headers_, cancellationToken).ConfigureAwait(false); if (objectResponse_.Object == null) { throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); } throw new ApiException<ProblemDetails>("Bad Request", status_, objectResponse_.Text, headers_, objectResponse_.Object, null); } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } /// <summary>Requests to stop the deployment tool. Any open sessions are implicitly closed. /// This may return Microsoft.AspNetCore.Mvc.OkResult prior to the server being stopped, /// clients may need to wait or check the health after requesting shutdown.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public System.Threading.Tasks.Task ShutdownAsync() { return ShutdownAsync(System.Threading.CancellationToken.None); } /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Requests to stop the deployment tool. Any open sessions are implicitly closed. /// This may return Microsoft.AspNetCore.Mvc.OkResult prior to the server being stopped, /// clients may need to wait or check the health after requesting shutdown.</summary> /// <returns>Success</returns> /// <exception cref="ApiException">A server side error occurred.</exception> public async System.Threading.Tasks.Task ShutdownAsync(System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/v1/Server/Shutdown"); var client_ = _httpClient; var disposeClient_ = false; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { request_.Content = new System.Net.Http.StringContent(string.Empty, System.Text.Encoding.UTF8, "application/json"); request_.Method = new System.Net.Http.HttpMethod("POST"); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); var disposeResponse_ = true; try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = (int)response_.StatusCode; if (status_ == 200) { return; } else { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); } } finally { if (disposeResponse_) response_.Dispose(); } } } finally { if (disposeClient_) client_.Dispose(); } } protected struct ObjectResponseResult<T> { public ObjectResponseResult(T responseObject, string responseText) { this.Object = responseObject; this.Text = responseText; } public T Object { get; } public string Text { get; } } public bool ReadResponseAsString { get; set; } protected virtual async System.Threading.Tasks.Task<ObjectResponseResult<T>> ReadObjectResponseAsync<T>(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary<string, System.Collections.Generic.IEnumerable<string>> headers, System.Threading.CancellationToken cancellationToken) { if (response == null || response.Content == null) { return new ObjectResponseResult<T>(default(T), string.Empty); } if (ReadResponseAsString) { var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); try { var typedBody = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responseText, JsonSerializerSettings); return new ObjectResponseResult<T>(typedBody, responseText); } catch (Newtonsoft.Json.JsonException exception) { var message = "Could not deserialize the response body string as " + typeof(T).FullName + "."; throw new ApiException(message, (int)response.StatusCode, responseText, headers, exception); } } else { try { using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) using (var streamReader = new System.IO.StreamReader(responseStream)) using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader)) { var serializer = Newtonsoft.Json.JsonSerializer.Create(JsonSerializerSettings); var typedBody = serializer.Deserialize<T>(jsonTextReader); return new ObjectResponseResult<T>(typedBody, string.Empty); } } catch (Newtonsoft.Json.JsonException exception) { var message = "Could not deserialize the response body stream as " + typeof(T).FullName + "."; throw new ApiException(message, (int)response.StatusCode, string.Empty, headers, exception); } } } private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) { if (value == null) { return ""; } if (value is System.Enum) { var name = System.Enum.GetName(value.GetType(), value); if (name != null) { var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name); if (field != null) { var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute)) as System.Runtime.Serialization.EnumMemberAttribute; if (attribute != null) { return attribute.Value != null ? attribute.Value : name; } } var converted = System.Convert.ToString(System.Convert.ChangeType(value, System.Enum.GetUnderlyingType(value.GetType()), cultureInfo)); return converted == null ? string.Empty : converted; } } else if (value is bool) { return System.Convert.ToString((bool)value, cultureInfo).ToLowerInvariant(); } else if (value is byte[]) { return System.Convert.ToBase64String((byte[]) value); } else if (value.GetType().IsArray) { var array = System.Linq.Enumerable.OfType<object>((System.Array) value); return string.Join(",", System.Linq.Enumerable.Select(array, o => ConvertToString(o, cultureInfo))); } var result = System.Convert.ToString(value, cultureInfo); return result == null ? "" : result; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class ApplyConfigSettingsInput { [Newtonsoft.Json.JsonProperty("updatedSettings", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.IDictionary<string, string> UpdatedSettings { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class ApplyConfigSettingsOutput { [Newtonsoft.Json.JsonProperty("failedConfigUpdates", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.IDictionary<string, string> FailedConfigUpdates { get; set; } } /// <summary>A category defined in the recipe that settings will be mapped to via the Id property.</summary> [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class CategorySummary { /// <summary>The id of the category that will be specified on top level settings.</summary> [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Id { get; set; } /// <summary>The display name of the category shown to users in UI screens.</summary> [Newtonsoft.Json.JsonProperty("displayName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DisplayName { get; set; } /// <summary>The order used to sort categories in UI screens. Categories will be shown in sorted descending order.</summary> [Newtonsoft.Json.JsonProperty("order", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public int Order { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public enum DeploymentStatus { [System.Runtime.Serialization.EnumMember(Value = @"NotStarted")] NotStarted = 0, [System.Runtime.Serialization.EnumMember(Value = @"Executing")] Executing = 1, [System.Runtime.Serialization.EnumMember(Value = @"Error")] Error = 2, [System.Runtime.Serialization.EnumMember(Value = @"Success")] Success = 3, } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public enum DeploymentTypes { [System.Runtime.Serialization.EnumMember(Value = @"CloudFormationStack")] CloudFormationStack = 0, [System.Runtime.Serialization.EnumMember(Value = @"BeanstalkEnvironment")] BeanstalkEnvironment = 1, [System.Runtime.Serialization.EnumMember(Value = @"ElasticContainerRegistryImage")] ElasticContainerRegistryImage = 2, } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class DeployToolExceptionSummary { [Newtonsoft.Json.JsonProperty("errorCode", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ErrorCode { get; set; } [Newtonsoft.Json.JsonProperty("message", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Message { get; set; } [Newtonsoft.Json.JsonProperty("processExitCode", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public int? ProcessExitCode { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class DisplayedResourceSummary { /// <summary>The Physical ID that represents a CloudFormation resource</summary> [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Id { get; set; } /// <summary>The description of the resource that is defined in the recipe definition</summary> [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Description { get; set; } /// <summary>The CloudFormation resource type</summary> [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Type { get; set; } /// <summary>The Key Value pair of additional data unique to this resource type</summary> [Newtonsoft.Json.JsonProperty("data", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.IDictionary<string, string> Data { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class ExistingDeploymentSummary { [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Name { get; set; } [Newtonsoft.Json.JsonProperty("baseRecipeId", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string BaseRecipeId { get; set; } [Newtonsoft.Json.JsonProperty("recipeId", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string RecipeId { get; set; } [Newtonsoft.Json.JsonProperty("recipeName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string RecipeName { get; set; } [Newtonsoft.Json.JsonProperty("isPersistedDeploymentProject", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public bool IsPersistedDeploymentProject { get; set; } [Newtonsoft.Json.JsonProperty("shortDescription", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ShortDescription { get; set; } [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Description { get; set; } [Newtonsoft.Json.JsonProperty("targetService", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string TargetService { get; set; } [Newtonsoft.Json.JsonProperty("lastUpdatedTime", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.DateTimeOffset? LastUpdatedTime { get; set; } [Newtonsoft.Json.JsonProperty("updatedByCurrentUser", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public bool UpdatedByCurrentUser { get; set; } [Newtonsoft.Json.JsonProperty("deploymentType", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] public DeploymentTypes DeploymentType { get; set; } [Newtonsoft.Json.JsonProperty("settingsCategories", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<CategorySummary> SettingsCategories { get; set; } [Newtonsoft.Json.JsonProperty("existingDeploymentId", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ExistingDeploymentId { get; set; } } /// <summary>The response that will be returned by the M:AWS.Deploy.CLI.ServerMode.Controllers.DeploymentController.GenerateCloudFormationTemplate(System.String) operation.</summary> [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class GenerateCloudFormationTemplateOutput { /// <summary>The CloudFormation template of the generated CDK deployment project.</summary> [Newtonsoft.Json.JsonProperty("cloudFormationTemplate", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string CloudFormationTemplate { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class GetCompatibilityOutput { [Newtonsoft.Json.JsonProperty("capabilities", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<SystemCapabilitySummary> Capabilities { get; set; } } /// <summary>Represents a list or table of options, generally used when selecting from /// a list of existing AWS resources to set an OptionSettingItem</summary> [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class GetConfigSettingResourcesOutput { /// <summary>Columns that should appear above the list of resources when /// presenting the user a table to select from</summary> [Newtonsoft.Json.JsonProperty("columns", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<TypeHintResourceColumn> Columns { get; set; } /// <summary>List of resources that the user could select from</summary> [Newtonsoft.Json.JsonProperty("resources", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<TypeHintResourceSummary> Resources { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class GetDeploymentDetailsOutput { /// <summary>The CloudApplication Name</summary> [Newtonsoft.Json.JsonProperty("cloudApplicationName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string CloudApplicationName { get; set; } /// <summary>The list of displayed resources based on the recipe definition</summary> [Newtonsoft.Json.JsonProperty("displayedResources", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<DisplayedResourceSummary> DisplayedResources { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class GetDeploymentStatusOutput { [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] public DeploymentStatus Status { get; set; } [Newtonsoft.Json.JsonProperty("exception", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public DeployToolExceptionSummary Exception { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class GetExistingDeploymentsOutput { [Newtonsoft.Json.JsonProperty("existingDeployments", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<ExistingDeploymentSummary> ExistingDeployments { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class GetOptionSettingsOutput { [Newtonsoft.Json.JsonProperty("optionSettings", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<OptionSettingItemSummary> OptionSettings { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class GetRecommendationsOutput { [Newtonsoft.Json.JsonProperty("recommendations", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<RecommendationSummary> Recommendations { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class HealthStatusOutput { [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] public SystemStatus Status { get; set; } } /// <summary>Output returned by the M:AWS.Deploy.CLI.ServerMode.Controllers.RecipeController.ListAllRecipes(System.String) API</summary> [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class ListAllRecipesOutput { /// <summary>A list of Recipe IDs</summary> [Newtonsoft.Json.JsonProperty("recipes", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<RecipeSummary> Recipes { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class OptionSettingItemSummary { /// <summary>The unique id of setting. This value will be persisted in other config files so its value should never change once a recipe is released.</summary> [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Id { get; set; } /// <summary>The fully qualified id of the setting that includes the Id and all of the parent's Ids. /// This helps easily reference the Option Setting without context of the parent setting.</summary> [Newtonsoft.Json.JsonProperty("fullyQualifiedId", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string FullyQualifiedId { get; set; } /// <summary>The display friendly name of the setting.</summary> [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Name { get; set; } /// <summary>The category for the setting. This value must match an id field in the list of categories.</summary> [Newtonsoft.Json.JsonProperty("category", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Category { get; set; } /// <summary>The description of what the setting is used for.</summary> [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Description { get; set; } /// <summary>The value used for the recipe if it is set by the user.</summary> [Newtonsoft.Json.JsonProperty("value", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public object Value { get; set; } /// <summary>The type of primitive value expected for this setting. /// For example String, Int</summary> [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Type { get; set; } /// <summary>Hint the the UI what type of setting this is optionally add additional UI features to select a value. /// For example a value of BeanstalkApplication tells the UI it can display the list of available Beanstalk applications for the user to pick from.</summary> [Newtonsoft.Json.JsonProperty("typeHint", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string TypeHint { get; set; } /// <summary>Type hint additional data required to facilitate handling of the option setting.</summary> [Newtonsoft.Json.JsonProperty("typeHintData", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.IDictionary<string, object> TypeHintData { get; set; } /// <summary>UI can use this to reduce the amount of settings to show to the user when confirming the recommendation. This can make it so the user sees only the most important settings /// they need to know about before deploying.</summary> [Newtonsoft.Json.JsonProperty("advanced", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public bool Advanced { get; set; } /// <summary>Indicates whether the setting can be edited</summary> [Newtonsoft.Json.JsonProperty("readOnly", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public bool ReadOnly { get; set; } /// <summary>Indicates whether the setting is visible/displayed on the UI</summary> [Newtonsoft.Json.JsonProperty("visible", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public bool Visible { get; set; } /// <summary>Indicates whether the setting can be displayed as part of the settings summary of the previous deployment.</summary> [Newtonsoft.Json.JsonProperty("summaryDisplayable", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public bool SummaryDisplayable { get; set; } /// <summary>The allowed values for the setting.</summary> [Newtonsoft.Json.JsonProperty("allowedValues", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<string> AllowedValues { get; set; } /// <summary>The value mapping for allowed values. The key of the dictionary is what is sent to services /// and the value is the display value shown to users.</summary> [Newtonsoft.Json.JsonProperty("valueMapping", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.IDictionary<string, string> ValueMapping { get; set; } /// <summary>Child option settings for AWS.Deploy.Common.Recipes.OptionSettingValueType.Object value types /// AWS.Deploy.CLI.ServerMode.Models.OptionSettingItemSummary.ChildOptionSettings value depends on the values of AWS.Deploy.CLI.ServerMode.Models.OptionSettingItemSummary.ChildOptionSettings</summary> [Newtonsoft.Json.JsonProperty("childOptionSettings", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<OptionSettingItemSummary> ChildOptionSettings { get; set; } /// <summary>The validation state of the setting that contains the validation status and message.</summary> [Newtonsoft.Json.JsonProperty("validation", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public OptionSettingValidation Validation { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class OptionSettingValidation { [Newtonsoft.Json.JsonProperty("validationStatus", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] public ValidationStatus ValidationStatus { get; set; } [Newtonsoft.Json.JsonProperty("validationMessage", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ValidationMessage { get; set; } [Newtonsoft.Json.JsonProperty("invalidValue", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public object InvalidValue { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class ProblemDetails { [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Type { get; set; } [Newtonsoft.Json.JsonProperty("title", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Title { get; set; } [Newtonsoft.Json.JsonProperty("status", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public int? Status { get; set; } [Newtonsoft.Json.JsonProperty("detail", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Detail { get; set; } [Newtonsoft.Json.JsonProperty("instance", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Instance { get; set; } private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>(); [Newtonsoft.Json.JsonExtensionData] public System.Collections.Generic.IDictionary<string, object> AdditionalProperties { get { return _additionalProperties; } set { _additionalProperties = value; } } } /// <summary>Represents a recipe AWS.Deploy.Common.Recipes.OptionSettingItem returned through server mode.</summary> [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class RecipeOptionSettingSummary { /// <summary>The unique id of setting.</summary> [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Id { get; set; } /// <summary>The display friendly name of the setting.</summary> [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Name { get; set; } /// <summary>The description of what the setting is used for.</summary> [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Description { get; set; } /// <summary>The type of primitive value expected for this setting. /// For example String, Int</summary> [Newtonsoft.Json.JsonProperty("type", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Type { get; set; } /// <summary>Child option settings for AWS.Deploy.Common.Recipes.OptionSettingValueType.Object value types.</summary> [Newtonsoft.Json.JsonProperty("settings", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<RecipeOptionSettingSummary> Settings { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class RecipeSummary { [Newtonsoft.Json.JsonProperty("id", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Id { get; set; } [Newtonsoft.Json.JsonProperty("version", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Version { get; set; } [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Name { get; set; } [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Description { get; set; } [Newtonsoft.Json.JsonProperty("shortDescription", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ShortDescription { get; set; } [Newtonsoft.Json.JsonProperty("targetService", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string TargetService { get; set; } [Newtonsoft.Json.JsonProperty("deploymentType", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DeploymentType { get; set; } [Newtonsoft.Json.JsonProperty("deploymentBundle", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DeploymentBundle { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class RecommendationSummary { [Newtonsoft.Json.JsonProperty("baseRecipeId", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string BaseRecipeId { get; set; } [Newtonsoft.Json.JsonProperty("recipeId", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string RecipeId { get; set; } [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Name { get; set; } [Newtonsoft.Json.JsonProperty("isPersistedDeploymentProject", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public bool IsPersistedDeploymentProject { get; set; } [Newtonsoft.Json.JsonProperty("shortDescription", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ShortDescription { get; set; } [Newtonsoft.Json.JsonProperty("description", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Description { get; set; } [Newtonsoft.Json.JsonProperty("targetService", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string TargetService { get; set; } [Newtonsoft.Json.JsonProperty("deploymentType", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] public DeploymentTypes DeploymentType { get; set; } [Newtonsoft.Json.JsonProperty("settingsCategories", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<CategorySummary> SettingsCategories { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class SetDeploymentTargetInput { [Newtonsoft.Json.JsonProperty("newDeploymentName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string NewDeploymentName { get; set; } [Newtonsoft.Json.JsonProperty("newDeploymentRecipeId", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string NewDeploymentRecipeId { get; set; } [Newtonsoft.Json.JsonProperty("existingDeploymentId", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ExistingDeploymentId { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class StartDeploymentSessionInput { [Newtonsoft.Json.JsonProperty("awsRegion", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string AwsRegion { get; set; } [Newtonsoft.Json.JsonProperty("projectPath", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string ProjectPath { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class StartDeploymentSessionOutput { [Newtonsoft.Json.JsonProperty("sessionId", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string SessionId { get; set; } [Newtonsoft.Json.JsonProperty("defaultDeploymentName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DefaultDeploymentName { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class SystemCapabilitySummary { [Newtonsoft.Json.JsonProperty("name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Name { get; set; } [Newtonsoft.Json.JsonProperty("message", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Message { get; set; } [Newtonsoft.Json.JsonProperty("installationUrl", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string InstallationUrl { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public enum SystemStatus { [System.Runtime.Serialization.EnumMember(Value = @"Ready")] Ready = 0, [System.Runtime.Serialization.EnumMember(Value = @"Error")] Error = 1, } /// <summary>Represents a column for a list/grid of AWS.Deploy.CLI.ServerMode.Models.TypeHintResourceSummary rows</summary> [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class TypeHintResourceColumn { /// <summary>Name of the column to be displayed to users</summary> [Newtonsoft.Json.JsonProperty("displayName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DisplayName { get; set; } } /// <summary>Represents a single type hint option, generally used when selecting from /// a list of existing AWS resources to set an OptionSettingItem</summary> [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public partial class TypeHintResourceSummary { /// <summary>Resource Id, used when saving a selected resource to an OptionSettingItem</summary> [Newtonsoft.Json.JsonProperty("systemName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string SystemName { get; set; } /// <summary>Resource name, used for display</summary> [Newtonsoft.Json.JsonProperty("displayName", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string DisplayName { get; set; } /// <summary>Additional data about the resource, which may be used when displaying a table /// or grid of options for the user to select from. The indices into this list should /// match the column indicies of a list of AWS.Deploy.CLI.ServerMode.Models.TypeHintResourceColumn</summary> [Newtonsoft.Json.JsonProperty("columnDisplayValues", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public System.Collections.Generic.ICollection<string> ColumnDisplayValues { get; set; } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.4.1.0 (Newtonsoft.Json v13.0.0.0)")] public enum ValidationStatus { [System.Runtime.Serialization.EnumMember(Value = @"Valid")] Valid = 0, [System.Runtime.Serialization.EnumMember(Value = @"Invalid")] Invalid = 1, } [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.10.9.0 (NJsonSchema v10.4.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial class ApiException : System.Exception { public int StatusCode { get; private set; } public string Response { get; private set; } public System.Collections.Generic.IReadOnlyDictionary<string, System.Collections.Generic.IEnumerable<string>> Headers { get; private set; } public ApiException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary<string, System.Collections.Generic.IEnumerable<string>> headers, System.Exception innerException) : base(message + "\n\nStatus: " + statusCode + "\nResponse: \n" + ((response == null) ? "(null)" : response.Substring(0, response.Length >= 512 ? 512 : response.Length)), innerException) { StatusCode = statusCode; Response = response; Headers = headers; } public override string ToString() { return string.Format("HTTP Response: \n\n{0}\n\n{1}", Response, base.ToString()); } } [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.10.9.0 (NJsonSchema v10.4.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial class ApiException<TResult> : ApiException { public TResult Result { get; private set; } public ApiException(string message, int statusCode, string response, System.Collections.Generic.IReadOnlyDictionary<string, System.Collections.Generic.IEnumerable<string>> headers, TResult result, System.Exception innerException) : base(message, statusCode, response, headers, innerException) { Result = result; } } } #pragma warning restore 1591 #pragma warning restore 1573 #pragma warning restore 472 #pragma warning restore 114 #pragma warning restore 108
2,611
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.Net.Http; using System.Net.Http.Headers; using Amazon.Runtime; using System.Threading.Tasks; using System.Threading; using System.Security.Cryptography; using System.IO; using System.Globalization; namespace AWS.Deploy.ServerMode.Client { /// <summary> /// This derived HttpClient is created with a handler to make sure the AWS credentials are used to create the authorization header for calls to the deploy tool server mode. /// Instances of this class are created with the ServerModeHttpClientFactory factory. /// </summary> public class ServerModeHttpClient : HttpClient { internal ServerModeHttpClient(ServerModeHttpClientAuthorizationHandler handler) : base(handler) { } } /// <summary> /// HttpClient handler that gets the latest credentials from the client sets the authorization header. /// </summary> public class ServerModeHttpClientAuthorizationHandler : HttpClientHandler { private readonly Func<Task<AWSCredentials>> _credentialsGenerator; private readonly Aes? _aes; private static readonly object AES_LOCK = new object(); internal ServerModeHttpClientAuthorizationHandler(Func<Task<AWSCredentials>> credentialsGenerator, Aes? aes = null) { _credentialsGenerator = credentialsGenerator; _aes = aes; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var awsCreds = await _credentialsGenerator(); if(awsCreds != null) { var immutableCredentials = await awsCreds.GetCredentialsAsync(); AddAuthorizationHeader(request, immutableCredentials, _aes); } return await base.SendAsync(request, cancellationToken); } public static void AddAuthorizationHeader(HttpRequestMessage request, ImmutableCredentials credentials, Aes? aes = null) { var authParameters = new Dictionary<string, string> { {"awsAccessKeyId", credentials.AccessKey }, {"awsSecretKey", credentials.SecretKey }, {"requestId", Guid.NewGuid().ToString() }, {"issueDate", DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fffZ", DateTimeFormatInfo.InvariantInfo) } }; if(!string.IsNullOrEmpty(credentials.Token)) { authParameters["awsSessionToken"] = credentials.Token; } var json = Newtonsoft.Json.JsonConvert.SerializeObject(authParameters); string base64; if(aes != null) { byte[] iv; lock (AES_LOCK) { aes.GenerateIV(); iv = aes.IV; } var encryptor = aes.CreateEncryptor(aes.Key, iv); using var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(json)); using var outputStream = new MemoryStream(); using (var encryptStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write)) { inputStream.CopyTo(encryptStream); } base64 = $"{Convert.ToBase64String(iv)} {Convert.ToBase64String(outputStream.ToArray())}"; } else { base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); } request.Headers.Authorization = new AuthenticationHeaderValue("aws-deploy-tool-server-mode", base64); } } /// <summary> /// Factory for creating the ServerModeHttpClient. /// </summary> public static class ServerModeHttpClientFactory { public static ServerModeHttpClient ConstructHttpClient(Func<Task<AWSCredentials>> credentialsGenerator, Aes? aes = null) { return new ServerModeHttpClient(new ServerModeHttpClientAuthorizationHandler(credentialsGenerator, aes)); } } }
116
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.Diagnostics; using System.IO; using System.Linq; using System.Net.Http; using System.Net.NetworkInformation; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; using AWS.Deploy.ServerMode.Client.Utilities; using Newtonsoft.Json; namespace AWS.Deploy.ServerMode.Client { /// <summary> /// Helper class that allows launching deployment tool in server mode. /// It abstracts the server mode setup, CLI command execution and retries when desired port is unavailable. /// </summary> public interface IServerModeSession { /// <summary> /// Starts deployment tool in server mode. /// It creates symmetric key and tries to setup the server mode. /// It also handles the retries when a desired port is unavailable in the provided range. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <exception cref="InternalServerModeException">Throws when deployment tool server failed to start for un unknown reason.</exception> /// <exception cref="PortUnavailableException">Throws when deployment tool server failed to start due to unavailability of free ports.</exception> Task Start(CancellationToken cancellationToken); /// <summary> /// Builds <see cref="IRestAPIClient"/> client using the cached base URL. /// If succeeded, <param name="restApiClient"></param> is initialized with current session client. /// </summary> /// <param name="credentialsGenerator">Func to that provides AWS credentials</param> /// <param name="restApiClient"><see cref="IRestAPIClient"/> client to initialize.</param> /// <returns>True, if <param name="restApiClient"/> is initialized successfully.</returns> bool TryGetRestAPIClient(Func<Task<AWSCredentials>> credentialsGenerator, out IRestAPIClient? restApiClient); /// <summary> /// Builds <see cref="IDeploymentCommunicationClient"/> client using the cached base URL. /// If succeeded, <param name="deploymentCommunicationClient"></param> is initialized with current session client. /// </summary> /// <param name="deploymentCommunicationClient"><see cref="DeploymentCommunicationClient"/> client to initialize.</param> /// <returns>True, if <param name="deploymentCommunicationClient"/> is initialized successfully.</returns> bool TryGetDeploymentCommunicationClient(out IDeploymentCommunicationClient? deploymentCommunicationClient); /// <summary> /// Returns the status of the deployment server by checking /api/v1/health API. /// Returns true, if the deployment server returns a success HTTP code. /// </summary> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <returns>Returns true, if the deployment server returns a success HTTP code.</returns> Task<bool> IsAlive(CancellationToken cancellationToken); } public class ServerModeSession : IServerModeSession, IDisposable { private const int TCP_PORT_ERROR = -100; private readonly int _startPort; private readonly int _endPort; private readonly CommandLineWrapper _commandLineWrapper; private readonly HttpClientHandler _httpClientHandler; private readonly TimeSpan _serverTimeout; private readonly string _deployToolPath; private string? _baseUrl; private Aes? _aes; private string HealthUrl { get { if (_baseUrl == null) { throw new InvalidOperationException($"{nameof(_baseUrl)} must not be null."); } return $"{_baseUrl}/api/v1/health"; } } public ServerModeSession(int startPort = 10000, int endPort = 10100, string deployToolPath = "", bool diagnosticLoggingEnabled = false) : this(new CommandLineWrapper(diagnosticLoggingEnabled), new HttpClientHandler(), TimeSpan.FromSeconds(60), startPort, endPort, deployToolPath) { } public ServerModeSession(CommandLineWrapper commandLineWrapper, HttpClientHandler httpClientHandler, TimeSpan serverTimeout, int startPort = 10000, int endPort = 10100, string deployToolPath = "") { _startPort = startPort; _endPort = endPort; _commandLineWrapper = commandLineWrapper; _httpClientHandler = httpClientHandler; _serverTimeout = serverTimeout; _deployToolPath = deployToolPath; } public async Task Start(CancellationToken cancellationToken) { var deployToolRoot = "dotnet aws"; if (!string.IsNullOrEmpty(_deployToolPath)) { if (!PathUtilities.IsDeployToolPathValid(_deployToolPath)) throw new InvalidAssemblyReferenceException("The specified assembly location is invalid."); deployToolRoot = _deployToolPath; } var currentProcessId = Process.GetCurrentProcess().Id; for (var port = _startPort; port <= _endPort; port++) { // This ensures that deploy tool CLI doesn't try on the in-use port // because server availability task will return success response for // an in-use port if (IsPortInUse(port)) { continue; } _aes = Aes.Create(); _aes.GenerateKey(); var keyInfo = new EncryptionKeyInfo( EncryptionKeyInfo.VERSION_1_0, Convert.ToBase64String(_aes.Key)); var keyInfoStdin = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(keyInfo))); var command = $"\"{deployToolRoot}\" server-mode --port {port} --parent-pid {currentProcessId}"; var startServerTask = _commandLineWrapper.Run(command, keyInfoStdin); _baseUrl = $"http://localhost:{port}"; var isServerAvailableTask = IsServerAvailable(cancellationToken); if (isServerAvailableTask == await Task.WhenAny(startServerTask, isServerAvailableTask).ConfigureAwait(false)) { // The server timed out, this isn't a transient error, therefore, we throw if (!isServerAvailableTask.Result) { throw new InternalServerModeException($"\"{command}\" failed for unknown reason."); } // Server has started, it is safe to return return; } // For -100 errors, we want to check all the ports in the configured port range // If the error code other than -100, this is an unexpected exit code. if (startServerTask.Result.ExitCode != TCP_PORT_ERROR) { throw new InternalServerModeException( string.IsNullOrEmpty(startServerTask.Result.StandardError) ? $"\"{command}\" failed for unknown reason." : startServerTask.Result.StandardError); } } throw new PortUnavailableException($"Free port unavailable in {_startPort}-{_endPort} range."); } public bool TryGetRestAPIClient(Func<Task<AWSCredentials>> credentialsGenerator, out IRestAPIClient? restApiClient) { if (_baseUrl == null || _aes == null) { restApiClient = null; return false; } var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(credentialsGenerator, _aes); restApiClient = new RestAPIClient(_baseUrl, httpClient); return true; } /// <summary> /// Builds <see cref="IRestAPIClient"/> client based on a deploy tool server mode running on the specified port. /// </summary> public static bool TryGetRestAPIClient(int port, Aes? aes, Func<Task<AWSCredentials>> credentialsGenerator, out IRestAPIClient? restApiClient) { // This ensures that deploy tool CLI doesn't try on the in-use port // because server availability task will return success response for // an in-use port if (!IsPortInUse(port)) { restApiClient = null; throw new PortUnavailableException($"There is no running process on port {port}."); } var baseUrl = $"http://localhost:{port}"; var httpClient = ServerModeHttpClientFactory.ConstructHttpClient(credentialsGenerator, aes); restApiClient = new RestAPIClient(baseUrl, httpClient); return true; } public bool TryGetDeploymentCommunicationClient(out IDeploymentCommunicationClient? deploymentCommunicationClient) { if (_baseUrl == null || _aes == null) { deploymentCommunicationClient = null; return false; } deploymentCommunicationClient = new DeploymentCommunicationClient(_baseUrl); return true; } public async Task<bool> IsAlive(CancellationToken cancellationToken) { var client = new HttpClient(_httpClientHandler); try { var response = await client.GetAsync(HealthUrl, cancellationToken); return response.IsSuccessStatusCode; } catch (Exception) { return false; } } #region Private methods private Task<bool> IsServerAvailable(CancellationToken cancellationToken) { return WaitUntilHelper.WaitUntilSuccessStatusCode( HealthUrl, _httpClientHandler, TimeSpan.FromMilliseconds(100), _serverTimeout, cancellationToken); } private static bool IsPortInUse(int port) { var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); var listeners = ipGlobalProperties.GetActiveTcpListeners(); return listeners.Any(x => x.Port == port); } #endregion #region Disposable protected virtual void Dispose(bool disposing) { if (disposing) { _aes?.Dispose(); _aes = null; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion private class EncryptionKeyInfo { public const string VERSION_1_0 = "1.0"; public string Version { get; set; } public string Key { get; set; } public string? IV { get; set; } public EncryptionKeyInfo(string version, string key, string? iv = null) { Version = version; Key = key; IV = iv; } } } }
298
aws-dotnet-deploy
aws
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; namespace AWS.Deploy.ServerMode.Client.Utilities { public class CappedStringBuilder { public int LineLimit { get; } public int LineCount { get { return _lines?.Count ?? 0; } } private readonly Queue<string> _lines; public CappedStringBuilder(int lineLimit) { _lines = new Queue<string>(lineLimit); LineLimit = lineLimit; } public void AppendLine(string value) { if (LineCount >= LineLimit) { _lines.Dequeue(); } _lines.Enqueue(value); } public string GetLastLines(int lineCount) { return _lines.Reverse().Take(lineCount).Reverse().Aggregate((x, y) => x + Environment.NewLine + y); } public override string ToString() { return _lines.Aggregate((x, y) => x + Environment.NewLine + y); } } }
49