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-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.ElasticBeanstalk.Model; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using ThirdParty.Json.LitJson; namespace Amazon.ElasticBeanstalk.Tools.Commands { public class DeleteEnvironmentCommand : EBBaseCommand { public const string COMMAND_NAME = "delete-environment"; public const string COMMAND_DESCRIPTION = "Delete an AWS Elastic Beanstalk environment."; public static readonly IList<CommandOption> CommandOptions = BuildLineOptions(new List<CommandOption> { CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, EBDefinedCommandOptions.ARGUMENT_EB_APPLICATION, EBDefinedCommandOptions.ARGUMENT_EB_ENVIRONMENT }); DeleteEnvironmentProperties _deleteEnvironmentProperties; public DeleteEnvironmentProperties DeleteEnvironmentProperties { get { if (this._deleteEnvironmentProperties == null) { this._deleteEnvironmentProperties = new DeleteEnvironmentProperties(); } return this._deleteEnvironmentProperties; } set { this._deleteEnvironmentProperties = value; } } public DeleteEnvironmentCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, CommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); this.DeleteEnvironmentProperties.ParseCommandArguments(values); Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_PERSIST_CONFIG_FILE.Switch)) != null) this.PersistConfigFile = tuple.Item2.BoolValue; } protected override async Task<bool> PerformActionAsync() { string environment = this.GetStringValueOrDefault(this.DeleteEnvironmentProperties.Environment, EBDefinedCommandOptions.ARGUMENT_EB_ENVIRONMENT, true); if (!this.ConfirmDeletion("Elastic Beanstalk environment " + environment)) return true; try { await this.EBClient.TerminateEnvironmentAsync(new TerminateEnvironmentRequest { EnvironmentName = environment }); this.Logger?.WriteLine("Environment {0} deleted", environment); } catch(Exception e) { throw new ElasticBeanstalkExceptions(string.Format("Error deleting environment {0}: {1}", environment, e.Message), ElasticBeanstalkExceptions.EBCode.FailedToDeleteEnvironment); } return true; } protected override void SaveConfigFile(JsonData data) { this.DeleteEnvironmentProperties.PersistSettings(this, data); } } }
89
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.ElasticBeanstalk.Model; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using ThirdParty.Json.LitJson; namespace Amazon.ElasticBeanstalk.Tools.Commands { public class DeployEnvironmentCommand : EBBaseCommand { public const string COMMAND_NAME = "deploy-environment"; public const string COMMAND_DESCRIPTION = "Deploy the application to an AWS Elastic Beanstalk environment."; public static readonly IList<CommandOption> CommandOptions = BuildLineOptions(new List<CommandOption> { CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, CommonDefinedCommandOptions.ARGUMENT_SELF_CONTAINED, CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS, EBDefinedCommandOptions.ARGUMENT_EB_APPLICATION, EBDefinedCommandOptions.ARGUMENT_EB_ENVIRONMENT, EBDefinedCommandOptions.ARGUMENT_EB_VERSION_LABEL, EBDefinedCommandOptions.ARGUMENT_EB_TAGS, EBDefinedCommandOptions.ARGUMENT_APP_PATH, EBDefinedCommandOptions.ARGUMENT_IIS_WEBSITE, EBDefinedCommandOptions.ARGUMENT_EB_ADDITIONAL_OPTIONS, EBDefinedCommandOptions.ARGUMENT_CNAME_PREFIX, EBDefinedCommandOptions.ARGUMENT_SOLUTION_STACK, EBDefinedCommandOptions.ARGUMENT_ENVIRONMENT_TYPE, EBDefinedCommandOptions.ARGUMENT_EC2_KEYPAIR, EBDefinedCommandOptions.ARGUMENT_INSTANCE_TYPE, EBDefinedCommandOptions.ARGUMENT_HEALTH_CHECK_URL, EBDefinedCommandOptions.ARGUMENT_ENABLE_XRAY, EBDefinedCommandOptions.ARGUMENT_ENHANCED_HEALTH_TYPE, EBDefinedCommandOptions.ARGUMENT_INSTANCE_PROFILE, EBDefinedCommandOptions.ARGUMENT_SERVICE_ROLE, EBDefinedCommandOptions.ARGUMENT_INPUT_PACKAGE, EBDefinedCommandOptions.ARGUMENT_LOADBALANCER_TYPE, EBDefinedCommandOptions.ARGUMENT_ENABLE_STICKY_SESSIONS, EBDefinedCommandOptions.ARGUMENT_PROXY_SERVER, EBDefinedCommandOptions.ARGUMENT_APPLICATION_PORT, EBDefinedCommandOptions.ARGUMENT_WAIT_FOR_UPDATE }); const string OPTIONS_NAMESPACE_ENVIRONMENT_PROXY = "aws:elasticbeanstalk:environment:proxy"; const string OPTIONS_NAMESPACE_APPLICATION_ENVIRONMENT = "aws:elasticbeanstalk:application:environment"; const string OPTIONS_NAME_PROXY_SERVER = "ProxyServer"; const string OPTIONS_NAME_APPLICATION_PORT = "PORT"; public string Package { get; set; } public DeployEnvironmentProperties DeployEnvironmentOptions { get; } = new DeployEnvironmentProperties(); public DeployEnvironmentCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, CommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); this.DeployEnvironmentOptions.ParseCommandArguments(values); Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_INPUT_PACKAGE.Switch)) != null) this.Package = tuple.Item2.StringValue; } protected override async Task<bool> PerformActionAsync() { string package = this.GetStringValueOrDefault(this.Package, EBDefinedCommandOptions.ARGUMENT_INPUT_PACKAGE, false); string application = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.Application, EBDefinedCommandOptions.ARGUMENT_EB_APPLICATION, true); string versionLabel = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.VersionLabel, EBDefinedCommandOptions.ARGUMENT_EB_VERSION_LABEL, false) ?? DateTime.Now.Ticks.ToString(); string environment = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.Environment, EBDefinedCommandOptions.ARGUMENT_EB_ENVIRONMENT, true); bool doesApplicationExist = await DoesApplicationExist(application); var environmentDescription = doesApplicationExist ? await GetEnvironmentDescription(application, environment) : null; bool isWindowsEnvironment; List<ConfigurationOptionSetting> existingSettings = null; if(environmentDescription != null) { isWindowsEnvironment = EBUtilities.IsSolutionStackWindows(environmentDescription.SolutionStackName); var response = await this.EBClient.DescribeConfigurationSettingsAsync(new DescribeConfigurationSettingsRequest { ApplicationName = environmentDescription.ApplicationName, EnvironmentName = environmentDescription.EnvironmentName }); if(response.ConfigurationSettings.Count != 1) { throw new ElasticBeanstalkExceptions($"Unknown error to retrieving settings for existing Beanstalk environment.", ElasticBeanstalkExceptions.EBCode.FailedToDescribeEnvironmentSettings); } existingSettings = response.ConfigurationSettings[0].OptionSettings; } else { isWindowsEnvironment = EBUtilities.IsSolutionStackWindows(this.GetSolutionStackOrDefault(this.DeployEnvironmentOptions.SolutionStack, EBDefinedCommandOptions.ARGUMENT_SOLUTION_STACK, true)); } await CreateEBApplicationIfNotExist(application, doesApplicationExist); string zipArchivePath = null; if (string.IsNullOrEmpty(package)) { this.EnsureInProjectDirectory(); var projectLocation = Utilities.DetermineProjectLocation(this.WorkingDirectory, this.GetStringValueOrDefault(this.ProjectLocation, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false)); string configuration = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false) ?? "Release"; string targetFramework = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false); if (string.IsNullOrEmpty(targetFramework)) { targetFramework = Utilities.LookupTargetFrameworkFromProjectFile(projectLocation); if (string.IsNullOrEmpty(targetFramework)) { targetFramework = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, true); } } var dotnetCli = new DotNetCLIWrapper(this.Logger, projectLocation); var publishLocation = Utilities.DeterminePublishLocation(null, projectLocation, configuration, targetFramework); this.Logger?.WriteLine("Determine publish location: " + publishLocation); var publishOptions = GetPublishOptions(isWindowsEnvironment); this.Logger?.WriteLine("Executing publish command"); if (dotnetCli.Publish(projectLocation, publishLocation, targetFramework, configuration, publishOptions) != 0) { throw new ElasticBeanstalkExceptions("Error executing \"dotnet publish\"", ElasticBeanstalkExceptions.CommonErrorCode.DotnetPublishFailed); } if(isWindowsEnvironment) { this.Logger?.WriteLine("Configuring application bundle for a Windows deployment"); EBUtilities.SetupAWSDeploymentManifest(this.Logger, this, this.DeployEnvironmentOptions, publishLocation); } else { var proxyServer = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.ProxyServer, EBDefinedCommandOptions.ARGUMENT_PROXY_SERVER, false); if(string.IsNullOrEmpty(proxyServer)) { proxyServer = existingSettings.FindExistingValue(OPTIONS_NAMESPACE_ENVIRONMENT_PROXY, OPTIONS_NAMESPACE_APPLICATION_ENVIRONMENT); } var applicationPort = this.GetIntValueOrDefault(this.DeployEnvironmentOptions.ApplicationPort, EBDefinedCommandOptions.ARGUMENT_APPLICATION_PORT, false); if(!applicationPort.HasValue) { var strPort = existingSettings.FindExistingValue(OPTIONS_NAMESPACE_APPLICATION_ENVIRONMENT, OPTIONS_NAME_APPLICATION_PORT); int intPort; if(int.TryParse(strPort, NumberStyles.Any, CultureInfo.InvariantCulture, out intPort)) { applicationPort = intPort; } } this.Logger?.WriteLine("Configuring application bundle for a Linux deployment"); EBUtilities.SetupPackageForLinux(this.Logger, this, this.DeployEnvironmentOptions, publishLocation, proxyServer, applicationPort); } zipArchivePath = Path.Combine(Directory.GetParent(publishLocation).FullName, new DirectoryInfo(projectLocation).Name + "-" + DateTime.Now.Ticks + ".zip"); this.Logger?.WriteLine("Zipping up publish folder"); Utilities.ZipDirectory(this.Logger, publishLocation, zipArchivePath); this.Logger?.WriteLine("Zip archive created: " + zipArchivePath); } else { if (!File.Exists(package)) throw new ElasticBeanstalkExceptions($"Package {package} does not exist", ElasticBeanstalkExceptions.EBCode.InvalidPackage); if (!string.Equals(Path.GetExtension(package), ".zip", StringComparison.OrdinalIgnoreCase)) throw new ElasticBeanstalkExceptions($"Package {package} must be a zip file", ElasticBeanstalkExceptions.EBCode.InvalidPackage); this.Logger?.WriteLine($"Skipping compilation and using precompiled package {package}"); zipArchivePath = package; } S3Location s3Loc; try { s3Loc = await this.UploadDeploymentPackageAsync(application, versionLabel, zipArchivePath).ConfigureAwait(false); } catch (Exception e) { throw new ElasticBeanstalkExceptions("Error uploading application bundle to S3: " + e.Message, ElasticBeanstalkExceptions.EBCode.FailedToUploadBundle); } try { this.Logger?.WriteLine("Creating new application version: " + versionLabel); await this.EBClient.CreateApplicationVersionAsync(new CreateApplicationVersionRequest { ApplicationName = application, VersionLabel = versionLabel, SourceBundle = s3Loc }).ConfigureAwait(false); } catch(Exception e) { throw new ElasticBeanstalkExceptions("Error creating Elastic Beanstalk application version: " + e.Message, ElasticBeanstalkExceptions.EBCode.FailedCreateApplicationVersion); } this.Logger?.WriteLine("Getting latest environment event date before update"); var startingEventDate = await GetLatestEventDateAsync(application, environment); string environmentArn; if(environmentDescription != null) { environmentArn = await UpdateEnvironment(environmentDescription, versionLabel); } else { environmentArn = await CreateEnvironment(application, environment, versionLabel, isWindowsEnvironment); } bool? waitForUpdate = this.GetBoolValueOrDefault(this.DeployEnvironmentOptions.WaitForUpdate, EBDefinedCommandOptions.ARGUMENT_WAIT_FOR_UPDATE, false); if(!waitForUpdate.HasValue || waitForUpdate.Value) { this.Logger?.WriteLine("Waiting for environment update to complete"); var success = await this.WaitForDeploymentCompletionAsync(application, environment, startingEventDate); if (success) this.Logger?.WriteLine("Update Complete"); else throw new ElasticBeanstalkExceptions("Environment update failed", ElasticBeanstalkExceptions.EBCode.FailedEnvironmentUpdate); } else { this.Logger?.WriteLine("Environment update initiated"); } if (environmentDescription != null) { var tags = ConvertToTagsCollection(); if (tags != null && tags.Count > 0) { var updateTagsRequest = new UpdateTagsForResourceRequest { ResourceArn = environmentArn, TagsToAdd = tags }; this.Logger?.WriteLine("Updating Tags on environment"); try { await this.EBClient.UpdateTagsForResourceAsync(updateTagsRequest); } catch(Exception e) { throw new ElasticBeanstalkExceptions("Error updating tags for environment: " + e.Message, ElasticBeanstalkExceptions.EBCode.FailedToUpdateTags); } } } return true; } public string GetPublishOptions(bool isWindowsEnvironment) { var initialOptions = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.PublishOptions, CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS, false); var selfContained = this.GetBoolValueOrDefault(this.DeployEnvironmentOptions.SelfContained, CommonDefinedCommandOptions.ARGUMENT_SELF_CONTAINED, false) ?? false; return new PublishOptions(initialOptions, isWindowsEnvironment, selfContained).ToCliString(); } private async Task CreateEBApplicationIfNotExist(string application, bool doesApplicationExist) { if (!doesApplicationExist) { try { this.Logger?.WriteLine("Creating new Elastic Beanstalk Application"); await this.EBClient.CreateApplicationAsync(new CreateApplicationRequest { ApplicationName = application }); } catch (Exception e) { throw new ElasticBeanstalkExceptions("Error creating Elastic Beanstalk application: " + e.Message, ElasticBeanstalkExceptions.EBCode.FailedCreateApplication); } } } private List<Tag> ConvertToTagsCollection() { var tags = this.GetKeyValuePairOrDefault(this.DeployEnvironmentOptions.Tags, EBDefinedCommandOptions.ARGUMENT_EB_TAGS, false); if (tags == null || tags.Count == 0) return null; var collection = new List<Tag>(); foreach(var kvp in tags) { collection.Add(new Tag { Key = kvp.Key, Value = kvp.Value }); } return collection; } private async Task<string> CreateEnvironment(string application, string environment, string versionLabel, bool isWindowsEnvironment) { var createRequest = new CreateEnvironmentRequest { ApplicationName = application, EnvironmentName = environment, VersionLabel = versionLabel, SolutionStackName = this.GetSolutionStackOrDefault(this.DeployEnvironmentOptions.SolutionStack, EBDefinedCommandOptions.ARGUMENT_SOLUTION_STACK, true), CNAMEPrefix = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.CNamePrefix, EBDefinedCommandOptions.ARGUMENT_CNAME_PREFIX, false) }; string environmentType, loadBalancerType; DetermineEnvironment(out environmentType, out loadBalancerType); if (!string.IsNullOrEmpty(environmentType)) { createRequest.OptionSettings.Add(new ConfigurationOptionSetting() { Namespace = "aws:elasticbeanstalk:environment", OptionName = "EnvironmentType", Value = environmentType }); } var ec2KeyPair = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.EC2KeyPair, EBDefinedCommandOptions.ARGUMENT_EC2_KEYPAIR, false); if (!string.IsNullOrEmpty(ec2KeyPair)) { createRequest.OptionSettings.Add(new ConfigurationOptionSetting() { Namespace = "aws:autoscaling:launchconfiguration", OptionName = "EC2KeyName", Value = ec2KeyPair }); } var instanceType = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.InstanceType, EBDefinedCommandOptions.ARGUMENT_INSTANCE_TYPE, false); if (string.IsNullOrEmpty(instanceType)) { instanceType = isWindowsEnvironment ? EBConstants.DEFAULT_WINDOWS_INSTANCE_TYPE : EBConstants.DEFAULT_LINUX_INSTANCE_TYPE; } createRequest.OptionSettings.Add(new ConfigurationOptionSetting() { Namespace = "aws:autoscaling:launchconfiguration", OptionName = "InstanceType", Value = instanceType }); var instanceProfile = this.GetInstanceProfileOrDefault(this.DeployEnvironmentOptions.InstanceProfile, EBDefinedCommandOptions.ARGUMENT_INSTANCE_PROFILE, true, string.Format("eb_{0}_{1}", application, environment)); if (!string.IsNullOrEmpty(instanceProfile)) { int pos = instanceProfile.LastIndexOf('/'); if (pos != -1) { instanceProfile = instanceProfile.Substring(pos + 1); } createRequest.OptionSettings.Add(new ConfigurationOptionSetting() { Namespace = "aws:autoscaling:launchconfiguration", OptionName = "IamInstanceProfile", Value = instanceProfile }); } var serviceRole = this.GetServiceRoleOrCreateIt(this.DeployEnvironmentOptions.ServiceRole, EBDefinedCommandOptions.ARGUMENT_SERVICE_ROLE, "aws-elasticbeanstalk-service-role", Constants.ELASTICBEANSTALK_ASSUME_ROLE_POLICY, null, "AWSElasticBeanstalkManagedUpdatesCustomerRolePolicy", "AWSElasticBeanstalkEnhancedHealth"); if (!string.IsNullOrEmpty(serviceRole)) { int pos = serviceRole.LastIndexOf('/'); if(pos != -1) { serviceRole = serviceRole.Substring(pos + 1); } createRequest.OptionSettings.Add(new ConfigurationOptionSetting() { Namespace = "aws:elasticbeanstalk:environment", OptionName = "ServiceRole", Value = serviceRole }); } if (!string.IsNullOrWhiteSpace(loadBalancerType)) { if (!EBConstants.ValidLoadBalancerType.Contains(loadBalancerType)) throw new ElasticBeanstalkExceptions($"The loadbalancer type {loadBalancerType} is invalid. Valid values are: {string.Join(", ", EBConstants.ValidLoadBalancerType)}", ElasticBeanstalkExceptions.EBCode.InvalidLoadBalancerType); createRequest.OptionSettings.Add(new ConfigurationOptionSetting() { Namespace = "aws:elasticbeanstalk:environment", OptionName = "LoadBalancerType", Value = loadBalancerType }); } AddAdditionalOptions(createRequest.OptionSettings, true, isWindowsEnvironment); var tags = ConvertToTagsCollection(); if (tags != null && tags.Count > 0) createRequest.Tags = tags; try { var createResponse = await this.EBClient.CreateEnvironmentAsync(createRequest); return createResponse.EnvironmentArn; } catch (Exception e) { throw new ElasticBeanstalkExceptions("Error creating environment: " + e.Message, ElasticBeanstalkExceptions.EBCode.FailedToCreateEnvironment); } } private void AddAdditionalOptions(IList<ConfigurationOptionSetting> settings, bool createEnvironmentMode, bool isWindowsEnvironment) { var additionalOptions = this.GetKeyValuePairOrDefault(this.DeployEnvironmentOptions.AdditionalOptions, EBDefinedCommandOptions.ARGUMENT_EB_ADDITIONAL_OPTIONS, false); if (additionalOptions != null && additionalOptions.Count > 0) { foreach (var kvp in additionalOptions) { var tokens = kvp.Key.Split(','); if (tokens.Length != 2) { throw new ToolsException("Additional option \"" + kvp.Key + "=" + kvp.Value + "\" in incorrect format. Format should be <option-namespace>,<option-name>=<option-value>.", ToolsException.CommonErrorCode.DefaultsParseFail); } settings.Add(new ConfigurationOptionSetting { Namespace = tokens[0], OptionName = tokens[1], Value = kvp.Value }); } } var enableXRay = this.GetBoolValueOrDefault(this.DeployEnvironmentOptions.EnableXRay, EBDefinedCommandOptions.ARGUMENT_ENABLE_XRAY, false); if(enableXRay.HasValue) { settings.Add(new ConfigurationOptionSetting() { Namespace = "aws:elasticbeanstalk:xray", OptionName = "XRayEnabled", Value = enableXRay.Value.ToString(CultureInfo.InvariantCulture).ToLowerInvariant() }); this.Logger?.WriteLine($"Enable AWS X-Ray: {enableXRay.Value}"); } var enhancedHealthType = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.EnhancedHealthType, EBDefinedCommandOptions.ARGUMENT_ENHANCED_HEALTH_TYPE, false); if(!string.IsNullOrWhiteSpace(enhancedHealthType)) { if (!EBConstants.ValidEnhanceHealthType.Contains(enhancedHealthType)) throw new ElasticBeanstalkExceptions($"The enhanced value type {enhancedHealthType} is invalid. Valid values are: {string.Join(", ", EBConstants.ValidEnhanceHealthType)}", ElasticBeanstalkExceptions.EBCode.InvalidEnhancedHealthType); settings.Add(new ConfigurationOptionSetting() { Namespace = "aws:elasticbeanstalk:healthreporting:system", OptionName = "SystemType", Value = enhancedHealthType }); } string environmentType, loadBalancerType; DetermineEnvironment(out environmentType, out loadBalancerType); var healthCheckURL = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.HealthCheckUrl, EBDefinedCommandOptions.ARGUMENT_HEALTH_CHECK_URL, false); // If creating a new load balanced environment then a heath check url must be set. if (createEnvironmentMode && string.IsNullOrEmpty(healthCheckURL) && EBUtilities.IsLoadBalancedEnvironmentType(environmentType)) { healthCheckURL = "/"; } if (!string.IsNullOrEmpty(healthCheckURL)) { settings.Add(new ConfigurationOptionSetting() { Namespace = "aws:elasticbeanstalk:application", OptionName = "Application Healthcheck URL", Value = healthCheckURL }); if (EBUtilities.IsLoadBalancedEnvironmentType(environmentType) && string.Equals(loadBalancerType, EBConstants.LOADBALANCER_TYPE_APPLICATION)) { settings.Add(new ConfigurationOptionSetting() { Namespace = "aws:elasticbeanstalk:environment:process:default", OptionName = "HealthCheckPath", Value = healthCheckURL }); } } if(!isWindowsEnvironment) { var proxyServer = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.ProxyServer, EBDefinedCommandOptions.ARGUMENT_PROXY_SERVER, false); if (!string.IsNullOrEmpty(proxyServer)) { if (!EBConstants.ValidProxyServer.Contains(proxyServer)) throw new ElasticBeanstalkExceptions($"The proxy server {proxyServer} is invalid. Valid values are: {string.Join(", ", EBConstants.ValidProxyServer)}", ElasticBeanstalkExceptions.EBCode.InvalidProxyServer); Logger?.WriteLine($"Configuring reverse proxy to {proxyServer}"); settings.Add(new ConfigurationOptionSetting() { Namespace = OPTIONS_NAMESPACE_ENVIRONMENT_PROXY, OptionName = OPTIONS_NAME_PROXY_SERVER, Value = proxyServer }); } var applicationPort = this.GetIntValueOrDefault(this.DeployEnvironmentOptions.ApplicationPort, EBDefinedCommandOptions.ARGUMENT_APPLICATION_PORT, false); if (applicationPort.HasValue) { Logger?.WriteLine($"Application port to {applicationPort}"); settings.Add(new ConfigurationOptionSetting() { Namespace = OPTIONS_NAMESPACE_APPLICATION_ENVIRONMENT, OptionName = OPTIONS_NAME_APPLICATION_PORT, Value = applicationPort.Value.ToString(CultureInfo.InvariantCulture) }); } } var enableStickySessions = this.GetBoolValueOrDefault(this.DeployEnvironmentOptions.EnableStickySessions, EBDefinedCommandOptions.ARGUMENT_ENABLE_STICKY_SESSIONS, false); if (enableStickySessions.HasValue) { if(enableStickySessions.Value) { Logger?.WriteLine($"Enabling sticky sessions"); } settings.Add(new ConfigurationOptionSetting() { Namespace = "aws:elasticbeanstalk:environment:process:default", OptionName = "StickinessEnabled", Value = enableStickySessions.Value.ToString(CultureInfo.InvariantCulture).ToLowerInvariant() }); } } private async Task<string> UpdateEnvironment(EnvironmentDescription environmentDescription, string versionLabel) { this.Logger?.WriteLine("Updating environment {0} to new application version", environmentDescription.EnvironmentName); var updateRequest = new UpdateEnvironmentRequest { ApplicationName = environmentDescription.ApplicationName, EnvironmentName = environmentDescription.EnvironmentName, VersionLabel = versionLabel }; AddAdditionalOptions(updateRequest.OptionSettings, false, EBUtilities.IsSolutionStackWindows(environmentDescription.SolutionStackName)); try { var updateEnvironmentResponse = await this.EBClient.UpdateEnvironmentAsync(updateRequest); return updateEnvironmentResponse.EnvironmentArn; } catch(Exception e) { throw new ElasticBeanstalkExceptions("Error updating environment: " + e.Message, ElasticBeanstalkExceptions.EBCode.FailedToUpdateEnvironment); } } private void DetermineEnvironment(out string environmentType, out string loadBalancerType) { environmentType = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.EnvironmentType, EBDefinedCommandOptions.ARGUMENT_ENVIRONMENT_TYPE, false); loadBalancerType = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.LoadBalancerType, EBDefinedCommandOptions.ARGUMENT_LOADBALANCER_TYPE, false); if (string.IsNullOrWhiteSpace(environmentType)) { environmentType = string.IsNullOrWhiteSpace(loadBalancerType) ? EBConstants.ENVIRONMENT_TYPE_SINGLEINSTANCE : EBConstants.ENVIRONMENT_TYPE_LOADBALANCED; } if (string.IsNullOrWhiteSpace(loadBalancerType) && EBUtilities.IsLoadBalancedEnvironmentType(environmentType)) { loadBalancerType = EBConstants.LOADBALANCER_TYPE_APPLICATION; } } private async Task<bool> DoesApplicationExist(string applicationName) { var request = new DescribeApplicationsRequest(); request.ApplicationNames.Add(applicationName); var response = await this.EBClient.DescribeApplicationsAsync(request); return response.Applications.Count == 1; } private async Task<EnvironmentDescription> GetEnvironmentDescription(string applicationName, string environmentName) { var request = new DescribeEnvironmentsRequest { ApplicationName = applicationName }; request.EnvironmentNames.Add(environmentName); var response = await this.EBClient.DescribeEnvironmentsAsync(request); if (response.Environments.Where(x => x.Status != EnvironmentStatus.Terminated && x.Status != EnvironmentStatus.Terminating).Count() != 1) return null; var environment = response.Environments[0]; if (environment.Status == EnvironmentStatus.Terminated || environment.Status == EnvironmentStatus.Terminating) return null; return environment; } private async Task<bool> WaitForDeploymentCompletionAsync(string applicationName, string environmentName, DateTime startingEventDate) { var requestEnvironment = new DescribeEnvironmentsRequest { ApplicationName = applicationName, EnvironmentNames = new List<string> { environmentName } }; var requestEvents = new DescribeEventsRequest { ApplicationName = applicationName, EnvironmentName = environmentName, StartTimeUtc = startingEventDate }; var success = true; var lastPrintedEventDate = startingEventDate; EnvironmentDescription environment = new EnvironmentDescription(); do { Thread.Sleep(5000); var responseEnvironments = await this.EBClient.DescribeEnvironmentsAsync(requestEnvironment); if (responseEnvironments.Environments.Count == 0) throw new ElasticBeanstalkExceptions("Failed to find environment when waiting for deployment completion", ElasticBeanstalkExceptions.EBCode.FailedToFindEnvironment ); environment = responseEnvironments.Environments[0]; requestEvents.StartTimeUtc = lastPrintedEventDate; var responseEvents = await this.EBClient.DescribeEventsAsync(requestEvents); if(responseEvents.Events.Count > 0) { for(int i = responseEvents.Events.Count - 1; i >= 0; i--) { var evnt = responseEvents.Events[i]; if (evnt.EventDate <= lastPrintedEventDate) continue; this.Logger?.WriteLine(evnt.EventDate.ToLocalTime() + " " + evnt.Severity + " " + evnt.Message); if(evnt.Message.StartsWith("Failed to deploy application", StringComparison.OrdinalIgnoreCase) || evnt.Message.StartsWith("Failed to launch environment", StringComparison.OrdinalIgnoreCase) || evnt.Message.StartsWith("Error occurred during build: Command hooks failed", StringComparison.OrdinalIgnoreCase)) { success = false; } } lastPrintedEventDate = responseEvents.Events[0].EventDate; } } while (environment.Status == EnvironmentStatus.Launching || environment.Status == EnvironmentStatus.Updating); if(success) { this.Logger?.WriteLine("Environment update complete: http://{0}/", environment.EndpointURL); } return success; } private async Task<DateTime> GetLatestEventDateAsync(string application, string environment) { var request = new DescribeEventsRequest { ApplicationName = application, EnvironmentName = environment }; var response = await this.EBClient.DescribeEventsAsync(request); if (response.Events.Count == 0) return DateTime.Now; return response.Events[0].EventDate; } private async Task<S3Location> UploadDeploymentPackageAsync(string application, string versionLabel, string deploymentPackage) { var bucketName = (await this.EBClient.CreateStorageLocationAsync()).S3Bucket; // can't use deploymentPackage directly as vs2008/vs2010 pass different names (vs08 already has version in it), // so synthesize one string key = string.Format("{0}/AWSDeploymentArchive_{0}_{1}{2}", application.Replace(' ', '-'), versionLabel.Replace(' ', '-'), Path.GetExtension(deploymentPackage)); var fileInfo = new FileInfo(deploymentPackage); if (!(await Utilities.EnsureBucketExistsAsync(this.Logger, this.S3Client, bucketName))) throw new ElasticBeanstalkExceptions("Detected error in deployment bucket preparation; abandoning deployment", ElasticBeanstalkExceptions.EBCode.EnsureBucketExistsError ); this.Logger?.WriteLine("... Uploading from file path {0}, size {1} bytes to Amazon S3", deploymentPackage, fileInfo.Length); using (var stream = File.OpenRead(deploymentPackage)) { await Utilities.UploadToS3Async(this.Logger, this.S3Client, bucketName, key, stream); } return new S3Location() { S3Bucket = bucketName, S3Key = key }; } protected override void SaveConfigFile(JsonData data) { this.DeployEnvironmentOptions.PersistSettings(this, data); } } }
735
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Amazon.Common.DotNetCli.Tools.Commands; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using System.Threading.Tasks; namespace Amazon.ElasticBeanstalk.Tools.Commands { public abstract class EBBaseCommand : BaseCommand<ElasticBeanstalkToolsDefaults> { public EBBaseCommand(IToolLogger logger, string workingDirectory) : base(logger, workingDirectory) { } public EBBaseCommand(IToolLogger logger, string workingDirectory, IList<CommandOption> possibleOptions, string[] args) : base(logger, workingDirectory, possibleOptions, args) { } protected override string ToolName => "AWSElasticBeanstalkToolsDotnet"; IAmazonElasticBeanstalk _ebClient; public IAmazonElasticBeanstalk EBClient { get { if (this._ebClient == null) { SetUserAgentString(); var config = new AmazonElasticBeanstalkConfig(); config.RegionEndpoint = DetermineAWSRegion(); this._ebClient = new AmazonElasticBeanstalkClient(DetermineAWSCredentials(), config); } return this._ebClient; } set { this._ebClient = value; } } public string GetSolutionStackOrDefault(string propertyValue, CommandOption option, bool required) { var value = GetStringValueOrDefault(propertyValue, option, false); if (!string.IsNullOrEmpty(value)) { return value; } else if (required && !this.DisableInteractive) { var solutionStacks = FindSolutionStacksAsync().Result; int chosenOption = PromptForValue(option, solutionStacks); var solutionStack = solutionStacks[chosenOption]; if(!string.IsNullOrEmpty(solutionStack)) { _cachedRequestedValues[option] = solutionStack; } return solutionStack; } if (required) { throw new ToolsException($"Missing required parameter: {option.Switch}", ToolsException.CommonErrorCode.MissingRequiredParameter); } return null; } public async Task<IList<string>> FindSolutionStacksAsync() { var solutionStacks = new List<string>(); var allSolutionStacks = (await this.EBClient.ListAvailableSolutionStacksAsync()).SolutionStacks; foreach (var stack in allSolutionStacks.OrderByDescending(x => x)) { if (EBUtilities.IsSolutionStackWindows(stack) || EBUtilities.IsSolutionStackLinuxNETCore(stack)) solutionStacks.Add(stack); } return FilterSolutionStackToLatestVersion(solutionStacks); } private static SolutionStackNameProperties ParseSolutionStackName(string solutionStackName) { Version version = null; var tokens = solutionStackName.Split(' '); var familyName = new StringBuilder(); foreach (var token in tokens) { if (token.StartsWith("v") && char.IsNumber(token[1])) { Version.TryParse(token.Substring(1), out version); } else { familyName.Append(token + " "); } } if (version == null) { return new SolutionStackNameProperties { FamilyName = solutionStackName, FullName = solutionStackName }; } return new SolutionStackNameProperties { FamilyName = familyName.ToString().TrimEnd(), FullName = solutionStackName, Version = version }; } public static IList<string> FilterSolutionStackToLatestVersion(IList<string> allSolutionStacks) { var latestVersions = new Dictionary<string, SolutionStackNameProperties>(); foreach(var solutionStackName in allSolutionStacks) { var properties = ParseSolutionStackName(solutionStackName); if(properties.Version == null) { latestVersions[properties.FamilyName] = properties; } else if(latestVersions.TryGetValue(properties.FamilyName, out var current)) { if(current.Version < properties.Version) { latestVersions[properties.FamilyName] = properties; } } else { latestVersions[properties.FamilyName] = properties; } } var filterList = latestVersions.Values.Select(x => x.FullName).OrderBy(x => x).ToList(); return filterList; } class SolutionStackNameProperties { public string FamilyName { get; set; } public string FullName { get; set; } public Version Version { get; set; } } } }
152
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.ElasticBeanstalk.Model; using System; using System.Collections.Generic; using System.Threading.Tasks; using ThirdParty.Json.LitJson; namespace Amazon.ElasticBeanstalk.Tools.Commands { public class ListEnvironmentsCommand : EBBaseCommand { public const string COMMAND_NAME = "list-environments"; public const string COMMAND_DESCRIPTION = "List the AWS Elastic Beanstalk environments."; public static readonly IList<CommandOption> CommandOptions = BuildLineOptions(new List<CommandOption> { CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION }); public ListEnvironmentsCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, CommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); } protected override async Task<bool> PerformActionAsync() { try { var response = new DescribeEnvironmentsResponse(); do { response = await this.EBClient.DescribeEnvironmentsAsync(new DescribeEnvironmentsRequest { NextToken = response.NextToken }); foreach(var environment in response.Environments) { if (environment.Status == EnvironmentStatus.Terminated) continue; this.Logger?.WriteLine((environment.EnvironmentName + " (" + environment.Status + "/" + environment.Health + ")").PadRight(45) + " http://" + (environment.CNAME ?? environment.EndpointURL) + "/"); } } while (!string.IsNullOrEmpty(response.NextToken)); } catch (Exception e) { throw new ElasticBeanstalkExceptions(string.Format("Error listing environments: {0}", e.Message), ElasticBeanstalkExceptions.EBCode.FailedToDeleteEnvironment); } return true; } protected override void SaveConfigFile(JsonData data) { } } }
72
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using ThirdParty.Json.LitJson; namespace Amazon.ElasticBeanstalk.Tools.Commands { public class PackageCommand : EBBaseCommand { public const string COMMAND_NAME = "package"; public const string COMMAND_DESCRIPTION = "Package the application to a zip file to be deployed later to an Elastic Beanstalk environment"; public static readonly IList<CommandOption> CommandOptions = BuildLineOptions(new List<CommandOption> { CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS, EBDefinedCommandOptions.ARGUMENT_APP_PATH, EBDefinedCommandOptions.ARGUMENT_IIS_WEBSITE, EBDefinedCommandOptions.ARGUMENT_OUTPUT_PACKAGE }); public string OutputPackageFileName { get; set; } public DeployEnvironmentProperties DeployEnvironmentOptions { get; } = new DeployEnvironmentProperties(); public PackageCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, CommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); this.DeployEnvironmentOptions.ParseCommandArguments(values); Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(EBDefinedCommandOptions.ARGUMENT_OUTPUT_PACKAGE.Switch)) != null) this.OutputPackageFileName = tuple.Item2.StringValue; } protected override Task<bool> PerformActionAsync() { this.EnsureInProjectDirectory(); var projectLocation = Utilities.DetermineProjectLocation(this.WorkingDirectory, this.GetStringValueOrDefault(this.ProjectLocation, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false)); string configuration = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false) ?? "Release"; string targetFramework = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false); string publishOptions = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.PublishOptions, CommonDefinedCommandOptions.ARGUMENT_PUBLISH_OPTIONS, false); if (string.IsNullOrEmpty(targetFramework)) { targetFramework = Utilities.LookupTargetFrameworkFromProjectFile(projectLocation); if (string.IsNullOrEmpty(targetFramework)) { targetFramework = this.GetStringValueOrDefault(this.DeployEnvironmentOptions.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, true); } } var dotnetCli = new DotNetCLIWrapper(this.Logger, projectLocation); var publishLocation = Utilities.DeterminePublishLocation(null, projectLocation, configuration, targetFramework); this.Logger?.WriteLine("Determine publish location: " + publishLocation); this.Logger?.WriteLine("Executing publish command"); if (dotnetCli.Publish(projectLocation, publishLocation, targetFramework, configuration, publishOptions) != 0) { throw new ElasticBeanstalkExceptions("Error executing \"dotnet publish\"", ElasticBeanstalkExceptions.CommonErrorCode.DotnetPublishFailed); } EBUtilities.SetupAWSDeploymentManifest(this.Logger, this, this.DeployEnvironmentOptions, publishLocation); string package = this.GetStringValueOrDefault(this.OutputPackageFileName, EBDefinedCommandOptions.ARGUMENT_OUTPUT_PACKAGE, false); string zipArchivePath = null; if (!string.IsNullOrWhiteSpace(package)) { zipArchivePath = package; } else { zipArchivePath = Path.Combine(Directory.GetParent(publishLocation).FullName, new DirectoryInfo(projectLocation).Name + "-" + DateTime.Now.Ticks + ".zip"); } this.Logger?.WriteLine("Zipping up publish folder"); Utilities.ZipDirectory(this.Logger, publishLocation, zipArchivePath); this.Logger?.WriteLine("Zip archive created: " + zipArchivePath); return Task.FromResult(true); } protected override void SaveConfigFile(JsonData data) { this.DeployEnvironmentOptions.PersistSettings(this, data); data.SetIfNotNull(EBDefinedCommandOptions.ARGUMENT_OUTPUT_PACKAGE.ConfigFileKey, this.GetStringValueOrDefault(this.OutputPackageFileName, EBDefinedCommandOptions.ARGUMENT_OUTPUT_PACKAGE, false)); } } }
114
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Runtime; namespace Amazon.Lambda.Tools { /// <summary> /// The deploy tool exception. This is used to throw back an error to the user but is considerd a known error /// so the stack trace will not be displayed. /// </summary> public class LambdaToolsException : ToolsException { public enum LambdaErrorCode { CloudFormationCreateChangeSet, CloudFormationCreateStack, CloudFormationDeleteStack, CloudFormationDescribeChangeSet, CloudFormationDescribeStack, CloudFormationDescribeStackEvents, InvalidCloudFormationStackState, FailedToCreateChangeSet, FailedLambdaCreateOrUpdate, InvalidPackage, FrameworkNewerThanRuntime, AspNetCoreAllValidation, IAMAttachRole, IAMCreateRole, IAMGetRole, LambdaFunctionUrlGet, LambdaFunctionUrlCreate, LambdaFunctionUrlUpdate, LambdaFunctionUrlDelete, LambdaCreateFunction, LambdaDeleteFunction, LambdaGetConfiguration, LambdaInvokeFunction, LambdaListFunctions, LambdaUpdateFunctionCode, LambdaUpdateFunctionConfiguration, LambdaPublishFunction, LambdaTaggingFunction, LambdaPublishLayerVersion, LambdaListLayers, LambdaListLayerVersions, LambdaGetLayerVersionDetails, LambdaDeleteLayerVersion, ParseLayerVersionArnFail, LambdaWaitTillFunctionAvailable, UnknownLayerType, StoreCommandError, FailedToFindArtifactZip, LayerPackageManifestNotFound, UnsupportedOptimizationPlatform, ServerlessTemplateNotFound, ServerlessTemplateParseError, ServerlessTemplateMissingResourceSection, ServerlessTemplateSubstitutionError, ServerlessTemplateMissingLocalPath, ServerlessTemplateUnknownActionForLocalPath, WaitingForStackError, FailedToFindZipProgram, FailedToDetectSdkVersion, LayerNetSdkVersionMismatch, FailedToResolveS3Bucket, DisabledSupportForNET31Layers, InvalidNativeAotTargetFramework, Net7OnArmNotSupported, InvalidArchitectureProvided, UnsupportedDefaultContainerBuild, NativeAotOutputTypeError, MismatchedNativeAotArchitectures, ContainerBuildFailed, FailedToPushImage } public LambdaToolsException(string message, LambdaErrorCode code) : base(message, code.ToString(), null) { } public LambdaToolsException(string message, CommonErrorCode code) : base(message, code.ToString(), null) { } public LambdaToolsException(string message, LambdaErrorCode code, Exception e) : base(message, code.ToString(), e) { } public LambdaToolsException(string message, CommonErrorCode code, Exception e) : base(message, code.ToString(), e) { } } }
110
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Amazon.Lambda.Tools { internal enum TemplateFormat { Json, Yaml } public static class LambdaConstants { public const string TOOLNAME = "AWSLambdaToolsDotnet"; public const string ENV_DOTNET_SHARED_STORE = "DOTNET_SHARED_STORE"; public const string LAYER_TYPE_RUNTIME_PACKAGE_STORE_DISPLAY_NAME = ".NET Runtime Package Store"; public const string LAYER_TYPE_RUNTIME_PACKAGE_STORE = "runtime-package-store"; public const string LAYER_TYPE_ALLOWED_VALUES = LAYER_TYPE_RUNTIME_PACKAGE_STORE; public const string DEFAULT_LAYER_OPT_DIRECTORY = "dotnetcore/store"; public static readonly Version MINIMUM_DOTNET_SDK_VERSION_FOR_ASPNET_LAYERS = new Version("2.2.100"); public const string ENV_DOTNET_LAMBDA_CLI_LOCAL_MANIFEST_OVERRIDE = "DOTNET_LAMBDA_CLI_LOCAL_MANIFEST_OVERRIDE"; public const string IAM_ARN_PREFIX = "arn:aws:iam::"; public const string AWS_MANAGED_POLICY_ARN_PREFIX = "arn:aws:iam::aws:policy"; public const string SERVERLESS_TAG_NAME = "AWSServerlessAppNETCore"; public const int MAX_TEMPLATE_BODY_IN_REQUEST_SIZE = 50000; public const string DEFAULT_BUILD_CONFIGURATION = "Release"; // The .NET Core 1.0 version of the runtime hierarchies for .NET Core taken from the corefx repository // https://github.com/dotnet/corefx/blob/release/1.0.0/pkg/Microsoft.NETCore.Platforms/runtime.json internal const string RUNTIME_HIERARCHY = "netcore.runtime.hierarchy.json"; internal const string PRUNE_LIST_SDK_XML = "publish-layer-31sdk-prunelist.xml"; internal const string PRUNE_LIST_SDKWEB_XML = "publish-layer-31sdkweb-prunelist.xml"; // The runtime identifier used for older Lambda runtimes running on Amazon Linux 1. internal const string LEGACY_RUNTIME_HIERARCHY_STARTING_POINT = "rhel.7.2-x64"; public const string RUNTIME_LINUX_X64 = "linux-x64"; public const string RUNTIME_LINUX_ARM64 = "linux-arm64"; public const string ARCHITECTURE_X86_64 = "x86_64"; public const string ARCHITECTURE_ARM64 = "arm64"; public const string DEFAULT_BUCKET_NAME_PREFIX = "aws-dotnet-lambda-tools-"; // This is the same value the console is using. public const string FUNCTION_URL_PUBLIC_PERMISSION_STATEMENT_ID = "FunctionURLAllowPublicAccess"; public const string AWS_LAMBDA_MANAGED_POLICY_PREFIX = "AWSLambda"; public static readonly Dictionary<string, string> KNOWN_MANAGED_POLICY_DESCRIPTIONS = new Dictionary<string, string> { {"arn:aws:iam::aws:policy/PowerUserAccess","Provides full access to AWS services and resources, but does not allow management of users and groups."}, {"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole","Provides write permissions to CloudWatch Logs."}, {"arn:aws:iam::aws:policy/service-role/AWSLambdaDynamoDBExecutionRole","Provides list and read access to DynamoDB streams and write permissions to CloudWatch Logs."}, {"arn:aws:iam::aws:policy/AWSLambdaExecute","Provides Put, Get access to S3 and full access to CloudWatch Logs."}, {"arn:aws:iam::aws:policy/AWSLambdaInvocation-DynamoDB","Provides read access to DynamoDB Streams."}, {"arn:aws:iam::aws:policy/service-role/AWSLambdaKinesisExecutionRole","Provides list and read access to Kinesis streams and write permissions to CloudWatch Logs."}, {"arn:aws:iam::aws:policy/service-role/AWSLambdaRole","Default policy for AWS Lambda service role."}, {"arn:aws:iam::aws:policy/service-role/AWSLambdaSQSQueueExecutionRole","Provides receive message, delete message, and read attribute access to SQS queues, and write permissions to CloudWatch logs."}, {"arn:aws:iam::aws:policy/service-role/AWSCodeDeployRoleForLambda","Provides CodeDeploy service access to perform a Lambda deployment on your behalf."}, {"arn:aws:iam::aws:policy/service-role/AWSLambdaENIManagementAccess","Provides minimum permissions for a Lambda function to manage ENIs (create, describe, delete) used by a VPC-enabled Lambda Function."}, {"arn:aws:iam::aws:policy/AWSDeepLensLambdaFunctionAccessPolicy","This policy specifies permissions required by DeepLens Administrative lambda functions that run on a DeepLens device"}, {"arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole","Provides minimum permissions for a Lambda function to execute while accessing a resource within a VPC"}, {"arn:aws:iam::aws:policy/aws-service-role/AWSLambdaReplicator","Grants Lambda Replicator necessary permissions to replicate functions across regions "}, {"arn:aws:iam::aws:policy/service-role/AWSLambdaMSKExecutionRole","Provides permissions required to access MSK Cluster within a VPC, manage ENIs (create, describe, delete) in the VPC and write permissions to CloudWatch Logs."}, {"arn:aws:iam::aws:policy/AWSLambda_ReadOnlyAccess","Grants read-only access to AWS Lambda service, AWS Lambda console features, and other related AWS services."}, {"arn:aws:iam::aws:policy/AWSLambda_FullAccess","Grants full access to AWS Lambda service, AWS Lambda console features, and other related AWS services."} }; public const string CF_LAMBDA_PACKAGE_TYPE = "PackageType"; public const string CF_SERVERLESS_METADATA = "Metadata"; public const string CF_SERVERLESS_DOCKERCONTEXT = "DockerContext"; public const string CF_LAMBDA_IMAGEURI = "ImageUri"; public const string CF_LAMBDA_CODEURI = "CodeUri"; public const string CF_LAMBDA_CODE = "Code"; public const string CF_LAMBDA_S3BUCKET = "S3Bucket"; public const string CF_LAMBDA_S3KEY = "S3Key"; } }
89
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools.Options; namespace Amazon.Lambda.Tools { /// <summary> /// This class defines all the possible options across all the commands. The individual commands will then /// references the options that are appropiate. /// </summary> public static class LambdaDefinedCommandOptions { public static readonly CommandOption ARGUMENT_DISABLE_VERSION_CHECK = new CommandOption { Name = "Disable Version Check", ShortSwitch = "-dvc", Switch = "--disable-version-check", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "Disable the .NET Core version check. Only for advanced usage.", }; public static readonly CommandOption ARGUMENT_PACKAGE = new CommandOption { Name = "Package", ShortSwitch = "-pac", Switch = "--package", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Application package to use for deployment, skips building the project", }; public static readonly CommandOption ARGUMENT_FUNCTION_NAME = new CommandOption { Name = "Function Name", ShortSwitch = "-fn", Switch = "--function-name", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "AWS Lambda function name" }; public static readonly CommandOption ARGUMENT_FUNCTION_DESCRIPTION = new CommandOption { Name = "Function Description", ShortSwitch = "-fd", Switch = "--function-description", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "AWS Lambda function description" }; public static readonly CommandOption ARGUMENT_FUNCTION_PUBLISH = new CommandOption { Name = "Publish", ShortSwitch = "-fp", Switch = "--function-publish", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "Publish a new version as an atomic operation" }; public static readonly CommandOption ARGUMENT_FUNCTION_HANDLER = new CommandOption { Name = "Handler", ShortSwitch = "-fh", Switch = "--function-handler", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Handler for the function <assembly>::<type>::<method>" }; public static readonly CommandOption ARGUMENT_PACKAGE_TYPE = new CommandOption { Name = "Package Type", ShortSwitch = "-pt", Switch = "--package-type", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The deployment package type for Lambda function. Valid values: image, zip" }; public static readonly CommandOption ARGUMENT_FUNCTION_MEMORY_SIZE = new CommandOption { Name = "Memory Size", ShortSwitch = "-fms", Switch = "--function-memory-size", ValueType = CommandOption.CommandOptionValueType.IntValue, Description = "The amount of memory, in MB, your Lambda function is given", }; public static readonly CommandOption ARGUMENT_FUNCTION_ROLE = new CommandOption { Name = "Role", ShortSwitch = "-frole", Switch = "--function-role", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The IAM role that Lambda assumes when it executes your function" }; public static readonly CommandOption ARGUMENT_FUNCTION_TIMEOUT = new CommandOption { Name = "Timeout", ShortSwitch = "-ft", Switch = "--function-timeout", ValueType = CommandOption.CommandOptionValueType.IntValue, Description = "The function execution timeout in seconds" }; public static readonly CommandOption ARGUMENT_FUNCTION_RUNTIME = new CommandOption { Name = "Runtime", ShortSwitch = "-frun", Switch = "--function-runtime", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The runtime environment for the Lambda function" }; public static readonly CommandOption ARGUMENT_FUNCTION_ARCHITECTURE = new CommandOption { Name = "Architecture", ShortSwitch = "-farch", Switch = "--function-architecture", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"The architecture of the Lambda function. Valid values: {LambdaConstants.ARCHITECTURE_X86_64} or {LambdaConstants.ARCHITECTURE_ARM64}. Default is {LambdaConstants.ARCHITECTURE_X86_64}" }; public static readonly CommandOption ARGUMENT_FUNCTION_SUBNETS = new CommandOption { Name = "Subnets", ShortSwitch = "-fsub", Switch = "--function-subnets", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "Comma delimited list of subnet ids if your function references resources in a VPC" }; public static readonly CommandOption ARGUMENT_FUNCTION_SECURITY_GROUPS = new CommandOption { Name = "Security Groups", ShortSwitch = "-fsec", Switch = "--function-security-groups", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "Comma delimited list of security group ids if your function references resources in a VPC" }; public static readonly CommandOption ARGUMENT_FUNCTION_LAYERS = new CommandOption { Name = "Function Layers", ShortSwitch = "-fl", Switch = "--function-layers", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "Comma delimited list of Lambda layer version arns" }; public static readonly CommandOption ARGUMENT_OPT_DIRECTORY = new CommandOption { Name = "Opt Directory", ShortSwitch = "-od", Switch = "--opt-directory", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"The directory under the /opt directory the contents of the layer will be placed. If not set a directory name /opt/{LambdaConstants.DEFAULT_LAYER_OPT_DIRECTORY}/." }; public static readonly CommandOption ARGUMENT_DEADLETTER_TARGET_ARN = new CommandOption { Name = "Dead Letter Target ARN", ShortSwitch = "-dlta", Switch = "--dead-letter-target-arn", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Target ARN of an SNS topic or SQS Queue for the Dead Letter Queue" }; public static readonly CommandOption ARGUMENT_TRACING_MODE = new CommandOption { Name = "Tracing Mode", ShortSwitch = "-tm", Switch = "--tracing-mode", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Configures when AWS X-Ray should trace the function. Valid values: PassThrough or Active" }; public static readonly CommandOption ARGUMENT_ENVIRONMENT_VARIABLES = new CommandOption { Name = "Environment Variables", ShortSwitch = "-ev", Switch = "--environment-variables", ValueType = CommandOption.CommandOptionValueType.KeyValuePairs, Description = "Environment variables set for the function. For existing functions this replaces the current environment variables. Format is <key1>=<value1>;<key2>=<value2>" }; public static readonly CommandOption ARGUMENT_APPEND_ENVIRONMENT_VARIABLES = new CommandOption { Name = "Append Environment Variables", ShortSwitch = "-aev", Switch = "--append-environment-variables", ValueType = CommandOption.CommandOptionValueType.KeyValuePairs, Description = "Append environment variables to the existing set of environment variables for the function. Format is <key1>=<value1>;<key2>=<value2>" }; public static readonly CommandOption ARGUMENT_FUNCTION_TAGS = new CommandOption { Name = "Tags", Switch = "--tags", ValueType = CommandOption.CommandOptionValueType.KeyValuePairs, Description = "AWS tags to apply. Format is <name1>=<value1>;<name2>=<value2>" }; public static readonly CommandOption ARGUMENT_KMS_KEY_ARN = new CommandOption { Name = "KMS Key ARN", ShortSwitch = "-kk", Switch = "--kms-key", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "KMS Key ARN of a customer key used to encrypt the function's environment variables" }; public static readonly CommandOption ARGUMENT_RESOLVE_S3 = new CommandOption { Name = "Resolve S3 Bucket", ShortSwitch = "-rs", Switch = "--resolve-s3", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = $"If set to true a bucket with the name format of \"{LambdaConstants.DEFAULT_BUCKET_NAME_PREFIX}<region>-<account-id>\" will be configured to store build outputs" }; public static readonly CommandOption ARGUMENT_S3_BUCKET = new CommandOption { Name = "S3 Bucket", ShortSwitch = "-sb", Switch = "--s3-bucket", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "S3 bucket to upload the build output" }; public static readonly CommandOption ARGUMENT_S3_PREFIX = new CommandOption { Name = "S3 Key Prefix", ShortSwitch = "-sp", Switch = "--s3-prefix", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "S3 prefix for for the build output" }; public static readonly CommandOption ARGUMENT_STACK_NAME = new CommandOption { Name = "CloudFormation Stack Name", ShortSwitch = "-sn", Switch = "--stack-name", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "CloudFormation stack name for an AWS Serverless application" }; public static readonly CommandOption ARGUMENT_CLOUDFORMATION_TEMPLATE = new CommandOption { Name = "CloudFormation Template", ShortSwitch = "-t", Switch = "--template", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Path to the CloudFormation template" }; public static readonly CommandOption ARGUMENT_CLOUDFORMATION_TEMPLATE_PARAMETER = new CommandOption { Name = "CloudFormation Template Parameters", ShortSwitch = "-tp", Switch = "--template-parameters", ValueType = CommandOption.CommandOptionValueType.KeyValuePairs, Description = "CloudFormation template parameters. Format is <key1>=<value1>;<key2>=<value2>" }; public static readonly CommandOption ARGUMENT_CLOUDFORMATION_TEMPLATE_SUBSTITUTIONS = new CommandOption { Name = "CloudFormation Template Substitutions", ShortSwitch = "-ts", Switch = "--template-substitutions", ValueType = CommandOption.CommandOptionValueType.KeyValuePairs, Description = "JSON based CloudFormation template substitutions. Format is <JSONPath>=<Substitution>;<JSONPath>=..." }; public static readonly CommandOption ARGUMENT_CLOUDFORMATION_DISABLE_CAPABILITIES = new CommandOption { Name = "Disable Capabilities", ShortSwitch = "-dc", Switch = "--disable-capabilities", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "Comma delimited list of capabilities to disable when creating a CloudFormation Stack." }; public static readonly CommandOption ARGUMENT_STACK_WAIT = new CommandOption { Name = "Stack Wait", ShortSwitch = "-sw", Switch = "--stack-wait", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "If true wait for the Stack to finish updating before exiting. Default is true." }; public static readonly CommandOption ARGUMENT_CLOUDFORMATION_ROLE = new CommandOption { Name = "CloudFormation Role ARN", ShortSwitch = "-cfrole", Switch = "--cloudformation-role", ValueType = CommandOption.CommandOptionValueType. StringValue, Description = "Optional role that CloudFormation assumes when creating or updated CloudFormation stack." }; public static readonly CommandOption ARGUMENT_PAYLOAD = new CommandOption { Name = "Payload for function", ShortSwitch = "-p", Switch = "--payload", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The input payload to send to the Lambda function" }; public static readonly CommandOption ARGUMENT_OUTPUT_PACKAGE = new CommandOption { Name = "The output zip file name", ShortSwitch = "-o", Switch = "--output-package", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "The zip file that will be created with compiled and packaged Lambda function." }; public static readonly CommandOption ARGUMENT_OUTPUT_CLOUDFORMATION_TEMPLATE = new CommandOption { Name = "CloudFormation Ouptut Template", ShortSwitch = "-ot", Switch = "--output-template", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Path to write updated serverless template with CodeURI fields updated to the location of the packaged build artifacts in S3." }; public static readonly CommandOption ARGUMENT_APPLY_DEFAULTS_FOR_UPDATE_OBSOLETE = new CommandOption { Name = "Apply Defaults for Update", Switch = "--apply-defaults", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "Obsolete: as of version 3.0.0.0 defaults are always applied." }; public static readonly CommandOption ARGUMENT_LAYER_NAME = new CommandOption { Name = "Layer Name", Switch = "--layer-name", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "AWS Lambda layer name" }; public static readonly CommandOption ARGUMENT_LAYER_VERSION_ARN = new CommandOption { Name = "Layer Version Arn", Switch = "--layer-version-arn", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "AWS Lambda layer version arn" }; public static readonly CommandOption ARGUMENT_LAYER_TYPE = new CommandOption { Name = "Layer Type", Switch = "--layer-type", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"The type of layer to publish. Valid values are: {LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE}" }; public static readonly CommandOption ARGUMENT_LAYER_LICENSE_INFO = new CommandOption { Name = "Layer License Info", Switch = "--layer-license-info", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"License info to set on the Lambda layer" }; public static readonly CommandOption ARGUMENT_PACKAGE_MANIFEST = new CommandOption { Name = "Package Manifest", Switch = "--package-manifest", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"Package manifest for a \"{LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE}\" layer that indicates the NuGet packages to add to the layer." }; public static readonly CommandOption ARGUMENT_ENABLE_PACKAGE_OPTIMIZATION = new CommandOption { Name = "Enable Package Optimization", Switch = "--enable-package-optimization", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "If true the packages will be pre-jitted to improve cold start performance. This must done on an Amazon Linux environment." }; public static readonly CommandOption ARGUMENT_IMAGE_ENTRYPOINT = new CommandOption { Name = "Image Entrypoint", ShortSwitch = "-ie", Switch = "--image-entrypoint", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "Overrides the image's ENTRYPOINT when package type is set \"image\"." }; public static readonly CommandOption ARGUMENT_IMAGE_COMMAND = new CommandOption { Name = "Image Command", ShortSwitch = "-ic", Switch = "--image-command", ValueType = CommandOption.CommandOptionValueType.CommaDelimitedList, Description = "Overrides the image's CMD when package type is set \"image\"." }; public static readonly CommandOption ARGUMENT_IMAGE_WORKING_DIRECTORY = new CommandOption { Name = "Image Working Directory", ShortSwitch = "-iwd", Switch = "--image-working-directory", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Overrides the image's working directory when package type is set \"image\"." }; public static readonly CommandOption ARGUMENT_IMAGE_TAG = new CommandOption { Name = "Docker Image Tag", ShortSwitch = "-it", Switch = "--image-tag", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = "Docker image name and tag in the 'name:tag' format." }; public static readonly CommandOption ARGUMENT_EPHEMERAL_STORAGE_SIZE = new CommandOption { Name = "Ephemerals Storage Size", Switch = "--ephemerals-storage-size", ValueType = CommandOption.CommandOptionValueType.IntValue, Description = "The size of the function's /tmp directory in MB. The default value is 512, but can be any whole number between 512 and 10240 MB" }; public static readonly CommandOption ARGUMENT_FUNCTION_URL_ENABLE = new CommandOption { Name = "Function Url Enable", Switch = "--function-url-enable", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = "Enable function URL. A function URL is a dedicated HTTP(S) endpoint for your Lambda function." }; public static readonly CommandOption ARGUMENT_FUNCTION_URL_AUTH = new CommandOption { Name = "Function Url Auth Type", Switch = "--function-url-auth", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"The type of authentication that your function URL uses, default value is NONE. Valid values: {FunctionUrlAuthType.NONE} or {FunctionUrlAuthType.AWS_IAM}" }; public static readonly CommandOption ARGUMENT_USE_CONTAINER_FOR_BUILD = new CommandOption { Name = "Use Container For Build", Switch = "--use-container-for-build", ShortSwitch = "-ucfb", ValueType = CommandOption.CommandOptionValueType.BoolValue, Description = $"Use a local container to build the Lambda binary. A default image will be provided if none is supplied." }; public static readonly CommandOption ARGUMENT_CONTAINER_IMAGE_FOR_BUILD = new CommandOption { Name = "Container Image For Build", Switch = "--container-image-for-build", ShortSwitch = "-cifb", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"The container image tag (with version) to be used for building the Lambda binary." }; public static readonly CommandOption ARGUMENT_CODE_MOUNT_DIRECTORY = new CommandOption { Name = "Code Mount Directory", Switch = "--code-mount-directory", ShortSwitch = "-cmd", ValueType = CommandOption.CommandOptionValueType.StringValue, Description = $"Path to the directory to mount to the build container. Otherwise, look upward for a solution folder." }; } }
482
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; using Amazon.Common.DotNetCli.Tools; using System.Linq; namespace Amazon.Lambda.Tools { /// <summary> /// Wrapper around the dotnet cli used to execute the publish command. /// </summary> public class LambdaDotNetCLIWrapper { string _workingDirectory; IToolLogger _logger; public LambdaDotNetCLIWrapper(IToolLogger logger, string workingDirectory) { this._logger = logger; this._workingDirectory = workingDirectory; } /// <summary> /// Execute the dotnet store command on the provided package manifest /// </summary> /// <param name="defaults"></param> /// <param name="projectLocation"></param> /// <param name="outputLocation"></param> /// <param name="targetFramework"></param> /// <param name="packageManifest"></param> /// <param name="enableOptimization"></param> /// <returns></returns> public int Store(LambdaToolsDefaults defaults, string projectLocation, string outputLocation, string targetFramework, string packageManifest, string architecture, bool enableOptimization) { if (outputLocation == null) throw new ArgumentNullException(nameof(outputLocation)); if (Directory.Exists(outputLocation)) { try { Directory.Delete(outputLocation, true); _logger?.WriteLine("Deleted previous publish folder"); } catch (Exception e) { _logger?.WriteLine($"Warning unable to delete previous publish folder: {e.Message}"); } } var dotnetCLI = FindExecutableInPath("dotnet.exe"); if (dotnetCLI == null) dotnetCLI = FindExecutableInPath("dotnet"); if (string.IsNullOrEmpty(dotnetCLI)) throw new Exception("Failed to locate dotnet CLI executable. Make sure the dotnet CLI is installed in the environment PATH."); var fullProjectLocation = this._workingDirectory; if (!string.IsNullOrEmpty(projectLocation)) { fullProjectLocation = Utilities.DetermineProjectLocation(this._workingDirectory, projectLocation); } var fullPackageManifest = Path.Combine(fullProjectLocation, packageManifest); _logger?.WriteLine($"... invoking 'dotnet store' for manifest {fullPackageManifest} into output directory {outputLocation}"); StringBuilder arguments = new StringBuilder("store"); if (!string.IsNullOrEmpty(outputLocation)) { arguments.Append($" --output \"{outputLocation}\""); } if (!string.IsNullOrEmpty(targetFramework)) { arguments.Append($" --framework \"{targetFramework}\""); } arguments.Append($" --manifest \"{fullPackageManifest}\""); arguments.Append($" --runtime {LambdaUtilities.DetermineRuntimeParameter(targetFramework, architecture)}"); if(!enableOptimization) { arguments.Append(" --skip-optimization"); } var psi = new ProcessStartInfo { FileName = dotnetCLI, Arguments = arguments.ToString(), WorkingDirectory = this._workingDirectory, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; var handler = (DataReceivedEventHandler)((o, e) => { if (string.IsNullOrEmpty(e.Data)) return; // Skip outputting this warning message as it adds a lot of noise to the output and is not actionable. // Full warning message being skipped: message NETSDK1062: // Unable to use package assets cache due to I/O error. This can occur when the same project is built // more than once in parallel. Performance may be degraded, but the build result will not be impacted. if (e.Data.Contains("message NETSDK1062")) return; _logger?.WriteLine("... store: " + e.Data); }); int exitCode; using (var proc = new Process()) { proc.StartInfo = psi; proc.Start(); proc.ErrorDataReceived += handler; proc.OutputDataReceived += handler; proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.EnableRaisingEvents = true; proc.WaitForExit(); exitCode = proc.ExitCode; } return exitCode; } /// <summary> /// Executes the dotnet publish command for the provided project /// </summary> /// <param name="defaults"></param> /// <param name="projectLocation"></param> /// <param name="outputLocation"></param> /// <param name="targetFramework"></param> /// <param name="configuration"></param> /// <param name="msbuildParameters"></param> /// <param name="deploymentTargetPackageStoreManifestContent"></param> public int Publish(LambdaToolsDefaults defaults, string projectLocation, string outputLocation, string targetFramework, string configuration, string msbuildParameters, string architecture, IList<string> publishManifests) { if (outputLocation == null) throw new ArgumentNullException(nameof(outputLocation)); if (Directory.Exists(outputLocation)) { try { Directory.Delete(outputLocation, true); _logger?.WriteLine("Deleted previous publish folder"); } catch (Exception e) { _logger?.WriteLine($"Warning unable to delete previous publish folder: {e.Message}"); } } _logger?.WriteLine($"... invoking 'dotnet publish', working folder '{outputLocation}'"); var dotnetCLI = FindExecutableInPath("dotnet.exe"); if (dotnetCLI == null) dotnetCLI = FindExecutableInPath("dotnet"); if (string.IsNullOrEmpty(dotnetCLI)) throw new Exception("Failed to locate dotnet CLI executable. Make sure the dotnet CLI is installed in the environment PATH."); var fullProjectLocation = this._workingDirectory; if (!string.IsNullOrEmpty(projectLocation)) { fullProjectLocation = Utilities.DetermineProjectLocation(this._workingDirectory, projectLocation); } var arguments = GetPublishArguments(fullProjectLocation, outputLocation, targetFramework, configuration, msbuildParameters, architecture, publishManifests); // echo the full dotnet command for debug _logger?.WriteLine($"... dotnet {arguments}"); var psi = new ProcessStartInfo { FileName = dotnetCLI, Arguments = arguments, WorkingDirectory = this._workingDirectory, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; var handler = (DataReceivedEventHandler)((o, e) => { if (string.IsNullOrEmpty(e.Data)) return; _logger?.WriteLine("... publish: " + e.Data); }); int exitCode; using (var proc = new Process()) { proc.StartInfo = psi; proc.Start(); proc.ErrorDataReceived += handler; proc.OutputDataReceived += handler; proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.EnableRaisingEvents = true; proc.WaitForExit(); exitCode = proc.ExitCode; } if (exitCode == 0) { ProcessAdditionalFiles(defaults, outputLocation); var chmodPath = FindExecutableInPath("chmod"); if (!string.IsNullOrEmpty(chmodPath) && File.Exists(chmodPath)) { // as we are not invoking through a shell, which would handle // wildcard expansion for us, we need to invoke per-file var files = Directory.GetFiles(outputLocation, "*", SearchOption.TopDirectoryOnly); foreach (var file in files) { var filename = Path.GetFileName(file); var psiChmod = new ProcessStartInfo { FileName = chmodPath, Arguments = "+rx \"" + filename + "\"", WorkingDirectory = outputLocation, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; using (var proc = new Process()) { proc.StartInfo = psiChmod; proc.Start(); proc.ErrorDataReceived += handler; proc.OutputDataReceived += handler; proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.EnableRaisingEvents = true; proc.WaitForExit(); if (proc.ExitCode == 0) { this._logger?.WriteLine($"Changed permissions on published file (chmod +rx {filename})."); } } } } } return exitCode; } public string GetPublishArguments(string projectLocation, string outputLocation, string targetFramework, string configuration, string msbuildParameters, string architecture, IList<string> publishManifests, bool isNativeAot = false, string projectLocationInsideContainer = null) { StringBuilder arguments = new StringBuilder("publish"); if (!string.IsNullOrEmpty(projectLocationInsideContainer)) { arguments.Append($" \"{projectLocationInsideContainer}\""); } else if (!string.IsNullOrEmpty(projectLocation)) { arguments.Append($" \"{projectLocation}\""); } if (!string.IsNullOrEmpty(outputLocation)) { arguments.Append($" --output \"{outputLocation}\""); } if (!string.IsNullOrEmpty(configuration)) { arguments.Append($" --configuration \"{configuration}\""); } if (!string.IsNullOrEmpty(targetFramework)) { arguments.Append($" --framework \"{targetFramework}\""); } if (!string.IsNullOrEmpty(msbuildParameters)) { arguments.Append($" {msbuildParameters}"); } if (!string.Equals("netcoreapp1.0", targetFramework, StringComparison.OrdinalIgnoreCase)) { arguments.Append(" /p:GenerateRuntimeConfigurationFiles=true"); // Define an action to set the runtime and self-contained switches. var applyRuntimeSwitchAction = (Action)(() => { if (msbuildParameters == null || msbuildParameters.IndexOf("--runtime", StringComparison.InvariantCultureIgnoreCase) == -1) { arguments.Append($" --runtime {LambdaUtilities.DetermineRuntimeParameter(targetFramework, architecture)}"); } if (!Utilities.HasExplicitSelfContainedFlag(projectLocation, msbuildParameters)) { arguments.Append($" --self-contained {isNativeAot} "); } }); // This is here to not change existing behavior for the 2.0 and 2.1 runtimes. For those runtimes if // cshtml files are being used we need to support that cshtml being compiled at runtime. In order to do that we // need to not turn PreserveCompilationContext which provides reference assemblies to the runtime // compilation and not set a runtime. // // If there are no cshtml then disable PreserveCompilationContext to reduce package size and continue // to use the same runtime identifier that we used when those runtimes were launched. if (new string[] { "netcoreapp2.0", "netcoreapp2.1" }.Contains(targetFramework)) { if (Directory.GetFiles(projectLocation, "*.cshtml", SearchOption.AllDirectories).Length == 0) { applyRuntimeSwitchAction(); if (string.IsNullOrEmpty(msbuildParameters) || !msbuildParameters.Contains("PreserveCompilationContext")) { _logger?.WriteLine("... Disabling compilation context to reduce package size. If compilation context is needed pass in the \"/p:PreserveCompilationContext=false\" switch."); arguments.Append(" /p:PreserveCompilationContext=false"); } } } else { applyRuntimeSwitchAction(); } // If we have a manifest of packages already deploy in target deployment environment then write it to disk and add the // command line switch if (publishManifests != null && publishManifests.Count > 0) { foreach (var manifest in publishManifests) { arguments.Append($" --manifest \"{manifest}\""); } } if (isNativeAot) { // StripSymbols will greatly reduce output binary size with Native AOT arguments.Append(" /p:StripSymbols=true"); } } return arguments.ToString(); } private void ProcessAdditionalFiles(LambdaToolsDefaults defaults, string publishLocation) { var listOfDependencies = new List<string>(); var extraDependences = defaults["additional-files"] as string[]; if (extraDependences != null) { foreach (var item in extraDependences) listOfDependencies.Add(item); } foreach (var relativePath in listOfDependencies) { var fileName = Path.GetFileName(relativePath); string source; if (Path.IsPathRooted(relativePath)) source = relativePath; else source = Path.Combine(publishLocation, relativePath); var target = Path.Combine(publishLocation, fileName); if (File.Exists(source) && !File.Exists(target)) { File.Copy(source, target); _logger?.WriteLine($"... publish: Adding additional file {relativePath}"); } } } /// <summary> /// A collection of known paths for common utilities that are usually not found in the path /// </summary> static readonly IDictionary<string, string> KNOWN_LOCATIONS = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { {"dotnet.exe", @"C:\Program Files\dotnet\dotnet.exe" }, {"chmod", @"/bin/chmod" }, {"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> public static string FindExecutableInPath(string command) { if (File.Exists(command)) return Path.GetFullPath(command); #if NETCOREAPP3_1_OR_GREATER if (string.Equals(command, "dotnet.exe")) { if(!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { command = "dotnet"; } var mainModule = Process.GetCurrentProcess().MainModule; if (!string.IsNullOrEmpty(mainModule?.FileName) && Path.GetFileName(mainModule.FileName).Equals(command, StringComparison.OrdinalIgnoreCase)) { return mainModule.FileName; } } #endif 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"); if (envPath != null) { foreach (var path in envPath.Split(Path.PathSeparator)) { try { var fullPath = Path.Combine(quoteRemover(path), command); if (File.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) && File.Exists(KNOWN_LOCATIONS[command])) return KNOWN_LOCATIONS[command]; return null; } } }
478
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Amazon.Lambda.Tools { /// <summary> /// Class representing ImageTag associated with a image based lambda /// </summary> public class LambdaImageTagData { public string Repo { get; set; } public string Tag { get; set; } /// <summary> /// Parse input imagetag to retrieve image repo and image tag /// </summary> /// <param name="text">Format: repoName:TagName</param> public static bool TryParse(string text, out LambdaImageTagData data) { if (string.IsNullOrEmpty(text)) { data = null; return false; } if (text.Contains(":")) { var textArray = text.Split(':'); data = new LambdaImageTagData { Repo = textArray[0], Tag = textArray[1] }; return true; } data = new LambdaImageTagData { Repo = text, Tag = null }; return true; } } }
37
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Amazon.Common.DotNetCli.Tools; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools { /// <summary> /// This class will create the lambda zip package that can be upload to Lambda for deployment. /// </summary> public static class LambdaPackager { private const string Shebang = "#!"; private const char LinuxLineEnding = '\n'; private const string BootstrapFilename = "bootstrap"; private const string LinuxOSReleaseFile = @"/etc/os-release"; private const string AmazonLinux2InOSReleaseFile = "PRETTY_NAME=\"Amazon Linux 2\""; #if NETCOREAPP3_1_OR_GREATER private static readonly string BuildLambdaZipCliPath = Path.Combine( Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().Location).LocalPath), "Resources\\build-lambda-zip.exe"); #else private static readonly string BuildLambdaZipCliPath = Path.Combine( Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath), "Resources\\build-lambda-zip.exe"); #endif static IDictionary<string, Version> NETSTANDARD_LIBRARY_VERSIONS = new Dictionary<string, Version> { { "netcoreapp1.0", Version.Parse("1.6.0") }, { "netcoreapp1.1", Version.Parse("1.6.1") } }; private static bool IsAmazonLinux2(IToolLogger logger) { #if !NETCOREAPP3_1_OR_GREATER return false; #else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { if (File.Exists(LinuxOSReleaseFile)) { logger?.WriteLine($"Found {LinuxOSReleaseFile}"); string readText = File.ReadAllText(LinuxOSReleaseFile); if (readText.Contains(AmazonLinux2InOSReleaseFile)) { logger?.WriteLine( $"Linux distribution is Amazon Linux 2, NativeAOT container build is optional"); return true; } } } return false; #endif } /// <summary> /// Execute the dotnet publish command and zip up the resulting publish folder. /// </summary> /// <param name="defaults"></param> /// <param name="logger"></param> /// <param name="workingDirectory"></param> /// <param name="projectLocation"></param> /// <param name="targetFramework"></param> /// <param name="configuration"></param> /// <param name="msbuildParameters"></param> /// <param name="disableVersionCheck"></param> /// <param name="publishLocation"></param> /// <param name="zipArchivePath"></param> public static bool CreateApplicationBundle(LambdaToolsDefaults defaults, IToolLogger logger, string workingDirectory, string projectLocation, string configuration, string targetFramework, string msbuildParameters, string architecture, bool disableVersionCheck, LayerPackageInfo layerPackageInfo, bool isNativeAot, bool? useContainerForBuild, string containerImageForBuild, string codeMountDirectory, out string publishLocation, ref string zipArchivePath) { LambdaUtilities.ValidateTargetFramework(projectLocation, targetFramework, isNativeAot); LambdaUtilities.ValidateNativeAotArchitecture(architecture, isNativeAot); // If use container is set to false explicitly, then that overrides other values. if (useContainerForBuild.HasValue && !useContainerForBuild.Value) { containerImageForBuild = null; } // Else, if we haven't been given a build image, we need to figure out if we should use a default else if (string.IsNullOrWhiteSpace(containerImageForBuild)) { // Use a default container image if Use Container is set to true, or if we need to build NativeAOT on non-AL2 if ((useContainerForBuild.HasValue && useContainerForBuild.Value) || (isNativeAot && !IsAmazonLinux2(logger))) { containerImageForBuild = LambdaUtilities.GetDefaultBuildImage(targetFramework, architecture, logger); } } // Otherwise, we've been given a build image to use, so always use that. // Below, the code only considers whether containerImageForBuild is set or not LogDeprecationMessagesIfNecessary(logger, targetFramework); if (string.Equals(architecture, LambdaConstants.ARCHITECTURE_ARM64) && msbuildParameters != null && msbuildParameters.Contains("--self-contained true")) { logger.WriteLine("WARNING: There is an issue with self contained ARM based .NET Lambda functions using custom runtimes that causes functions to fail to run. The following GitHub issue has further information and workaround."); logger.WriteLine("https://github.com/aws/aws-lambda-dotnet/issues/920"); } if (string.IsNullOrEmpty(configuration)) configuration = LambdaConstants.DEFAULT_BUILD_CONFIGURATION; var lambdaRuntimePackageStoreManifestContent = LambdaUtilities.LoadPackageStoreManifest(logger, targetFramework); var publishManifestPath = new List<string>(); if (!string.IsNullOrEmpty(lambdaRuntimePackageStoreManifestContent)) { var tempFile = Path.GetTempFileName(); File.WriteAllText(tempFile, lambdaRuntimePackageStoreManifestContent); publishManifestPath.Add(tempFile); } if (layerPackageInfo != null) { foreach (var info in layerPackageInfo.Items) { publishManifestPath.Add(info.ManifestPath); } } publishLocation = Utilities.DeterminePublishLocation(workingDirectory, projectLocation, configuration, targetFramework); logger?.WriteLine("Executing publish command"); var cli = new LambdaDotNetCLIWrapper(logger, workingDirectory); if (!string.IsNullOrWhiteSpace(containerImageForBuild)) { var containerBuildLogMessage = isNativeAot ? $"Starting container for native AOT build using build image: {containerImageForBuild}." : $"Starting container for build using build image: {containerImageForBuild}."; logger.WriteLine(containerBuildLogMessage); var directoryToMountToContainer = Utilities.GetSolutionDirectoryFullPath(workingDirectory, projectLocation, codeMountDirectory); var dockerCli = new DockerCLIWrapper(logger, directoryToMountToContainer); var containerName = $"tempLambdaBuildContainer-{Guid.NewGuid()}"; string relativeContainerPathToProjectLocation = string.Concat(DockerCLIWrapper.WorkingDirectoryMountLocation, Utilities.RelativePathTo(directoryToMountToContainer, projectLocation)); // This value is the path inside of the container that will map directly to the out parameter "publishLocation" on the host machine string relativeContainerPathToPublishLocation = Utilities.DeterminePublishLocation(null, relativeContainerPathToProjectLocation, configuration, targetFramework); var publishCommand = "dotnet " + cli.GetPublishArguments(projectLocation, relativeContainerPathToPublishLocation, targetFramework, configuration, msbuildParameters, architecture, publishManifestPath, isNativeAot, relativeContainerPathToProjectLocation); var runResult = dockerCli.Run(containerImageForBuild, containerName, publishCommand); if (runResult != 0) { throw new LambdaToolsException($"ERROR: Container build returned {runResult}", LambdaToolsException.LambdaErrorCode.ContainerBuildFailed); } } else { if (cli.Publish(defaults: defaults, projectLocation: projectLocation, outputLocation: publishLocation, targetFramework: targetFramework, configuration: configuration, msbuildParameters: msbuildParameters, architecture: architecture, publishManifests: publishManifestPath) != 0) { throw new LambdaToolsException($"ERROR: The dotnet publish command return unsuccessful error code", LambdaToolsException.CommonErrorCode.ShellOutToDotnetPublishFailed); } } var buildLocation = Utilities.DetermineBuildLocation(workingDirectory, projectLocation, configuration, targetFramework); // This is here for legacy reasons. Some older versions of the dotnet CLI were not // copying the deps.json file into the publish folder. foreach (var file in Directory.GetFiles(buildLocation, "*.deps.json", SearchOption.TopDirectoryOnly)) { var destinationPath = Path.Combine(publishLocation, Path.GetFileName(file)); if (!File.Exists(destinationPath)) File.Copy(file, destinationPath); } bool flattenRuntime = false; var depsJsonTargetNode = GetDepsJsonTargetNode(logger, publishLocation); // If there is no target node then this means the tool is being used on a future version of .NET Core // then was available when the this tool was written. Go ahead and continue the deployment with warnings so the // user can see if the future version will work. if (depsJsonTargetNode != null && string.Equals(targetFramework, "netcoreapp1.0", StringComparison.OrdinalIgnoreCase)) { // Make sure the project is not pulling in dependencies requiring a later version of .NET Core then the declared target framework if (!ValidateDependencies(logger, targetFramework, depsJsonTargetNode, disableVersionCheck)) return false; // Flatten the runtime folder which reduces the package size by not including native dependencies // for other platforms. flattenRuntime = FlattenRuntimeFolder(logger, publishLocation, depsJsonTargetNode); } FlattenPowerShellRuntimeModules(logger, publishLocation, targetFramework); if (zipArchivePath == null) zipArchivePath = Path.Combine(Directory.GetParent(publishLocation).FullName, new DirectoryInfo(projectLocation).Name + ".zip"); zipArchivePath = Path.GetFullPath(zipArchivePath); logger?.WriteLine($"Zipping publish folder {publishLocation} to {zipArchivePath}"); if (File.Exists(zipArchivePath)) File.Delete(zipArchivePath); var zipArchiveParentDirectory = Path.GetDirectoryName(zipArchivePath); if (!Directory.Exists(zipArchiveParentDirectory)) { logger?.WriteLine($"Creating directory {zipArchiveParentDirectory}"); new DirectoryInfo(zipArchiveParentDirectory).Create(); } BundleDirectory(zipArchivePath, publishLocation, flattenRuntime, logger); return true; } public static void BundleDirectory(string zipArchivePath, string sourceDirectory, bool flattenRuntime, IToolLogger logger) { #if NETCOREAPP3_1_OR_GREATER if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { BundleWithBuildLambdaZip(zipArchivePath, sourceDirectory, flattenRuntime, logger); } else { // Use the native zip utility if it exist which will maintain linux/osx file permissions var zipCLI = LambdaDotNetCLIWrapper.FindExecutableInPath("zip"); if (!string.IsNullOrEmpty(zipCLI)) { BundleWithZipCLI(zipCLI, zipArchivePath, sourceDirectory, flattenRuntime, logger); } else { throw new LambdaToolsException("Failed to find the \"zip\" utility program in path. This program is required to maintain Linux file permissions in the zip archive.", LambdaToolsException.LambdaErrorCode.FailedToFindZipProgram); } } #else BundleWithBuildLambdaZip(zipArchivePath, sourceDirectory, flattenRuntime, logger); #endif } public static void BundleFiles(string zipArchivePath, string rootDirectory, string[] files, IToolLogger logger) { var includedFiles = ConvertToMapOfFiles(rootDirectory, files); #if NETCOREAPP3_1_OR_GREATER if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { BundleWithBuildLambdaZip(zipArchivePath, rootDirectory, includedFiles, logger); } else { // Use the native zip utility if it exist which will maintain linux/osx file permissions var zipCLI = LambdaDotNetCLIWrapper.FindExecutableInPath("zip"); if (!string.IsNullOrEmpty(zipCLI)) { BundleWithZipCLI(zipCLI, zipArchivePath, rootDirectory, includedFiles, logger); } else { throw new LambdaToolsException("Failed to find the \"zip\" utility program in path. This program is required to maintain Linux file permissions in the zip archive.", LambdaToolsException.LambdaErrorCode.FailedToFindZipProgram); } } #else BundleWithBuildLambdaZip(zipArchivePath, rootDirectory, includedFiles, logger); #endif } public static IDictionary<string, string> ConvertToMapOfFiles(string rootDirectory, string[] files) { rootDirectory = rootDirectory.Replace("\\", "/"); if (!rootDirectory.EndsWith("/")) rootDirectory += "/"; var includedFiles = new Dictionary<string, string>(files.Length); foreach (var file in files) { var normalizedFile = file.Replace("\\", "/"); if (Path.IsPathRooted(file)) { var relativePath = file.Substring(rootDirectory.Length); includedFiles[relativePath] = normalizedFile; } else { includedFiles[normalizedFile] = Path.Combine(rootDirectory, normalizedFile).Replace("\\", "/"); } } return includedFiles; } /// <summary> /// Return the targets node which declares all the dependencies for the project along with the dependency's dependencies. /// </summary> /// <param name="logger"></param> /// <param name="publishLocation"></param> /// <returns></returns> private static JsonData GetDepsJsonTargetNode(IToolLogger logger, string publishLocation) { var depsJsonFilepath = Directory.GetFiles(publishLocation, "*.deps.json", SearchOption.TopDirectoryOnly).FirstOrDefault(); if (!File.Exists(depsJsonFilepath)) { logger?.WriteLine($"Missing deps.json file. Skipping flattening runtime folder because {depsJsonFilepath} is an unrecognized format"); return null; } var depsRootData = JsonMapper.ToObject(File.ReadAllText(depsJsonFilepath)); var runtimeTargetNode = depsRootData["runtimeTarget"]; if (runtimeTargetNode == null) { logger?.WriteLine($"Missing runtimeTarget node. Skipping flattening runtime folder because {depsJsonFilepath} is an unrecognized format"); return null; } string runtimeTarget; if (runtimeTargetNode.IsString) { runtimeTarget = runtimeTargetNode.ToString(); } else { runtimeTarget = runtimeTargetNode["name"]?.ToString(); } if (runtimeTarget == null) { logger?.WriteLine($"Missing runtimeTarget name. Skipping flattening runtime folder because {depsJsonFilepath} is an unrecognized format"); return null; } var target = depsRootData["targets"]?[runtimeTarget]; if (target == null) { logger?.WriteLine($"Missing targets node. Skipping flattening runtime folder because {depsJsonFilepath} is an unrecognized format"); return null; } return target; } /// <summary> /// Check to see if any of the dependencies listed in the deps.json file are pulling in later version of NETStandard.Library /// then the target framework supports. /// </summary> /// <param name="logger"></param> /// <param name="targetFramework"></param> /// <param name="depsJsonTargetNode"></param> /// <param name="disableVersionCheck"></param> /// <returns></returns> private static bool ValidateDependencies(IToolLogger logger, string targetFramework, JsonData depsJsonTargetNode, bool disableVersionCheck) { Version maxNETStandardLibraryVersion; // If we don't know the NETStandard.Library NuGet package version then skip validation. This is to handle // the case we are packaging up for a future target framework verion then this version of the tooling knows about. // Skip validation so the tooling doesn't get in the way. if (!NETSTANDARD_LIBRARY_VERSIONS.TryGetValue(targetFramework, out maxNETStandardLibraryVersion)) return true; var dependenciesUsingNETStandard = new List<string>(); Version referencedNETStandardLibrary = null; var errorLevel = disableVersionCheck ? "Warning" : "Error"; foreach (KeyValuePair<string, JsonData> dependencyNode in depsJsonTargetNode) { var nameAndVersion = dependencyNode.Key.Split('/'); if (nameAndVersion.Length != 2) continue; if (string.Equals(nameAndVersion[0], "netstandard.library", StringComparison.OrdinalIgnoreCase)) { if(!Version.TryParse(nameAndVersion[1], out referencedNETStandardLibrary)) { logger.WriteLine($"{errorLevel} parsing version number for declared NETStandard.Library: {nameAndVersion[1]}"); return true; } } // Collect the dependencies that are pulling in the NETStandard.Library metapackage else { var subDependencies = dependencyNode.Value["dependencies"]; if (subDependencies != null) { foreach (KeyValuePair<string, JsonData> subDependency in subDependencies) { if (string.Equals(subDependency.Key, "netstandard.library", StringComparison.OrdinalIgnoreCase)) { dependenciesUsingNETStandard.Add(nameAndVersion[0] + " : " + nameAndVersion[1]); break; } } } } } // If true the project is pulling in a new version of NETStandard.Library then the target framework supports. if(referencedNETStandardLibrary != null && maxNETStandardLibraryVersion < referencedNETStandardLibrary) { logger?.WriteLine($"{errorLevel}: Project is referencing NETStandard.Library version {referencedNETStandardLibrary}. Max version supported by {targetFramework} is {maxNETStandardLibraryVersion}."); // See if we can find the target framework that does support the version the project is pulling in. // This can help the user know what framework their dependencies are targeting instead of understanding NuGet version numbers. var matchingTargetFramework = NETSTANDARD_LIBRARY_VERSIONS.FirstOrDefault(x => { return x.Value.Equals(referencedNETStandardLibrary); }); if(!string.IsNullOrEmpty(matchingTargetFramework.Key)) { logger?.WriteLine($"{errorLevel}: NETStandard.Library {referencedNETStandardLibrary} is used for target framework {matchingTargetFramework.Key}."); } if (dependenciesUsingNETStandard.Count != 0) { logger?.WriteLine($"{errorLevel}: Check the following dependencies for versions compatible with {targetFramework}:"); foreach(var dependency in dependenciesUsingNETStandard) { logger?.WriteLine($"{errorLevel}: \t{dependency}"); } } // If disable version check is true still write the warning messages // but return true to continue deployment. return disableVersionCheck; } return true; } /// <summary> /// Work around issues with Microsoft.PowerShell.SDK NuGet package not working correctly when publish with a /// runtime switch. The nested Module folder under runtimes/unix/lib/{targetFramework}/ needs to be copied to the root of the deployment bundle. /// /// https://github.com/PowerShell/PowerShell/issues/13132 /// </summary> /// <param name="logger"></param> /// <param name="publishLocation"></param> private static void FlattenPowerShellRuntimeModules(IToolLogger logger, string publishLocation, string targetFramework) { var runtimeModuleDirectory = Path.Combine(publishLocation, $"runtimes/unix/lib/{targetFramework}/Modules"); if (!File.Exists(Path.Combine(publishLocation, "Microsoft.PowerShell.SDK.dll")) || !Directory.Exists(runtimeModuleDirectory)) return; Utilities.CopyDirectory(runtimeModuleDirectory, Path.Combine(publishLocation, "Modules"), true); } /// <summary> /// Process the runtime folder from the dotnet publish to flatten the platform specific dependencies to the /// root. /// </summary> /// <param name="logger"></param> /// <param name="publishLocation"></param> /// <param name="depsJsonTargetNode"></param> /// <returns> /// Returns true if flattening was successful. If the publishing folder changes in the future then flattening might fail. /// In that case we want to publish the archive untouched so the tooling doesn't get in the way and let the user see if the /// Lambda runtime has been updated to support the future changes. Warning messages will be written in case of failures. /// </returns> private static bool FlattenRuntimeFolder(IToolLogger logger, string publishLocation, JsonData depsJsonTargetNode) { bool flattenAny = false; // Copy file function if the file hasn't already copied. var copyFileIfNotExist = new Action<string>(sourceRelativePath => { var sourceFullPath = Path.Combine(publishLocation, sourceRelativePath); var targetFullPath = Path.Combine(publishLocation, Path.GetFileName(sourceFullPath)); // Skip the copy if it has already been copied. if (File.Exists(targetFullPath)) return; // Only write the log message about flattening if we are actually going to flatten anything. if(!flattenAny) { logger?.WriteLine("Flattening platform specific dependencies"); flattenAny = true; } logger?.WriteLine($"... flatten: {sourceRelativePath}"); File.Copy(sourceFullPath, targetFullPath); }); var runtimeHierarchy = CalculateRuntimeHierarchy(); // Loop through all the valid runtimes in precedence order so we copy over the first match foreach (var runtime in runtimeHierarchy) { foreach (KeyValuePair<string, JsonData> dependencyNode in depsJsonTargetNode) { var depRuntimeTargets = dependencyNode.Value["runtimeTargets"]; if (depRuntimeTargets == null) continue; foreach (KeyValuePair<string, JsonData> depRuntimeTarget in depRuntimeTargets) { var rid = depRuntimeTarget.Value["rid"]?.ToString(); if(string.Equals(rid, runtime, StringComparison.Ordinal)) { copyFileIfNotExist(depRuntimeTarget.Key); } } } } return true; } /// <summary> /// Compute the hierarchy of runtimes to search for platform dependencies. /// </summary> /// <returns></returns> private static IList<string> CalculateRuntimeHierarchy() { var runtimeHierarchy = new List<string>(); var lambdaAssembly = typeof(LambdaPackager).GetTypeInfo().Assembly; // The full name for the embedded resource changes between the dotnet CLI and AWS Toolkit for VS so just look for the resource by is file name. var manifestName = lambdaAssembly.GetManifestResourceNames().FirstOrDefault(x => x.EndsWith(LambdaConstants.RUNTIME_HIERARCHY)); using (var stream = typeof(LambdaPackager).GetTypeInfo().Assembly.GetManifestResourceStream(manifestName)) using (var reader = new StreamReader(stream)) { var rootData = JsonMapper.ToObject(reader.ReadToEnd()); var runtimes = rootData["runtimes"]; // Use a queue to do a breadth first search through the list of runtimes. var queue = new Queue<string>(); queue.Enqueue(LambdaConstants.LEGACY_RUNTIME_HIERARCHY_STARTING_POINT); while(queue.Count > 0) { var runtime = queue.Dequeue(); if (runtimeHierarchy.Contains(runtime)) continue; runtimeHierarchy.Add(runtime); var imports = runtimes[runtime]["#import"]; if (imports != null) { foreach (JsonData importedRuntime in imports) { queue.Enqueue(importedRuntime.ToString()); } } } } return runtimeHierarchy; } /// <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> /// <param name="publishLocation"></param> /// <param name="flattenRuntime">If true the runtimes folder will be flatten</param> /// <returns></returns> private static IDictionary<string, string> GetFilesToIncludeInArchive(string publishLocation, bool flattenRuntime) { string RUNTIME_FOLDER_PREFIX = "runtimes" + Path.DirectorySeparatorChar; var includedFiles = new Dictionary<string, string>(); var allFiles = Directory.GetFiles(publishLocation, "*.*", SearchOption.AllDirectories); foreach (var file in allFiles) { var relativePath = file.Substring(publishLocation.Length); if (relativePath[0] == Path.DirectorySeparatorChar) relativePath = relativePath.Substring(1); if (flattenRuntime && relativePath.StartsWith(RUNTIME_FOLDER_PREFIX)) continue; // Native debug symbols are very large and are being excluded to keep deployment size down. if (relativePath.EndsWith(".dbg", StringComparison.OrdinalIgnoreCase)) continue; includedFiles[relativePath] = file; } return includedFiles; } /// <summary> /// Zip up the publish folder using the build-lambda-zip utility which will maintain linux/osx file permissions. /// This is what is used when run on Windows. /// <param name="zipArchivePath">The path and name of the zip archive to create.</param> /// <param name="publishLocation">The location to be bundled.</param> /// <param name="flattenRuntime">If true the runtimes folder will be flatten</param> /// <param name="logger">Logger instance.</param> private static void BundleWithBuildLambdaZip(string zipArchivePath, string publishLocation, bool flattenRuntime, IToolLogger logger) { var includedFiles = GetFilesToIncludeInArchive(publishLocation, flattenRuntime); BundleWithBuildLambdaZip(zipArchivePath, publishLocation, includedFiles, logger); } /// <summary> /// Zip up the publish folder using the build-lambda-zip utility which will maintain linux/osx file permissions. /// This is what is used when run on Windows. /// </summary> /// <param name="zipArchivePath">The path and name of the zip archive to create.</param> /// <param name="rootDirectory">The root directory where all of the relative paths in includedFiles is pointing to.</param> /// <param name="includedFiles">Map of relative to absolute path of files to include in bundle.</param> /// <param name="logger">Logger instance.</param> private static void BundleWithBuildLambdaZip(string zipArchivePath, string rootDirectory, IDictionary<string, string> includedFiles, IToolLogger logger) { if (!File.Exists(BuildLambdaZipCliPath)) { throw new LambdaToolsException("Failed to find the \"build-lambda-zip\" utility. This program is required to maintain Linux file permissions in the zip archive.", LambdaToolsException.LambdaErrorCode.FailedToFindZipProgram); } EnsureBootstrapLinuxLineEndings(rootDirectory, includedFiles); //Write the files to disk to avoid the command line size limit when we have a large number of files to zip. var inputFilename = zipArchivePath + ".txt"; using(var writer = new StreamWriter(inputFilename)) { foreach (var kvp in includedFiles) { writer.WriteLine(kvp.Key); } } var args = new StringBuilder($"-o \"{zipArchivePath}\" -i \"{inputFilename}\""); var psiZip = new ProcessStartInfo { FileName = BuildLambdaZipCliPath, Arguments = args.ToString(), WorkingDirectory = rootDirectory, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; var handler = (DataReceivedEventHandler)((o, e) => { if (string.IsNullOrEmpty(e.Data)) return; logger?.WriteLine("... zipping: " + e.Data); }); try { using (var proc = new Process()) { proc.StartInfo = psiZip; proc.Start(); proc.ErrorDataReceived += handler; proc.OutputDataReceived += handler; proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.EnableRaisingEvents = true; proc.WaitForExit(); if (proc.ExitCode == 0) { logger?.WriteLine(string.Format("Created publish archive ({0}).", zipArchivePath)); } } } finally { try { File.Delete(inputFilename); } catch (Exception e) { logger?.WriteLine($"Warning: Unable to delete temporary input file, {inputFilename}, after zipping files: {e.Message}"); } } } /// <summary> /// Detects if there is a bootstrap file, and if it's a script (as opposed to an actual executable), /// and corrects the line endings so it can be run in Linux. /// /// TODO: possibly expand to allow files other than bootstrap to be corrected /// </summary> /// <param name="rootDirectory"></param> /// <param name="includedFiles"></param> private static void EnsureBootstrapLinuxLineEndings(string rootDirectory, IDictionary<string, string> includedFiles) { if (includedFiles.ContainsKey(BootstrapFilename)) { var bootstrapPath = Path.Combine(rootDirectory, BootstrapFilename); if (FileIsLinuxShellScript(bootstrapPath)) { var lines = File.ReadAllLines(bootstrapPath); using (var sw = File.CreateText(bootstrapPath)) { foreach (var line in lines) { sw.Write(line); sw.Write(LinuxLineEnding); } } } } } /// <summary> /// Returns true if the first characters of the file are #!, false otherwise. /// </summary> /// <param name="filePath"></param> /// <returns></returns> private static bool FileIsLinuxShellScript(string filePath) { using (var sr = File.OpenText(filePath)) { while (!sr.EndOfStream) { var line = sr.ReadLine().Trim(); if (line.Length > 0) { return line.StartsWith(Shebang); } } } return false; } /// <summary> /// Creates the deployment bundle using the native zip tool installed /// on the system (default /usr/bin/zip). This is what is typically used on Linux and OSX /// </summary> /// <param name="zipCLI">The path to the located zip binary.</param> /// <param name="zipArchivePath">The path and name of the zip archive to create.</param> /// <param name="publishLocation">The location to be bundled.</param> /// <param name="flattenRuntime">If true the runtimes folder will be flatten</param> /// <param name="logger">Logger instance.</param> private static void BundleWithZipCLI(string zipCLI, string zipArchivePath, string publishLocation, bool flattenRuntime, IToolLogger logger) { var allFiles = GetFilesToIncludeInArchive(publishLocation, flattenRuntime); BundleWithZipCLI(zipCLI, zipArchivePath, publishLocation, allFiles, logger); } /// <summary> /// Creates the deployment bundle using the native zip tool installed /// on the system (default /usr/bin/zip). This is what is typically used on Linux and OSX /// </summary> /// <param name="zipCLI">The path to the located zip binary.</param> /// <param name="zipArchivePath">The path and name of the zip archive to create.</param> /// <param name="rootDirectory">The root directory where all of the relative paths in includedFiles is pointing to.</param> /// <param name="includedFiles">Map of relative to absolute path of files to include in bundle.</param> /// <param name="logger">Logger instance.</param> private static void BundleWithZipCLI(string zipCLI, string zipArchivePath, string rootDirectory, IDictionary<string, string> includedFiles, IToolLogger logger) { EnsureBootstrapLinuxLineEndings(rootDirectory, includedFiles); var args = new StringBuilder("\"" + zipArchivePath + "\""); foreach (var kvp in includedFiles) { args.AppendFormat(" \"{0}\"", kvp.Key); } var psiZip = new ProcessStartInfo { FileName = zipCLI, Arguments = args.ToString(), WorkingDirectory = rootDirectory, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; var handler = (DataReceivedEventHandler)((o, e) => { if (string.IsNullOrEmpty(e.Data)) return; logger?.WriteLine("... zipping: " + e.Data); }); using (var proc = new Process()) { proc.StartInfo = psiZip; proc.Start(); proc.ErrorDataReceived += handler; proc.OutputDataReceived += handler; proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.EnableRaisingEvents = true; proc.WaitForExit(); if (proc.ExitCode == 0) { logger?.WriteLine(string.Format("Created publish archive ({0}).", zipArchivePath)); } } } internal static void LogDeprecationMessagesIfNecessary(IToolLogger logger, string targetFramework) { if (targetFramework == "netcoreapp2.0" && logger != null) { logger.WriteLine("--------------------------------------------------------------------------------"); logger.WriteLine(".NET Core 2.0 Lambda Function Deprecation Notice"); logger.WriteLine("--------------------------------------------------------------------------------"); logger.WriteLine("Support for .NET Core 2.0 Lambda functions will soon be deprecated."); logger.WriteLine(""); logger.WriteLine("Support for .NET Core 2.0 was discontinued by Microsoft in October 2018. This"); logger.WriteLine("version of the runtime is no longer receiving bug fixes or security updates from"); logger.WriteLine("Microsoft. AWS Lambda has discontinued updates to this runtime as well."); logger.WriteLine(""); logger.WriteLine("You can find Lambda's runtime support policy here:"); logger.WriteLine("https://docs.aws.amazon.com/lambda/latest/dg/runtime-support-policy.html"); logger.WriteLine(""); logger.WriteLine("You will notice an initial change 30 days prior to the deprecation."); logger.WriteLine("During the 30 day grace period you will be able to update existing .NET Core 2.0"); logger.WriteLine("Lambda functions but you will not be able to create new ones. After the"); logger.WriteLine("deprecation has been finalized you will be unable to create or update .NET Core"); logger.WriteLine("2.0 functions."); logger.WriteLine(""); logger.WriteLine("However, both during and after the grace period you WILL be able to invoke .NET "); logger.WriteLine("Core 2.0 functions. Existing .NET Core 2.0 function invocation will continue to"); logger.WriteLine("be available, subject to Lambda's runtime support policy."); logger.WriteLine(""); logger.WriteLine("--------------------------------------------------------------------------------"); } } } }
849
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools { /// <summary> /// This class gives access to the default values for the CommandOptions defined in the project's default json file. /// </summary> public class LambdaToolsDefaults : DefaultConfigFile { public const string DEFAULT_FILE_NAME = "aws-lambda-tools-defaults.json"; public LambdaToolsDefaults() { } public LambdaToolsDefaults(string sourceFile) : this(new JsonData(), sourceFile) { } public LambdaToolsDefaults(JsonData data, string sourceFile) : base(data, sourceFile) { } public override string DefaultConfigFileName => DEFAULT_FILE_NAME; public string Profile => GetValueAsString(CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE); public string Region => GetValueAsString(CommonDefinedCommandOptions.ARGUMENT_AWS_REGION); public string FunctionHandler => GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_HANDLER); public string FunctionName => GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME); public string FunctionRuntime => GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_RUNTIME); public string FunctionArchitecture => GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE); public string FunctionRole => GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ROLE); public int? FunctionMemory { get { var data = GetValue(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_MEMORY_SIZE); if (data != null && data.IsInt) { return (int)data; } return null; } } public int? FunctionTimeout { get { var data = GetValue(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TIMEOUT); if (data != null && data.IsInt) { return (int)data; } return null; } } public string CloudFormationTemplate => GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE); public IDictionary<string, string> CloudFormationTemplateParameters { get { var str = GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE_PARAMETER); if (string.IsNullOrEmpty(str)) return null; try { return Utilities.ParseKeyValueOption(str); } catch (Exception) { return null; } } } public IDictionary<string, string> EnvironmentVariables { get { var str = GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_ENVIRONMENT_VARIABLES); if (string.IsNullOrEmpty(str)) return null; try { return Utilities.ParseKeyValueOption(str); } catch (Exception) { return null; } } } public string[] FunctionSubnets { get { var str = GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SUBNETS); if (string.IsNullOrEmpty(str)) return null; try { return str.SplitByComma(); } catch (Exception) { return null; } } } public string[] FunctionSecurityGroups { get { var str = GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SECURITY_GROUPS); if (string.IsNullOrEmpty(str)) return null; try { return str.SplitByComma(); } catch (Exception) { return null; } } } public string KMSKeyArn => GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_KMS_KEY_ARN); public string StackName => GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_STACK_NAME); public string S3Bucket => GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET); public string S3Prefix => GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX); public string Configuration => GetValueAsString(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION); public string Framework => GetValueAsString(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK); public string DeadLetterTargetArn => GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_DEADLETTER_TARGET_ARN); public string TracingMode => GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_TRACING_MODE); public string ImageRepo { get { if (LambdaImageTagData.TryParse(GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_IMAGE_TAG), out var data)) return data.Repo; return null; } } public string ImageTag { get { if (LambdaImageTagData.TryParse(GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_IMAGE_TAG), out var data)) return data.Tag; return null; } } public string ImageCommand => GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_IMAGE_COMMAND); public string PackageType => GetValueAsString(LambdaDefinedCommandOptions.ARGUMENT_PACKAGE_TYPE); } }
197
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using YamlDotNet.RepresentationModel; using YamlDotNet.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ThirdParty.Json.LitJson; using System.Xml.Linq; using Amazon.Common.DotNetCli.Tools; using Amazon.Lambda.Model; using Amazon.S3; using Amazon.S3.Model; using System.Threading.Tasks; using System.Xml.XPath; using Environment = System.Environment; using Amazon.SecurityToken; using System.ComponentModel; using System.Runtime.InteropServices; namespace Amazon.Lambda.Tools { public static class TargetFrameworkMonikers { public const string net70 = "net7.0"; public const string net60 = "net6.0"; public const string net50 = "net5.0"; public const string netcoreapp31 = "netcoreapp3.1"; public const string netcoreapp30 = "netcoreapp3.0"; public const string netcoreapp21 = "netcoreapp2.1"; public const string netcoreapp20 = "netcoreapp2.0"; public const string netcoreapp10 = "netcoreapp1.0"; public static readonly List<string> OrderedTargetFrameworkMonikers = new List<string> { netcoreapp10, netcoreapp20, netcoreapp21, netcoreapp30, netcoreapp31, net50, net60, net70 }; } public static class LambdaUtilities { public static readonly IList<string> ValidProjectExtensions = new List<string> { ".csproj", ".fsproj", ".vbproj" }; public static readonly IReadOnlyDictionary<string, string> _lambdaRuntimeToDotnetFramework = new Dictionary<string, string>() { {Amazon.Lambda.Runtime.Dotnet6.Value, TargetFrameworkMonikers.net60}, {Amazon.Lambda.Runtime.Dotnetcore31.Value, TargetFrameworkMonikers.netcoreapp31}, {Amazon.Lambda.Runtime.Dotnetcore21.Value, TargetFrameworkMonikers.netcoreapp21}, {Amazon.Lambda.Runtime.Dotnetcore20.Value, TargetFrameworkMonikers.netcoreapp20}, {Amazon.Lambda.Runtime.Dotnetcore10.Value, TargetFrameworkMonikers.netcoreapp10} }; public static string DetermineTargetFrameworkFromLambdaRuntime(string lambdaRuntime, string projectLocation) { string framework; if (_lambdaRuntimeToDotnetFramework.TryGetValue(lambdaRuntime, out framework)) return framework; framework = Utilities.LookupTargetFrameworkFromProjectFile(projectLocation); return framework; } public static string DetermineLambdaRuntimeFromTargetFramework(string targetFramework) { var kvp = _lambdaRuntimeToDotnetFramework.FirstOrDefault(x => string.Equals(x.Value, targetFramework, StringComparison.OrdinalIgnoreCase)); if (string.IsNullOrEmpty(kvp.Key)) return null; return kvp.Key; } public static void ValidateTargetFramework(string projectLocation, string targetFramework, bool isNativeAot) { var outputType = Utilities.LookupOutputTypeFromProjectFile(projectLocation); var ouputTypeIsExe = outputType != null && outputType.ToLower().Equals("exe"); if (isNativeAot && !ouputTypeIsExe) { throw new LambdaToolsException($"Native AOT applications must have output type 'exe'.", LambdaToolsException.LambdaErrorCode.NativeAotOutputTypeError); } // Native AOT is only supported with .NET 7 and later var indexOfTargetFramework = TargetFrameworkMonikers.OrderedTargetFrameworkMonikers.IndexOf(targetFramework); if (isNativeAot && indexOfTargetFramework < TargetFrameworkMonikers.OrderedTargetFrameworkMonikers.IndexOf(TargetFrameworkMonikers.net70)) { // In the case where IndexOf returns -1, that means we don't know this target framework, so assume it's a newer framework that supports native AOT. if (indexOfTargetFramework != -1) { throw new LambdaToolsException($"Can't use native AOT with target framework less than {TargetFrameworkMonikers.net70}, however, provided target framework is {targetFramework}", LambdaToolsException.LambdaErrorCode.InvalidNativeAotTargetFramework); } } } public static string GetDefaultBuildImage(string targetFramework, string architecture, IToolLogger logger) { if (string.IsNullOrWhiteSpace(architecture)) { logger?.WriteLine($"Architecture not provided, defaulting to {LambdaConstants.ARCHITECTURE_X86_64} for container build image."); architecture = LambdaConstants.ARCHITECTURE_X86_64; } else if (architecture != LambdaConstants.ARCHITECTURE_X86_64 && architecture != LambdaConstants.ARCHITECTURE_ARM64) { throw new LambdaToolsException($"Architecture {architecture} is not a valid option, use {LambdaConstants.ARCHITECTURE_X86_64} or {LambdaConstants.ARCHITECTURE_ARM64}.", LambdaToolsException.LambdaErrorCode.InvalidArchitectureProvided); } switch (targetFramework?.ToLower()) { case TargetFrameworkMonikers.net70: return $"public.ecr.aws/sam/build-dotnet7:latest-{architecture}"; case TargetFrameworkMonikers.net60: return $"public.ecr.aws/sam/build-dotnet6:latest-{architecture}"; case TargetFrameworkMonikers.netcoreapp31: return $"public.ecr.aws/sam/build-dotnetcore3.1:latest-{architecture}"; default: throw new LambdaToolsException($"No container build image available for targetFramework {targetFramework} and architecture {architecture}.", LambdaToolsException.LambdaErrorCode.UnsupportedDefaultContainerBuild); } } public static Lambda.PackageType DeterminePackageType(string packageType) { if (string.IsNullOrEmpty(packageType) || string.Equals(packageType, Lambda.PackageType.Zip.Value, StringComparison.OrdinalIgnoreCase)) { return Lambda.PackageType.Zip; } else if (string.Equals(packageType, Lambda.PackageType.Image.Value, StringComparison.OrdinalIgnoreCase)) { return Lambda.PackageType.Image; } throw new LambdaToolsException($"Unknown value for package type {packageType}", ToolsException.CommonErrorCode.CommandLineParseError); } /// <summary> /// Make sure nobody is trying to deploy a function based on a higher .NET Core framework than the Lambda runtime knows about. /// </summary> /// <param name="lambdaRuntime"></param> /// <param name="targetFramework"></param> public static void ValidateTargetFrameworkAndLambdaRuntime(string lambdaRuntime, string targetFramework) { if (lambdaRuntime.Length < 3) return; string suffix = lambdaRuntime.Substring(lambdaRuntime.Length - 3); Version runtimeVersion; if (!Version.TryParse(suffix, out runtimeVersion)) return; if (targetFramework.Length < 3) return; suffix = targetFramework.Substring(targetFramework.Length - 3); Version frameworkVersion; if (!Version.TryParse(suffix, out frameworkVersion)) return; if (runtimeVersion < frameworkVersion) { throw new LambdaToolsException($"The framework {targetFramework} is a newer version than Lambda runtime {lambdaRuntime} supports", LambdaToolsException.LambdaErrorCode.FrameworkNewerThanRuntime); } } public static string LoadPackageStoreManifest(IToolLogger logger, string targetFramework) { if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(LambdaConstants.ENV_DOTNET_LAMBDA_CLI_LOCAL_MANIFEST_OVERRIDE))) { var filePath = Environment.GetEnvironmentVariable(LambdaConstants.ENV_DOTNET_LAMBDA_CLI_LOCAL_MANIFEST_OVERRIDE); if (File.Exists(filePath)) { logger?.WriteLine($"Using local manifest override: {filePath}"); return File.ReadAllText(filePath); } else { logger?.WriteLine("Using local manifest override"); return null; } } string manifestFilename = null; if (string.Equals("netcoreapp2.0", targetFramework, StringComparison.OrdinalIgnoreCase)) manifestFilename = "LambdaPackageStoreManifest.xml"; else if (string.Equals("netcoreapp2.1", targetFramework, StringComparison.OrdinalIgnoreCase)) manifestFilename = "LambdaPackageStoreManifest-v2.1.xml"; if (manifestFilename == null) return null; return ToolkitConfigFileFetcher.Instance.GetFileContentAsync(logger, manifestFilename).Result; } public static string ProcessTemplateSubstitions(IToolLogger logger, string templateBody, IDictionary<string, string> substitutions, string workingDirectory) { if (DetermineTemplateFormat(templateBody) != TemplateFormat.Json || substitutions == null || !substitutions.Any()) return templateBody; logger?.WriteLine($"Processing {substitutions.Count} substitutions."); var root = JsonConvert.DeserializeObject(templateBody) as JObject; foreach (var kvp in substitutions) { logger?.WriteLine($"Processing substitution: {kvp.Key}"); var token = root.SelectToken(kvp.Key); if (token == null) throw new LambdaToolsException($"Failed to locate JSONPath {kvp.Key} for template substitution.", LambdaToolsException.LambdaErrorCode.ServerlessTemplateSubstitutionError); logger?.WriteLine($"\tFound element of type {token.Type}"); string replacementValue; if (workingDirectory != null && File.Exists(Path.Combine(workingDirectory, kvp.Value))) { var path = Path.Combine(workingDirectory, kvp.Value); logger?.WriteLine($"\tReading: {path}"); replacementValue = File.ReadAllText(path); } else { replacementValue = kvp.Value; } try { switch (token.Type) { case JTokenType.String: ((JValue)token).Value = replacementValue; break; case JTokenType.Boolean: bool b; if (bool.TryParse(replacementValue, out b)) { ((JValue)token).Value = b; } else { throw new LambdaToolsException($"Failed to convert {replacementValue} to a bool", LambdaToolsException.LambdaErrorCode.ServerlessTemplateSubstitutionError); } break; case JTokenType.Integer: int i; if (int.TryParse(replacementValue, out i)) { ((JValue)token).Value = i; } else { throw new LambdaToolsException($"Failed to convert {replacementValue} to an int", LambdaToolsException.LambdaErrorCode.ServerlessTemplateSubstitutionError); } break; case JTokenType.Float: double d; if (double.TryParse(replacementValue, out d)) { ((JValue)token).Value = d; } else { throw new LambdaToolsException($"Failed to convert {replacementValue} to a double", LambdaToolsException.LambdaErrorCode.ServerlessTemplateSubstitutionError); } break; case JTokenType.Array: case JTokenType.Object: var jcon = token as JContainer; var jprop = jcon.Parent as JProperty; JToken subData; try { subData = JsonConvert.DeserializeObject(replacementValue) as JToken; } catch (Exception e) { throw new LambdaToolsException($"Failed to parse substitue JSON data: {e.Message}", LambdaToolsException.LambdaErrorCode.ServerlessTemplateSubstitutionError); } jprop.Value = subData; break; default: throw new LambdaToolsException($"Unable to determine how to convert substitute value into the template. " + "Make sure to have a default value in the template which is used to determine the type. " + "For example \"\" for string fields or {} for JSON objects.", LambdaToolsException.LambdaErrorCode.ServerlessTemplateSubstitutionError); } } catch (Exception e) { throw new LambdaToolsException($"Error setting property {kvp.Key} with value {kvp.Value}: {e.Message}", LambdaToolsException.LambdaErrorCode.ServerlessTemplateSubstitutionError); } } var json = JsonConvert.SerializeObject(root); return json; } /// <summary> /// Search for the CloudFormation resources that references the app bundle sent to S3 and update them. /// </summary> /// <param name="templateBody"></param> /// <param name="s3Bucket"></param> /// <param name="s3Key"></param> /// <returns></returns> public static string UpdateCodeLocationInTemplate(string templateBody, string s3Bucket, string s3Key) { switch (LambdaUtilities.DetermineTemplateFormat(templateBody)) { case TemplateFormat.Json: return UpdateCodeLocationInJsonTemplate(templateBody, s3Bucket, s3Key); case TemplateFormat.Yaml: return UpdateCodeLocationInYamlTemplate(templateBody, s3Bucket, s3Key); default: throw new LambdaToolsException("Unable to determine template file format", LambdaToolsException.LambdaErrorCode.ServerlessTemplateParseError); } } public static string UpdateCodeLocationInJsonTemplate(string templateBody, string s3Bucket, string s3Key) { var s3Url = $"s3://{s3Bucket}/{s3Key}"; JsonData root; try { root = JsonMapper.ToObject(templateBody); } catch (Exception e) { throw new LambdaToolsException($"Error parsing CloudFormation template: {e.Message}", LambdaToolsException.LambdaErrorCode.ServerlessTemplateParseError, e); } var resources = root["Resources"]; if (resources == null) throw new LambdaToolsException("CloudFormation template does not define any AWS resources", LambdaToolsException.LambdaErrorCode.ServerlessTemplateMissingResourceSection); foreach (var field in resources.PropertyNames) { var resource = resources[field]; if (resource == null) continue; var properties = resource["Properties"]; if (properties == null) continue; var type = resource["Type"]?.ToString(); if (string.Equals(type, "AWS::Serverless::Function", StringComparison.Ordinal)) { properties["CodeUri"] = s3Url; } if (string.Equals(type, "AWS::Lambda::Function", StringComparison.Ordinal)) { var code = new JsonData(); code["S3Bucket"] = s3Bucket; code["S3Key"] = s3Key; properties["Code"] = code; } } var json = JsonMapper.ToJson(root); return json; } public static string UpdateCodeLocationInYamlTemplate(string templateBody, string s3Bucket, string s3Key) { var s3Url = $"s3://{s3Bucket}/{s3Key}"; // Setup the input var input = new StringReader(templateBody); // Load the stream var yaml = new YamlStream(); yaml.Load(input); // Examine the stream var root = (YamlMappingNode)yaml.Documents[0].RootNode; if (root == null) return templateBody; var resourcesKey = new YamlScalarNode("Resources"); if (!root.Children.ContainsKey(resourcesKey)) return templateBody; var resources = (YamlMappingNode)root.Children[resourcesKey]; foreach (var resource in resources.Children) { var resourceBody = (YamlMappingNode)resource.Value; var type = (YamlScalarNode)resourceBody.Children[new YamlScalarNode("Type")]; var properties = (YamlMappingNode)resourceBody.Children[new YamlScalarNode("Properties")]; if (properties == null) continue; if (type == null) continue; if (string.Equals(type?.Value, "AWS::Serverless::Function", StringComparison.Ordinal)) { properties.Children.Remove(new YamlScalarNode("CodeUri")); properties.Add("CodeUri", s3Url); } else if (string.Equals(type?.Value, "AWS::Lambda::Function", StringComparison.Ordinal)) { properties.Children.Remove(new YamlScalarNode("Code")); var code = new YamlMappingNode(); code.Add("S3Bucket", s3Bucket); code.Add("S3Key", s3Key); properties.Add("Code", code); } } var myText = new StringWriter(); yaml.Save(myText); return myText.ToString(); } internal static TemplateFormat DetermineTemplateFormat(string templateBody) { templateBody = templateBody.Trim(); if (templateBody.Length > 0 && templateBody[0] == '{') return TemplateFormat.Json; return TemplateFormat.Yaml; } /// <summary> /// If the template is a JSON document get the list of parameters to make sure the passed in parameters are valid for the template. /// </summary> /// <param name="templateBody"></param> /// <returns></returns> internal static List<Tuple<string, bool>> GetTemplateDefinedParameters(string templateBody) { if (templateBody.Trim().StartsWith("{")) return GetJsonTemplateDefinedParameters(templateBody); else return GetYamlTemplateDefinedParameters(templateBody); } private static List<Tuple<string, bool>> GetJsonTemplateDefinedParameters(string templateBody) { try { var root = Newtonsoft.Json.JsonConvert.DeserializeObject(templateBody) as JObject; if (root == null) return null; var parameters = root["Parameters"] as JObject; var parms = new List<Tuple<string, bool>>(); if (parameters == null) return parms; foreach (var property in parameters.Properties()) { var noEcho = false; var prop = parameters[property.Name] as JObject; if (prop != null && prop["NoEcho"] != null) { noEcho = Boolean.Parse(prop["NoEcho"].ToString()); } parms.Add(new Tuple<string, bool>(property.Name, noEcho)); } return parms; } catch { return null; } } private static List<Tuple<string, bool>> GetYamlTemplateDefinedParameters(string templateBody) { try { var yaml = new YamlStream(); yaml.Load(new StringReader(templateBody)); // Examine the stream var root = (YamlMappingNode)yaml.Documents[0].RootNode; if (root == null) return null; var parms = new List<Tuple<string, bool>>(); var parametersKey = new YamlScalarNode("Parameters"); if (!root.Children.ContainsKey(parametersKey)) return parms; var parameters = (YamlMappingNode)root.Children[parametersKey]; var noEchoKey = new YamlScalarNode("NoEcho"); foreach (var parameter in parameters.Children) { var parameterBody = parameter.Value as YamlMappingNode; if (parameterBody == null) continue; var noEcho = false; if(parameterBody.Children.ContainsKey(noEchoKey)) { noEcho = bool.Parse(parameterBody.Children[noEchoKey].ToString()); } parms.Add(new Tuple<string, bool>(parameter.Key.ToString(), noEcho)); } return parms; } catch { return null; } } public static async Task<LayerPackageInfo> LoadLayerPackageInfos(IToolLogger logger, IAmazonLambda lambdaClient, IAmazonS3 s3Client, IEnumerable<string> layerVersionArns) { var info = new LayerPackageInfo(); if (layerVersionArns == null || !layerVersionArns.Any()) return info; logger.WriteLine("Inspecting Lambda layers for runtime package store manifests"); foreach(var arn in layerVersionArns) { try { var p = ParseLayerVersionArn(arn); var getLayerResponse = await lambdaClient.GetLayerVersionAsync(new GetLayerVersionRequest { LayerName = p.Name, VersionNumber = p.VersionNumber }); LayerDescriptionManifest manifest; if (!LambdaUtilities.AttemptToParseLayerDescriptionManifest(getLayerResponse.Description, out manifest)) { logger.WriteLine($"... {arn}: Skipped, does not contain a layer description manifest"); continue; } if (manifest.Nlt != LayerDescriptionManifest.ManifestType.RuntimePackageStore) { logger.WriteLine($"... {arn}: Skipped, layer is of type {manifest.Nlt.ToString()}, not {LayerDescriptionManifest.ManifestType.RuntimePackageStore}"); continue; } string GetLastArnComponent(string input) { return input.Substring(input.LastIndexOf(':') + 1); } var layerName = GetLastArnComponent(getLayerResponse.LayerArn); var layerVers = GetLastArnComponent(getLayerResponse.LayerVersionArn); var tempPath = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())); var filePath = Path.Combine(tempPath.FullName, $"{layerName}-v{layerVers}.xml"); using (var getResponse = await s3Client.GetObjectAsync(manifest.Buc, manifest.Key)) using (var reader = new StreamReader(getResponse.ResponseStream)) { await getResponse.WriteResponseStreamToFileAsync(filePath, false, default(System.Threading.CancellationToken)); } logger.WriteLine($"... {arn}: Downloaded package manifest for runtime package store layer"); info.Items.Add(new LayerPackageInfo.LayerPackageInfoItem { Directory = manifest.Dir, ManifestPath = filePath }); } catch(Exception e) { logger.WriteLine($"... {arn}: Skipped, error inspecting layer. {e.Message}"); } } return info; } internal static bool AttemptToParseLayerDescriptionManifest(string json, out LayerDescriptionManifest manifest) { manifest = null; if (string.IsNullOrEmpty(json) || json[0] != '{') return false; try { manifest = JsonMapper.ToObject<LayerDescriptionManifest>(json); return true; } catch { return false; } } internal class ParseLayerVersionArnResult { internal string Name { get; } internal long VersionNumber { get; } internal ParseLayerVersionArnResult(string name, long versionNumber) { this.Name = name; this.VersionNumber = versionNumber; } } internal static ParseLayerVersionArnResult ParseLayerVersionArn(string layerVersionArn) { try { int pos = layerVersionArn.LastIndexOf(':'); var number = long.Parse(layerVersionArn.Substring(pos + 1)); var arn = layerVersionArn.Substring(0, pos); return new ParseLayerVersionArnResult(arn, number); } catch (Exception) { throw new LambdaToolsException("Error parsing layer version arn into layer name and version number", LambdaToolsException.LambdaErrorCode.ParseLayerVersionArnFail); } } public static string DetermineListDisplayLayerDescription(string description, int maxDescriptionLength) { if (string.IsNullOrWhiteSpace(description)) return ""; try { LayerDescriptionManifest manifest; var parsed = AttemptToParseLayerDescriptionManifest(description, out manifest); if(parsed) { if (manifest?.Nlt == LayerDescriptionManifest.ManifestType.RuntimePackageStore) { if (manifest.Op == LayerDescriptionManifest.OptimizedState.Optimized) return LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE_DISPLAY_NAME + " (Optimized)"; return LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE_DISPLAY_NAME; } } } catch (Exception) { } if (description.Length <= maxDescriptionLength) { return description; } return description.Substring(0, maxDescriptionLength); } public class ConvertManifestToSdkManifestResult { public bool ShouldDelete { get; } public string PackageManifest { get; } public ConvertManifestToSdkManifestResult(bool shouldDelete, string packageManifest) { this.ShouldDelete = shouldDelete; this.PackageManifest = packageManifest; } } public static ConvertManifestToSdkManifestResult ConvertManifestToSdkManifest(string targetFramework, string packageManifest) { var content = File.ReadAllText(packageManifest); var result = ConvertManifestContentToSdkManifest(targetFramework, content); if (!result.Updated) { return new ConvertManifestToSdkManifestResult(false, packageManifest); } var newPath = Path.GetTempFileName(); File.WriteAllText(newPath, result.UpdatedContent); return new ConvertManifestToSdkManifestResult(true, newPath); } public class ConvertManifestContentToSdkManifestResult { public bool Updated { get; } public string UpdatedContent { get; } public ConvertManifestContentToSdkManifestResult(bool updated, string updatedContent) { this.Updated = updated; this.UpdatedContent = updatedContent; } } public static ConvertManifestContentToSdkManifestResult ConvertManifestContentToSdkManifest(string targetFramework, string packageManifestContent) { var originalDoc = XDocument.Parse(packageManifestContent); var sdkType = originalDoc.Root.Attribute("Sdk")?.Value ?? "Microsoft.NET.Sdk"; var isWebSdk = string.Equals(sdkType, "Microsoft.NET.Sdk.Web", StringComparison.OrdinalIgnoreCase); if (string.Equals("netcoreapp2.1", targetFramework) && !isWebSdk) return new ConvertManifestContentToSdkManifestResult(false, packageManifestContent); var root = new XElement("Project"); root.SetAttributeValue("Sdk", "Microsoft.NET.Sdk"); var itemGroup = new XElement("ItemGroup"); root.Add(itemGroup); Version dotnetSdkVersion; try { dotnetSdkVersion = Amazon.Common.DotNetCli.Tools.DotNetCLIWrapper.GetSdkVersion(); } catch (Exception e) { throw new LambdaToolsException("Error detecting .NET SDK version: \n\t" + e.Message, LambdaToolsException.LambdaErrorCode.FailedToDetectSdkVersion, e ); } if (isWebSdk) { if(string.Equals("netcoreapp2.1", targetFramework, StringComparison.OrdinalIgnoreCase)) { if (dotnetSdkVersion < LambdaConstants.MINIMUM_DOTNET_SDK_VERSION_FOR_ASPNET_LAYERS) { throw new LambdaToolsException($"To create a runtime package store layer for an ASP.NET Core project " + $"version {LambdaConstants.MINIMUM_DOTNET_SDK_VERSION_FOR_ASPNET_LAYERS} " + "or above of the .NET Core SDK must be installed. " + "If a 2.1.X SDK is used then the \"dotnet store\" command will include all " + "of the ASP.NET Core dependencies that are already available in Lambda.", LambdaToolsException.LambdaErrorCode.LayerNetSdkVersionMismatch); } // These were added to make sure the ASP.NET Core dependencies are filter if any of the packages // depend on them. // See issue for more info: https://github.com/dotnet/cli/issues/10784 var aspNerCorePackageReference = new XElement("PackageReference"); aspNerCorePackageReference.SetAttributeValue("Include", "Microsoft.AspNetCore.App"); itemGroup.Add(aspNerCorePackageReference); var aspNerCoreUpdatePackageReference = new XElement("PackageReference"); aspNerCoreUpdatePackageReference.SetAttributeValue("Update", "Microsoft.NETCore.App"); aspNerCoreUpdatePackageReference.SetAttributeValue("Publish", "false"); itemGroup.Add(aspNerCoreUpdatePackageReference); } else { var frameworkReference = new XElement("FrameworkReference"); frameworkReference.SetAttributeValue("Include", "Microsoft.AspNetCore.App"); var frameworkReferenceGroupItemGroup = new XElement("ItemGroup"); frameworkReferenceGroupItemGroup.Add(frameworkReference); root.Add(frameworkReferenceGroupItemGroup); } } foreach (var packageReference in originalDoc.XPathSelectElements("//ItemGroup/PackageReference")) { var packageName = packageReference.Attribute("Include")?.Value; var version = packageReference.Attribute("Version")?.Value; if (string.Equals(packageName, "Microsoft.AspNetCore.App", StringComparison.OrdinalIgnoreCase) || string.Equals(packageName, "Microsoft.AspNetCore.All", StringComparison.OrdinalIgnoreCase)) continue; var newRef = new XElement("PackageReference"); newRef.SetAttributeValue("Include", packageName); newRef.SetAttributeValue("Version", version); itemGroup.Add(newRef); } // In .NET Core 3.1 the dotnet store command will include system dependencies like System.Runtime if // any of the packages referenced in the packages included explicit references system dependencies. // This is common on older packages or versions of packages before .NET Core 2.1. Newtonsoft.Json version 9.0.1 // is an example of this behavior. // // To avoid these system dependencies getting added to the layer we need to inject the list of system // dependency to prune from the store graph. // // For further information on the issue check out this GitHub issue: https://github.com/dotnet/sdk/issues/10973 if (string.Equals(targetFramework, "netcoreapp3.1", StringComparison.OrdinalIgnoreCase)) { var lambdaAssembly = typeof(LambdaUtilities).Assembly; string manifestName; if (isWebSdk) { manifestName = lambdaAssembly.GetManifestResourceNames().FirstOrDefault(x => x.EndsWith(LambdaConstants.PRUNE_LIST_SDKWEB_XML)); } else { manifestName = lambdaAssembly.GetManifestResourceNames().FirstOrDefault(x => x.EndsWith(LambdaConstants.PRUNE_LIST_SDK_XML)); } string pruneListString; using (var stream = lambdaAssembly.GetManifestResourceStream(manifestName)) { pruneListString = new StreamReader(stream).ReadToEnd(); } var pruneListElement = XElement.Parse(pruneListString); root.Add(pruneListElement); } var updatedDoc = new XDocument(root); var updatedContent = updatedDoc.ToString(); return new ConvertManifestContentToSdkManifestResult(true, updatedContent); } /// <summary> /// Determines what runtime identifier (RID) to use when running a dotnet CLI command. For the /// older .NET Lambda runtimes that are not running on Amazon Linux 2 keep using the existing rhel.7.2-x64 /// RID. For all other runtimes that are running on Amazon Linux 2 use the newer linux-x64 RID which did /// not exist when this tool was first created. /// </summary> /// <param name="targetFramework"></param> /// <returns></returns> public static string DetermineRuntimeParameter(string targetFramework, string architecture) { if (string.Equals(LambdaConstants.ARCHITECTURE_ARM64, architecture, StringComparison.InvariantCultureIgnoreCase)) { return LambdaConstants.RUNTIME_LINUX_ARM64; } else if(string.IsNullOrEmpty(architecture) || string.Equals(LambdaConstants.ARCHITECTURE_X86_64, architecture, StringComparison.InvariantCultureIgnoreCase)) { switch (targetFramework) { case "netcoreapp1.0": case "netcoreapp2.0": case "netcoreapp2.1": return LambdaConstants.LEGACY_RUNTIME_HIERARCHY_STARTING_POINT; default: return LambdaConstants.RUNTIME_LINUX_X64; } } else { throw new LambdaToolsException($"Value of {architecture} is invalid for function architecture", ToolsException.CommonErrorCode.InvalidParameterValue); } } public static async Task WaitTillFunctionAvailableAsync(IToolLogger logger, IAmazonLambda lambdaClient, string functionName) { const int POLL_INTERVAL = 3000; const int MAX_TIMEOUT_MINUTES = 20; try { var request = new GetFunctionConfigurationRequest { FunctionName = functionName }; GetFunctionConfigurationResponse response = null; bool logInitialMessage = false; var timeout = DateTime.UtcNow.AddMinutes(MAX_TIMEOUT_MINUTES); var startTime = DateTime.UtcNow; do { response = await lambdaClient.GetFunctionConfigurationAsync(request); if (response.LastUpdateStatus != LastUpdateStatus.InProgress && response.State != State.Pending) { if(response.LastUpdateStatus == LastUpdateStatus.Failed) { // Not throwing exception because it is possible the calling code could be fixing the failed state. logger.WriteLine($"Warning: function {functionName} is currently in failed state: {response.LastUpdateStatusReason}"); } return; } if(!logInitialMessage) { logger.WriteLine($"An update is currently in progress for Lambda function {functionName}. Waiting till update completes."); logInitialMessage = true; } else { var ts = DateTime.UtcNow - startTime; logger.WriteLine($"... Waiting ({ts.TotalSeconds.ToString("N2")} seconds)"); } await Task.Delay(POLL_INTERVAL); } while (DateTime.UtcNow < timeout); } catch(Exception e) { throw new LambdaToolsException($"Error waiting for Lambda function to be in available status: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaWaitTillFunctionAvailable); } throw new LambdaToolsException($"Timeout waiting for function {functionName} to become available", LambdaToolsException.LambdaErrorCode.LambdaWaitTillFunctionAvailable); } public static async Task<string> ResolveDefaultS3Bucket(IToolLogger logger, IAmazonS3 s3Client, IAmazonSecurityTokenService stsClient) { var region = s3Client.Config.RegionEndpoint?.SystemName; if(string.IsNullOrEmpty(region)) { throw new LambdaToolsException("Error resolving default S3 bucket for deployment bundles: region could not be determined", LambdaToolsException.LambdaErrorCode.FailedToResolveS3Bucket); } try { var accountId = (await stsClient.GetCallerIdentityAsync(new SecurityToken.Model.GetCallerIdentityRequest())).Account; var bucketName = $"{LambdaConstants.DEFAULT_BUCKET_NAME_PREFIX}{region}-{accountId}"; if (!(await s3Client.ListBucketsAsync(new ListBucketsRequest())).Buckets.Any(x => string.Equals(x.BucketName, bucketName, StringComparison.CurrentCultureIgnoreCase))) { logger?.WriteLine($"Creating S3 bucket {bucketName} for storage of deployment bundles"); await s3Client.PutBucketAsync(new PutBucketRequest { BucketName = bucketName, UseClientRegion = true }); } else { logger?.WriteLine($"Using S3 bucket {bucketName} for storage of deployment bundles"); } return bucketName; } catch(Exception e) { throw new LambdaToolsException("Error resolving default S3 bucket for deployment bundles: " + e.Message, LambdaToolsException.LambdaErrorCode.FailedToResolveS3Bucket); } } public static void ValidateNativeAotArchitecture(string architecture, bool isNativeAot) { if (!isNativeAot) { return; } #if !NETCOREAPP3_1_OR_GREATER return; // If we're below netcoreapp3.1, we're probably running from the visual studio extension, and therefore probably not running on ARM #else var hostArchitecture = RuntimeInformation.ProcessArchitecture; if (hostArchitecture == System.Runtime.InteropServices.Architecture.X86) hostArchitecture = System.Runtime.InteropServices.Architecture.X64; var targetArchitecture = string.Equals(architecture, LambdaConstants.ARCHITECTURE_ARM64, StringComparison.OrdinalIgnoreCase) ? System.Runtime.InteropServices.Architecture.Arm64 : System.Runtime.InteropServices.Architecture.X64; if (hostArchitecture != targetArchitecture) { throw new LambdaToolsException($"Host machine architecture ({hostArchitecture}) differs from Lambda architecture ({targetArchitecture}). Building Native AOT Lambda functions require the host and lambda architectures to match.", LambdaToolsException.LambdaErrorCode.MismatchedNativeAotArchitectures); } #endif } } }
973
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.Tools { /// <summary> /// Is class is serialized as the description of the layer. Space in the description is limited /// so property names are kept short. Enum are also stored as numbers. /// </summary> public class LayerDescriptionManifest { public LayerDescriptionManifest() { } public LayerDescriptionManifest(ManifestType type) { this.Nlt = type; } public enum ManifestType { RuntimePackageStore=1 } public enum OptimizedState { NoOptimized=0, Optimized=1} /// <summary> /// .NET Layer Type /// </summary> public ManifestType Nlt { get; set; } /// <summary> /// The sub directory in the packages zip file that NuGet packages will be placed. This /// will be the sub folder under the /opt directory in the Lambda environment. /// </summary> public string Dir { get; set; } /// <summary> /// Indicates whether the packages were pre-jitted when the store was created. /// </summary> public OptimizedState Op { get; set; } /// <summary> /// The S3 bucket containing the artifact.xml file. /// </summary> public string Buc { get; set; } /// <summary> /// THe S3 object key for the artifact.xml file. /// </summary> public string Key { get; set; } } }
53
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.Tools { /// <summary> /// This class contains the runtime package store information from a collection of Lambda layers. /// </summary> public class LayerPackageInfo { public IList<LayerPackageInfoItem> Items { get; } = new List<LayerPackageInfoItem>(); /// <summary> /// Generates the value that must be set for the DOTNET_SHARED_STORE environment variable. /// </summary> /// <returns></returns> public string GenerateDotnetSharedStoreValue() { var sb = new StringBuilder(); var processedDirectories = new HashSet<string>(); foreach(var item in Items) { if (processedDirectories.Contains(item.Directory)) continue; processedDirectories.Add(item.Directory); if (sb.Length > 0) sb.Append(":"); sb.Append($"/opt/{item.Directory}/"); } return sb.ToString(); } public class LayerPackageInfoItem { /// <summary> /// The directory under /opt folder in the Lambda environment that the store will be placed/ /// </summary> public string Directory { get; set; } /// <summary> /// Local file path the artifact.xml file that list the NuGet packages in the Layer. /// </summary> public string ManifestPath { get; set; } } } }
52
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using Amazon.Common.DotNetCli.Tools.CLi; using Amazon.Common.DotNetCli.Tools.Commands; using Amazon.Lambda.Tools.Commands; namespace Amazon.Lambda.Tools { public class Program { static void Main(string[] args) { var application = new Application("lambda", "Amazon Lambda Tools for .NET Core applications", "https://github.com/aws/aws-extensions-for-dotnet-cli, https://github.com/aws/aws-lambda-dotnet", new List<ICommandInfo>() { new GroupHeaderInfo("Commands to deploy and manage AWS Lambda functions:"), new CommandInfo<DeployFunctionCommand>(DeployFunctionCommand.COMMAND_DEPLOY_NAME, DeployFunctionCommand.COMMAND_DEPLOY_DESCRIPTION, DeployFunctionCommand.DeployCommandOptions, DeployFunctionCommand.COMMAND_ARGUMENTS), new CommandInfo<InvokeFunctionCommand>(InvokeFunctionCommand.COMMAND_NAME, InvokeFunctionCommand.COMMAND_DESCRIPTION, InvokeFunctionCommand.InvokeCommandOptions, InvokeFunctionCommand.COMMAND_ARGUMENTS), new CommandInfo<ListFunctionCommand>(ListFunctionCommand.COMMAND_NAME, ListFunctionCommand.COMMAND_DESCRIPTION, ListFunctionCommand.ListCommandOptions), new CommandInfo<DeleteFunctionCommand>(DeleteFunctionCommand.COMMAND_NAME, DeleteFunctionCommand.COMMAND_DESCRIPTION, DeleteFunctionCommand.DeleteCommandOptions, DeleteFunctionCommand.COMMAND_ARGUMENTS), new CommandInfo<GetFunctionConfigCommand>(GetFunctionConfigCommand.COMMAND_NAME, GetFunctionConfigCommand.COMMAND_DESCRIPTION, GetFunctionConfigCommand.GetConfigCommandOptions, GetFunctionConfigCommand.COMMAND_ARGUMENTS), new CommandInfo<UpdateFunctionConfigCommand>(UpdateFunctionConfigCommand.COMMAND_NAME, UpdateFunctionConfigCommand.COMMAND_DESCRIPTION, UpdateFunctionConfigCommand.UpdateCommandOptions, UpdateFunctionConfigCommand.COMMAND_ARGUMENTS), new GroupHeaderInfo("Commands to deploy and manage AWS Serverless applications using AWS CloudFormation:"), new CommandInfo<DeployServerlessCommand>(DeployServerlessCommand.COMMAND_NAME, DeployServerlessCommand.COMMAND_DESCRIPTION, DeployServerlessCommand.DeployServerlessCommandOptions, DeployServerlessCommand.COMMAND_ARGUMENTS), new CommandInfo<ListServerlessCommand>(ListServerlessCommand.COMMAND_NAME, ListServerlessCommand.COMMAND_DESCRIPTION, ListServerlessCommand.ListCommandOptions), new CommandInfo<DeleteServerlessCommand>(DeleteServerlessCommand.COMMAND_NAME, DeleteServerlessCommand.COMMAND_DESCRIPTION, DeleteServerlessCommand.DeleteCommandOptions, DeleteServerlessCommand.COMMAND_ARGUMENTS), new GroupHeaderInfo("Commands to publish and manage AWS Lambda Layers:"), new CommandInfo<PublishLayerCommand>(PublishLayerCommand.COMMAND_NAME, PublishLayerCommand.COMMAND_DESCRIPTION, PublishLayerCommand.PublishLayerCommandOptions, PublishLayerCommand.COMMAND_ARGUMENTS), new CommandInfo<ListLayersCommand>(ListLayersCommand.COMMAND_NAME, ListLayersCommand.COMMAND_DESCRIPTION, ListLayersCommand.ListCommandOptions), new CommandInfo<ListLayerVersionsCommand>(ListLayerVersionsCommand.COMMAND_NAME, ListLayerVersionsCommand.COMMAND_DESCRIPTION, ListLayerVersionsCommand.ListCommandOptions, ListLayerVersionsCommand.COMMAND_ARGUMENTS), new CommandInfo<GetLayerVersionDetailsCommand>(GetLayerVersionDetailsCommand.COMMAND_NAME, GetLayerVersionDetailsCommand.COMMAND_DESCRIPTION, GetLayerVersionDetailsCommand.CommandOptions, GetLayerVersionDetailsCommand.COMMAND_ARGUMENTS), new CommandInfo<DeleteLayerVersionCommand>(DeleteLayerVersionCommand.COMMAND_NAME, DeleteLayerVersionCommand.COMMAND_DESCRIPTION, DeleteLayerVersionCommand.CommandOptions, DeleteLayerVersionCommand.COMMAND_ARGUMENTS), new GroupHeaderInfo("Other Commands:"), new CommandInfo<PackageCommand>(PackageCommand.COMMAND_NAME, PackageCommand.COMMAND_DESCRIPTION, PackageCommand.PackageCommandOptions, PackageCommand.COMMAND_ARGUMENTS), new CommandInfo<PackageCICommand>(PackageCICommand.COMMAND_NAME, PackageCICommand.COMMAND_SYNOPSIS, PackageCICommand.PackageCICommandOptions), new CommandInfo<PushDockerImageCommand>(PushDockerImageCommand.COMMAND_NAME, PushDockerImageCommand.COMMAND_DESCRIPTION, PushDockerImageCommand.LambdaPushCommandOptions) }); var exitCode = application.Execute(args); if (exitCode != 0) { Environment.Exit(-1); } } } }
51
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Lambda.Model; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.Commands { /// <summary> /// Command to delete a function /// </summary> public class DeleteFunctionCommand : LambdaBaseCommand { public const string COMMAND_NAME = "delete-function"; public const string COMMAND_DESCRIPTION = "Command to delete a Lambda function"; public const string COMMAND_ARGUMENTS = "<FUNCTION-NAME> The name of the function to delete"; public static readonly IList<CommandOption> DeleteCommandOptions = BuildLineOptions(new List<CommandOption> { LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME }); public string FunctionName { get; set; } public DeleteFunctionCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, DeleteCommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); if (values.Arguments.Count > 0) { this.FunctionName = values.Arguments[0]; } Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME.Switch)) != null) this.FunctionName = tuple.Item2.StringValue; } protected override async Task<bool> PerformActionAsync() { var deleteRequest = new DeleteFunctionRequest { FunctionName = this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true) }; try { await this.LambdaClient.DeleteFunctionAsync(deleteRequest); } catch(Exception e) { throw new LambdaToolsException("Error deleting Lambda function: " + e.Message, LambdaToolsException.LambdaErrorCode.LambdaDeleteFunction, e); } this.Logger?.WriteLine($"Lambda function {deleteRequest.FunctionName} deleted"); return true; } protected override void SaveConfigFile(JsonData data) { data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME.ConfigFileKey, this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, false)); } } }
86
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Lambda.Model; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.Commands { /// <summary> /// Command to delete a Lambda layer version /// </summary> public class DeleteLayerVersionCommand : LambdaBaseCommand { public const string COMMAND_NAME = "delete-layer-version"; public const string COMMAND_DESCRIPTION = "Command to delete a version of a Layer"; public const string COMMAND_ARGUMENTS = "<LAYER-VERSION-ARN> The arn of the Layer version to delete"; public static readonly IList<CommandOption> CommandOptions = BuildLineOptions(new List<CommandOption> { LambdaDefinedCommandOptions.ARGUMENT_LAYER_VERSION_ARN }); public string LayerVersionArn { get; set; } public DeleteLayerVersionCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, CommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); if (values.Arguments.Count > 0) { this.LayerVersionArn = values.Arguments[0]; } Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_LAYER_VERSION_ARN.Switch)) != null) this.LayerVersionArn = tuple.Item2.StringValue; } protected override async Task<bool> PerformActionAsync() { var layerVersionArn = this.GetStringValueOrDefault(this.LayerVersionArn, LambdaDefinedCommandOptions.ARGUMENT_LAYER_VERSION_ARN, true); var results = LambdaUtilities.ParseLayerVersionArn(layerVersionArn); var deleteRequest = new DeleteLayerVersionRequest { LayerName = results.Name, VersionNumber = results.VersionNumber }; try { await this.LambdaClient.DeleteLayerVersionAsync(deleteRequest); } catch(Exception e) { throw new LambdaToolsException("Error deleting Lambda layer version: " + e.Message, LambdaToolsException.LambdaErrorCode.LambdaDeleteLayerVersion, e); } this.Logger?.WriteLine($"Deleted version {results.VersionNumber} for layer {results.Name}"); return true; } protected override void SaveConfigFile(JsonData data) { } } }
89
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.CloudFormation.Model; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.Commands { public class DeleteServerlessCommand : LambdaBaseCommand { public const string COMMAND_NAME = "delete-serverless"; public const string COMMAND_DESCRIPTION = "Command to delete an AWS Serverless application"; public const string COMMAND_ARGUMENTS = "<STACK-NAME> The CloudFormation stack for the AWS Serverless application"; public static readonly IList<CommandOption> DeleteCommandOptions = BuildLineOptions(new List<CommandOption> { LambdaDefinedCommandOptions.ARGUMENT_STACK_NAME }); public string StackName { get; set; } public DeleteServerlessCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, DeleteCommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); if (values.Arguments.Count > 0) { this.StackName = values.Arguments[0]; } Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_STACK_NAME.Switch)) != null) this.StackName = tuple.Item2.StringValue; } protected override async Task<bool> PerformActionAsync() { var deleteRequest = new DeleteStackRequest { StackName = this.GetStringValueOrDefault(this.StackName, LambdaDefinedCommandOptions.ARGUMENT_STACK_NAME, true) }; try { await this.CloudFormationClient.DeleteStackAsync(deleteRequest); } catch (Exception e) { throw new LambdaToolsException("Error deleting CloudFormation stack: " + e.Message, LambdaToolsException.LambdaErrorCode.CloudFormationDeleteStack, e); } this.Logger.WriteLine($"CloudFormation stack {deleteRequest.StackName} deleted"); return true; } protected override void SaveConfigFile(JsonData data) { data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_STACK_NAME.ConfigFileKey, this.GetStringValueOrDefault(this.StackName, LambdaDefinedCommandOptions.ARGUMENT_STACK_NAME, false)); } } }
82
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Model; using ThirdParty.Json.LitJson; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Commands; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Runtime.Internal; namespace Amazon.Lambda.Tools.Commands { /// <summary> /// Command to deploy a function to AWS Lambda. When redeploying an existing function only function configuration properties /// that were explicitly set will be used. Default function configuration values are ignored for redeploy. This /// is to avoid any accidental changes to the function. /// </summary> public class DeployFunctionCommand : UpdateFunctionConfigCommand { public const string COMMAND_DEPLOY_NAME = "deploy-function"; public const string COMMAND_DEPLOY_DESCRIPTION = "Command to deploy the project to AWS Lambda"; public const string COMMAND_DEPLOY_ARGUMENTS = "<FUNCTION-NAME> The name of the function to deploy"; public static readonly IList<CommandOption> DeployCommandOptions = BuildLineOptions(new List<CommandOption> { CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, LambdaDefinedCommandOptions.ARGUMENT_PACKAGE, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_DESCRIPTION, LambdaDefinedCommandOptions.ARGUMENT_PACKAGE_TYPE, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_PUBLISH, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_MEMORY_SIZE, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ROLE, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TIMEOUT, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_HANDLER, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_RUNTIME, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_LAYERS, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_ENTRYPOINT, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_COMMAND, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_WORKING_DIRECTORY, CommonDefinedCommandOptions.ARGUMENT_DOCKER_TAG, LambdaDefinedCommandOptions.ARGUMENT_EPHEMERAL_STORAGE_SIZE, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_ENABLE, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_AUTH, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TAGS, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SUBNETS, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SECURITY_GROUPS, LambdaDefinedCommandOptions.ARGUMENT_DEADLETTER_TARGET_ARN, LambdaDefinedCommandOptions.ARGUMENT_TRACING_MODE, LambdaDefinedCommandOptions.ARGUMENT_ENVIRONMENT_VARIABLES, LambdaDefinedCommandOptions.ARGUMENT_APPEND_ENVIRONMENT_VARIABLES, LambdaDefinedCommandOptions.ARGUMENT_KMS_KEY_ARN, LambdaDefinedCommandOptions.ARGUMENT_APPLY_DEFAULTS_FOR_UPDATE_OBSOLETE, LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX, LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK, CommonDefinedCommandOptions.ARGUMENT_LOCAL_DOCKER_IMAGE, CommonDefinedCommandOptions.ARGUMENT_DOCKERFILE, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY, CommonDefinedCommandOptions.ARGUMENT_HOST_BUILD_OUTPUT, LambdaDefinedCommandOptions.ARGUMENT_USE_CONTAINER_FOR_BUILD, LambdaDefinedCommandOptions.ARGUMENT_CONTAINER_IMAGE_FOR_BUILD, LambdaDefinedCommandOptions.ARGUMENT_CODE_MOUNT_DIRECTORY }); public string Architecture { get; set; } public string Configuration { get; set; } public string TargetFramework { get; set; } public string Package { get; set; } public string MSBuildParameters { get; set; } public bool? ResolveS3 { get; set; } public string S3Bucket { get; set; } public string S3Prefix { get; set; } public bool? DisableVersionCheck { get; set; } public string DockerFile { get; set; } public string DockerBuildOptions { get; set; } public string DockerBuildWorkingDirectory { get; set; } public string DockerImageTag { get; set; } public string HostBuildOutput { get; set; } public string LocalDockerImage { get; set; } public bool? UseContainerForBuild { get; set; } public string ContainerImageForBuild { get; set; } public string CodeMountDirectory { get; set; } public DeployFunctionCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, DeployCommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); if (values.Arguments.Count > 0) { this.FunctionName = values.Arguments[0]; } Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION.Switch)) != null) this.Configuration = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.Switch)) != null) this.TargetFramework = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_PACKAGE.Switch)) != null) this.Package = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3.Switch)) != null) this.ResolveS3 = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET.Switch)) != null) this.S3Bucket = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX.Switch)) != null) this.S3Prefix = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK.Switch)) != null) this.DisableVersionCheck = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE.Switch)) != null) this.Architecture = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS.Switch)) != null) this.MSBuildParameters = tuple.Item2.StringValue; if (!string.IsNullOrEmpty(values.MSBuildParameters)) { if (this.MSBuildParameters == null) this.MSBuildParameters = values.MSBuildParameters; else this.MSBuildParameters += " " + values.MSBuildParameters; } if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_PACKAGE_TYPE.Switch)) != null) this.PackageType = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_DOCKERFILE.Switch)) != null) this.DockerFile = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS.Switch)) != null) this.DockerBuildOptions = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY.Switch)) != null) this.DockerBuildWorkingDirectory = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_IMAGE_TAG.Switch)) != null) this.DockerImageTag = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_HOST_BUILD_OUTPUT.Switch)) != null) this.HostBuildOutput = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_LOCAL_DOCKER_IMAGE.Switch)) != null) this.LocalDockerImage = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_USE_CONTAINER_FOR_BUILD.Switch)) != null) this.UseContainerForBuild = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_CONTAINER_IMAGE_FOR_BUILD.Switch)) != null) this.ContainerImageForBuild = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_CODE_MOUNT_DIRECTORY.Switch)) != null) this.CodeMountDirectory = tuple.Item2.StringValue; } protected override async Task<bool> PerformActionAsync() { string projectLocation = Utilities.DetermineProjectLocation(this.WorkingDirectory, this.GetStringValueOrDefault(this.ProjectLocation, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false)); string zipArchivePath = null; string package = this.GetStringValueOrDefault(this.Package, LambdaDefinedCommandOptions.ARGUMENT_PACKAGE, false); var layerVersionArns = this.GetStringValuesOrDefault(this.LayerVersionArns, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_LAYERS, false); var layerPackageInfo = await LambdaUtilities.LoadLayerPackageInfos(this.Logger, this.LambdaClient, this.S3Client, layerVersionArns); var architecture = this.GetStringValueOrDefault(this.Architecture, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE, false); Lambda.PackageType packageType = DeterminePackageType(); string ecrImageUri = null; if (packageType == Lambda.PackageType.Image) { var pushResults = await PushLambdaImageAsync(); if (!pushResults.Success) { if (pushResults.LastException != null) throw pushResults.LastException; throw new LambdaToolsException("Failed to push container image to ECR.", LambdaToolsException.LambdaErrorCode.FailedToPushImage); } ecrImageUri = pushResults.ImageUri; } else { if (string.IsNullOrEmpty(package)) { EnsureInProjectDirectory(); // Release will be the default configuration if nothing set. string configuration = this.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false); var targetFramework = this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false); if (string.IsNullOrEmpty(targetFramework)) { targetFramework = Utilities.LookupTargetFrameworkFromProjectFile(projectLocation); // If we still don't know what the target framework is ask the user what targetframework to use. // This is common when a project is using multi targeting. if(string.IsNullOrEmpty(targetFramework)) { targetFramework = this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, true); } } string msbuildParameters = this.GetStringValueOrDefault(this.MSBuildParameters, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, false); bool isNativeAot = Utilities.LookPublishAotFlag(projectLocation, this.MSBuildParameters); ValidateTargetFrameworkAndLambdaRuntime(targetFramework); bool disableVersionCheck = this.GetBoolValueOrDefault(this.DisableVersionCheck, LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK, false).GetValueOrDefault(); string publishLocation; LambdaPackager.CreateApplicationBundle(defaults: this.DefaultConfig, logger: this.Logger, workingDirectory: this.WorkingDirectory, projectLocation: projectLocation, configuration: configuration, targetFramework: targetFramework, msbuildParameters: msbuildParameters, architecture: architecture, disableVersionCheck: disableVersionCheck, layerPackageInfo: layerPackageInfo, isNativeAot: isNativeAot, useContainerForBuild: GetBoolValueOrDefault(this.UseContainerForBuild, LambdaDefinedCommandOptions.ARGUMENT_USE_CONTAINER_FOR_BUILD, false), containerImageForBuild: GetStringValueOrDefault(this.ContainerImageForBuild, LambdaDefinedCommandOptions.ARGUMENT_CONTAINER_IMAGE_FOR_BUILD, false), codeMountDirectory: GetStringValueOrDefault(this.CodeMountDirectory, LambdaDefinedCommandOptions.ARGUMENT_CODE_MOUNT_DIRECTORY, false), publishLocation: out publishLocation, zipArchivePath: ref zipArchivePath ); if (string.IsNullOrEmpty(zipArchivePath)) throw new LambdaToolsException("Failed to create Lambda deployment bundle.", ToolsException.CommonErrorCode.DotnetPublishFailed); } else { if (!File.Exists(package)) throw new LambdaToolsException($"Package {package} does not exist", LambdaToolsException.LambdaErrorCode.InvalidPackage); if (!string.Equals(Path.GetExtension(package), ".zip", StringComparison.OrdinalIgnoreCase)) throw new LambdaToolsException($"Package {package} must be a zip file", LambdaToolsException.LambdaErrorCode.InvalidPackage); this.Logger.WriteLine($"Skipping compilation and using precompiled package {package}"); zipArchivePath = package; } } MemoryStream lambdaZipArchiveStream = null; if(zipArchivePath != null) { lambdaZipArchiveStream = new MemoryStream(File.ReadAllBytes(zipArchivePath)); } try { var s3Bucket = this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, false); bool? resolveS3 = this.GetBoolValueOrDefault(this.ResolveS3, LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3, false); string s3Key = null; if (zipArchivePath != null && (resolveS3 == true || !string.IsNullOrEmpty(s3Bucket))) { if(string.IsNullOrEmpty(s3Bucket)) { s3Bucket = await LambdaUtilities.ResolveDefaultS3Bucket(this.Logger, this.S3Client, this.STSClient); } else { await Utilities.ValidateBucketRegionAsync(this.S3Client, s3Bucket); } var functionName = this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true); var s3Prefix = this.GetStringValueOrDefault(this.S3Prefix, LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX, false); s3Key = await Utilities.UploadToS3Async(this.Logger, this.S3Client, s3Bucket, s3Prefix, functionName, lambdaZipArchiveStream); } var currentConfiguration = await GetFunctionConfigurationAsync(); if (currentConfiguration == null) { this.Logger.WriteLine($"Creating new Lambda function {this.FunctionName}"); var createRequest = new CreateFunctionRequest { PackageType = packageType, FunctionName = this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true), Description = this.GetStringValueOrDefault(this.Description, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_DESCRIPTION, false), Role = this.GetRoleValueOrDefault(this.Role, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ROLE, Constants.LAMBDA_PRINCIPAL, LambdaConstants.AWS_LAMBDA_MANAGED_POLICY_PREFIX, LambdaConstants.KNOWN_MANAGED_POLICY_DESCRIPTIONS, true), Publish = this.GetBoolValueOrDefault(this.Publish, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_PUBLISH, false).GetValueOrDefault(), MemorySize = this.GetIntValueOrDefault(this.MemorySize, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_MEMORY_SIZE, true).GetValueOrDefault(), Timeout = this.GetIntValueOrDefault(this.Timeout, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TIMEOUT, true).GetValueOrDefault(), KMSKeyArn = this.GetStringValueOrDefault(this.KMSKeyArn, LambdaDefinedCommandOptions.ARGUMENT_KMS_KEY_ARN, false), VpcConfig = new VpcConfig { SubnetIds = this.GetStringValuesOrDefault(this.SubnetIds, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SUBNETS, false)?.ToList(), SecurityGroupIds = this.GetStringValuesOrDefault(this.SecurityGroupIds, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SECURITY_GROUPS, false)?.ToList() } }; var ephemeralSize = this.GetIntValueOrDefault(this.EphemeralStorageSize, LambdaDefinedCommandOptions.ARGUMENT_EPHEMERAL_STORAGE_SIZE, false); if(ephemeralSize.HasValue) { createRequest.EphemeralStorage = new EphemeralStorage { Size = ephemeralSize.Value }; } if (!string.IsNullOrEmpty(architecture)) { createRequest.Architectures = new List<string> { architecture }; } if(packageType == Lambda.PackageType.Zip) { createRequest.Handler = this.GetStringValueOrDefault(this.Handler, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_HANDLER, true); createRequest.Runtime = this.GetStringValueOrDefault(this.Runtime, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_RUNTIME, true); createRequest.Layers = layerVersionArns?.ToList(); if (s3Bucket != null) { createRequest.Code = new FunctionCode { S3Bucket = s3Bucket, S3Key = s3Key }; } else { createRequest.Code = new FunctionCode { ZipFile = lambdaZipArchiveStream }; } } else if(packageType == Lambda.PackageType.Image) { createRequest.Code = new FunctionCode { ImageUri = ecrImageUri }; createRequest.ImageConfig = new ImageConfig { Command = this.GetStringValuesOrDefault(this.ImageCommand, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_COMMAND, false)?.ToList(), EntryPoint = this.GetStringValuesOrDefault(this.ImageEntryPoint, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_ENTRYPOINT, false)?.ToList(), WorkingDirectory = this.GetStringValueOrDefault(this.ImageWorkingDirectory, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_WORKING_DIRECTORY, false) }; } var environmentVariables = GetEnvironmentVariables(null); var dotnetShareStoreVal = layerPackageInfo.GenerateDotnetSharedStoreValue(); if(!string.IsNullOrEmpty(dotnetShareStoreVal)) { if(environmentVariables == null) { environmentVariables = new Dictionary<string, string>(); } environmentVariables[LambdaConstants.ENV_DOTNET_SHARED_STORE] = dotnetShareStoreVal; } if (environmentVariables != null && environmentVariables.Count > 0) { createRequest.Environment = new Model.Environment { Variables = environmentVariables }; } var tags = this.GetKeyValuePairOrDefault(this.Tags, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TAGS, false); if(tags != null && tags.Count > 0) { createRequest.Tags = tags; } var deadLetterQueue = this.GetStringValueOrDefault(this.DeadLetterTargetArn, LambdaDefinedCommandOptions.ARGUMENT_DEADLETTER_TARGET_ARN, false); if(!string.IsNullOrEmpty(deadLetterQueue)) { createRequest.DeadLetterConfig = new DeadLetterConfig {TargetArn = deadLetterQueue }; } var tracingMode = this.GetStringValueOrDefault(this.TracingMode, LambdaDefinedCommandOptions.ARGUMENT_TRACING_MODE, false); if(!string.IsNullOrEmpty(tracingMode)) { createRequest.TracingConfig = new TracingConfig { Mode = tracingMode }; } try { await this.LambdaClient.CreateFunctionAsync(createRequest); this.Logger.WriteLine("New Lambda function created"); } catch (Exception e) { throw new LambdaToolsException($"Error creating Lambda function: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaCreateFunction, e); } if(this.GetBoolValueOrDefault(this.FunctionUrlEnable, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_ENABLE, false).GetValueOrDefault()) { var authType = this.GetStringValueOrDefault(this.FunctionUrlAuthType, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_AUTH, false); await base.CreateFunctionUrlConfig(createRequest.FunctionName, authType); this.Logger.WriteLine($"Function url config created: {this.FunctionUrlLink}"); } } else { this.Logger.WriteLine($"Updating code for existing function {this.FunctionName}"); var updateCodeRequest = new UpdateFunctionCodeRequest { FunctionName = this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true) }; if (!string.IsNullOrEmpty(architecture)) { updateCodeRequest.Architectures = new List<string> { architecture }; } // In case the function is currently being updated from previous deployment wait till it available // to be updated. if (currentConfiguration.LastUpdateStatus == LastUpdateStatus.InProgress) { await LambdaUtilities.WaitTillFunctionAvailableAsync(Logger, this.LambdaClient, updateCodeRequest.FunctionName); } if (packageType == Lambda.PackageType.Zip) { if (s3Bucket != null) { updateCodeRequest.S3Bucket = s3Bucket; updateCodeRequest.S3Key = s3Key; } else { updateCodeRequest.ZipFile = lambdaZipArchiveStream; } } else if (packageType == Lambda.PackageType.Image) { updateCodeRequest.ImageUri = ecrImageUri; } var configUpdated = false; try { // Update config should run before updating the function code to avoid a situation such as // upgrading from an EOL .NET version to a supported version where the update would fail // since lambda thinks we are updating an EOL version instead of upgrading. configUpdated = await base.UpdateConfigAsync(currentConfiguration, layerPackageInfo.GenerateDotnetSharedStoreValue()); } catch (Exception e) { throw new LambdaToolsException($"Error updating configuration for Lambda function: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaUpdateFunctionConfiguration, e); } try { await LambdaUtilities.WaitTillFunctionAvailableAsync(Logger, this.LambdaClient, updateCodeRequest.FunctionName); await this.LambdaClient.UpdateFunctionCodeAsync(updateCodeRequest); } catch (Exception e) { if (configUpdated) { await base.AttemptRevertConfigAsync(currentConfiguration); } throw new LambdaToolsException($"Error updating code for Lambda function: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaUpdateFunctionCode, e); } await base.ApplyTags(currentConfiguration.FunctionArn); var publish = this.GetBoolValueOrDefault(this.Publish, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_PUBLISH, false).GetValueOrDefault(); if(publish) { await base.PublishFunctionAsync(updateCodeRequest.FunctionName); } } } finally { lambdaZipArchiveStream?.Dispose(); } return true; } private Lambda.PackageType DeterminePackageType() { var strPackageType = this.GetStringValueOrDefault(this.PackageType, LambdaDefinedCommandOptions.ARGUMENT_PACKAGE_TYPE, false); return LambdaUtilities.DeterminePackageType(strPackageType); } private async Task<PushLambdaImageResult> PushLambdaImageAsync() { var pushCommand = new PushDockerImageCommand(this.Logger, this.WorkingDirectory, this.OriginalCommandLineArguments) { ConfigFile = this.ConfigFile, DisableInteractive = this.DisableInteractive, Credentials = this.Credentials, ECRClient = this.ECRClient, Profile = this.Profile, ProfileLocation = this.ProfileLocation, ProjectLocation = this.ProjectLocation, Region = this.Region, WorkingDirectory = this.WorkingDirectory, PushDockerImageProperties = new BasePushDockerImageCommand<LambdaToolsDefaults>.PushDockerImagePropertyContainer { Configuration = this.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false), TargetFramework = this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false), LocalDockerImage = this.GetStringValueOrDefault(this.LocalDockerImage, CommonDefinedCommandOptions.ARGUMENT_LOCAL_DOCKER_IMAGE, false), DockerFile = this.GetStringValueOrDefault(this.DockerFile, CommonDefinedCommandOptions.ARGUMENT_DOCKERFILE, false), DockerBuildOptions = this.GetStringValueOrDefault(this.DockerBuildOptions, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS, false), DockerBuildWorkingDirectory = this.GetStringValueOrDefault(this.DockerBuildWorkingDirectory, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY, false), DockerImageTag = this.GetStringValueOrDefault(this.DockerImageTag, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_TAG, false), PublishOptions = this.GetStringValueOrDefault(this.MSBuildParameters, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, false), HostBuildOutput = this.GetStringValueOrDefault(this.HostBuildOutput, CommonDefinedCommandOptions.ARGUMENT_HOST_BUILD_OUTPUT, false) } }; var result = new PushLambdaImageResult(); result.Success = await pushCommand.ExecuteAsync(); result.ImageUri = pushCommand.PushedImageUri; result.LastException = pushCommand.LastException; return result; } private void ValidateTargetFrameworkAndLambdaRuntime(string targetFramework) { string runtimeName = this.GetStringValueOrDefault(this.Runtime, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_RUNTIME, true); LambdaUtilities.ValidateTargetFrameworkAndLambdaRuntime(runtimeName, targetFramework); } protected override void SaveConfigFile(JsonData data) { data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_AWS_REGION.ConfigFileKey, this.GetStringValueOrDefault(this.Region, CommonDefinedCommandOptions.ARGUMENT_AWS_REGION, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE.ConfigFileKey, this.GetStringValueOrDefault(this.Profile, CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE_LOCATION.ConfigFileKey, this.GetStringValueOrDefault(this.ProfileLocation, CommonDefinedCommandOptions.ARGUMENT_AWS_PROFILE_LOCATION, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION.ConfigFileKey, this.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.ConfigFileKey, this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS.ConfigFileKey, this.GetStringValueOrDefault(this.MSBuildParameters, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME.ConfigFileKey, this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_DESCRIPTION.ConfigFileKey, this.GetStringValueOrDefault(this.Description, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_DESCRIPTION, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TAGS.ConfigFileKey, LambdaToolsDefaults.FormatKeyValue(this.GetKeyValuePairOrDefault(this.Tags, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TAGS, false))); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_PACKAGE_TYPE.ConfigFileKey, this.GetStringValueOrDefault(this.PackageType, LambdaDefinedCommandOptions.ARGUMENT_PACKAGE_TYPE, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_PUBLISH.ConfigFileKey, this.GetBoolValueOrDefault(this.Publish, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_PUBLISH, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_HANDLER.ConfigFileKey, this.GetStringValueOrDefault(this.Handler, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_HANDLER, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_MEMORY_SIZE.ConfigFileKey, this.GetIntValueOrDefault(this.MemorySize, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_MEMORY_SIZE, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ROLE.ConfigFileKey, this.GetStringValueOrDefault(this.Role, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ROLE, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TIMEOUT.ConfigFileKey, this.GetIntValueOrDefault(this.Timeout, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TIMEOUT, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_RUNTIME.ConfigFileKey, this.GetStringValueOrDefault(this.Runtime, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_RUNTIME, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE.ConfigFileKey, this.GetStringValueOrDefault(this.Architecture, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_LAYERS.ConfigFileKey, LambdaToolsDefaults.FormatCommaDelimitedList(this.GetStringValuesOrDefault(this.LayerVersionArns, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_LAYERS, false))); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_EPHEMERAL_STORAGE_SIZE.ConfigFileKey, this.GetIntValueOrDefault(this.EphemeralStorageSize, LambdaDefinedCommandOptions.ARGUMENT_EPHEMERAL_STORAGE_SIZE, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_ENABLE.ConfigFileKey, this.GetBoolValueOrDefault(this.FunctionUrlEnable, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_ENABLE, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_AUTH.ConfigFileKey, this.GetStringValueOrDefault(this.FunctionUrlAuthType, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_AUTH, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_IMAGE_ENTRYPOINT.ConfigFileKey, LambdaToolsDefaults.FormatCommaDelimitedList(this.GetStringValuesOrDefault(this.ImageEntryPoint, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_ENTRYPOINT, false))); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_IMAGE_COMMAND.ConfigFileKey, LambdaToolsDefaults.FormatCommaDelimitedList(this.GetStringValuesOrDefault(this.ImageCommand, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_COMMAND, false))); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_IMAGE_WORKING_DIRECTORY.ConfigFileKey, this.GetStringValueOrDefault(this.ImageWorkingDirectory, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_WORKING_DIRECTORY, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SUBNETS.ConfigFileKey, LambdaToolsDefaults.FormatCommaDelimitedList(this.GetStringValuesOrDefault(this.SubnetIds, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SUBNETS, false))); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SECURITY_GROUPS.ConfigFileKey, LambdaToolsDefaults.FormatCommaDelimitedList(this.GetStringValuesOrDefault(this.SecurityGroupIds, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SECURITY_GROUPS, false))); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_DEADLETTER_TARGET_ARN.ConfigFileKey, this.GetStringValueOrDefault(this.DeadLetterTargetArn, LambdaDefinedCommandOptions.ARGUMENT_DEADLETTER_TARGET_ARN, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_TRACING_MODE.ConfigFileKey, this.GetStringValueOrDefault(this.TracingMode, LambdaDefinedCommandOptions.ARGUMENT_TRACING_MODE, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_ENVIRONMENT_VARIABLES.ConfigFileKey, LambdaToolsDefaults.FormatKeyValue(this.GetKeyValuePairOrDefault(this.EnvironmentVariables, LambdaDefinedCommandOptions.ARGUMENT_ENVIRONMENT_VARIABLES, false))); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_APPEND_ENVIRONMENT_VARIABLES.ConfigFileKey, LambdaToolsDefaults.FormatKeyValue(this.GetKeyValuePairOrDefault(this.AppendEnvironmentVariables, LambdaDefinedCommandOptions.ARGUMENT_APPEND_ENVIRONMENT_VARIABLES, false))); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_KMS_KEY_ARN.ConfigFileKey, this.GetStringValueOrDefault(this.KMSKeyArn, LambdaDefinedCommandOptions.ARGUMENT_KMS_KEY_ARN, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3.ConfigFileKey, this.GetBoolValueOrDefault(this.ResolveS3, LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET.ConfigFileKey, this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX.ConfigFileKey, this.GetStringValueOrDefault(this.S3Prefix, LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX, false)); var projectLocation = Utilities.DetermineProjectLocation(this.WorkingDirectory, this.GetStringValueOrDefault(this.ProjectLocation, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false)); data.SetFilePathIfNotNull(CommonDefinedCommandOptions.ARGUMENT_DOCKERFILE.ConfigFileKey, this.GetStringValueOrDefault(this.DockerFile, CommonDefinedCommandOptions.ARGUMENT_DOCKERFILE, false), projectLocation); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS.ConfigFileKey, this.GetStringValueOrDefault(this.DockerBuildOptions, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY.ConfigFileKey, this.GetStringValueOrDefault(this.DockerBuildWorkingDirectory, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_HOST_BUILD_OUTPUT.ConfigFileKey, this.GetStringValueOrDefault(this.HostBuildOutput, CommonDefinedCommandOptions.ARGUMENT_HOST_BUILD_OUTPUT, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_IMAGE_TAG.ConfigFileKey, this.GetStringValueOrDefault(this.DockerImageTag, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_TAG, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_USE_CONTAINER_FOR_BUILD.ConfigFileKey, this.GetBoolValueOrDefault(this.UseContainerForBuild, LambdaDefinedCommandOptions.ARGUMENT_USE_CONTAINER_FOR_BUILD, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_CONTAINER_IMAGE_FOR_BUILD.ConfigFileKey, this.GetStringValueOrDefault(this.ContainerImageForBuild, LambdaDefinedCommandOptions.ARGUMENT_CONTAINER_IMAGE_FOR_BUILD, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_CODE_MOUNT_DIRECTORY.ConfigFileKey, this.GetStringValueOrDefault(this.CodeMountDirectory, LambdaDefinedCommandOptions.ARGUMENT_CODE_MOUNT_DIRECTORY, false)); } } }
628
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using ThirdParty.Json.LitJson; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Lambda.Tools.TemplateProcessor; using Newtonsoft.Json.Linq; namespace Amazon.Lambda.Tools.Commands { /// <summary> /// Deployment command that uses an AWS Serverless CloudFormation template to drive the creation of the resources /// for an AWS Serverless application. /// </summary> public class DeployServerlessCommand : LambdaBaseCommand { public const string COMMAND_NAME = "deploy-serverless"; public const string COMMAND_DESCRIPTION = "Command to deploy an AWS Serverless application"; public const string COMMAND_ARGUMENTS = "<STACK-NAME> The name of the CloudFormation stack used to deploy the AWS Serverless application"; // CloudFormation statuses for when the stack is in transition all end with IN_PROGRESS const string IN_PROGRESS_SUFFIX = "IN_PROGRESS"; public static readonly IList<CommandOption> DeployServerlessCommandOptions = BuildLineOptions(new List<CommandOption> { CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, LambdaDefinedCommandOptions.ARGUMENT_PACKAGE, LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE_PARAMETER, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE_SUBSTITUTIONS, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_ROLE, LambdaDefinedCommandOptions.ARGUMENT_STACK_NAME, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_DISABLE_CAPABILITIES, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TAGS, LambdaDefinedCommandOptions.ARGUMENT_STACK_WAIT, LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK }); public string Configuration { get; set; } public string TargetFramework { get; set; } public string Package { get; set; } public string MSBuildParameters { get; set; } public bool? ResolveS3 { get; set; } public string S3Bucket { get; set; } public string S3Prefix { get; set; } public string CloudFormationTemplate { get; set; } public string StackName { get; set; } public bool? WaitForStackToComplete { get; set; } public string CloudFormationRole { get; set; } public Dictionary<string, string> TemplateParameters { get; set; } public Dictionary<string, string> TemplateSubstitutions { get; set; } public Dictionary<string, string> Tags { get; set; } public bool? DisableVersionCheck { get; set; } public string[] DisabledCapabilities { get; set; } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); if (values.Arguments.Count > 0) { this.StackName = values.Arguments[0]; } Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION.Switch)) != null) this.Configuration = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.Switch)) != null) this.TargetFramework = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_PACKAGE.Switch)) != null) this.Package = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3.Switch)) != null) this.ResolveS3 = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET.Switch)) != null) this.S3Bucket = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX.Switch)) != null) this.S3Prefix = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_STACK_NAME.Switch)) != null) this.StackName = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE.Switch)) != null) this.CloudFormationTemplate = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_STACK_WAIT.Switch)) != null) this.WaitForStackToComplete = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE_PARAMETER.Switch)) != null) this.TemplateParameters = tuple.Item2.KeyValuePairs; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE_SUBSTITUTIONS.Switch)) != null) this.TemplateSubstitutions = tuple.Item2.KeyValuePairs; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_ROLE.Switch)) != null) this.CloudFormationRole = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK.Switch)) != null) this.DisableVersionCheck = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TAGS.Switch)) != null) this.Tags = tuple.Item2.KeyValuePairs; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS.Switch)) != null) this.MSBuildParameters = tuple.Item2.StringValue; if (!string.IsNullOrEmpty(values.MSBuildParameters)) { if (this.MSBuildParameters == null) this.MSBuildParameters = values.MSBuildParameters; else this.MSBuildParameters += " " + values.MSBuildParameters; } } public DeployServerlessCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, DeployServerlessCommandOptions, args) { } protected override async Task<bool> PerformActionAsync() { string projectLocation = this.GetStringValueOrDefault(this.ProjectLocation, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false); string stackName = this.GetStringValueOrDefault(this.StackName, LambdaDefinedCommandOptions.ARGUMENT_STACK_NAME, true); string s3Prefix = this.GetStringValueOrDefault(this.S3Prefix, LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX, false); string templatePath = this.GetStringValueOrDefault(this.CloudFormationTemplate, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE, true); string s3Bucket = await DetermineS3Bucket(); await Utilities.ValidateBucketRegionAsync(this.S3Client, s3Bucket); if (!Path.IsPathRooted(templatePath)) { templatePath = Path.Combine(Utilities.DetermineProjectLocation(this.WorkingDirectory, projectLocation), templatePath); } if (!File.Exists(templatePath)) throw new LambdaToolsException($"Template file {templatePath} cannot be found.", LambdaToolsException.LambdaErrorCode.ServerlessTemplateNotFound); // Read in the serverless template and update all the locations for Lambda functions to point to the app bundle that was just uploaded. string templateBody = File.ReadAllText(templatePath); // Process any template substitutions templateBody = LambdaUtilities.ProcessTemplateSubstitions(this.Logger, templateBody, this.GetKeyValuePairOrDefault(this.TemplateSubstitutions, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE_SUBSTITUTIONS, false), Utilities.DetermineProjectLocation(this.WorkingDirectory, projectLocation)); var options = new DefaultLocationOption { Configuration = this.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false), TargetFramework = this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false), MSBuildParameters = this.GetStringValueOrDefault(this.MSBuildParameters, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, false), DisableVersionCheck = this.GetBoolValueOrDefault(this.DisableVersionCheck, LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK, false).GetValueOrDefault(), Package = this.GetStringValueOrDefault(this.Package, LambdaDefinedCommandOptions.ARGUMENT_PACKAGE, false) }; var templateProcessor = new TemplateProcessorManager(this, s3Bucket, s3Prefix, options); templateBody = await templateProcessor.TransformTemplateAsync(templatePath, templateBody, OriginalCommandLineArguments); // Upload the template to S3 instead of sending it straight to CloudFormation to avoid the size limitation string s3KeyTemplate; using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(templateBody))) { s3KeyTemplate = await Utilities.UploadToS3Async(this.Logger, this.S3Client, s3Bucket, s3Prefix, stackName + "-" + Path.GetFileName(templatePath), stream); } var existingStack = await GetExistingStackAsync(stackName); this.Logger.WriteLine("Found existing stack: " + (existingStack != null)); var changeSetName = "Lambda-Tools-" + DateTime.Now.Ticks; List<Tag> tagList = null; { var tags = this.GetKeyValuePairOrDefault(this.Tags, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TAGS, false); if(tags != null) { tagList = new List<Tag>(); foreach(var kvp in tags) { tagList.Add(new Tag { Key = kvp.Key, Value = kvp.Value }); } } } // Determine if the stack is in a good state to be updated. ChangeSetType changeSetType; if (existingStack == null || existingStack.StackStatus == StackStatus.REVIEW_IN_PROGRESS || existingStack.StackStatus == StackStatus.DELETE_COMPLETE) { changeSetType = ChangeSetType.CREATE; } // If the status was ROLLBACK_COMPLETE that means the stack failed on initial creation // and the resources were cleaned up. It is safe to delete the stack so we can recreate it. else if (existingStack.StackStatus == StackStatus.ROLLBACK_COMPLETE) { await DeleteRollbackCompleteStackAsync(existingStack); changeSetType = ChangeSetType.CREATE; } // If the status was ROLLBACK_IN_PROGRESS that means the initial creation is failing. // Wait to see if it goes into ROLLBACK_COMPLETE status meaning everything got cleaned up and then delete it. else if (existingStack.StackStatus == StackStatus.ROLLBACK_IN_PROGRESS) { existingStack = await WaitForNoLongerInProgress(existingStack.StackName); if (existingStack != null && existingStack.StackStatus == StackStatus.ROLLBACK_COMPLETE) await DeleteRollbackCompleteStackAsync(existingStack); changeSetType = ChangeSetType.CREATE; } // If the status was DELETE_IN_PROGRESS then just wait for delete to complete else if (existingStack.StackStatus == StackStatus.DELETE_IN_PROGRESS) { await WaitForNoLongerInProgress(existingStack.StackName); changeSetType = ChangeSetType.CREATE; } // The Stack state is in a normal state and ready to be updated. else if (existingStack.StackStatus == StackStatus.CREATE_COMPLETE || existingStack.StackStatus == StackStatus.UPDATE_COMPLETE || existingStack.StackStatus == StackStatus.UPDATE_ROLLBACK_COMPLETE) { changeSetType = ChangeSetType.UPDATE; if(tagList == null) { tagList = existingStack.Tags; } } // All other states means the Stack is in an inconsistent state. else { throw new LambdaToolsException($"The stack's current state of {existingStack.StackStatus} is invalid for updating", LambdaToolsException.LambdaErrorCode.InvalidCloudFormationStackState); } CreateChangeSetResponse changeSetResponse; try { var definedParameters = LambdaUtilities.GetTemplateDefinedParameters(templateBody); var templateParameters = GetTemplateParameters(changeSetType == ChangeSetType.UPDATE ? existingStack : null, definedParameters); if (templateParameters != null && templateParameters.Any()) { var setParameters = templateParameters.Where(x => !x.UsePreviousValue); // ReSharper disable once PossibleMultipleEnumeration if (setParameters.Any()) { this.Logger.WriteLine("Template Parameters Applied:"); foreach (var parameter in setParameters) { Tuple<string, bool> dp = null; if (definedParameters != null) { dp = definedParameters.FirstOrDefault(x => string.Equals(x.Item1, parameter.ParameterKey)); } if (dp != null && dp.Item2) { this.Logger.WriteLine($"\t{parameter.ParameterKey}: ****"); } else { this.Logger.WriteLine($"\t{parameter.ParameterKey}: {parameter.ParameterValue}"); } } } } var capabilities = new List<string>(); var disabledCapabilties = GetStringValuesOrDefault(this.DisabledCapabilities, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_DISABLE_CAPABILITIES, false); if (disabledCapabilties?.FirstOrDefault(x => string.Equals(x, "CAPABILITY_IAM", StringComparison.OrdinalIgnoreCase)) == null) { capabilities.Add("CAPABILITY_IAM"); } if (disabledCapabilties?.FirstOrDefault(x => string.Equals(x, "CAPABILITY_NAMED_IAM", StringComparison.OrdinalIgnoreCase)) == null) { capabilities.Add("CAPABILITY_NAMED_IAM"); } if (disabledCapabilties?.FirstOrDefault(x => string.Equals(x, "CAPABILITY_AUTO_EXPAND", StringComparison.OrdinalIgnoreCase)) == null) { capabilities.Add("CAPABILITY_AUTO_EXPAND"); } if (tagList == null) { tagList = new List<Tag>(); } if(tagList.FirstOrDefault(x => string.Equals(x.Key, LambdaConstants.SERVERLESS_TAG_NAME)) == null) { tagList.Add(new Tag { Key = LambdaConstants.SERVERLESS_TAG_NAME, Value = "true" }); } var changeSetRequest = new CreateChangeSetRequest { StackName = stackName, Parameters = templateParameters, ChangeSetName = changeSetName, ChangeSetType = changeSetType, Capabilities = capabilities, RoleARN = this.GetStringValueOrDefault(this.CloudFormationRole, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_ROLE, false), Tags = tagList }; if(templateBody.Length < LambdaConstants.MAX_TEMPLATE_BODY_IN_REQUEST_SIZE) { changeSetRequest.TemplateBody = templateBody; } else { changeSetRequest.TemplateURL = this.S3Client.GetPreSignedURL(new S3.Model.GetPreSignedUrlRequest { BucketName = s3Bucket, Key = s3KeyTemplate, Expires = DateTime.Now.AddHours(1) }); } // Create the change set which performs the transformation on the Serverless resources in the template. changeSetResponse = await this.CloudFormationClient.CreateChangeSetAsync(changeSetRequest); this.Logger.WriteLine("CloudFormation change set created"); } catch(LambdaToolsException) { throw; } catch (Exception e) { throw new LambdaToolsException($"Error creating CloudFormation change set: {e.Message}", LambdaToolsException.LambdaErrorCode.CloudFormationCreateStack, e); } // The change set can take a few seconds to be reviewed and be ready to be executed. await WaitForChangeSetBeingAvailableAsync(changeSetResponse.Id); var executeChangeSetRequest = new ExecuteChangeSetRequest { StackName = stackName, ChangeSetName = changeSetResponse.Id }; // Execute the change set. DateTime timeChangeSetExecuted = DateTime.Now; try { await this.CloudFormationClient.ExecuteChangeSetAsync(executeChangeSetRequest); if (changeSetType == ChangeSetType.CREATE) this.Logger.WriteLine($"Created CloudFormation stack {stackName}"); else this.Logger.WriteLine($"Initiated CloudFormation stack update on {stackName}"); } catch (Exception e) { throw new LambdaToolsException($"Error executing CloudFormation change set: {e.Message}", LambdaToolsException.LambdaErrorCode.CloudFormationCreateChangeSet, e); } // Wait for the stack to finish unless the user opts out of waiting. The VS Toolkit opts out and // instead shows the stack view in the IDE, enabling the user to view progress. var shouldWait = GetBoolValueOrDefault(this.WaitForStackToComplete, LambdaDefinedCommandOptions.ARGUMENT_STACK_WAIT, false); if (!shouldWait.HasValue || shouldWait.Value) { var updatedStack = await WaitStackToCompleteAsync(stackName, timeChangeSetExecuted); if (updatedStack.StackStatus == StackStatus.CREATE_COMPLETE || updatedStack.StackStatus == StackStatus.UPDATE_COMPLETE) { this.Logger.WriteLine($"Stack finished updating with status: {updatedStack.StackStatus}"); // Display the output parameters. DisplayOutputs(updatedStack); } else { throw new LambdaToolsException($"Stack update failed with status: {updatedStack.StackStatus} ({updatedStack.StackStatusReason})", LambdaToolsException.LambdaErrorCode.FailedLambdaCreateOrUpdate); } } return true; } private void DisplayOutputs(Stack stack) { if (stack.Outputs.Count == 0) return; const int OUTPUT_NAME_WIDTH = 30; const int OUTPUT_VALUE_WIDTH = 50; this.Logger.WriteLine(" "); this.Logger.WriteLine("Output Name".PadRight(OUTPUT_NAME_WIDTH) + " " + "Value".PadRight(OUTPUT_VALUE_WIDTH)); this.Logger.WriteLine($"{new string('-', OUTPUT_NAME_WIDTH)} {new string('-', OUTPUT_VALUE_WIDTH)}"); foreach (var output in stack.Outputs) { string line = output.OutputKey.PadRight(OUTPUT_NAME_WIDTH) + " " + output.OutputValue?.PadRight(OUTPUT_VALUE_WIDTH); this.Logger.WriteLine(line); } } static readonly TimeSpan POLLING_PERIOD = TimeSpan.FromSeconds(3); private async Task<Stack> WaitStackToCompleteAsync(string stackName, DateTime mintimeStampForEvents) { const int TIMESTAMP_WIDTH = 20; const int LOGICAL_RESOURCE_WIDTH = 40; const int RESOURCE_STATUS = 40; string mostRecentEventId = ""; // Write header for the status table. this.Logger.WriteLine(" "); this.Logger.WriteLine( "Timestamp".PadRight(TIMESTAMP_WIDTH) + " " + "Logical Resource Id".PadRight(LOGICAL_RESOURCE_WIDTH) + " " + "Status".PadRight(RESOURCE_STATUS) + " "); this.Logger.WriteLine( new string('-', TIMESTAMP_WIDTH) + " " + new string('-', LOGICAL_RESOURCE_WIDTH) + " " + new string('-', RESOURCE_STATUS) + " "); Stack stack; do { Thread.Sleep(POLLING_PERIOD); stack = await GetExistingStackAsync(stackName); var events = await GetLatestEventsAsync(stackName, mintimeStampForEvents, mostRecentEventId); if (events.Count > 0) mostRecentEventId = events[0].EventId; for (int i = events.Count - 1; i >= 0; i--) { string line = events[i].Timestamp.ToString("g").PadRight(TIMESTAMP_WIDTH) + " " + events[i].LogicalResourceId.PadRight(LOGICAL_RESOURCE_WIDTH) + " " + events[i].ResourceStatus.ToString().PadRight(RESOURCE_STATUS); // To save screen space only show error messages. if (!events[i].ResourceStatus.ToString().EndsWith(IN_PROGRESS_SUFFIX) && !string.IsNullOrEmpty(events[i].ResourceStatusReason)) line += " " + events[i].ResourceStatusReason; this.Logger.WriteLine(line); } } while (stack.StackStatus.ToString().EndsWith(IN_PROGRESS_SUFFIX)); return stack; } private async Task<List<StackEvent>> GetLatestEventsAsync(string stackName, DateTime mintimeStampForEvents, string mostRecentEventId) { bool noNewEvents = false; List<StackEvent> events = new List<StackEvent>(); DescribeStackEventsResponse response = null; do { var request = new DescribeStackEventsRequest() { StackName = stackName }; if (response != null) request.NextToken = response.NextToken; try { response = await this.CloudFormationClient.DescribeStackEventsAsync(request); } catch (Exception e) { throw new LambdaToolsException($"Error getting events for stack: {e.Message}", LambdaToolsException.LambdaErrorCode.CloudFormationDescribeStackEvents, e); } foreach (var evnt in response.StackEvents) { if (string.Equals(evnt.EventId, mostRecentEventId) || evnt.Timestamp < mintimeStampForEvents) { noNewEvents = true; break; } events.Add(evnt); } } while (!noNewEvents && !string.IsNullOrEmpty(response.NextToken)); return events; } private async Task DeleteRollbackCompleteStackAsync(Stack stack) { try { if (stack.StackStatus == StackStatus.ROLLBACK_COMPLETE) await this.CloudFormationClient.DeleteStackAsync(new DeleteStackRequest { StackName = stack.StackName }); await WaitForNoLongerInProgress(stack.StackName); } catch (Exception e) { throw new LambdaToolsException($"Error removing previous failed stack creation {stack.StackName}: {e.Message}", LambdaToolsException.LambdaErrorCode.CloudFormationDeleteStack, e); } } private async Task<Stack> WaitForNoLongerInProgress(string stackName) { try { long start = DateTime.Now.Ticks; Stack currentStack = null; do { if (currentStack != null) this.Logger.WriteLine($"... Waiting for stack's state to change from {currentStack.StackStatus}: {TimeSpan.FromTicks(DateTime.Now.Ticks - start).TotalSeconds.ToString("0").PadLeft(3)} secs"); Thread.Sleep(POLLING_PERIOD); currentStack = await GetExistingStackAsync(stackName); } while (currentStack != null && currentStack.StackStatus.ToString().EndsWith(IN_PROGRESS_SUFFIX)); return currentStack; } catch (Exception e) { throw new LambdaToolsException($"Error waiting for stack state change: {e.Message}", LambdaToolsException.LambdaErrorCode.WaitingForStackError, e); } } private async Task WaitForChangeSetBeingAvailableAsync(string changeSetId) { try { var request = new DescribeChangeSetRequest { ChangeSetName = changeSetId }; this.Logger.WriteLine("... Waiting for change set to be reviewed"); DescribeChangeSetResponse response; do { Thread.Sleep(POLLING_PERIOD); response = await this.CloudFormationClient.DescribeChangeSetAsync(request); } while (response.Status == ChangeSetStatus.CREATE_IN_PROGRESS || response.Status == ChangeSetStatus.CREATE_PENDING); if (response.Status == ChangeSetStatus.FAILED) { throw new LambdaToolsException($"Failed to create CloudFormation change set: {response.StatusReason}", LambdaToolsException.LambdaErrorCode.FailedToCreateChangeSet); } } catch (Exception e) { throw new LambdaToolsException($"Error getting status of change set: {e.Message}", LambdaToolsException.LambdaErrorCode.CloudFormationDescribeChangeSet, e); } } public async Task<Stack> GetExistingStackAsync(string stackName) { try { var response = await this.CloudFormationClient.DescribeStacksAsync(new DescribeStacksRequest { StackName = stackName }); if (response.Stacks.Count != 1) return null; return response.Stacks[0]; } catch (AmazonCloudFormationException) { return null; } } private List<Parameter> GetTemplateParameters(Stack stack, List<Tuple<string, bool>> definedParameters) { var parameters = new List<Parameter>(); var map = GetKeyValuePairOrDefault(this.TemplateParameters, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE_PARAMETER, false); if (map != null) { foreach (var kvp in map) { Tuple<string, bool> dp = null; if(definedParameters != null) { dp = definedParameters.FirstOrDefault(x => string.Equals(x.Item1, kvp.Key)); } if (dp == null) { this.Logger.WriteLine($"Skipping passed in template parameter {kvp.Key} because the template does not define that parameter"); } else { parameters.Add(new Parameter { ParameterKey = kvp.Key, ParameterValue = kvp.Value ?? "" }); } } } if (stack != null) { foreach (var existingParameter in stack.Parameters) { if ((definedParameters == null || definedParameters.FirstOrDefault(x => string.Equals(x.Item1, existingParameter.ParameterKey)) != null) && !parameters.Any(x => string.Equals(x.ParameterKey, existingParameter.ParameterKey))) { parameters.Add(new Parameter { ParameterKey = existingParameter.ParameterKey, UsePreviousValue = true }); } } } return parameters; } private async Task<string> DetermineS3Bucket() { string s3Bucket = this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, false); bool? resolveS3 = this.GetBoolValueOrDefault(this.ResolveS3, LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3, false); if (string.IsNullOrEmpty(s3Bucket)) { if (resolveS3 == true) { s3Bucket = await LambdaUtilities.ResolveDefaultS3Bucket(this.Logger, this.S3Client, this.STSClient); } else { // Since a bucket wasn't explicitly passed in nor was resolve s3 passed in then ask the user for the S3 bucket. s3Bucket = this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, true); } } return s3Bucket; } protected override void SaveConfigFile(JsonData data) { data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION.ConfigFileKey, this.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.ConfigFileKey, this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS.ConfigFileKey, this.GetStringValueOrDefault(this.MSBuildParameters, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3.ConfigFileKey, this.GetBoolValueOrDefault(this.ResolveS3, LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET.ConfigFileKey, this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX.ConfigFileKey, this.GetStringValueOrDefault(this.S3Prefix, LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX, false)); var template = this.GetStringValueOrDefault(this.CloudFormationTemplate, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE, false); if(Path.IsPathRooted(template)) { string projectLocation = this.GetStringValueOrDefault(this.ProjectLocation, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false); var projectRoot = Utilities.DetermineProjectLocation(this.WorkingDirectory, projectLocation); if(template.StartsWith(projectRoot)) { template = template.Substring(projectRoot.Length + 1); } } data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE.ConfigFileKey, template); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE_PARAMETER.ConfigFileKey, LambdaToolsDefaults.FormatKeyValue(this.GetKeyValuePairOrDefault(this.TemplateParameters, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE_PARAMETER, false))); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_STACK_NAME.ConfigFileKey, this.GetStringValueOrDefault(this.StackName, LambdaDefinedCommandOptions.ARGUMENT_STACK_NAME, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_DISABLE_CAPABILITIES.ConfigFileKey, LambdaToolsDefaults.FormatCommaDelimitedList(this.GetStringValuesOrDefault(this.DisabledCapabilities, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_DISABLE_CAPABILITIES, false))); } } }
665
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Lambda.Model; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.Commands { /// <summary> /// Get the current configuration for a deployed function /// </summary> public class GetFunctionConfigCommand : LambdaBaseCommand { public const string COMMAND_NAME = "get-function-config"; public const string COMMAND_DESCRIPTION = "Command to get the current runtime configuration for a Lambda function"; public const string COMMAND_ARGUMENTS = "<FUNCTION-NAME> The name of the function to get the configuration for"; public static readonly IList<CommandOption> GetConfigCommandOptions = BuildLineOptions(new List<CommandOption> { LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME }); public string FunctionName { get; set; } public GetFunctionConfigCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, GetConfigCommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); if (values.Arguments.Count > 0) { this.FunctionName = values.Arguments[0]; } Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME.Switch)) != null) this.FunctionName = tuple.Item2.StringValue; } protected override async Task<bool> PerformActionAsync() { GetFunctionConfigurationResponse response; var functionName = this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true); try { response = await this.LambdaClient.GetFunctionConfigurationAsync(functionName); } catch (Exception e) { throw new LambdaToolsException("Error getting configuration for Lambda function: " + e.Message, LambdaToolsException.LambdaErrorCode.LambdaGetConfiguration, e); } const int PAD_SIZE = 30; this.Logger.WriteLine("Name:".PadRight(PAD_SIZE) + response.FunctionName); this.Logger.WriteLine("Arn:".PadRight(PAD_SIZE) + response.FunctionArn); if(!string.IsNullOrEmpty(response.Description)) this.Logger.WriteLine("Description:".PadRight(PAD_SIZE) + response.Description); this.Logger.WriteLine("Package Type:".PadRight(PAD_SIZE) + response.PackageType); if (response.PackageType == PackageType.Image) { if(response.ImageConfigResponse?.ImageConfig?.Command?.Count > 0) this.Logger.WriteLine("Image Command:".PadRight(PAD_SIZE) + FormatAsJsonStringArray(response.ImageConfigResponse?.ImageConfig?.Command)); if (response.ImageConfigResponse?.ImageConfig?.EntryPoint?.Count > 0) this.Logger.WriteLine("Image EntryPoint:".PadRight(PAD_SIZE) + FormatAsJsonStringArray(response.ImageConfigResponse?.ImageConfig?.EntryPoint)); if (!string.IsNullOrEmpty(response.ImageConfigResponse?.ImageConfig?.WorkingDirectory)) this.Logger.WriteLine("Image WorkingDirectory:".PadRight(PAD_SIZE) + response.ImageConfigResponse?.ImageConfig?.WorkingDirectory); } else { this.Logger.WriteLine("Runtime:".PadRight(PAD_SIZE) + response.Runtime); this.Logger.WriteLine("Function Handler:".PadRight(PAD_SIZE) + response.Handler); } this.Logger.WriteLine("Last Modified:".PadRight(PAD_SIZE) + response.LastModified); this.Logger.WriteLine("Memory Size:".PadRight(PAD_SIZE) + response.MemorySize); if(response.EphemeralStorage != null) { this.Logger.WriteLine("Ephemeral Storage Size:".PadRight(PAD_SIZE) + response.EphemeralStorage.Size); } this.Logger.WriteLine("Role:".PadRight(PAD_SIZE) + response.Role); this.Logger.WriteLine("Timeout:".PadRight(PAD_SIZE) + response.Timeout); this.Logger.WriteLine("Version:".PadRight(PAD_SIZE) + response.Version); this.Logger.WriteLine("State:".PadRight(PAD_SIZE) + response.State); if(!string.IsNullOrEmpty(response.StateReason)) this.Logger.WriteLine("State Reason:".PadRight(PAD_SIZE) + response.StateReason); this.Logger.WriteLine("Last Update Status:".PadRight(PAD_SIZE) + response.LastUpdateStatus); if (!string.IsNullOrEmpty(response.LastUpdateStatusReason)) this.Logger.WriteLine("Last Update Status Reason:".PadRight(PAD_SIZE) + response.LastUpdateStatusReason); if (!string.IsNullOrEmpty(response.KMSKeyArn)) this.Logger.WriteLine("KMS Key ARN:".PadRight(PAD_SIZE) + response.KMSKeyArn); else this.Logger.WriteLine("KMS Key ARN:".PadRight(PAD_SIZE) + "(default) aws/lambda"); if(!string.IsNullOrEmpty(response.DeadLetterConfig?.TargetArn)) { this.Logger.WriteLine("Dead Letter Target:".PadRight(PAD_SIZE) + response.DeadLetterConfig.TargetArn); } if (response.Environment?.Variables?.Count > 0) { StringBuilder sb = new StringBuilder(); foreach(var kvp in response.Environment.Variables) { if (sb.Length > 0) sb.Append(";"); sb.Append($"{kvp.Key}={kvp.Value}"); } this.Logger.WriteLine("Environment Vars:".PadRight(PAD_SIZE) + sb); } if (response.VpcConfig != null && !string.IsNullOrEmpty(response.VpcConfig.VpcId)) { this.Logger.WriteLine("VPC Config"); this.Logger.WriteLine(" VPC: ".PadRight(22) + response.VpcConfig.VpcId); this.Logger.WriteLine(" Security Groups: ".PadRight(22) + string.Join(",", response.VpcConfig?.SecurityGroupIds)); this.Logger.WriteLine(" Subnets: ".PadRight(22) + string.Join(",", response.VpcConfig?.SubnetIds)); } var urlConfig = await GetFunctionUrlConfigAsync(functionName); if(urlConfig != null) { this.Logger.WriteLine("Function Url Config"); this.Logger.WriteLine(" Url: ".PadRight(PAD_SIZE) + urlConfig.FunctionUrl); this.Logger.WriteLine(" Auth: ".PadRight(PAD_SIZE) + urlConfig.AuthType.Value); } return true; } private async Task<GetFunctionUrlConfigResponse> GetFunctionUrlConfigAsync(string functionName) { try { var urlConfig = (await this.LambdaClient.GetFunctionUrlConfigAsync(new GetFunctionUrlConfigRequest { FunctionName = functionName })); return urlConfig; } catch (AmazonLambdaException ex) when (ex.StatusCode == HttpStatusCode.NotFound || ex.StatusCode == HttpStatusCode.Unauthorized) { return null; } catch (Exception e) { throw new LambdaToolsException("Error getting configuration url config for Lambda function: " + e.Message, LambdaToolsException.LambdaErrorCode.LambdaGetConfiguration, e); } } private static string FormatAsJsonStringArray(IList<string> items) { if (items.Count == 0) return null; var sb = new StringBuilder(); sb.Append("["); foreach(var token in items) { if(sb.Length > 1) { sb.Append(", "); } sb.Append("\"" + token + "\""); } sb.Append("]"); return sb.ToString(); } protected override void SaveConfigFile(JsonData data) { data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME.ConfigFileKey, this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, false)); } } }
199
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Lambda.Model; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.Commands { /// <summary> /// Get all the details for a Lambda layer including the .NET Runtime package store manifest /// </summary> public class GetLayerVersionDetailsCommand : LambdaBaseCommand { const int PAD_SIZE = 25; public const string COMMAND_NAME = "get-layer-version"; public const string COMMAND_DESCRIPTION = "Command to get the details of a Layer version"; public const string COMMAND_ARGUMENTS = "<LAYER-VERSION-ARN> The layer version arn to get details for"; public static readonly IList<CommandOption> CommandOptions = BuildLineOptions(new List<CommandOption> { LambdaDefinedCommandOptions.ARGUMENT_LAYER_VERSION_ARN }); public string LayerVersionArn { get; set; } public GetLayerVersionDetailsCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, CommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); if (values.Arguments.Count > 0) { this.LayerVersionArn = values.Arguments[0]; } Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_LAYER_VERSION_ARN.Switch)) != null) this.LayerVersionArn = tuple.Item2.StringValue; } protected override async Task<bool> PerformActionAsync() { var layerVersionArn = this.GetStringValueOrDefault(this.LayerVersionArn, LambdaDefinedCommandOptions.ARGUMENT_LAYER_VERSION_ARN, true); var result = LambdaUtilities.ParseLayerVersionArn(layerVersionArn); var getRequest = new GetLayerVersionRequest { LayerName = result.Name, VersionNumber = result.VersionNumber }; try { var response = await this.LambdaClient.GetLayerVersionAsync(getRequest); this.Logger.WriteLine("Layer ARN:".PadRight(PAD_SIZE) + response.LayerArn); this.Logger.WriteLine("Version Number:".PadRight(PAD_SIZE) + response.Version); this.Logger.WriteLine("Created:".PadRight(PAD_SIZE) + DateTime.Parse(response.CreatedDate).ToString("g")); this.Logger.WriteLine("License Info:".PadRight(PAD_SIZE) + response.LicenseInfo); this.Logger.WriteLine("Compatible Runtimes:".PadRight(PAD_SIZE) + string.Join(", ", response.CompatibleRuntimes.ToArray())); LayerDescriptionManifest manifest; if (!LambdaUtilities.AttemptToParseLayerDescriptionManifest(response.Description, out manifest)) { this.Logger.WriteLine("Description:".PadRight(PAD_SIZE) + response.Description); } else { switch (manifest.Nlt) { case LayerDescriptionManifest.ManifestType.RuntimePackageStore: this.Logger.WriteLine("Layer Type:".PadRight(PAD_SIZE) + LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE_DISPLAY_NAME); await GetRuntimePackageManifest(manifest); break; default: this.Logger.WriteLine("Layer Type:".PadRight(PAD_SIZE) + manifest.Nlt); break; } } } catch(Exception e) { throw new LambdaToolsException("Error getting layer version details: " + e.Message, LambdaToolsException.LambdaErrorCode.LambdaGetLayerVersionDetails, e); } return true; } private async Task GetRuntimePackageManifest(LayerDescriptionManifest manifest) { try { this.Logger.WriteLine(""); this.Logger.WriteLine($"{LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE_DISPLAY_NAME} Details:"); this.Logger.WriteLine("Manifest Location:".PadRight(PAD_SIZE) + $"s3://{manifest.Buc}/{manifest.Key}"); this.Logger.WriteLine("Packages Optimized:".PadRight(PAD_SIZE) + (manifest.Op == LayerDescriptionManifest.OptimizedState.Optimized)); this.Logger.WriteLine("Packages Directory:".PadRight(PAD_SIZE) + "/opt/" + manifest.Dir); using (var response = await this.S3Client.GetObjectAsync(manifest.Buc, manifest.Key)) using(var reader = new StreamReader(response.ResponseStream)) { this.Logger.WriteLine(""); this.Logger.WriteLine("Manifest Contents"); this.Logger.WriteLine("-----------------------"); this.Logger.WriteLine(reader.ReadToEnd()); } } catch (Exception) { } } protected override void SaveConfigFile(JsonData data) { } } }
136
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Lambda.Model; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.Commands { /// <summary> /// Invoke a function running in Lambda /// </summary> public class InvokeFunctionCommand : LambdaBaseCommand { public const string COMMAND_NAME = "invoke-function"; public const string COMMAND_DESCRIPTION = "Command to invoke a function in Lambda with an optional input"; public const string COMMAND_ARGUMENTS = "<FUNCTION-NAME> The name of the function to invoke"; public static readonly IList<CommandOption> InvokeCommandOptions = BuildLineOptions(new List<CommandOption> { LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, LambdaDefinedCommandOptions.ARGUMENT_PAYLOAD }); public string FunctionName { get; set; } /// <summary> /// If the value for Payload points to an existing file then the contents of the file is sent, otherwise /// the value of Payload is sent as the input to the function. /// </summary> public string Payload { get; set; } public InvokeFunctionCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, InvokeCommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); if(values.Arguments.Count > 0) { this.FunctionName = values.Arguments[0]; } Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME.Switch)) != null) this.FunctionName = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_PAYLOAD.Switch)) != null) this.Payload = tuple.Item2.StringValue; } protected override async Task<bool> PerformActionAsync() { var invokeRequest = new InvokeRequest { FunctionName = this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true), LogType = LogType.Tail }; if (!string.IsNullOrWhiteSpace(this.Payload)) { if (File.Exists(this.Payload)) { Logger.WriteLine($"Reading {Path.GetFullPath(this.Payload)} as input to Lambda function"); invokeRequest.Payload = File.ReadAllText(this.Payload); } else { invokeRequest.Payload = this.Payload.Trim(); } if(!invokeRequest.Payload.StartsWith("{")) { invokeRequest.Payload = "\"" + invokeRequest.Payload + "\""; } } InvokeResponse response; try { await LambdaUtilities.WaitTillFunctionAvailableAsync(this.Logger, this.LambdaClient, invokeRequest.FunctionName); response = await this.LambdaClient.InvokeAsync(invokeRequest); } catch(Exception e) { throw new LambdaToolsException("Error invoking Lambda function: " + e.Message, LambdaToolsException.LambdaErrorCode.LambdaInvokeFunction, e); } this.Logger.WriteLine("Payload:"); PrintPayload(response); this.Logger.WriteLine(""); this.Logger.WriteLine("Log Tail:"); var log = System.Text.UTF8Encoding.UTF8.GetString(Convert.FromBase64String(response.LogResult)); this.Logger.WriteLine(log); return true; } private void PrintPayload(InvokeResponse response) { try { var payload = new StreamReader(response.Payload).ReadToEnd(); this.Logger.WriteLine(payload); } catch (Exception) { this.Logger.WriteLine("<unparseable data>"); } } protected override void SaveConfigFile(JsonData data) { data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME.ConfigFileKey, this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_PAYLOAD.ConfigFileKey, this.GetStringValueOrDefault(this.Payload, LambdaDefinedCommandOptions.ARGUMENT_PAYLOAD, false)); } } }
134
aws-extensions-for-dotnet-cli
aws
C#
using System.Collections.Generic; using Amazon.CloudFormation; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Commands; using Amazon.Common.DotNetCli.Tools.Options; namespace Amazon.Lambda.Tools.Commands { public abstract class LambdaBaseCommand : BaseCommand<LambdaToolsDefaults> { public LambdaBaseCommand(IToolLogger logger, string workingDirectory) : base(logger, workingDirectory) { } public LambdaBaseCommand(IToolLogger logger, string workingDirectory, IList<CommandOption> possibleOptions, string[] args) : base(logger, workingDirectory, possibleOptions, args) { } protected override string ToolName => LambdaConstants.TOOLNAME; IAmazonLambda _lambdaClient; public IAmazonLambda LambdaClient { get { if (this._lambdaClient != null) return this._lambdaClient; SetUserAgentString(); var config = new AmazonLambdaConfig {RegionEndpoint = DetermineAWSRegion()}; this._lambdaClient = new AmazonLambdaClient(DetermineAWSCredentials(), config); return this._lambdaClient; } set { this._lambdaClient = value; } } IAmazonCloudFormation _cloudFormationClient; public IAmazonCloudFormation CloudFormationClient { get { if (this._cloudFormationClient == null) { SetUserAgentString(); AmazonCloudFormationConfig config = new AmazonCloudFormationConfig {RegionEndpoint = DetermineAWSRegion()}; this._cloudFormationClient = new AmazonCloudFormationClient(DetermineAWSCredentials(), config); } return this._cloudFormationClient; } set { this._cloudFormationClient = value; } } } }
65
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Lambda.Model; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.Commands { /// <summary> /// List all the functions currently deployed to Lambda /// </summary> public class ListFunctionCommand : LambdaBaseCommand { public const string COMMAND_NAME = "list-functions"; public const string COMMAND_DESCRIPTION = "Command to list all your Lambda functions"; public static readonly IList<CommandOption> ListCommandOptions = BuildLineOptions(new List<CommandOption> { }); public ListFunctionCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, ListCommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); } protected override async Task<bool> PerformActionAsync() { ListFunctionsRequest request = new ListFunctionsRequest(); ListFunctionsResponse response = null; do { if (response != null) request.Marker = response.NextMarker; try { response = await this.LambdaClient.ListFunctionsAsync(request); } catch (Exception e) { throw new LambdaToolsException("Error listing Lambda functions: " + e.Message, LambdaToolsException.LambdaErrorCode.LambdaListFunctions, e); } foreach (var function in response.Functions) { var extraInfo = function.PackageType == Lambda.PackageType.Zip ? "Runtime: " + function.Runtime.Value : "Package Type: " + function.PackageType.Value; this.Logger.WriteLine((function.FunctionName.PadRight(40) + " (" + extraInfo + ")").PadRight(10) + "\t" + function.Description); } } while (!string.IsNullOrEmpty(response.NextMarker)); return true; } protected override void SaveConfigFile(JsonData data) { } } }
74
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Lambda.Model; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.Commands { /// <summary> /// List the Lambda layers /// </summary> public class ListLayersCommand : LambdaBaseCommand { public const string COMMAND_NAME = "list-layers"; public const string COMMAND_DESCRIPTION = "Command to list Layers"; const int TIMESTAMP_WIDTH = 20; const int LAYER_NAME_WIDTH = 30; const int LAYER_ARN_WIDTH = 30; const int LAYER_COMPATIBLE_RUNTIMES_WIDTH = 30; const int LAYER_DESCRIPTION_WIDTH = 40; public static readonly IList<CommandOption> ListCommandOptions = BuildLineOptions(new List<CommandOption> { }); public ListLayersCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, ListCommandOptions, args) { } protected override async Task<bool> PerformActionAsync() { this.Logger.WriteLine("Name".PadRight(LAYER_NAME_WIDTH) + " " + "Description".PadRight(LAYER_DESCRIPTION_WIDTH) + " " + "Compatible Runtimes".PadRight(LAYER_COMPATIBLE_RUNTIMES_WIDTH) + " " + "Created".PadRight(TIMESTAMP_WIDTH) + " " + "Latest Version ARN".PadRight(LAYER_ARN_WIDTH) ); this.Logger.WriteLine($"{new string('-', LAYER_NAME_WIDTH)} {new string('-', LAYER_DESCRIPTION_WIDTH)} {new string('-', LAYER_COMPATIBLE_RUNTIMES_WIDTH)} {new string('-', TIMESTAMP_WIDTH)} {new string('-', LAYER_ARN_WIDTH)}"); var request = new ListLayersRequest(); ListLayersResponse response = null; do { if (response != null) request.Marker = response.NextMarker; try { response = await this.LambdaClient.ListLayersAsync(request); } catch (Exception e) { throw new LambdaToolsException("Error listing Lambda layers: " + e.Message, LambdaToolsException.LambdaErrorCode.LambdaListLayers, e); } foreach (var layer in response.Layers) { var latestVersion = layer.LatestMatchingVersion; this.Logger.WriteLine(layer.LayerName.PadRight(LAYER_NAME_WIDTH) + " " + LambdaUtilities.DetermineListDisplayLayerDescription(latestVersion.Description, LAYER_DESCRIPTION_WIDTH).PadRight(LAYER_DESCRIPTION_WIDTH) + " " + string.Join(", ", latestVersion.CompatibleRuntimes.ToArray()).PadRight(LAYER_COMPATIBLE_RUNTIMES_WIDTH) + " " + DateTime.Parse(latestVersion.CreatedDate).ToString("g").PadRight(TIMESTAMP_WIDTH) + " " + latestVersion.LayerVersionArn ); } } while (!string.IsNullOrEmpty(response.NextMarker)); return true; } protected override void SaveConfigFile(JsonData data) { } } }
85
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Lambda.Model; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.Commands { /// <summary> /// List the all of the versions of a Lambda layer. /// </summary> public class ListLayerVersionsCommand : LambdaBaseCommand { public const string COMMAND_NAME = "list-layer-versions"; public const string COMMAND_DESCRIPTION = "Command to list versions for a Layer"; public const string COMMAND_ARGUMENTS = "<LAYER-NAME> The name of the layer"; const int TIMESTAMP_WIDTH = 20; const int LAYER_ARN_WIDTH = 30; const int LAYER_COMPATIBLE_RUNTIMES_WIDTH = 30; const int LAYER_DESCRIPTION_WIDTH = 40; public static readonly IList<CommandOption> ListCommandOptions = BuildLineOptions(new List<CommandOption> { LambdaDefinedCommandOptions.ARGUMENT_LAYER_NAME }); public ListLayerVersionsCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, ListCommandOptions, args) { } public string LayerName { get; set; } protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); if (values.Arguments.Count > 0) { this.LayerName = values.Arguments[0]; } Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_LAYER_NAME.Switch)) != null) this.LayerName = tuple.Item2.StringValue; } protected override async Task<bool> PerformActionAsync() { var layerName = this.GetStringValueOrDefault(this.LayerName, LambdaDefinedCommandOptions.ARGUMENT_LAYER_NAME, true); this.Logger.WriteLine("Description".PadRight(LAYER_DESCRIPTION_WIDTH) + " " + "Compatible Runtimes".PadRight(LAYER_COMPATIBLE_RUNTIMES_WIDTH) + " " + "Created".PadRight(TIMESTAMP_WIDTH) + " " + "Latest Version ARN".PadRight(LAYER_ARN_WIDTH) ); this.Logger.WriteLine($"{new string('-', LAYER_DESCRIPTION_WIDTH)} {new string('-', LAYER_COMPATIBLE_RUNTIMES_WIDTH)} {new string('-', TIMESTAMP_WIDTH)} {new string('-', LAYER_ARN_WIDTH)}"); var request = new ListLayerVersionsRequest { LayerName = layerName}; ListLayerVersionsResponse response = null; do { request.Marker = response?.NextMarker; try { response = await this.LambdaClient.ListLayerVersionsAsync(request); } catch (Exception e) { throw new LambdaToolsException("Error listing versions for Lambda layer: " + e.Message, LambdaToolsException.LambdaErrorCode.LambdaListLayerVersions, e); } foreach (var layerVersion in response.LayerVersions) { this.Logger.WriteLine( LambdaUtilities.DetermineListDisplayLayerDescription(layerVersion.Description, LAYER_DESCRIPTION_WIDTH).PadRight(LAYER_DESCRIPTION_WIDTH) + " " + string.Join(", ", layerVersion.CompatibleRuntimes.ToArray()).PadRight(LAYER_COMPATIBLE_RUNTIMES_WIDTH) + " " + DateTime.Parse(layerVersion.CreatedDate).ToString("g").PadRight(TIMESTAMP_WIDTH) + " " + layerVersion.LayerVersionArn ); } } while (!string.IsNullOrEmpty(response.NextMarker)); return true; } protected override void SaveConfigFile(JsonData data) { } } }
99
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.CloudFormation.Model; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.Commands { /// <summary> /// List all the CloudFormation Stacks deployed as AWS Serverless applications. /// AWS Serverless applications are identified by the tag AWSServerlessAppNETCore which /// was automatically assigned to the stacks by the deploy-serverless command. /// </summary> public class ListServerlessCommand : LambdaBaseCommand { public const string COMMAND_NAME = "list-serverless"; public const string COMMAND_DESCRIPTION = "Command to list all your AWS Serverless applications"; public static readonly IList<CommandOption> ListCommandOptions = BuildLineOptions(new List<CommandOption> { }); public ListServerlessCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, ListCommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); } protected override async Task<bool> PerformActionAsync() { const int TIMESTAMP_WIDTH = 20; const int STACK_NAME_WIDTH = 30; const int STACK_STATUS_WIDTH = 20; this.Logger.WriteLine("Name".PadRight(STACK_NAME_WIDTH) + " " + "Status".PadRight(STACK_STATUS_WIDTH) + " " + "Created".PadRight(TIMESTAMP_WIDTH) + " " + "Last Modifed".PadRight(TIMESTAMP_WIDTH) ); this.Logger.WriteLine($"{new string('-', STACK_NAME_WIDTH)} {new string('-', STACK_STATUS_WIDTH)} {new string('-', TIMESTAMP_WIDTH)} {new string('-', TIMESTAMP_WIDTH)}"); var request = new DescribeStacksRequest(); DescribeStacksResponse response = null; do { if (response != null) request.NextToken = response.NextToken; try { response = await this.CloudFormationClient.DescribeStacksAsync(request); } catch (Exception e) { throw new LambdaToolsException("Error listing AWS Serverless applications: " + e.Message, LambdaToolsException.LambdaErrorCode.CloudFormationDescribeStack, e); } foreach (var stack in response.Stacks) { if (stack.Tags.Any(x => string.Equals(x.Key, LambdaConstants.SERVERLESS_TAG_NAME))) { this.Logger.WriteLine( stack.StackName.PadRight(STACK_NAME_WIDTH) + " " + stack.StackStatus.ToString().PadRight(STACK_STATUS_WIDTH) + " " + stack.CreationTime.ToString("g").PadRight(STACK_STATUS_WIDTH) + " " + stack.LastUpdatedTime.ToString("g").PadRight(TIMESTAMP_WIDTH) ); } } } while (!string.IsNullOrEmpty(response.NextToken)); return true; } protected override void SaveConfigFile(JsonData data) { } } }
97
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Lambda.Tools.TemplateProcessor; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.Commands { public class PackageCICommand : LambdaBaseCommand { public const string COMMAND_NAME = "package-ci"; public const string COMMAND_SYNOPSIS = "Command to use as part of a continuous integration system."; public const string COMMAND_DESCRIPTION = "Command for use as part of the build step in a continuous integration pipeline. To perform the deployment this command requires a CloudFormation template similar to the one used by Serverless projects. " + "The command performs the following actions: \n" + "\t 1) Build and package .NET Core project\n" + "\t 2) Upload build archive to Amazon S3\n" + "\t 3) Read in AWS CloudFormation template\n" + "\t 4) Update AWS::Lambda::Function and AWS::Serverless::Function resources to the location of the uploaded build archive\n" + "\t 5) Write out updated CloudFormation template\n\n" + "The output CloudFormation template should be used as the build step's output artifact. The deployment stage of the pipeline will use the outputted template to create a CloudFormation ChangeSet and then execute ChangeSet."; public static readonly IList<CommandOption> PackageCICommandOptions = BuildLineOptions(new List<CommandOption> { CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE_SUBSTITUTIONS, LambdaDefinedCommandOptions.ARGUMENT_OUTPUT_CLOUDFORMATION_TEMPLATE, LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX, LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK }); public string Configuration { get; set; } public string TargetFramework { get; set; } public string MSBuildParameters { get; set; } public bool? ResolveS3 { get; set; } public string S3Bucket { get; set; } public string S3Prefix { get; set; } public string CloudFormationTemplate { get; set; } public Dictionary<string, string> TemplateSubstitutions { get; set; } public bool? DisableVersionCheck { get; set; } public string CloudFormationOutputTemplate { get; set; } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION.Switch)) != null) this.Configuration = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.Switch)) != null) this.TargetFramework = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE.Switch)) != null) this.CloudFormationTemplate = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE_SUBSTITUTIONS.Switch)) != null) this.TemplateSubstitutions = tuple.Item2.KeyValuePairs; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_OUTPUT_CLOUDFORMATION_TEMPLATE.Switch)) != null) this.CloudFormationOutputTemplate = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3.Switch)) != null) this.ResolveS3 = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET.Switch)) != null) this.S3Bucket = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX.Switch)) != null) this.S3Prefix = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK.Switch)) != null) this.DisableVersionCheck = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS.Switch)) != null) this.MSBuildParameters = tuple.Item2.StringValue; if (!string.IsNullOrEmpty(values.MSBuildParameters)) { if (this.MSBuildParameters == null) this.MSBuildParameters = values.MSBuildParameters; else this.MSBuildParameters += " " + values.MSBuildParameters; } } public PackageCICommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, PackageCICommandOptions, args) { } protected override async Task<bool> PerformActionAsync() { // Disable interactive since this command is intended to be run as part of a pipeline. DisableInteractive = true; string projectLocation = this.GetStringValueOrDefault(this.ProjectLocation, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false); string s3Prefix = this.GetStringValueOrDefault(this.S3Prefix, LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX, false); string templatePath = this.GetStringValueOrDefault(this.CloudFormationTemplate, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE, true); string outputTemplatePath = this.GetStringValueOrDefault(this.CloudFormationOutputTemplate, LambdaDefinedCommandOptions.ARGUMENT_OUTPUT_CLOUDFORMATION_TEMPLATE, true); string s3Bucket = await DetermineS3Bucket(); if (!Path.IsPathRooted(templatePath)) { templatePath = Path.Combine(Utilities.DetermineProjectLocation(this.WorkingDirectory, projectLocation), templatePath); } if (!File.Exists(templatePath)) throw new LambdaToolsException($"Template file {templatePath} cannot be found.", LambdaToolsException.LambdaErrorCode.ServerlessTemplateNotFound); await Utilities.ValidateBucketRegionAsync(this.S3Client, s3Bucket); var templateBody = File.ReadAllText(templatePath); // Process any template substitutions templateBody = LambdaUtilities.ProcessTemplateSubstitions(this.Logger, templateBody, this.GetKeyValuePairOrDefault(this.TemplateSubstitutions, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE_SUBSTITUTIONS, false), Utilities.DetermineProjectLocation(this.WorkingDirectory, projectLocation)); var options = new DefaultLocationOption { Configuration = this.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false), TargetFramework = this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false), MSBuildParameters = this.GetStringValueOrDefault(this.MSBuildParameters, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, false), DisableVersionCheck = this.GetBoolValueOrDefault(this.DisableVersionCheck, LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK, false).GetValueOrDefault() }; var templateProcessor = new TemplateProcessorManager(this, s3Bucket, s3Prefix, options); templateBody = await templateProcessor.TransformTemplateAsync(templatePath, templateBody, OriginalCommandLineArguments); this.Logger.WriteLine($"Writing updated template: {outputTemplatePath}"); File.WriteAllText(outputTemplatePath, templateBody); return true; } private async Task<string> DetermineS3Bucket() { string s3Bucket = this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, false); bool? resolveS3 = this.GetBoolValueOrDefault(this.ResolveS3, LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3, false); if (string.IsNullOrEmpty(s3Bucket)) { if (resolveS3 == true) { s3Bucket = await LambdaUtilities.ResolveDefaultS3Bucket(this.Logger, this.S3Client, this.STSClient); } else { // Since a bucket wasn't explicitly passed in nor was resolve s3 passed in then ask the user for the S3 bucket. s3Bucket = this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, true); } } return s3Bucket; } protected override void SaveConfigFile(JsonData data) { data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION.ConfigFileKey, this.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.ConfigFileKey, this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS.ConfigFileKey, this.GetStringValueOrDefault(this.MSBuildParameters, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK.ConfigFileKey, this.GetBoolValueOrDefault(this.DisableVersionCheck, LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK, false)); var template = this.GetStringValueOrDefault(this.CloudFormationTemplate, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE, false); if(Path.IsPathRooted(template)) { string projectLocation = this.GetStringValueOrDefault(this.ProjectLocation, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false); var projectRoot = Utilities.DetermineProjectLocation(this.WorkingDirectory, projectLocation); if(template.StartsWith(projectRoot)) { template = template.Substring(projectRoot.Length + 1); } } data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE.ConfigFileKey, template); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE_SUBSTITUTIONS.ConfigFileKey, LambdaToolsDefaults.FormatKeyValue(this.GetKeyValuePairOrDefault(this.TemplateSubstitutions, LambdaDefinedCommandOptions.ARGUMENT_CLOUDFORMATION_TEMPLATE_SUBSTITUTIONS, false))); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_OUTPUT_CLOUDFORMATION_TEMPLATE.ConfigFileKey, this.GetStringValueOrDefault(this.CloudFormationOutputTemplate, LambdaDefinedCommandOptions.ARGUMENT_OUTPUT_CLOUDFORMATION_TEMPLATE, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3.ConfigFileKey, this.GetBoolValueOrDefault(this.ResolveS3, LambdaDefinedCommandOptions.ARGUMENT_RESOLVE_S3, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET.ConfigFileKey, this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX.ConfigFileKey, this.GetStringValueOrDefault(this.S3Prefix, LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX, false)); } } }
193
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Commands; using Amazon.Common.DotNetCli.Tools.Options; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.Commands { public class PackageCommand : LambdaBaseCommand { public const string COMMAND_NAME = "package"; public const string COMMAND_DESCRIPTION = "Command to package a Lambda project either into a zip file or docker image if --package-type is set to \"image\". The output can later be deployed to Lambda " + "with either deploy-function command or with another tool."; public const string COMMAND_ARGUMENTS = "<ZIP-FILE> The name of the zip file to package the project into"; public static readonly IList<CommandOption> PackageCommandOptions = BuildLineOptions(new List<CommandOption> { CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_LAYERS, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, CommonDefinedCommandOptions.ARGUMENT_CONFIG_FILE, CommonDefinedCommandOptions.ARGUMENT_PERSIST_CONFIG_FILE, LambdaDefinedCommandOptions.ARGUMENT_OUTPUT_PACKAGE, LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK, LambdaDefinedCommandOptions.ARGUMENT_PACKAGE_TYPE, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_TAG, CommonDefinedCommandOptions.ARGUMENT_DOCKERFILE, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY, CommonDefinedCommandOptions.ARGUMENT_HOST_BUILD_OUTPUT, LambdaDefinedCommandOptions.ARGUMENT_USE_CONTAINER_FOR_BUILD, LambdaDefinedCommandOptions.ARGUMENT_CONTAINER_IMAGE_FOR_BUILD, LambdaDefinedCommandOptions.ARGUMENT_CODE_MOUNT_DIRECTORY }); public string Architecture { get; set; } public string Configuration { get; set; } public string TargetFramework { get; set; } public string OutputPackageFileName { get; set; } public string MSBuildParameters { get; set; } public string[] LayerVersionArns { get; set; } public bool? DisableVersionCheck { get; set; } public string PackageType { get; set; } public string DockerFile { get; set; } public string DockerBuildOptions { get; set; } public string DockerBuildWorkingDirectory { get; set; } public string DockerImageTag { get; set; } public string HostBuildOutput { get; set; } public bool? UseContainerForBuild { get; set; } public string ContainerImageForBuild { get; set; } public string CodeMountDirectory { get; private set; } /// <summary> /// Property set when the package command is being created from another command or tool /// and the service clients have been copied over. In that case there is no reason /// to look for a region or aws credentials. /// </summary> public bool DisableRegionAndCredentialsCheck { get; set; } /// <summary> /// If runtime package store layers were specified the DOTNET_SHARED_STORE environment variable /// has to be set. This property will contain the value the environment variable must be set. /// </summary> public string NewDotnetSharedStoreValue { get; private set; } /// <summary> /// If the value for Payload points to an existing file then the contents of the file is sent, otherwise /// value of Payload is sent as the input to the function. /// </summary> public string Payload { get; set; } public PackageCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, PackageCommandOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); if (values.Arguments.Count > 0) { this.OutputPackageFileName = values.Arguments[0]; } Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION.Switch)) != null) this.Configuration = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.Switch)) != null) this.TargetFramework = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_OUTPUT_PACKAGE.Switch)) != null) this.OutputPackageFileName = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK.Switch)) != null) this.DisableVersionCheck = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS.Switch)) != null) this.MSBuildParameters = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_LAYERS.Switch)) != null) this.LayerVersionArns = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE.Switch)) != null) this.Architecture = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_USE_CONTAINER_FOR_BUILD.Switch)) != null) this.UseContainerForBuild = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_CONTAINER_IMAGE_FOR_BUILD.Switch)) != null) this.ContainerImageForBuild = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_CODE_MOUNT_DIRECTORY.Switch)) != null) this.CodeMountDirectory = tuple.Item2.StringValue; if (!string.IsNullOrEmpty(values.MSBuildParameters)) { if (this.MSBuildParameters == null) this.MSBuildParameters = values.MSBuildParameters; else this.MSBuildParameters += " " + values.MSBuildParameters; } if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_PACKAGE_TYPE.Switch)) != null) this.PackageType = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_DOCKERFILE.Switch)) != null) this.DockerFile = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS.Switch)) != null) this.DockerBuildOptions = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY.Switch)) != null) this.DockerBuildWorkingDirectory = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_IMAGE_TAG.Switch)) != null) this.DockerImageTag = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_HOST_BUILD_OUTPUT.Switch)) != null) this.HostBuildOutput = tuple.Item2.StringValue; } protected override async Task<bool> PerformActionAsync() { EnsureInProjectDirectory(); // Disable interactive since this command is intended to be run as part of a pipeline. this.DisableInteractive = true; string projectLocation = Utilities.DetermineProjectLocation(this.WorkingDirectory, this.GetStringValueOrDefault(this.ProjectLocation, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false)); Lambda.PackageType packageType = LambdaUtilities.DeterminePackageType(this.GetStringValueOrDefault(this.PackageType, LambdaDefinedCommandOptions.ARGUMENT_PACKAGE_TYPE, false)); if(packageType == Lambda.PackageType.Image) { var pushResults = await PushLambdaImageAsync(); if (!pushResults.Success) { if (pushResults.LastException != null) throw pushResults.LastException; throw new LambdaToolsException("Failed to push container image to ECR.", LambdaToolsException.LambdaErrorCode.FailedToPushImage); } } else { var layerVersionArns = this.GetStringValuesOrDefault(this.LayerVersionArns, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_LAYERS, false); LayerPackageInfo layerPackageInfo = null; if (layerVersionArns != null) { if (!this.DisableRegionAndCredentialsCheck) { // Region and credentials are only required if using layers. This is new behavior so do a preemptive check when there are layers to // see if region and credentials are set. If they are not set give a specific error message about region and credentials required // when using layers. try { base.DetermineAWSRegion(); } catch (Exception) { throw new ToolsException("Region is required for the package command when layers are specified. The layers must be inspected to see how they affect packaging.", ToolsException.CommonErrorCode.RegionNotConfigured); } try { base.DetermineAWSCredentials(); } catch (Exception) { throw new ToolsException("AWS credentials are required for the package command when layers are specified. The layers must be inspected to see how they affect packaging.", ToolsException.CommonErrorCode.InvalidCredentialConfiguration); } } layerPackageInfo = await LambdaUtilities.LoadLayerPackageInfos(this.Logger, this.LambdaClient, this.S3Client, layerVersionArns); } else { layerPackageInfo = new LayerPackageInfo(); } // Release will be the default configuration if nothing set. var configuration = this.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false); var targetFramework = this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false); if (string.IsNullOrEmpty(targetFramework)) { targetFramework = Utilities.LookupTargetFrameworkFromProjectFile(projectLocation); // If we still don't know what the target framework is ask the user what targetframework to use. // This is common when a project is using multi targeting. if (string.IsNullOrEmpty(targetFramework)) { targetFramework = this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, true); } } bool isNativeAot = Utilities.LookPublishAotFlag(projectLocation, this.MSBuildParameters); var msbuildParameters = this.GetStringValueOrDefault(this.MSBuildParameters, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, false); var architecture = this.GetStringValueOrDefault(this.Architecture, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE, false); var disableVersionCheck = this.GetBoolValueOrDefault(this.DisableVersionCheck, LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK, false).GetValueOrDefault(); var zipArchivePath = GetStringValueOrDefault(this.OutputPackageFileName, LambdaDefinedCommandOptions.ARGUMENT_OUTPUT_PACKAGE, false); string publishLocation; var success = LambdaPackager.CreateApplicationBundle(defaults: this.DefaultConfig, logger: this.Logger, workingDirectory: this.WorkingDirectory, projectLocation: projectLocation, configuration: configuration, targetFramework: targetFramework, msbuildParameters: msbuildParameters, architecture: architecture, disableVersionCheck: disableVersionCheck, layerPackageInfo: layerPackageInfo, isNativeAot: isNativeAot, useContainerForBuild: GetBoolValueOrDefault(this.UseContainerForBuild, LambdaDefinedCommandOptions.ARGUMENT_USE_CONTAINER_FOR_BUILD, false), containerImageForBuild: GetStringValueOrDefault(this.ContainerImageForBuild, LambdaDefinedCommandOptions.ARGUMENT_CONTAINER_IMAGE_FOR_BUILD, false), codeMountDirectory: GetStringValueOrDefault(this.CodeMountDirectory, LambdaDefinedCommandOptions.ARGUMENT_CODE_MOUNT_DIRECTORY, false), publishLocation: out publishLocation, zipArchivePath: ref zipArchivePath); if (!success) { throw new LambdaToolsException("Failed to create Lambda deployment bundle.", ToolsException.CommonErrorCode.DotnetPublishFailed); } this.Logger.WriteLine("Lambda project successfully packaged: " + zipArchivePath); var dotnetSharedStoreValue = layerPackageInfo.GenerateDotnetSharedStoreValue(); if (!string.IsNullOrEmpty(dotnetSharedStoreValue)) { this.NewDotnetSharedStoreValue = dotnetSharedStoreValue; this.Logger.WriteLine($"\nWarning: You must set the {LambdaConstants.ENV_DOTNET_SHARED_STORE} environment variable when deploying the package. " + "If not set the layers specified will not be located by the .NET Core runtime. The trailing '/' is required."); this.Logger.WriteLine($"{LambdaConstants.ENV_DOTNET_SHARED_STORE}: {dotnetSharedStoreValue}"); } } return true; } private async Task<PushLambdaImageResult> PushLambdaImageAsync() { var pushCommand = new PushDockerImageCommand(this.Logger, this.WorkingDirectory, this.OriginalCommandLineArguments) { ConfigFile = this.ConfigFile, DisableInteractive = this.DisableInteractive, Credentials = this.Credentials, ECRClient = this.ECRClient, Profile = this.Profile, ProfileLocation = this.ProfileLocation, ProjectLocation = this.ProjectLocation, Region = this.Region, WorkingDirectory = this.WorkingDirectory, SkipPushToECR = true, PushDockerImageProperties = new BasePushDockerImageCommand<LambdaToolsDefaults>.PushDockerImagePropertyContainer { Configuration = this.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false), TargetFramework = this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false), DockerFile = this.GetStringValueOrDefault(this.DockerFile, CommonDefinedCommandOptions.ARGUMENT_DOCKERFILE, false), DockerBuildOptions = this.GetStringValueOrDefault(this.DockerBuildOptions, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_OPTIONS, false), DockerBuildWorkingDirectory = this.GetStringValueOrDefault(this.DockerBuildWorkingDirectory, CommonDefinedCommandOptions.ARGUMENT_DOCKER_BUILD_WORKING_DIRECTORY, false), DockerImageTag = this.GetStringValueOrDefault(this.DockerImageTag, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_TAG, false), PublishOptions = this.GetStringValueOrDefault(this.MSBuildParameters, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, false), HostBuildOutput = this.GetStringValueOrDefault(this.HostBuildOutput, CommonDefinedCommandOptions.ARGUMENT_HOST_BUILD_OUTPUT, false) } }; var result = new PushLambdaImageResult(); result.Success = await pushCommand.ExecuteAsync(); result.LastException = pushCommand.LastException; if(result.Success) { this.Logger.WriteLine($"Packaged project as image: \"{pushCommand.PushedImageUri}\""); } return result; } protected override void SaveConfigFile(JsonData data) { data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION.ConfigFileKey, this.GetStringValueOrDefault(this.ProjectLocation, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION.ConfigFileKey, this.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.ConfigFileKey, this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE.ConfigFileKey, this.GetStringValueOrDefault(this.Architecture, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE, false)); data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS.ConfigFileKey, this.GetStringValueOrDefault(this.MSBuildParameters, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_OUTPUT_PACKAGE.ConfigFileKey, this.GetStringValueOrDefault(this.OutputPackageFileName, LambdaDefinedCommandOptions.ARGUMENT_OUTPUT_PACKAGE, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK.ConfigFileKey, this.GetBoolValueOrDefault(this.DisableVersionCheck, LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_USE_CONTAINER_FOR_BUILD.ConfigFileKey, this.GetBoolValueOrDefault(this.UseContainerForBuild, LambdaDefinedCommandOptions.ARGUMENT_USE_CONTAINER_FOR_BUILD, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_CONTAINER_IMAGE_FOR_BUILD.ConfigFileKey, this.GetStringValueOrDefault(this.ContainerImageForBuild, LambdaDefinedCommandOptions.ARGUMENT_CONTAINER_IMAGE_FOR_BUILD, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_CODE_MOUNT_DIRECTORY.ConfigFileKey, this.GetStringValueOrDefault(this.CodeMountDirectory, LambdaDefinedCommandOptions.ARGUMENT_CODE_MOUNT_DIRECTORY, false)); } } }
325
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using ThirdParty.Json.LitJson; using Amazon.Lambda.Model; using System.Runtime.InteropServices; namespace Amazon.Lambda.Tools.Commands { public class PublishLayerCommand : LambdaBaseCommand { public const string COMMAND_NAME = "publish-layer"; public const string COMMAND_DESCRIPTION = "Command to publish a Layer that can be associated with a Lambda function"; public const string COMMAND_ARGUMENTS = "<LAYER-NAME> The name of the layer"; public static readonly IList<CommandOption> PublishLayerCommandOptions = BuildLineOptions(new List <CommandOption> { CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX, LambdaDefinedCommandOptions.ARGUMENT_LAYER_NAME, LambdaDefinedCommandOptions.ARGUMENT_LAYER_TYPE, LambdaDefinedCommandOptions.ARGUMENT_LAYER_LICENSE_INFO, LambdaDefinedCommandOptions.ARGUMENT_PACKAGE_MANIFEST, LambdaDefinedCommandOptions.ARGUMENT_OPT_DIRECTORY, LambdaDefinedCommandOptions.ARGUMENT_ENABLE_PACKAGE_OPTIMIZATION }); public string Architecture { get; set; } public string TargetFramework { get; set; } public string S3Bucket { get; set; } public string S3Prefix { get; set; } public string LayerName { get; set; } public string LayerType { get; set; } public string LayerLicenseInfo { get; set; } public string PackageManifest { get; set; } public string OptDirectory { get; set; } public bool? EnablePackageOptimization { get; set; } public string NewLayerArn { get; set; } public long NewLayerVersionNumber { get; set; } public string NewLayerVersionArn { get; set; } public PublishLayerCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, PublishLayerCommandOptions, args) { } protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); if (values.Arguments.Count > 0) { this.LayerName = values.Arguments[0]; } Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.Switch)) != null) this.TargetFramework = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET.Switch)) != null) this.S3Bucket = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX.Switch)) != null) this.S3Prefix = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_LAYER_NAME.Switch)) != null) this.LayerName = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_LAYER_TYPE.Switch)) != null) this.LayerType = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_LAYER_LICENSE_INFO.Switch)) != null) this.LayerLicenseInfo = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_PACKAGE_MANIFEST.Switch)) != null) this.PackageManifest = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_OPT_DIRECTORY.Switch)) != null) this.OptDirectory = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_ENABLE_PACKAGE_OPTIMIZATION.Switch)) != null) this.EnablePackageOptimization = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE.Switch)) != null) this.Architecture = tuple.Item2.StringValue; } protected override async Task<bool> PerformActionAsync() { var layerName = this.GetStringValueOrDefault(this.LayerName, LambdaDefinedCommandOptions.ARGUMENT_LAYER_NAME, true); var s3Bucket = this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, true); var s3Prefix = this.GetStringValueOrDefault(this.S3Prefix, LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX, false); // This command will store 2 file in S3. The object structure will be // <provided-prefix>/ // <layer-name>-<unique-ticks>/ // packages.zip -- Zip file containing the NuGet packages // artifact.xml -- Xml file describe the NuGet packages in the layer if (string.IsNullOrEmpty(s3Prefix)) { s3Prefix = string.Empty; } else if(!s3Prefix.EndsWith("/")) { s3Prefix += "/"; } s3Prefix += $"{layerName}-{DateTime.UtcNow.Ticks}/"; var layerType = this.GetStringValueOrDefault(this.LayerType, LambdaDefinedCommandOptions.ARGUMENT_LAYER_TYPE, true); CreateLayerZipFileResult createResult; switch (layerType) { case LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE: createResult = await CreateRuntimePackageStoreLayerZipFile(layerName, s3Prefix); break; default: throw new LambdaToolsException($"Unknown layer type {layerType}. Allowed values are: {LambdaConstants.LAYER_TYPE_ALLOWED_VALUES}", LambdaToolsException.LambdaErrorCode.UnknownLayerType); } this.Logger.WriteLine($"Uploading layer input zip file to S3"); var s3ZipKey = await UploadFile(createResult.ZipFile, $"{s3Prefix}packages.zip"); var request = new PublishLayerVersionRequest { LayerName = layerName, Description = createResult.Description, Content = new LayerVersionContentInput { S3Bucket = s3Bucket, S3Key = s3ZipKey }, CompatibleRuntimes = createResult.CompatibleRuntimes, LicenseInfo = this.GetStringValueOrDefault(this.LayerLicenseInfo, LambdaDefinedCommandOptions.ARGUMENT_LAYER_LICENSE_INFO, false) }; var architecture = this.GetStringValueOrDefault(this.Architecture, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE, false); if (!string.IsNullOrEmpty(architecture)) { request.CompatibleArchitectures = new List<string> { architecture }; } try { var publishResponse = await this.LambdaClient.PublishLayerVersionAsync(request); this.NewLayerArn = publishResponse.LayerArn; this.NewLayerVersionArn = publishResponse.LayerVersionArn; this.NewLayerVersionNumber = publishResponse.Version; } catch(Exception e) { throw new LambdaToolsException($"Error calling the Lambda service to publish the layer: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaPublishLayerVersion, e); } this.Logger?.WriteLine($"Layer publish with arn {this.NewLayerVersionArn}"); return true; } private async Task<CreateLayerZipFileResult> CreateRuntimePackageStoreLayerZipFile(string layerName, string s3Prefix) { var targetFramework = this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, true); var projectLocation = this.GetStringValueOrDefault(this.ProjectLocation, CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION, false); var enableOptimization = this.GetBoolValueOrDefault(this.EnablePackageOptimization, LambdaDefinedCommandOptions.ARGUMENT_ENABLE_PACKAGE_OPTIMIZATION, false).GetValueOrDefault(); if(string.Equals(targetFramework, "netcoreapp3.1")) { var version = DotNetCLIWrapper.GetSdkVersion(); // .NET SDK 3.1 versions less then 3.1.400 have an issue throwing NullReferenceExceptions when pruning packages out with the manifest. // https://github.com/dotnet/sdk/issues/10973 if (version < Version.Parse("3.1.400")) { var message = $"Publishing runtime package store layers targeting .NET Core 3.1 requires at least version 3.1.400 of the .NET SDK. Current version installed is {version}."; throw new LambdaToolsException(message, LambdaToolsException.LambdaErrorCode.DisabledSupportForNET31Layers); } } #if NETCOREAPP3_1_OR_GREATER if (enableOptimization) { if(!RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { throw new LambdaToolsException($"Package optimization is only possible on Amazon Linux. To use this feature execute the command in an Amazon Linux environment.", LambdaToolsException.LambdaErrorCode.UnsupportedOptimizationPlatform); } else { this.Logger.WriteLine("Warning: Package optimization has been enabled. Be sure to run this on an Amazon Linux environment or the optimization might not be compatbile with the Lambda runtime."); } } #else // This is the case the code is run in the AWS Toolkit for Visual Studio which will never run on Amazon Linux. enableOptimization = false; #endif // This is the manifest that list the NuGet packages via <PackageReference> elements in the msbuild project file. var packageManifest = this.GetStringValueOrDefault(this.PackageManifest, LambdaDefinedCommandOptions.ARGUMENT_PACKAGE_MANIFEST, false); // If this is null attempt to use the current directory. This is likely if the intent is to make a // layer from the current Lambda project. if (string.IsNullOrEmpty(packageManifest)) { packageManifest = Utilities.DetermineProjectLocation(this.WorkingDirectory, projectLocation); } // If this is a directory look to see if there is a single csproj of fsproj in the directory in use that. // This is to make it easy to make a layer in the current directory of a Lambda function. if (Directory.Exists(packageManifest)) { var files = Directory.GetFiles(packageManifest, "*.csproj"); if(files.Length == 1) { packageManifest = Path.Combine(packageManifest, files[0]); } else if(files.Length == 0) { files = Directory.GetFiles(packageManifest, "*.fsproj"); if (files.Length == 1) { packageManifest = Path.Combine(packageManifest, files[0]); } } } if(!File.Exists(packageManifest)) { throw new LambdaToolsException($"Can not find package manifest {packageManifest}. Make sure to point to a file not a directory.", LambdaToolsException.LambdaErrorCode.LayerPackageManifestNotFound); } // Create second subdirectory so that when the directory is zipped the sub directory is retained in the zip file. // The sub directory will be created in the /opt directory in the Lambda environment. var tempDirectoryName = $"{layerName}-{DateTime.UtcNow.Ticks}".ToLower(); var optDirectory = this.GetStringValueOrDefault(this.OptDirectory, LambdaDefinedCommandOptions.ARGUMENT_OPT_DIRECTORY, false); if (string.IsNullOrEmpty(optDirectory)) { optDirectory = LambdaConstants.DEFAULT_LAYER_OPT_DIRECTORY; } var tempRootPath = Path.Combine(Path.GetTempPath(), tempDirectoryName); var storeOutputDirectory = Path.Combine(tempRootPath, optDirectory); { var convertResult = LambdaUtilities.ConvertManifestToSdkManifest(targetFramework, packageManifest); if (convertResult.ShouldDelete) { this.Logger?.WriteLine("Converted ASP.NET Core project file to temporary package manifest file."); } var architecture = this.GetStringValueOrDefault(this.Architecture, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE, false); var cliWrapper = new LambdaDotNetCLIWrapper(this.Logger, this.WorkingDirectory); if(cliWrapper.Store(defaults: this.DefaultConfig, projectLocation: projectLocation, outputLocation: storeOutputDirectory, targetFramework: targetFramework, packageManifest: convertResult.PackageManifest, architecture: architecture, enableOptimization: enableOptimization) != 0) { throw new LambdaToolsException($"Error executing the 'dotnet store' command", LambdaToolsException.LambdaErrorCode.StoreCommandError); } if (convertResult.ShouldDelete) { File.Delete(convertResult.PackageManifest); } } // The artifact.xml file is generated by the "dotnet store" command that lists the packages that were added to the store. // It is required during a "dotnet publish" so the NuGet packages in the store will be filtered out. var artifactXmlPath = Path.Combine(storeOutputDirectory, "x64", targetFramework, "artifact.xml"); if(!File.Exists(artifactXmlPath)) { throw new LambdaToolsException($"Failed to find artifact.xml file in created local store.", LambdaToolsException.LambdaErrorCode.FailedToFindArtifactZip); } this.Logger.WriteLine($"Uploading runtime package store manifest to S3"); var s3Key = await UploadFile(artifactXmlPath, $"{s3Prefix}artifact.xml"); this.Logger.WriteLine($"Create zip file of runtime package store directory"); var zipPath = Path.Combine(Path.GetTempPath(), $"{layerName}-{DateTime.UtcNow.Ticks}.zip"); if(File.Exists(zipPath)) { File.Delete(zipPath); } LambdaPackager.BundleDirectory(zipPath, tempRootPath, false, this.Logger); var result = new CreateLayerZipFileResult { ZipFile = zipPath, LayerDirectory = optDirectory }; var s3Bucket = this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, true); // Set the description field to the our JSON layer manifest file so when the tooling is used // to create a package of a Lambda function in the future the artifact.xml file can be used during "dotnet publish". result.Description = GeneratorRuntimePackageManifestLayerDescription(optDirectory, s3Bucket, s3Key, enableOptimization); var compatibleRuntime = LambdaUtilities.DetermineLambdaRuntimeFromTargetFramework(targetFramework); if(!string.IsNullOrEmpty(compatibleRuntime)) { result.CompatibleRuntimes = new List<string>() { compatibleRuntime }; } return result; } public static string GeneratorRuntimePackageManifestLayerDescription(string directory, string s3Bucket, string s3Key, bool enableOptimization) { var manifestDescription = new LayerDescriptionManifest(LayerDescriptionManifest.ManifestType.RuntimePackageStore); manifestDescription.Dir = directory; manifestDescription.Buc = s3Bucket; manifestDescription.Key = s3Key; manifestDescription.Op = enableOptimization ? LayerDescriptionManifest.OptimizedState.Optimized : LayerDescriptionManifest.OptimizedState.NoOptimized; var json = JsonMapper.ToJson(manifestDescription); return json; } private async Task<string> UploadFile(string filePath, string s3Key) { var s3Bucket = this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, true); string s3ZipKey; using (var stream = File.OpenRead(filePath)) { s3ZipKey = await Utilities.UploadToS3Async(this.Logger, this.S3Client, s3Bucket, s3Key, stream); this.Logger?.WriteLine($"Upload complete to s3://{s3Bucket}/{s3ZipKey}"); } return s3ZipKey; } protected override void SaveConfigFile(JsonData data) { data.SetIfNotNull(CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK.ConfigFileKey, this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE.ConfigFileKey, this.GetStringValueOrDefault(this.Architecture, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET.ConfigFileKey, this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX.ConfigFileKey, this.GetStringValueOrDefault(this.S3Prefix, LambdaDefinedCommandOptions.ARGUMENT_S3_PREFIX, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_LAYER_NAME.ConfigFileKey, this.GetStringValueOrDefault(this.LayerName, LambdaDefinedCommandOptions.ARGUMENT_LAYER_NAME, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_LAYER_TYPE.ConfigFileKey, this.GetStringValueOrDefault(this.LayerType, LambdaDefinedCommandOptions.ARGUMENT_LAYER_TYPE, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_LAYER_LICENSE_INFO.ConfigFileKey, this.GetStringValueOrDefault(this.LayerLicenseInfo, LambdaDefinedCommandOptions.ARGUMENT_LAYER_LICENSE_INFO, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_PACKAGE_MANIFEST.ConfigFileKey, this.GetStringValueOrDefault(this.PackageManifest, LambdaDefinedCommandOptions.ARGUMENT_PACKAGE_MANIFEST, false)); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_ENABLE_PACKAGE_OPTIMIZATION.ConfigFileKey, this.GetBoolValueOrDefault(this.EnablePackageOptimization, LambdaDefinedCommandOptions.ARGUMENT_ENABLE_PACKAGE_OPTIMIZATION, false)); } class CreateLayerZipFileResult { public string ZipFile { get; set; } public string Description { get; set; } public List<string> CompatibleRuntimes { get; set; } public string LayerDirectory { get; set; } } } }
355
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Commands; using Amazon.Common.DotNetCli.Tools.Options; using System; using System.Collections.Generic; using System.IO; using System.Text; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.Commands { public class PushDockerImageCommand : BasePushDockerImageCommand<LambdaToolsDefaults> { public const string COMMAND_NAME = "push-image"; public const string COMMAND_DESCRIPTION = "Build Lambda Docker image and push the image to Amazon ECR."; public static readonly IList<CommandOption> LambdaPushCommandOptions = BuildLineOptions(new List<CommandOption> { LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE, }, BasePushDockerImageCommand<LambdaToolsDefaults>.CommandOptions); protected override string ToolName => LambdaConstants.TOOLNAME; public string Architecture { get; set; } public PushDockerImageCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, LambdaPushCommandOptions, args) { } protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE.Switch)) != null) this.Architecture = tuple.Item2.StringValue; } /// <summary> /// Exposed to allow other command within Amazon.Lambda.Tools to reuse the push command but not have the exception trapping logic /// in the ExecuteAsync method. /// </summary> /// <returns></returns> internal System.Threading.Tasks.Task<bool> PushImageAsync() { return base.PerformActionAsync(); } protected override void BuildProject(string projectLocation, string configuration, string targetFramework, string publishOptions, string publishLocation) { this.EnsureInProjectDirectory(); var architecture = this.GetStringValueOrDefault(this.Architecture, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE, false); var dotnetCli = new LambdaDotNetCLIWrapper(this.Logger, projectLocation); this.Logger?.WriteLine("Executing publish command"); if (dotnetCli.Publish(defaults: this.DefaultConfig, projectLocation: projectLocation, outputLocation: publishLocation, targetFramework: targetFramework, configuration: configuration, msbuildParameters: publishOptions, architecture: architecture, publishManifests: null) != 0) { throw new ToolsException("Error executing \"dotnet publish\"", ToolsException.CommonErrorCode.DotnetPublishFailed); } } protected override int ExecuteDockerBuild(DockerCLIWrapper dockerCli, string dockerBuildWorkingDirectory, string fullDockerfilePath, string dockerImageTag, string dockerBuildOptions) { var architecture = this.GetStringValueOrDefault(this.Architecture, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE, false); var arm64Build = false; if (string.Equals(LambdaConstants.RUNTIME_LINUX_ARM64, LambdaUtilities.DetermineRuntimeParameter(null, architecture))) { arm64Build = true; } return dockerCli.Build(dockerBuildWorkingDirectory, fullDockerfilePath, dockerImageTag, dockerBuildOptions, arm64Build); } protected override void SaveConfigFile(JsonData data) { base.SaveConfigFile(data); data.SetIfNotNull(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE.ConfigFileKey, this.GetStringValueOrDefault(this.Architecture, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ARCHITECTURE, false)); } } }
91
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Common.DotNetCli.Tools; using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.Tools.Commands { public class PushLambdaImageResult { public bool Success { get; set; } public Exception LastException { get; set; } public string ImageUri { get; set; } } }
15
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Lambda; using Amazon.Lambda.Model; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.Commands { /// <summary> /// Updates the configuration for an existing function. To avoid any accidental changes to the function /// only fields that were explicitly set are changed and defaults are ignored. /// </summary> public class UpdateFunctionConfigCommand : LambdaBaseCommand { public const string COMMAND_NAME = "update-function-config"; public const string COMMAND_DESCRIPTION = "Command to update the runtime configuration for a Lambda function"; public const string COMMAND_ARGUMENTS = "<FUNCTION-NAME> The name of the function to be updated"; public static readonly IList<CommandOption> UpdateCommandOptions = BuildLineOptions(new List<CommandOption> { LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_DESCRIPTION, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_PUBLISH, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_MEMORY_SIZE, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ROLE, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TIMEOUT, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_RUNTIME, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_HANDLER, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_LAYERS, LambdaDefinedCommandOptions.ARGUMENT_EPHEMERAL_STORAGE_SIZE, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_ENABLE, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_AUTH, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_ENTRYPOINT, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_COMMAND, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_WORKING_DIRECTORY, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TAGS, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SUBNETS, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SECURITY_GROUPS, LambdaDefinedCommandOptions.ARGUMENT_DEADLETTER_TARGET_ARN, LambdaDefinedCommandOptions.ARGUMENT_TRACING_MODE, LambdaDefinedCommandOptions.ARGUMENT_ENVIRONMENT_VARIABLES, LambdaDefinedCommandOptions.ARGUMENT_APPEND_ENVIRONMENT_VARIABLES, LambdaDefinedCommandOptions.ARGUMENT_KMS_KEY_ARN, LambdaDefinedCommandOptions.ARGUMENT_APPLY_DEFAULTS_FOR_UPDATE_OBSOLETE }); public string FunctionName { get; set; } public string Description { get; set; } public bool? Publish { get; set; } public string Handler { get; set; } public int? MemorySize { get; set; } public string Role { get; set; } public int? Timeout { get; set; } public string[] LayerVersionArns { get; set; } public string[] SubnetIds { get; set; } public string[] SecurityGroupIds { get; set; } public Runtime Runtime { get; set; } public Dictionary<string, string> EnvironmentVariables { get; set; } public Dictionary<string, string> AppendEnvironmentVariables { get; set; } public Dictionary<string, string> Tags { get; set; } public string KMSKeyArn { get; set; } public string DeadLetterTargetArn { get; set; } public string TracingMode { get; set; } public string[] ImageEntryPoint { get; set; } public string[] ImageCommand { get; set; } public string ImageWorkingDirectory { get; set; } public string PackageType { get; set; } public int? EphemeralStorageSize { get; set; } public bool? FunctionUrlEnable { get; set; } public string FunctionUrlAuthType { get; set; } public string FunctionUrlLink { get; private set; } public UpdateFunctionConfigCommand(IToolLogger logger, string workingDirectory, string[] args) : base(logger, workingDirectory, UpdateCommandOptions, args) { } protected UpdateFunctionConfigCommand(IToolLogger logger, string workingDirectory, IList<CommandOption> possibleOptions, string[] args) : base(logger, workingDirectory, possibleOptions, args) { } /// <summary> /// Parse the CommandOptions into the Properties on the command. /// </summary> /// <param name="values"></param> protected override void ParseCommandArguments(CommandOptions values) { base.ParseCommandArguments(values); if (values.Arguments.Count > 0) { this.FunctionName = values.Arguments[0]; } Tuple<CommandOption, CommandOptionValue> tuple; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME.Switch)) != null) this.FunctionName = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_DESCRIPTION.Switch)) != null) this.Description = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_PUBLISH.Switch)) != null) this.Publish = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_HANDLER.Switch)) != null) this.Handler = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_MEMORY_SIZE.Switch)) != null) this.MemorySize = tuple.Item2.IntValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ROLE.Switch)) != null) this.Role = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TIMEOUT.Switch)) != null) this.Timeout = tuple.Item2.IntValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_RUNTIME.Switch)) != null) this.Runtime = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_LAYERS.Switch)) != null) this.LayerVersionArns = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TAGS.Switch)) != null) this.Tags = tuple.Item2.KeyValuePairs; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SUBNETS.Switch)) != null) this.SubnetIds = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SECURITY_GROUPS.Switch)) != null) this.SecurityGroupIds = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_DEADLETTER_TARGET_ARN.Switch)) != null) this.DeadLetterTargetArn = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_TRACING_MODE.Switch)) != null) this.TracingMode = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_ENVIRONMENT_VARIABLES.Switch)) != null) this.EnvironmentVariables = tuple.Item2.KeyValuePairs; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_APPEND_ENVIRONMENT_VARIABLES.Switch)) != null) this.AppendEnvironmentVariables = tuple.Item2.KeyValuePairs; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_KMS_KEY_ARN.Switch)) != null) this.KMSKeyArn = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_IMAGE_ENTRYPOINT.Switch)) != null) this.ImageEntryPoint = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_IMAGE_COMMAND.Switch)) != null) this.ImageCommand = tuple.Item2.StringValues; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_IMAGE_WORKING_DIRECTORY.Switch)) != null) this.ImageWorkingDirectory = tuple.Item2.StringValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_EPHEMERAL_STORAGE_SIZE.Switch)) != null) this.EphemeralStorageSize = tuple.Item2.IntValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_ENABLE.Switch)) != null) this.FunctionUrlEnable = tuple.Item2.BoolValue; if ((tuple = values.FindCommandOption(LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_AUTH.Switch)) != null) this.FunctionUrlAuthType = tuple.Item2.StringValue; } protected override async Task<bool> PerformActionAsync() { var currentConfiguration = await GetFunctionConfigurationAsync(); if(currentConfiguration == null) { this.Logger.WriteLine($"Could not find existing Lambda function {this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true)}"); return false; } var layerVersionArns = this.GetStringValuesOrDefault(this.LayerVersionArns, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_LAYERS, false); var layerPackageInfo = await LambdaUtilities.LoadLayerPackageInfos(this.Logger, this.LambdaClient, this.S3Client, layerVersionArns); await UpdateConfigAsync(currentConfiguration, layerPackageInfo.GenerateDotnetSharedStoreValue()); await ApplyTags(currentConfiguration.FunctionArn); var publish = this.GetBoolValueOrDefault(this.Publish, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_PUBLISH, false).GetValueOrDefault(); if (publish) { await PublishFunctionAsync(currentConfiguration.FunctionName); } return true; } protected async Task PublishFunctionAsync(string functionName) { try { await LambdaUtilities.WaitTillFunctionAvailableAsync(this.Logger, this.LambdaClient, functionName); var response = await this.LambdaClient.PublishVersionAsync(new PublishVersionRequest { FunctionName = functionName }); this.Logger.WriteLine("Published new Lambda function version: " + response.Version); } catch (Exception e) { throw new LambdaToolsException($"Error publishing Lambda function: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaPublishFunction, e); } } protected async Task ApplyTags(string functionArn) { try { var tags = this.GetKeyValuePairOrDefault(this.Tags, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TAGS, false); if (tags == null || tags.Count == 0) return; var tagRequest = new TagResourceRequest { Resource = functionArn, Tags = tags }; await this.LambdaClient.TagResourceAsync(tagRequest); this.Logger?.WriteLine($"Applying {tags.Count} tag(s) to function"); } catch (Exception e) { throw new LambdaToolsException($"Error tagging Lambda function: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaTaggingFunction, e); } } /// <summary> /// Reverts the lambda configuration to an earlier point, which is needed if updating the lambda function code failed. /// </summary> /// <param name="existingConfiguration"></param> protected async Task AttemptRevertConfigAsync(GetFunctionConfigurationResponse existingConfiguration) { try { var request = CreateRevertConfigurationRequest(existingConfiguration); await LambdaUtilities.WaitTillFunctionAvailableAsync(Logger, this.LambdaClient, request.FunctionName); this.Logger.WriteLine($"Reverting runtime configuration for function {this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true)}"); await this.LambdaClient.UpdateFunctionConfigurationAsync(request); } catch (Exception e) { this.Logger.WriteLine($"Error reverting configuration for Lambda function: {e.Message}"); } } protected async Task<bool> UpdateConfigAsync(GetFunctionConfigurationResponse existingConfiguration, string dotnetSharedStoreValue) { var configUpdated = false; var request = CreateConfigurationRequestIfDifferent(existingConfiguration, dotnetSharedStoreValue); if (request != null) { await LambdaUtilities.WaitTillFunctionAvailableAsync(Logger, this.LambdaClient, request.FunctionName); this.Logger.WriteLine($"Updating runtime configuration for function {this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true)}"); try { await this.LambdaClient.UpdateFunctionConfigurationAsync(request); configUpdated = true; } catch (Exception e) { throw new LambdaToolsException($"Error updating configuration for Lambda function: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaUpdateFunctionConfiguration, e); } } // only attempt to modify function url if the user has explicitly opted-in to use FunctionUrl if (GetBoolValueOrDefault(FunctionUrlEnable, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_ENABLE, false).HasValue) { var urlConfig = await this.GetFunctionUrlConfig(existingConfiguration.FunctionName); // To determine what is the state of the function url check to see if the user explicitly set a value. If they did set a value then use that // to either add or remove the url config. If the user didn't set a value check to see if there is an existing config to make sure we don't remove // the config url if the user didn't set a value. bool enableUrlConfig = this.GetBoolValueOrDefault(this.FunctionUrlEnable, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_ENABLE, false).HasValue ? this.GetBoolValueOrDefault(this.FunctionUrlEnable, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_ENABLE, false).Value : urlConfig != null; var authType = this.GetStringValueOrDefault(this.FunctionUrlAuthType, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_URL_AUTH, false); if (urlConfig != null) { this.FunctionUrlLink = urlConfig.FunctionUrl; } if (urlConfig != null && !enableUrlConfig) { await this.DeleteFunctionUrlConfig(existingConfiguration.FunctionName, urlConfig.AuthType); this.Logger.WriteLine("Removing function url config"); } else if(urlConfig == null && enableUrlConfig) { await this.CreateFunctionUrlConfig(existingConfiguration.FunctionName, authType); this.Logger.WriteLine($"Creating function url config: {this.FunctionUrlLink}"); } else if (urlConfig != null && enableUrlConfig && !string.Equals(authType, urlConfig.AuthType.Value, StringComparison.Ordinal)) { await this.UpdateFunctionUrlConfig(existingConfiguration.FunctionName, urlConfig.AuthType, authType); this.Logger.WriteLine($"Updating function url config: {this.FunctionUrlLink}"); } } return configUpdated; } public async Task<GetFunctionConfigurationResponse> GetFunctionConfigurationAsync() { var request = new GetFunctionConfigurationRequest { FunctionName = this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true) }; try { var response = await this.LambdaClient.GetFunctionConfigurationAsync(request); return response; } catch (ResourceNotFoundException) { return null; } catch(Exception e) { throw new LambdaToolsException($"Error retrieving configuration for function {request.FunctionName}: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaGetConfiguration, e); } } /// <summary> /// Create an UpdateFunctionConfigurationRequest for the current configuration to be used to revert a failed configuration update. /// </summary> /// <param name="existingConfiguration"></param> /// <returns><see cref="UpdateFunctionConfigurationRequest"/></returns> private UpdateFunctionConfigurationRequest CreateRevertConfigurationRequest(GetFunctionConfigurationResponse existingConfiguration) { var request = new UpdateFunctionConfigurationRequest { FunctionName = existingConfiguration.FunctionName, Description = existingConfiguration.Description, Role = existingConfiguration.Role, MemorySize = existingConfiguration.MemorySize, EphemeralStorage = existingConfiguration.EphemeralStorage, Timeout = existingConfiguration.Timeout, Layers = existingConfiguration.Layers?.Select(x => x.Arn).ToList(), DeadLetterConfig = existingConfiguration.DeadLetterConfig, KMSKeyArn = existingConfiguration.KMSKeyArn }; if (existingConfiguration.VpcConfig != null) { request.VpcConfig = new VpcConfig { IsSecurityGroupIdsSet = existingConfiguration.VpcConfig.SecurityGroupIds?.Any() ?? false, IsSubnetIdsSet = existingConfiguration.VpcConfig.SubnetIds?.Any() ?? false, SecurityGroupIds = existingConfiguration.VpcConfig.SecurityGroupIds, SubnetIds = existingConfiguration.VpcConfig.SubnetIds }; } if (existingConfiguration.TracingConfig != null) { request.TracingConfig = new TracingConfig { Mode = existingConfiguration.TracingConfig.Mode }; } if (existingConfiguration.Environment != null) { request.Environment = new Model.Environment { IsVariablesSet = existingConfiguration.Environment.Variables?.Any() ?? false, Variables = existingConfiguration.Environment.Variables }; } if (existingConfiguration.PackageType == Lambda.PackageType.Zip) { request.Handler = existingConfiguration.Handler; request.Runtime = existingConfiguration.Runtime; } else if (existingConfiguration.PackageType == Lambda.PackageType.Image) { if (existingConfiguration.ImageConfigResponse != null) { request.ImageConfig = new ImageConfig { Command = existingConfiguration.ImageConfigResponse.ImageConfig?.Command, EntryPoint = existingConfiguration.ImageConfigResponse.ImageConfig?.EntryPoint, IsCommandSet = existingConfiguration.ImageConfigResponse.ImageConfig?.Command?.Any() ?? false, IsEntryPointSet = existingConfiguration.ImageConfigResponse.ImageConfig?.EntryPoint?.Any() ?? false, WorkingDirectory = existingConfiguration.ImageConfigResponse.ImageConfig?.WorkingDirectory }; } } return request; } /// <summary> /// Create an UpdateFunctionConfigurationRequest if any fields have changed. Otherwise it returns back null causing the Update /// to skip. /// </summary> /// <param name="existingConfiguration"></param> /// <returns></returns> private UpdateFunctionConfigurationRequest CreateConfigurationRequestIfDifferent(GetFunctionConfigurationResponse existingConfiguration, string dotnetSharedStoreValue) { bool different = false; var request = new UpdateFunctionConfigurationRequest { FunctionName = this.GetStringValueOrDefault(this.FunctionName, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_NAME, true) }; var description = this.GetStringValueOrDefault(this.Description, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_DESCRIPTION, false); if (!string.IsNullOrEmpty(description) && !string.Equals(description, existingConfiguration.Description, StringComparison.Ordinal)) { request.Description = description; different = true; } var role = this.GetStringValueOrDefault(this.Role, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_ROLE, false); if (!string.IsNullOrEmpty(role)) { string fullRole; if (role.StartsWith(LambdaConstants.IAM_ARN_PREFIX)) fullRole = role; else fullRole = RoleHelper.ExpandRoleName(this.IAMClient, role); if (!string.Equals(fullRole, existingConfiguration.Role, StringComparison.Ordinal)) { request.Role = fullRole; different = true; } } var memorySize = this.GetIntValueOrDefault(this.MemorySize, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_MEMORY_SIZE, false); if(memorySize.HasValue && memorySize.Value != existingConfiguration.MemorySize) { request.MemorySize = memorySize.Value; different = true; } var ephemeralSize = this.GetIntValueOrDefault(this.EphemeralStorageSize, LambdaDefinedCommandOptions.ARGUMENT_EPHEMERAL_STORAGE_SIZE, false); if (ephemeralSize.HasValue && ephemeralSize.Value != existingConfiguration.EphemeralStorage?.Size) { request.EphemeralStorage = new EphemeralStorage { Size = ephemeralSize.Value }; } var timeout = this.GetIntValueOrDefault(this.Timeout, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_TIMEOUT, false); if (timeout.HasValue && timeout.Value != existingConfiguration.Timeout) { request.Timeout = timeout.Value; different = true; } var layerVersionArns = this.GetStringValuesOrDefault(this.LayerVersionArns, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_LAYERS, false); if(layerVersionArns != null && AreDifferent(layerVersionArns, existingConfiguration.Layers?.Select(x => x.Arn))) { request.Layers = layerVersionArns.ToList(); request.IsLayersSet = true; different = true; } var subnetIds = this.GetStringValuesOrDefault(this.SubnetIds, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SUBNETS, false); if (subnetIds != null) { if (request.VpcConfig == null) { request.VpcConfig = new VpcConfig(); } request.VpcConfig.SubnetIds = subnetIds.ToList(); request.VpcConfig.IsSubnetIdsSet = true; if (existingConfiguration.VpcConfig == null || AreDifferent(subnetIds, existingConfiguration.VpcConfig.SubnetIds)) { different = true; } } var securityGroupIds = this.GetStringValuesOrDefault(this.SecurityGroupIds, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_SECURITY_GROUPS, false); if (securityGroupIds != null) { if (request.VpcConfig == null) { request.VpcConfig = new VpcConfig(); } request.VpcConfig.SecurityGroupIds = securityGroupIds.ToList(); request.VpcConfig.IsSecurityGroupIdsSet = true; if (existingConfiguration.VpcConfig == null || AreDifferent(securityGroupIds, existingConfiguration.VpcConfig.SecurityGroupIds)) { different = true; } } var deadLetterTargetArn = this.GetStringValueOrDefault(this.DeadLetterTargetArn, LambdaDefinedCommandOptions.ARGUMENT_DEADLETTER_TARGET_ARN, false); if (deadLetterTargetArn != null) { if (!string.IsNullOrEmpty(deadLetterTargetArn) && !string.Equals(deadLetterTargetArn, existingConfiguration.DeadLetterConfig?.TargetArn, StringComparison.Ordinal)) { request.DeadLetterConfig = existingConfiguration.DeadLetterConfig ?? new DeadLetterConfig(); request.DeadLetterConfig.TargetArn = deadLetterTargetArn; different = true; } else if (string.IsNullOrEmpty(deadLetterTargetArn) && !string.IsNullOrEmpty(existingConfiguration.DeadLetterConfig?.TargetArn)) { request.DeadLetterConfig = null; request.DeadLetterConfig = existingConfiguration.DeadLetterConfig ?? new DeadLetterConfig(); request.DeadLetterConfig.TargetArn = string.Empty; different = true; } } var tracingMode = this.GetStringValueOrDefault(this.TracingMode, LambdaDefinedCommandOptions.ARGUMENT_TRACING_MODE, false); if (tracingMode != null) { var eTraceMode = !string.Equals(tracingMode, string.Empty) ? Amazon.Lambda.TracingMode.FindValue(tracingMode) : null; if (eTraceMode != existingConfiguration.TracingConfig?.Mode) { request.TracingConfig = new TracingConfig(); request.TracingConfig.Mode = eTraceMode; different = true; } } var kmsKeyArn = this.GetStringValueOrDefault(this.KMSKeyArn, LambdaDefinedCommandOptions.ARGUMENT_KMS_KEY_ARN, false); if (!string.IsNullOrEmpty(kmsKeyArn) && !string.Equals(kmsKeyArn, existingConfiguration.KMSKeyArn, StringComparison.Ordinal)) { request.KMSKeyArn = kmsKeyArn; different = true; } var environmentVariables = GetEnvironmentVariables(existingConfiguration?.Environment?.Variables); // If runtime package store layers were set, then set the environment variable to tell the .NET Core runtime // to look for assemblies in the folder where the layer will be expanded. if(!string.IsNullOrEmpty(dotnetSharedStoreValue)) { if(environmentVariables == null) { environmentVariables = new Dictionary<string, string>(); } environmentVariables[LambdaConstants.ENV_DOTNET_SHARED_STORE] = dotnetSharedStoreValue; } if (environmentVariables != null && AreDifferent(environmentVariables, existingConfiguration?.Environment?.Variables)) { request.Environment = new Model.Environment { Variables = environmentVariables }; request.Environment.IsVariablesSet = true; different = true; } if (existingConfiguration.PackageType == Lambda.PackageType.Zip) { var handler = this.GetStringValueOrDefault(this.Handler, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_HANDLER, false); if (!string.IsNullOrEmpty(handler) && !string.Equals(handler, existingConfiguration.Handler, StringComparison.Ordinal)) { request.Handler = handler; different = true; } var runtime = this.GetStringValueOrDefault(this.Runtime, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_RUNTIME, false); if (runtime != null && runtime != existingConfiguration.Runtime) { request.Runtime = runtime; different = true; } } else if (existingConfiguration.PackageType == Lambda.PackageType.Image) { { var imageEntryPoints = this.GetStringValuesOrDefault(this.ImageEntryPoint, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_ENTRYPOINT, false); if (imageEntryPoints != null) { if (AreDifferent(imageEntryPoints, existingConfiguration.ImageConfigResponse?.ImageConfig?.EntryPoint)) { if (request.ImageConfig == null) { request.ImageConfig = new ImageConfig(); } request.ImageConfig.EntryPoint = imageEntryPoints.ToList(); request.ImageConfig.IsEntryPointSet = true; different = true; } } } { var imageCommands = this.GetStringValuesOrDefault(this.ImageCommand, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_COMMAND, false); if (imageCommands != null) { if (AreDifferent(imageCommands, existingConfiguration.ImageConfigResponse?.ImageConfig?.Command)) { if (request.ImageConfig == null) { request.ImageConfig = new ImageConfig(); } request.ImageConfig.Command = imageCommands.ToList(); request.ImageConfig.IsCommandSet = true; different = true; } } } var imageWorkingDirectory = this.GetStringValueOrDefault(this.ImageWorkingDirectory, LambdaDefinedCommandOptions.ARGUMENT_IMAGE_WORKING_DIRECTORY, false); if (imageWorkingDirectory != null) { if (request.ImageConfig == null) { request.ImageConfig = new ImageConfig(); } if(!string.Equals(imageWorkingDirectory, existingConfiguration.ImageConfigResponse?.ImageConfig?.WorkingDirectory, StringComparison.Ordinal)) { request.ImageConfig.WorkingDirectory = imageWorkingDirectory; different = true; } } } if (!different) return null; return request; } public Dictionary<string, string> GetEnvironmentVariables(Dictionary<string, string> existingEnvironmentVariables) { var specifiedEnvironmentVariables = this.GetKeyValuePairOrDefault(this.EnvironmentVariables, LambdaDefinedCommandOptions.ARGUMENT_ENVIRONMENT_VARIABLES, false); var appendEnvironmentVariables = this.GetKeyValuePairOrDefault(this.AppendEnvironmentVariables, LambdaDefinedCommandOptions.ARGUMENT_APPEND_ENVIRONMENT_VARIABLES, false); if (appendEnvironmentVariables == null) { return specifiedEnvironmentVariables; } var combineSet = specifiedEnvironmentVariables ?? existingEnvironmentVariables; if (combineSet == null) { combineSet = appendEnvironmentVariables; } else { foreach (var kvp in appendEnvironmentVariables) { combineSet[kvp.Key] = kvp.Value; } } return combineSet; } private bool AreDifferent(IDictionary<string, string> source, IDictionary<string, string> target) { if (target == null) target = new Dictionary<string, string>(); if (source.Count != target.Count) return true; foreach(var kvp in source) { string value; if (!target.TryGetValue(kvp.Key, out value)) return true; if (!string.Equals(kvp.Value, value, StringComparison.Ordinal)) return true; } foreach (var kvp in target) { string value; if (!source.TryGetValue(kvp.Key, out value)) return true; if (!string.Equals(kvp.Value, value, StringComparison.Ordinal)) return true; } return false; } private bool AreDifferent(IEnumerable<string> source, IEnumerable<string> target) { if (source == null && target == null) return false; if(source?.Count() != target?.Count()) return true; foreach(var item in source) { if (!target.Contains(item)) return true; } foreach (var item in target) { if (!source.Contains(item)) return true; } return false; } protected async Task<GetFunctionUrlConfigResponse> GetFunctionUrlConfig(string functionName) { var request = new GetFunctionUrlConfigRequest { FunctionName = functionName }; try { var response = await this.LambdaClient.GetFunctionUrlConfigAsync(request); return response; } catch (ResourceNotFoundException) { return null; } catch (Exception e) { throw new LambdaToolsException($"Error creating function url config for function {request.FunctionName}: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaFunctionUrlGet, e); } } protected async Task CreateFunctionUrlConfig(string functionName, FunctionUrlAuthType authType) { if (authType == null) authType = Amazon.Lambda.FunctionUrlAuthType.NONE; var request = new CreateFunctionUrlConfigRequest { FunctionName = functionName, AuthType = authType }; try { this.FunctionUrlLink = (await this.LambdaClient.CreateFunctionUrlConfigAsync(request)).FunctionUrl; if(authType == Amazon.Lambda.FunctionUrlAuthType.NONE) { await AddFunctionUrlPublicPermissionStatement(functionName); } } catch (Exception e) { throw new LambdaToolsException($"Error creating function url config for function {request.FunctionName}: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaFunctionUrlCreate, e); } } protected async Task UpdateFunctionUrlConfig(string functionName, FunctionUrlAuthType oldAuthType, FunctionUrlAuthType newAuthType) { if (newAuthType == null) newAuthType = Amazon.Lambda.FunctionUrlAuthType.NONE; var request = new UpdateFunctionUrlConfigRequest { FunctionName = functionName, AuthType = newAuthType }; try { this.FunctionUrlLink = (await this.LambdaClient.UpdateFunctionUrlConfigAsync(request)).FunctionUrl; if(oldAuthType != newAuthType) { if(newAuthType == Amazon.Lambda.FunctionUrlAuthType.NONE) { await AddFunctionUrlPublicPermissionStatement(functionName); } else { await RemoveFunctionUrlPublicPermissionStatement(functionName); } } } catch (Exception e) { throw new LambdaToolsException($"Error updating function url config for function {request.FunctionName}: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaFunctionUrlUpdate, e); } } protected async Task DeleteFunctionUrlConfig(string functionName, FunctionUrlAuthType oldAuthType) { var request = new DeleteFunctionUrlConfigRequest { FunctionName = functionName }; try { await this.LambdaClient.DeleteFunctionUrlConfigAsync(request); if (oldAuthType == Lambda.FunctionUrlAuthType.NONE) { await RemoveFunctionUrlPublicPermissionStatement(functionName); } this.FunctionUrlLink = null; } catch (Exception e) { throw new LambdaToolsException($"Error deleting function url config for function {request.FunctionName}: {e.Message}", LambdaToolsException.LambdaErrorCode.LambdaFunctionUrlDelete, e); } } private async Task AddFunctionUrlPublicPermissionStatement(string functionName) { var request = new AddPermissionRequest { StatementId = LambdaConstants.FUNCTION_URL_PUBLIC_PERMISSION_STATEMENT_ID, FunctionName = functionName, Principal = "*", Action = "lambda:InvokeFunctionUrl", FunctionUrlAuthType = Amazon.Lambda.FunctionUrlAuthType.NONE }; try { this.Logger.WriteLine("Adding Lambda permission statement to public access for Function Url"); await LambdaClient.AddPermissionAsync(request); } catch(Amazon.Lambda.Model.ResourceConflictException) { this.Logger.WriteLine($"Lambda permission with statement id {LambdaConstants.FUNCTION_URL_PUBLIC_PERMISSION_STATEMENT_ID} for public access already exists"); } } private async Task RemoveFunctionUrlPublicPermissionStatement(string functionName) { var request = new RemovePermissionRequest { FunctionName = functionName, StatementId = LambdaConstants.FUNCTION_URL_PUBLIC_PERMISSION_STATEMENT_ID }; try { this.Logger.WriteLine("Removing Lambda permission statement to allow public access for Function Url"); await LambdaClient.RemovePermissionAsync(request); } catch(Amazon.Lambda.Model.ResourceNotFoundException) { this.Logger.WriteLine($"Lambda permission with statement id {LambdaConstants.FUNCTION_URL_PUBLIC_PERMISSION_STATEMENT_ID} for public access not found to be removed"); } } protected override void SaveConfigFile(JsonData data) { } } }
860
aws-extensions-for-dotnet-cli
aws
C#
namespace Amazon.Lambda.Tools.TemplateProcessor { /// <summary> /// Properties to use when building the current project which might have come from the command line. /// </summary> public class DefaultLocationOption { /// <summary> /// Build Configuration e.g. Release /// </summary> /// public string Configuration { get; set; } /// <summary> /// .NET Target Framework e.g. netcoreapp3.1 /// </summary> public string TargetFramework { get; set; } /// <summary> /// Additional parameters to pass when invoking dotnet publish /// </summary> public string MSBuildParameters { get; set; } /// <summary> /// If true disables checking for correct version of Microsoft.AspNetCore.App. /// </summary> public bool DisableVersionCheck { get; set; } /// <summary> /// If the current project is already built pass in the current compiled package zip file. /// </summary> public string Package { get; set; } } }
33
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using Amazon.Lambda.Tools.Commands; using ThirdParty.Json.LitJson; using YamlDotNet.RepresentationModel; namespace Amazon.Lambda.Tools.TemplateProcessor { public enum CodeUploadType { Zip, Image} /// <summary> /// Interface to iterate over the CloudFormation resources that can be updated. /// </summary> public interface ITemplateParser { /// <summary> /// Iterator for the updatable resources. /// </summary> /// <returns></returns> IEnumerable<IUpdatableResource> UpdatableResources(); /// <summary> /// Get the new template after the resources have been updated. /// </summary> /// <returns></returns> string GetUpdatedTemplate(); } /// <summary> /// Interface for a CloudFormation resource that can be updated. /// </summary> public interface IUpdatableResource { /// <summary> /// The CloudFormation name of the resource. /// </summary> string Name { get; } /// <summary> /// The CloudFormation resource type. /// </summary> string ResourceType { get; } /// <summary> /// If the resource is a AWS::Lambda::Function or AWS::Serverless::Function get the Lambda runtime for it. /// </summary> string LambdaRuntime { get; } /// <summary> /// If the resource is a AWS::Lambda::Function or AWS::Serverless::Function get the Lambda architecture for it. /// </summary> string LambdaArchitecture { get; } /// <summary> /// Gets the list of layers specified if this is a Lambda function. /// </summary> /// <returns></returns> string[] LambdaLayers { get; } /// <summary> /// The list of fields that can be updated. /// </summary> IList<IUpdateResourceField> Fields { get; } /// <summary> /// Sets an environment variable for the resource. /// </summary> /// <param name="key"></param> /// <param name="value"></param> void SetEnvironmentVariable(string key, string value); /// <summary> /// Indicates whether the code should be uploaded to S3 as a zip or built as an image and pushed to ECR. /// </summary> CodeUploadType UploadType { get; } } /// <summary> /// Interface for the field in the IUpdatableResource that can be updated. /// </summary> public interface IUpdateResourceField { /// <summary> /// Gets the name of the field. /// </summary> string Name { get; } /// <summary> /// True if the field should contain code like a Lambda package bundle. /// </summary> bool IsCode { get; } /// <summary> /// True if the field points to an Image already pushed in ECR. /// </summary> bool IsImagePushed { get; } /// <summary> /// Reference back to the containing updatable resource. /// </summary> IUpdatableResource Resource { get; } /// <summary> /// Gets the local path for the resource. If the value is referencing an object in S3 then this returns null. /// </summary> /// <returns></returns> string GetLocalPath(); /// <summary> /// Updates the location the field is pointing to where the local path was uploaded to S3. /// </summary> /// <param name="s3Bucket"></param> /// <param name="s3Key"></param> void SetS3Location(string s3Bucket, string s3Key); /// <summary> /// Sets the image uri on the resource. /// </summary> /// <param name="imageUri"></param> void SetImageUri(string imageUri); /// <summary> /// Gets the name of the Dockerfile specified for an AWS::Serverless::Function /// </summary> /// <returns></returns> string GetMetadataDockerfile(); /// <summary> /// Gets the Docker image tag specified for an AWS::Serverless::Function /// </summary> /// <returns></returns> string GetMetadataDockerTag(); /// <summary> /// Gets the Docker build args specified for an AWS::Serverless::Function /// </summary> /// <returns></returns> Dictionary<string, string> GetMetadataDockerBuildArgs(); } /// <summary> /// Interface for the underlying datasource (JSON or YAML), /// </summary> public interface IUpdatableResourceDataSource { /// <summary> /// Gets value starting from the root document. /// </summary> /// <param name="keyPath"></param> /// <returns></returns> string GetValueFromRoot(params string[] keyPath); /// <summary> /// Gets the values for a list starting from the root document. /// </summary> /// <param name="keyPath"></param> /// <returns></returns> string[] GetValueListFromRoot(params string[] keyPath); /// <summary> /// Gets the value starting from the resource node. /// </summary> /// <param name="keyPath"></param> /// <returns></returns> string GetValueFromResource(params string[] keyPath); /// <summary> /// Gets value in datasource. /// </summary> /// <param name="keyPath"></param> /// <returns></returns> string GetValue(params string[] keyPath); /// <summary> /// Set value in datasource. /// </summary> /// <param name="value"></param> /// <param name="keyPath"></param> void SetValue(string value, params string[] keyPath); /// <summary> /// Gets the values for a list property. /// </summary> /// <param name="keyPath"></param> /// <returns></returns> string[] GetValueList(params string[] keyPath); Dictionary<string, string> GetValueDictionaryFromResource(params string[] keyPath); } }
194
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; using ThirdParty.Json.LitJson; namespace Amazon.Lambda.Tools.TemplateProcessor { /// <summary> /// JSON implementation of ITemplateParser /// </summary> public class JsonTemplateParser : ITemplateParser { JsonData Root { get; } public JsonTemplateParser(string templateBody) { try { this.Root = JsonMapper.ToObject(templateBody); } catch (Exception e) { throw new LambdaToolsException($"Error parsing CloudFormation template: {e.Message}", LambdaToolsException.LambdaErrorCode.ServerlessTemplateParseError, e); } } public string GetUpdatedTemplate() { var json = JsonMapper.ToJson(this.Root); return json; } public IEnumerable<IUpdatableResource> UpdatableResources() { var resources = this.Root["Resources"]; if (resources == null) throw new LambdaToolsException("CloudFormation template does not define any AWS resources", LambdaToolsException.LambdaErrorCode.ServerlessTemplateMissingResourceSection); foreach (var field in resources.PropertyNames) { var resource = resources[field]; if (resource == null) continue; var properties = resource["Properties"]; if (properties == null) continue; var type = resource["Type"]?.ToString(); UpdatableResourceDefinition updatableResourceDefinition; if (!UpdatableResourceDefinition.ValidUpdatableResourceDefinitions.TryGetValue(type, out updatableResourceDefinition)) continue; var updatableResource = new UpdatableResource(field, updatableResourceDefinition, new JsonUpdatableResourceDataSource(this.Root, resource, properties)); yield return updatableResource; } } /// <summary> /// The JSON implementation of IUpdatableResourceDataSource /// </summary> public class JsonUpdatableResourceDataSource : IUpdatableResourceDataSource { JsonData Root { get; } JsonData Resource { get; } JsonData Properties { get; } public JsonUpdatableResourceDataSource(JsonData root, JsonData resource, JsonData properties) { this.Root = root; this.Resource = resource; this.Properties = properties; } public string GetValueFromRoot(params string[] keyPath) { return GetValue(this.Root, keyPath); } public string[] GetValueListFromRoot(params string[] keyPath) { return GetValueList(this.Root, keyPath); } public string GetValueFromResource(params string[] keyPath) { return GetValue(this.Resource, keyPath); } public string GetValue(params string[] keyPath) { return GetValue(this.Properties, keyPath); } private static string GetValue(JsonData node, params string[] keyPath) { foreach (var key in keyPath) { if (node == null) return null; node = node[key]; } return node?.ToString(); } public string[] GetValueList(params string[] keyPath) { return GetValueList(this.Properties, keyPath); } public Dictionary<string, string> GetValueDictionaryFromResource(params string[] keyPath) { return GetValueDictionaryFromResource(this.Resource, keyPath); } private static string[] GetValueList(JsonData node, params string[] keyPath) { foreach (var key in keyPath) { if (node == null) return null; node = node[key]; } if (node == null || !node.IsArray || node.Count == 0) return null; var values = new string[node.Count]; for (var i = 0; i < values.Length; i++) { values[i] = node[i]?.ToString(); } return values; } public void SetValue(string value, params string[] keyPath) { JsonData node = Properties; for (int i = 0; i < keyPath.Length - 1; i++) { var childNode = node[keyPath[i]]; if (childNode == null) { childNode = new JsonData(); node[keyPath[i]] = childNode; } node = childNode; } node[keyPath[keyPath.Length - 1]] = value; } private static Dictionary<string, string> GetValueDictionaryFromResource(JsonData node, params string[] keyPath) { foreach (var key in keyPath) { if (node == null) return null; node = node[key]; } if (node == null || !node.IsObject || node.Count == 0) return null; var dictionary = new Dictionary<string, string>(node.Count); foreach (string key in node.PropertyNames) { if (dictionary.ContainsKey(key)) { dictionary[key] = node[key]?.ToString(); } else { dictionary.Add(key, node[key]?.ToString()); } } return dictionary; } } } }
188
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Commands; using Amazon.Runtime; using Amazon.S3; using Amazon.S3.Transfer; using Newtonsoft.Json.Schema; using Amazon.Lambda.Tools.Commands; using Amazon.Common.DotNetCli.Tools.Options; namespace Amazon.Lambda.Tools.TemplateProcessor { /// <summary> /// This class is the entry point to traversing a CloudFormation template and looking for any resources that are pointing to local /// paths. Those local paths are uploaded to S3 and the template is updated with the location in S3. Once this is complete this /// template can be deployed to CloudFormation to create or update a stack. /// </summary> public class TemplateProcessorManager { IToolLogger Logger { get; } IAmazonS3 S3Client { get; } /// <summary> /// The S3 bucket used to store all local paths in S3. /// </summary> string S3Bucket { get; } /// <summary> /// Prefix for any S3 objects uploaded to S3. /// </summary> string S3Prefix { get; } /// <summary> /// The command that initiated the template processor /// </summary> public LambdaBaseCommand OriginatingCommand { get; } /// <summary> /// Options to use when a local path is pointing to the current directory. This is needed to maintain backwards compatibility /// with the original version of the deploy-serverless and package-ci commands. /// </summary> DefaultLocationOption DefaultOptions { get; } public TemplateProcessorManager(LambdaBaseCommand originatingCommand, string s3Bucket, string s3Prefix, DefaultLocationOption defaultOptions) { this.OriginatingCommand = originatingCommand; this.Logger = originatingCommand.Logger; this.S3Client = originatingCommand.S3Client; this.S3Bucket = s3Bucket; this.S3Prefix = s3Prefix; this.DefaultOptions = defaultOptions; } /// <summary> /// Transforms the provided template by uploading to S3 any local resources the template is pointing to, /// like .NET projects for a Lambda project, and then updating the CloudFormation resources to point to the /// S3 locations. /// </summary> /// <param name="templateDirectory">The directory where the template was found.</param> /// <param name="templateBody">The template to search for updatable resources. The file isn't just read from /// templateDirectory because template substitutions might have occurred before this was executed.</param> /// <returns></returns> public async Task<string> TransformTemplateAsync(string templateDirectory, string templateBody, string[] args) { // Remove Project Location switch from arguments list since this should not be used for code base. string[] modifiedArguments = RemoveProjectLocationArgument(args); // If templateDirectory is actually pointing the CloudFormation template then grab its root. if (File.Exists(templateDirectory)) templateDirectory = Path.GetDirectoryName(templateDirectory); // Maintain a cache of local paths to S3 Keys so if the same local path is referred to for // multiple Lambda functions it is only built and uploaded once. var cacheOfLocalPathsToS3Keys = new Dictionary<string, UpdateResourceResults>(); var parser = CreateTemplateParser(templateBody); foreach(var updatableResource in parser.UpdatableResources()) { this.Logger?.WriteLine($"Processing CloudFormation resource {updatableResource.Name}"); foreach (var field in updatableResource.Fields) { var localPath = field.GetLocalPath(); if (localPath == null) continue; UpdateResourceResults updateResults; if (!cacheOfLocalPathsToS3Keys.TryGetValue(localPath, out updateResults)) { this.Logger?.WriteLine( $"Initiate packaging of {field.GetLocalPath()} for resource {updatableResource.Name}"); updateResults = await ProcessUpdatableResourceAsync(templateDirectory, field, modifiedArguments); cacheOfLocalPathsToS3Keys[localPath] = updateResults; } else { this.Logger?.WriteLine( $"Using previous upload artifact s3://{this.S3Bucket}/{updateResults.S3Key} for resource {updatableResource.Name}"); } if(updatableResource.UploadType == CodeUploadType.Zip) { field.SetS3Location(this.S3Bucket, updateResults.S3Key); } else if(updatableResource.UploadType == CodeUploadType.Image) { field.SetImageUri(updateResults.ImageUri); } else { throw new LambdaToolsException($"Unknown upload type for setting resource: {updatableResource.UploadType}", LambdaToolsException.LambdaErrorCode.ServerlessTemplateParseError); } if (!string.IsNullOrEmpty(updateResults.DotnetShareStoreEnv)) { field.Resource.SetEnvironmentVariable(LambdaConstants.ENV_DOTNET_SHARED_STORE, updateResults.DotnetShareStoreEnv); } } } var newTemplate = parser.GetUpdatedTemplate(); return newTemplate; } /// <summary> /// Determine the action to be done for the local path, like building a .NET Core package, then uploading the /// package to S3. The S3 key is returned to be updated in the template. /// </summary> /// <param name="templateDirectory"></param> /// <param name="field"></param> /// <returns></returns> /// <exception cref="LambdaToolsException"></exception> private async Task<UpdateResourceResults> ProcessUpdatableResourceAsync(string templateDirectory, IUpdateResourceField field, string[] args) { UpdateResourceResults results; var localPath = field.GetLocalPath(); if (!field.IsImagePushed && !Path.IsPathRooted(localPath)) localPath = Path.Combine(templateDirectory, localPath); bool deleteArchiveAfterUploaded = false; // If ImageUri needs to be processed. if (field.IsImagePushed) { results = new UpdateResourceResults { ImageUri = localPath }; } // Uploading a single file as the code for the resource. If the single file is not a zip file then zip the file first. else if (File.Exists(localPath)) { if(field.IsCode && !string.Equals(Path.GetExtension(localPath), ".zip", StringComparison.OrdinalIgnoreCase)) { this.Logger.WriteLine($"Creating zip archive for {localPath} file"); results = new UpdateResourceResults { ZipArchivePath = GenerateOutputZipFilename(field) }; LambdaPackager.BundleFiles(results.ZipArchivePath, Path.GetDirectoryName(localPath), new string[] { localPath }, this.Logger); } else { results = new UpdateResourceResults { ZipArchivePath = localPath }; } } // If IsCode is false then the local path needs to point to a file and not a directory. When IsCode is true // it can point either to a file or a directory. else if (!field.IsCode && !File.Exists(localPath)) { throw new LambdaToolsException($"File that the field {field.Resource.Name}/{field.Name} is pointing to doesn't exist", LambdaToolsException.LambdaErrorCode.ServerlessTemplateMissingLocalPath); } else if (!Directory.Exists(localPath)) { throw new LambdaToolsException($"Directory that the field {field.Resource.Name}/{field.Name} is pointing doesn't exist", LambdaToolsException.LambdaErrorCode.ServerlessTemplateMissingLocalPath); } // To maintain compatibility if the field is point to current directory or not set at all but a prepackaged zip archive is given // then use it as the package source. else if (IsCurrentDirectory(field.GetLocalPath()) && !string.IsNullOrEmpty(this.DefaultOptions.Package)) { results = new UpdateResourceResults { ZipArchivePath = this.DefaultOptions.Package }; } else if(field.IsCode) { // If the function is image upload then run the .NET tools to handle running // docker build even if the current folder is not a .NET project. The .NET // could be in a sub folder or be a self contained Docker build. if (IsDotnetProjectDirectory(localPath) || field.Resource.UploadType == CodeUploadType.Image) { results = await PackageDotnetProjectAsync(field, localPath, args); } else { results = new UpdateResourceResults { ZipArchivePath = GenerateOutputZipFilename(field) }; LambdaPackager.BundleDirectory(results.ZipArchivePath, localPath, false, this.Logger); } deleteArchiveAfterUploaded = true; } else { throw new LambdaToolsException($"Unable to determine package action for the field {field.Resource.Name}/{field.Name}", LambdaToolsException.LambdaErrorCode.ServerlessTemplateUnknownActionForLocalPath); } if(!string.IsNullOrEmpty(results.ZipArchivePath)) { string s3Key; using (var stream = File.OpenRead(results.ZipArchivePath)) { s3Key = await Utilities.UploadToS3Async(this.Logger, this.S3Client, this.S3Bucket, this.S3Prefix, Path.GetFileName(results.ZipArchivePath), stream); results.S3Key = s3Key; } // Now that the temp zip file is uploaded to S3 clean up by deleting the temp file. if (deleteArchiveAfterUploaded) { try { File.Delete(results.ZipArchivePath); } catch (Exception e) { this.Logger?.WriteLine($"Warning: Unable to delete temporary archive, {results.ZipArchivePath}, after uploading to S3: {e.Message}"); } } } return results; } /// <summary> /// Executes the package command to create the deployment bundle for the .NET project and returns the path. /// </summary> /// <param name="field"></param> /// <param name="location"></param> /// <returns></returns> /// <exception cref="LambdaToolsException"></exception> private async Task<UpdateResourceResults> PackageDotnetProjectAsync(IUpdateResourceField field, string location, string[] args) { if (field.Resource.UploadType == CodeUploadType.Zip) { var command = new Commands.PackageCommand(this.Logger, location, args); command.LambdaClient = this.OriginatingCommand?.LambdaClient; command.S3Client = this.OriginatingCommand?.S3Client; command.IAMClient = this.OriginatingCommand?.IAMClient; command.CloudFormationClient = this.OriginatingCommand?.CloudFormationClient; command.DisableRegionAndCredentialsCheck = true; var outputPackage = GenerateOutputZipFilename(field); command.OutputPackageFileName = outputPackage; command.TargetFramework = LambdaUtilities.DetermineTargetFrameworkFromLambdaRuntime(field.Resource.LambdaRuntime, location); command.Architecture = field.Resource.LambdaArchitecture; command.LayerVersionArns = field.Resource.LambdaLayers; // If the project is in the same directory as the CloudFormation template then use any parameters // that were specified on the command to build the project. if (IsCurrentDirectory(field.GetLocalPath())) { if (!string.IsNullOrEmpty(this.DefaultOptions.TargetFramework)) command.TargetFramework = this.DefaultOptions.TargetFramework; command.Configuration = this.DefaultOptions.Configuration; command.DisableVersionCheck = this.DefaultOptions.DisableVersionCheck; command.MSBuildParameters = this.DefaultOptions.MSBuildParameters; } if (!await command.ExecuteAsync()) { var message = $"Error packaging up project in {location} for CloudFormation resource {field.Resource.Name}"; if (command.LastToolsException != null) message += $": {command.LastToolsException.Message}"; throw new LambdaToolsException(message, ToolsException.CommonErrorCode.DotnetPublishFailed, command.LastToolsException); } var results = new UpdateResourceResults() { ZipArchivePath = outputPackage }; if (!string.IsNullOrEmpty(command.NewDotnetSharedStoreValue)) { results.DotnetShareStoreEnv = command.NewDotnetSharedStoreValue; } return results; } else if (field.Resource.UploadType == CodeUploadType.Image) { this.Logger.WriteLine($"Building Docker image for {location}"); var pushCommand = new PushDockerImageCommand(Logger, location, args); pushCommand.ECRClient = OriginatingCommand.ECRClient; pushCommand.IAMClient = OriginatingCommand.IAMClient; pushCommand.DisableInteractive = true; pushCommand.PushDockerImageProperties.DockerFile = field.GetMetadataDockerfile(); pushCommand.PushDockerImageProperties.DockerImageTag = field.GetMetadataDockerTag(); pushCommand.ImageTagUniqueSeed = field.Resource.Name; // Refer https://docs.docker.com/engine/reference/commandline/build/#set-build-time-variables---build-arg Dictionary<string, string> dockerBuildArgs = field.GetMetadataDockerBuildArgs(); if (dockerBuildArgs != null && dockerBuildArgs.Count > 0) { StringBuilder buildArgs = new StringBuilder(); foreach (var keyValuePair in dockerBuildArgs) { if (keyValuePair.Value != null) { buildArgs.Append($"--build-arg {keyValuePair.Key}={keyValuePair.Value} "); } else { // --build-arg flag could be used without a value, in which case the value from the local environment will be propagated into the Docker container. buildArgs.Append($"--build-arg {keyValuePair.Key} "); } } pushCommand.PushDockerImageProperties.DockerBuildOptions = buildArgs.ToString().TrimEnd(); } await pushCommand.PushImageAsync(); if (pushCommand.LastToolsException != null) throw pushCommand.LastToolsException; return new UpdateResourceResults { ImageUri = pushCommand.PushedImageUri }; } else { throw new LambdaToolsException($"Unknown upload type for packaging: {field.Resource.UploadType}", LambdaToolsException.LambdaErrorCode.ServerlessTemplateParseError); } } private string[] RemoveProjectLocationArgument(string[] args) { List<string> argumentList; if (args == null || args.Length == 0) return args; argumentList = new List<string>(); for (int counter = 0; counter < args.Length; counter++) { // Skip project location switch and it's value. if (string.Equals(args[counter], CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION.ShortSwitch, StringComparison.OrdinalIgnoreCase) || string.Equals(args[counter], CommonDefinedCommandOptions.ARGUMENT_PROJECT_LOCATION.Switch, StringComparison.OrdinalIgnoreCase)) { counter += 1; } else { argumentList.Add(args[counter]); } } return argumentList.ToArray(); } private static string GenerateOutputZipFilename(IUpdateResourceField field) { var outputPackage = Path.Combine(Path.GetTempPath(), $"{field.Resource.Name}-{field.Name}-{DateTime.Now.Ticks}.zip"); return outputPackage; } /// <summary> /// Check to see if the directory contains a .NET project file. /// </summary> /// <param name="localPath"></param> /// <returns></returns> private bool IsDotnetProjectDirectory(string localPath) { if (!Directory.Exists(localPath)) return false; var projectFiles = Directory.GetFiles(localPath, "*.??proj", SearchOption.TopDirectoryOnly) .Where(x => LambdaUtilities.ValidProjectExtensions.Contains(Path.GetExtension(x))).ToArray(); return projectFiles.Length == 1; } private bool IsCurrentDirectory(string localPath) { if (string.IsNullOrEmpty(localPath)) return true; if (string.Equals(".", localPath)) return true; if (string.Equals("./", localPath)) return true; if (string.Equals(@".\", localPath)) return true; return false; } /// <summary> /// Create the appropriate parser depending whether the template is JSON or YAML. /// </summary> /// <param name="templateBody"></param> /// <returns></returns> /// <exception cref="LambdaToolsException"></exception> public static ITemplateParser CreateTemplateParser(string templateBody) { switch (LambdaUtilities.DetermineTemplateFormat(templateBody)) { case TemplateFormat.Json: return new JsonTemplateParser(templateBody); case TemplateFormat.Yaml: return new YamlTemplateParser(templateBody); default: throw new LambdaToolsException("Unable to determine template file format", LambdaToolsException.LambdaErrorCode.ServerlessTemplateParseError); } } class UpdateResourceResults { public string ZipArchivePath { get; set; } public string S3Key { get; set; } public string DotnetShareStoreEnv { get; set; } public string ImageUri { get; set; } } } }
421
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; using System.Threading; namespace Amazon.Lambda.Tools.TemplateProcessor { /// <summary> /// The updatable resource like a CloudFormation AWS::Lambda::Function. This class combines the UpdatableResourceDefinition /// which identifies the fields that can be updated and IUpdatableResourceDataSource which abstracts the JSON or YAML definition. /// </summary> public class UpdatableResource : IUpdatableResource { public string Name { get; } public string ResourceType { get; } public IList<IUpdateResourceField> Fields { get; } UpdatableResourceDefinition Definition { get; } IUpdatableResourceDataSource DataSource { get; } public UpdatableResource(string name, UpdatableResourceDefinition definition, IUpdatableResourceDataSource dataSource) { this.Name = name; this.Definition = definition; this.DataSource = dataSource; this.Fields = new List<IUpdateResourceField>(); foreach (var fieldDefinition in definition.Fields) { this.Fields.Add(new UpdatableResourceField(this, fieldDefinition, dataSource)); } } public string LambdaRuntime { get { var runtime = this.DataSource.GetValue("Runtime"); if(string.IsNullOrEmpty(runtime)) { runtime = this.DataSource.GetValueFromRoot("Globals", "Function", "Runtime"); } return runtime; } } public string LambdaArchitecture { get { var architectures = this.DataSource.GetValueList("Architectures"); if(architectures == null || architectures.Length == 0) { architectures = this.DataSource.GetValueListFromRoot("Globals", "Function", "Architectures"); } if(architectures == null || architectures.Length == 0) { return LambdaConstants.ARCHITECTURE_X86_64; } else if(architectures.Length == 1) { return architectures[0]; } else { throw new LambdaToolsException("More then one architecture was specified. .NET Lambda functions only support a single architecture value for creating a deployment bundle for the specific architecture.", Common.DotNetCli.Tools.ToolsException.CommonErrorCode.InvalidParameterValue); } } } public string[] LambdaLayers { get { var layers = new List<string>(); var resourceLayers = this.DataSource.GetValueList("Layers"); if (resourceLayers != null) { layers.AddRange(resourceLayers); } var globalLayers = this.DataSource.GetValueListFromRoot("Globals", "Function", "Layers"); if (globalLayers != null) { layers.AddRange(globalLayers); } return layers.Count == 0 ? null : layers.ToArray(); } } public CodeUploadType UploadType { get { var packageType = this.DataSource.GetValue("PackageType"); if (string.Equals("image", packageType, StringComparison.OrdinalIgnoreCase)) { return CodeUploadType.Image; } return CodeUploadType.Zip; } } public void SetEnvironmentVariable(string key, string value) { this.DataSource.SetValue(value, "Environment", "Variables", key); } public class UpdatableResourceField : IUpdateResourceField { public IUpdatableResource Resource => this._resource; public UpdatableResource _resource; private UpdatableResourceDefinition.FieldDefinition Field { get; } private IUpdatableResourceDataSource DataSource; public UpdatableResourceField(UpdatableResource resource, UpdatableResourceDefinition.FieldDefinition field, IUpdatableResourceDataSource dataSource) { this._resource = resource; this.Field = field; this.DataSource = dataSource; } public string Name => this.Field.Name; public bool IsCode { get { if (!this.Field.IsCode) { return false; } if (!string.IsNullOrEmpty(this._resource.DataSource.GetValue("Code", "ZipFile"))) { // The template contains embedded code. return false; } else { string localPath = this._resource.DataSource.GetValueFromResource(LambdaConstants.CF_SERVERLESS_METADATA, LambdaConstants.CF_SERVERLESS_DOCKERCONTEXT); // Pointing to already pushed image, no package needs to be done. if (IsECRImage(localPath)) { return false; } // Metadata points to local path that needs to be packaged up return true for code. else if (!string.IsNullOrEmpty(localPath)) { return true; } // If no Docker Metadata was set fallback to looking for a local path in the resource's ImageUri property. localPath = this._resource.DataSource.GetValue(LambdaConstants.CF_LAMBDA_IMAGEURI); // Pointing to already pushed image, no package needs to be done. if (IsECRImage(localPath)) { return false; } return true; } } } public bool IsImagePushed { get { string localPath = this._resource.DataSource.GetValueFromResource(LambdaConstants.CF_SERVERLESS_METADATA, LambdaConstants.CF_SERVERLESS_DOCKERCONTEXT); // Pointing to already pushed image, no package needs to be done. if (IsECRImage(localPath)) { return true; } // Metadata points to local path that needs to be packaged up return true for code. else if (!string.IsNullOrEmpty(localPath)) { return false; } // If no Docker Metadata was set fallback to looking for a local path in the resource's ImageUri property. localPath = this._resource.DataSource.GetValue(LambdaConstants.CF_LAMBDA_IMAGEURI); // Pointing to already pushed image, no package needs to be done. if (IsECRImage(localPath)) { return true; } return false; } } public string GetLocalPath() { return this.Field.GetLocalPath(this._resource.DataSource); } public void SetS3Location(string s3Bucket, string s3Key) { this.Field.SetS3Location(this._resource.DataSource, s3Bucket, s3Key); } public void SetImageUri(string imageUri) { this.Field.SetImageUri(this._resource.DataSource, imageUri); } public string GetMetadataDockerfile() { return this.DataSource.GetValueFromResource("Metadata", "Dockerfile"); } public string GetMetadataDockerTag() { return this.DataSource.GetValueFromResource("Metadata", "DockerTag"); } public Dictionary<string, string> GetMetadataDockerBuildArgs() { return this.DataSource.GetValueDictionaryFromResource("Metadata", "DockerBuildArgs"); } public static bool IsECRImage(string path) { return (!string.IsNullOrEmpty(path) && path.Contains("dkr.ecr") && Regex.Match(path.Split('.')[0], @"^\d{12}$").Success); } } } }
241
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Amazon.Lambda.Tools.TemplateProcessor { /// <summary> /// Class that identifies the fields and the delegates to access those fields in a given IUpdatableResourceDataSource. /// </summary> public class UpdatableResourceDefinition { public static readonly UpdatableResourceDefinition DEF_LAMBDA_FUNCTION = new UpdatableResourceDefinition( "AWS::Lambda::Function", FieldDefinition.CreateFieldDefinitionForLambda(false) ); public static readonly UpdatableResourceDefinition DEF_SERVERLESS_FUNCTION = new UpdatableResourceDefinition( "AWS::Serverless::Function", FieldDefinition.CreateFieldDefinitionForLambda(true) ); public static readonly UpdatableResourceDefinition DEF_APIGATEWAY_RESTAPI = new UpdatableResourceDefinition( "AWS::ApiGateway::RestApi", FieldDefinition.CreateFieldDefinitionS3LocationStyle(false, "BodyS3Location", "Bucket", "Key") ); public static readonly UpdatableResourceDefinition DEF_APPSYNC_GRAPHQLSCHEMA = new UpdatableResourceDefinition( "AWS::AppSync::GraphQLSchema", FieldDefinition.CreateFieldDefinitionUrlStyle(false, "DefinitionS3Location") ); public static readonly UpdatableResourceDefinition DEF_APPSYNC_RESOLVER = new UpdatableResourceDefinition( "AWS::AppSync::Resolver", FieldDefinition.CreateFieldDefinitionUrlStyle(false, "ResponseMappingTemplateS3Location"), FieldDefinition.CreateFieldDefinitionUrlStyle(false, "RequestMappingTemplateS3Location") ); public static readonly UpdatableResourceDefinition DEF_SERVERLESS_API = new UpdatableResourceDefinition( "AWS::Serverless::Api", FieldDefinition.CreateFieldDefinitionUrlStyle(false, "DefinitionUri") ); public static readonly UpdatableResourceDefinition DEF_ELASTICBEANSTALK_APPLICATIONVERSION = new UpdatableResourceDefinition( "AWS::ElasticBeanstalk::ApplicationVersion", FieldDefinition.CreateFieldDefinitionS3LocationStyle(false, "SourceBundle", "S3Bucket", "S3Key") ); public static readonly UpdatableResourceDefinition DEF_CLOUDFORMATION_STACK = new UpdatableResourceDefinition( "AWS::CloudFormation::Stack", FieldDefinition.CreateFieldDefinitionUrlStyle(false, "TemplateUrl") ); /// <summary> /// All of the known CloudFormation resources that have fields pointing to S3 locations that can be updated from a local path. /// </summary> public static IDictionary<string, UpdatableResourceDefinition> ValidUpdatableResourceDefinitions = new Dictionary<string, UpdatableResourceDefinition> { {DEF_APIGATEWAY_RESTAPI.Name, DEF_APIGATEWAY_RESTAPI}, {DEF_LAMBDA_FUNCTION.Name, DEF_LAMBDA_FUNCTION}, {DEF_SERVERLESS_FUNCTION.Name, DEF_SERVERLESS_FUNCTION}, {DEF_APPSYNC_GRAPHQLSCHEMA.Name, DEF_APPSYNC_GRAPHQLSCHEMA}, {DEF_APPSYNC_RESOLVER.Name, DEF_APPSYNC_RESOLVER}, {DEF_SERVERLESS_API.Name, DEF_SERVERLESS_API}, {DEF_ELASTICBEANSTALK_APPLICATIONVERSION.Name, DEF_ELASTICBEANSTALK_APPLICATIONVERSION}, {DEF_CLOUDFORMATION_STACK.Name, DEF_CLOUDFORMATION_STACK}, }; public UpdatableResourceDefinition(string name, params FieldDefinition[] fields) { this.Name = name; this.Fields = fields; } public string Name { get; } public FieldDefinition[] Fields { get; } /// <summary> /// FieldDefinition identity what fields in a CloudFormation resource can be updated and the delegates to retrieve /// and set the information in the datasource. /// </summary> public class FieldDefinition { public string Name { get; set; } public bool IsCode { get; set; } /// <summary> /// The Func that knows how to get the local path for the field from the datasource. /// </summary> public Func<IUpdatableResourceDataSource, string> GetLocalPath { get; set; } /// <summary> /// The Action that knows how to set the S3 location for the field into this datasource. /// </summary> public Action<IUpdatableResourceDataSource, string, string> SetS3Location { get; set; } /// <summary> /// The Action that knows how to set the ImageUri for the field into this datasource. /// </summary> public Action<IUpdatableResourceDataSource, string> SetImageUri { get; set; } /// <summary> /// Creates a field definition that handles AWS::Lambda::Function or AWS::Serverless::Function resources. It will /// take care of settting either the S3 location or the ImageUri depending on the package type specified for the resource. /// </summary> /// <param name="isServerlessResource">True if the resource is AWS::Serverless::Function otherwise AWS::Lambda::Resource</param> /// <returns></returns> public static FieldDefinition CreateFieldDefinitionForLambda(bool isServerlessResource) { return new FieldDefinition { Name = "CodeUri-Or-ImageUri", IsCode = true, GetLocalPath = (s) => { string localPath; var packageType = s.GetValue(LambdaConstants.CF_LAMBDA_PACKAGE_TYPE); if(isServerlessResource) { if (string.Equals(PackageType.Image.Value, packageType, StringComparison.OrdinalIgnoreCase)) { localPath = s.GetValueFromResource(LambdaConstants.CF_SERVERLESS_METADATA, LambdaConstants.CF_SERVERLESS_DOCKERCONTEXT); if (string.IsNullOrEmpty(localPath)) { localPath = s.GetValue(LambdaConstants.CF_LAMBDA_IMAGEURI); } } else { localPath = s.GetValue(LambdaConstants.CF_LAMBDA_CODEURI); } } else { if (string.Equals(PackageType.Image.Value, packageType, StringComparison.OrdinalIgnoreCase)) { localPath = s.GetValue(LambdaConstants.CF_LAMBDA_CODE, LambdaConstants.CF_LAMBDA_IMAGEURI); } else { var bucket = s.GetValue(LambdaConstants.CF_LAMBDA_CODE, LambdaConstants.CF_LAMBDA_S3BUCKET); // If the bucket has a value then that means the CF template is referencing already // uploaded resource. if (!string.IsNullOrEmpty(bucket)) return null; localPath = s.GetValue(LambdaConstants.CF_LAMBDA_CODE, LambdaConstants.CF_LAMBDA_S3KEY); } } if (string.IsNullOrEmpty(localPath)) { localPath = "."; } else if (localPath.StartsWith("s3://")) { localPath = null; } return localPath; }, SetS3Location = (s, b, k) => { if(isServerlessResource) { var s3Url = $"s3://{b}/{k}"; s.SetValue(s3Url, LambdaConstants.CF_LAMBDA_CODEURI); } else { s.SetValue(b, LambdaConstants.CF_LAMBDA_CODE, LambdaConstants.CF_LAMBDA_S3BUCKET); s.SetValue(k, LambdaConstants.CF_LAMBDA_CODE, LambdaConstants.CF_LAMBDA_S3KEY); } }, SetImageUri = (s, i) => { if (isServerlessResource) { s.SetValue(i, LambdaConstants.CF_LAMBDA_IMAGEURI); } else { s.SetValue(i, LambdaConstants.CF_LAMBDA_CODE, LambdaConstants.CF_LAMBDA_IMAGEURI); } } }; } /// <summary> /// Creates a field definition that is storing the S3 location as a S3 path like s3://mybucket/myfile.zip /// </summary> /// <param name="isCode"></param> /// <param name="propertyName"></param> /// <returns></returns> public static FieldDefinition CreateFieldDefinitionUrlStyle(bool isCode, string propertyName) { return new FieldDefinition { Name = propertyName, IsCode = isCode, GetLocalPath = (s) => { var localPath = s.GetValue(propertyName); if (string.IsNullOrEmpty(localPath)) { if (isCode) { localPath = "."; } } else if (localPath.StartsWith("s3://")) { localPath = null; } return localPath; }, SetS3Location = (s, b, k) => { var s3Url = $"s3://{b}/{k}"; s.SetValue(s3Url, propertyName); } }; } /// <summary> /// Creates a field definition that is storing the S3 location using separate fields for bucket and key. /// </summary> /// <param name="isCode"></param> /// <param name="containerName"></param> /// <param name="s3BucketProperty"></param> /// <param name="s3KeyProperty"></param> /// <returns></returns> public static FieldDefinition CreateFieldDefinitionS3LocationStyle(bool isCode, string containerName, string s3BucketProperty, string s3KeyProperty) { return new FieldDefinition { Name = containerName, IsCode = isCode, GetLocalPath = (s) => { var bucket = s.GetValue(containerName, s3BucketProperty); if (!string.IsNullOrEmpty(bucket)) return null; var value = s.GetValue(containerName, s3KeyProperty); if (string.IsNullOrEmpty(value) && isCode) { value = "."; } return value; }, SetS3Location = (s, b, k) => { s.SetValue(b, containerName, s3BucketProperty); s.SetValue(k, containerName, s3KeyProperty); } }; } } } }
270
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using YamlDotNet.RepresentationModel; namespace Amazon.Lambda.Tools.TemplateProcessor { /// <summary> /// JSON implementation of ITemplateParser /// </summary> public class YamlTemplateParser : ITemplateParser { YamlStream Yaml { get; } public YamlTemplateParser(string templateBody) { var input = new StringReader(templateBody); // Load the stream this.Yaml = new YamlStream(); this.Yaml.Load(input); } public string GetUpdatedTemplate() { var myText = new StringWriter(); this.Yaml.Save(myText, assignAnchors: false); return myText.ToString(); } public IEnumerable<IUpdatableResource> UpdatableResources() { var root = (YamlMappingNode)this.Yaml.Documents[0].RootNode; if (root == null) throw new LambdaToolsException("CloudFormation template does not define any AWS resources", LambdaToolsException.LambdaErrorCode.ServerlessTemplateMissingResourceSection); var resourcesKey = new YamlScalarNode("Resources"); if (!root.Children.ContainsKey(resourcesKey)) throw new LambdaToolsException("CloudFormation template does not define any AWS resources", LambdaToolsException.LambdaErrorCode.ServerlessTemplateMissingResourceSection); var resources = (YamlMappingNode)root.Children[resourcesKey]; foreach (var resource in resources.Children) { var resourceBody = (YamlMappingNode)resource.Value; var type = (YamlScalarNode)resourceBody.Children[new YamlScalarNode("Type")]; if (!resourceBody.Children.ContainsKey("Properties")) continue; var properties = (YamlMappingNode)resourceBody.Children[new YamlScalarNode("Properties")]; if (properties == null) continue; if (type == null) continue; UpdatableResourceDefinition updatableResourceDefinition; if (!UpdatableResourceDefinition.ValidUpdatableResourceDefinitions.TryGetValue(type.Value, out updatableResourceDefinition)) continue; var updatableResource = new UpdatableResource(resource.Key.ToString(), updatableResourceDefinition, new YamlUpdatableResourceDataSource(root, resourceBody, properties)); yield return updatableResource; } } /// <summary> /// The JSON implementation of IUpdatableResourceDataSource /// </summary> public class YamlUpdatableResourceDataSource : IUpdatableResourceDataSource { YamlMappingNode Root { get; } YamlMappingNode Resource { get; } YamlMappingNode Properties { get; } public YamlUpdatableResourceDataSource(YamlMappingNode root, YamlMappingNode resource, YamlMappingNode properties) { this.Root = root; this.Resource = resource; this.Properties = properties; } public string GetValueFromRoot(params string[] keyPath) { return GetValue(this.Root, keyPath); } public string[] GetValueListFromRoot(params string[] keyPath) { return GetValueList(this.Root, keyPath); } public string GetValueFromResource(params string[] keyPath) { return GetValue(this.Resource, keyPath); } public string GetValue(params string[] keyPath) { return GetValue(this.Properties, keyPath); } private static string GetValue(YamlNode node, params string[] keyPath) { foreach (var key in keyPath) { if (node == null || !(node is YamlMappingNode)) return null; var mappingNode = ((YamlMappingNode)node); if (!mappingNode.Children.ContainsKey(key)) return null; node = mappingNode.Children[key]; } if (node is YamlScalarNode) { return ((YamlScalarNode)node).Value; } return null; } public string[] GetValueList(params string[] keyPath) { return GetValueList(this.Properties, keyPath); } public Dictionary<string, string> GetValueDictionaryFromResource(params string[] keyPath) { return GetValueDictionaryFromResource(this.Resource, keyPath); } private static string[] GetValueList(YamlNode node, params string[] keyPath) { foreach (var key in keyPath) { if (node == null || !(node is YamlMappingNode)) return null; var mappingNode = ((YamlMappingNode)node); if (!mappingNode.Children.ContainsKey(key)) return null; node = mappingNode.Children[key]; } var sequenceNode = node as YamlSequenceNode; if (sequenceNode == null || sequenceNode.Children.Count == 0) { return null; } var values = new string[sequenceNode.Children.Count]; for (var i = 0; i < sequenceNode.Children.Count; i++) { values[i] = sequenceNode.Children[i]?.ToString(); } return values; } public void SetValue(string value, params string[] keyPath) { YamlMappingNode node = this.Properties; for (int i = 0; i < keyPath.Length - 1; i++) { var childNode = node.Children.ContainsKey(keyPath[i]) ? node[keyPath[i]] as YamlMappingNode : null; if (childNode == null) { childNode = new YamlMappingNode(); ((YamlMappingNode)node).Children.Add(keyPath[i], childNode); } node = childNode; } node.Children.Remove(keyPath[keyPath.Length - 1]); node.Children.Add(keyPath[keyPath.Length - 1], new YamlScalarNode(value)); } private static Dictionary<string, string> GetValueDictionaryFromResource(YamlNode node, params string[] keyPath) { foreach (var key in keyPath) { if (node == null || !(node is YamlMappingNode)) return null; var mappingNode = ((YamlMappingNode)node); if (!mappingNode.Children.ContainsKey(key)) return null; node = mappingNode.Children[key]; } if (node is YamlMappingNode) { var mappingNode = (YamlMappingNode)node; if (mappingNode.Children.Count == 0) return null; Dictionary<string, string> dictionary = new Dictionary<string, string>(mappingNode.Children.Count); foreach (var key in mappingNode.Children.Keys) { if (dictionary.ContainsKey(key.ToString())) { dictionary[key.ToString()] = mappingNode.Children[key]?.ToString(); } else { dictionary.Add(key.ToString(), mappingNode.Children[key]?.ToString()); } } return dictionary; } return null; } } } }
231
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; using Amazon.Common.DotNetCli.Tools.Commands; using Amazon.Common.DotNetCli.Tools.Options; namespace Amazon.Common.DotNetCli.Tools.Test { public class CommandLineParserTest { [Fact] public void SingleStringArgument() { Action<CommandOptions> validation = x => { Assert.Equal(1, x.Count); var option = x.FindCommandOption("-c"); Assert.Equal("Release", option.Item2.StringValue); }; var options = new List<CommandOption> { new CommandOption { Name = "Configuration", ValueType = CommandOption.CommandOptionValueType.StringValue, ShortSwitch = "-c", Switch = "--configuration" } }; var values = CommandLineParser.ParseArguments(options, new string[] { "-c", "Release" }); validation(values); values = CommandLineParser.ParseArguments(options, new string[] { "--configuration", "Release" }); validation(values); } [Fact] public void SingleIntArgument() { Action<CommandOptions> validation = x => { Assert.Equal(1, x.Count); var option = x.FindCommandOption("-i"); Assert.Equal(100, option.Item2.IntValue); }; var options = new List<CommandOption> { new CommandOption { Name = "MyInt", ValueType = CommandOption.CommandOptionValueType.IntValue, ShortSwitch = "-i", Switch = "--integer" } }; var values = CommandLineParser.ParseArguments(options, new string[] { "-i", "100" }); validation(values); values = CommandLineParser.ParseArguments(options, new string[] { "--integer", "100" }); validation(values); } [Fact] public void SingleBoolArgument() { Action<CommandOptions> validation = x => { Assert.Equal(1, x.Count); var option = x.FindCommandOption("-b"); Assert.Equal(true, option.Item2.BoolValue); }; var options = new List<CommandOption> { new CommandOption { Name = "MyBool", ValueType = CommandOption.CommandOptionValueType.BoolValue, ShortSwitch = "-b", Switch = "--bool" } }; var values = CommandLineParser.ParseArguments(options, new string[] { "-b", "true" }); validation(values); values = CommandLineParser.ParseArguments(options, new string[] { "--bool", "true" }); validation(values); } } }
104
aws-extensions-for-dotnet-cli
aws
C#
using System; using Xunit; namespace Amazon.Common.DotNetCli.Tools.Test { public class EnvironmentReplacementTests { [Fact] public void NoVariables() { var result = Utilities.ReplaceEnvironmentVariables("some string"); Assert.Equal("some string", result); } [Fact] public void EnvironmentVariableNotSet() { var result = Utilities.ReplaceEnvironmentVariables("some string=$(variable)"); Assert.Equal("some string=$(variable)", result); } [Fact] public void SingleVariableMultipleReplacement() { Environment.SetEnvironmentVariable("Key1", "replacement1"); var result = Utilities.ReplaceEnvironmentVariables($"some string=$(Key1) other $(Key1)"); Assert.Equal("some string=replacement1 other replacement1", result); } [Fact] public void MultipleReplacement() { Environment.SetEnvironmentVariable("otherkey1", "replacement1"); Environment.SetEnvironmentVariable("Key2", "variable2"); Environment.SetEnvironmentVariable("KEY3", "3333"); var result = Utilities.ReplaceEnvironmentVariables($"some string=$(otherkey1) other $(Key2) last $(KEY3) set"); Assert.Equal("some string=replacement1 other variable2 last 3333 set", result); } } }
44
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Amazon.Common.DotNetCli.Tools.Test { public class OptionParseTests { [Fact] public void ParseNullParameter() { var parameters = Utilities.ParseKeyValueOption(null); Assert.Equal(0, parameters.Count); parameters = Utilities.ParseKeyValueOption(string.Empty); Assert.Equal(0, parameters.Count); } [Fact] public void ParseKeyValueParameter() { var parameters = Utilities.ParseKeyValueOption("Table=Blog"); Assert.Equal(1, parameters.Count); Assert.Equal("Blog", parameters["Table"]); parameters = Utilities.ParseKeyValueOption("Table=Blog;"); Assert.Equal(1, parameters.Count); Assert.Equal("Blog", parameters["Table"]); parameters = Utilities.ParseKeyValueOption("\"ConnectionString\"=\"User=foo;Password=test\""); Assert.Equal(1, parameters.Count); Assert.Equal("User=foo;Password=test", parameters["ConnectionString"]); } [Fact] public void ParseTwoKeyValueParameter() { var parameters = Utilities.ParseKeyValueOption("Table=Blog;Bucket=MyBucket"); Assert.Equal(2, parameters.Count); Assert.Equal("Blog", parameters["Table"]); Assert.Equal("MyBucket", parameters["Bucket"]); parameters = Utilities.ParseKeyValueOption("\"ConnectionString1\"=\"User=foo;Password=test\";\"ConnectionString2\"=\"Password=test;User=foo\""); Assert.Equal(2, parameters.Count); Assert.Equal("User=foo;Password=test", parameters["ConnectionString1"]); Assert.Equal("Password=test;User=foo", parameters["ConnectionString2"]); } [Fact] public void ParseEmptyValue() { var parameters = Utilities.ParseKeyValueOption("ShouldCreateTable=true;BlogTableName="); Assert.Equal(2, parameters.Count); Assert.Equal("true", parameters["ShouldCreateTable"]); Assert.Equal("", parameters["BlogTableName"]); parameters = Utilities.ParseKeyValueOption("BlogTableName=;ShouldCreateTable=true"); Assert.Equal(2, parameters.Count); Assert.Equal("true", parameters["ShouldCreateTable"]); Assert.Equal("", parameters["BlogTableName"]); } [Fact] public void ParseErrors() { Assert.Throws(typeof(ToolsException), () => Utilities.ParseKeyValueOption("=aaa")); } } }
74
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Diagnostics; using Xunit; using Amazon.Common.DotNetCli.Tools.Test.Mocks; #if NETCOREAPP3_1_OR_GREATER using System.Runtime.InteropServices; #endif namespace Amazon.Common.DotNetCli.Tools.Test; public class PosixUserHelperTest { /// <summary> /// This is more of a quasi-functional test than a unit test. /// If run under MacOS or Linux, it will confirm that UID and GID can be retrieved /// </summary> [Fact] public void TestGetEffectiveUser() { #if NETCOREAPP3_1_OR_GREATER if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD)) { var mockLogger = new MockToolLogger(); Assert.True(PosixUserHelper.IsRunningInPosix); var user = PosixUserHelper.GetEffectiveUser(mockLogger); Assert.True(user.HasValue); Assert.True(user.Value.UserID >= 0); Assert.True(user.Value.GroupID >= 0); } else { Assert.False(PosixUserHelper.IsRunningInPosix); } #else Assert.False(PosixUserHelper.IsRunningInPosix); #endif } /// <summary> /// This mocks execution of the "id" commands /// </summary> [Fact] public void TestGetEffectiveUserSucceeds() { var mockProcesses = new MockIdProcessFactory(new[] { new ProcessInstance.ProcessResults { Executed = true, ExitCode = 0, Output = "998", Error = "" }, new ProcessInstance.ProcessResults { Executed = true, ExitCode = 0, Output = "999", Error = "" } }); var mockLogger = new MockToolLogger(); var user = PosixUserHelper.GetEffectiveUser(mockLogger, mockProcesses); Assert.True(user.HasValue); Assert.True(user.Value.UserID >= 998); Assert.True(user.Value.GroupID >= 999); } [Fact] public void TestGetEffectiveUserFails() { var mockProcesses = new MockIdProcessFactory(new[] { new ProcessInstance.ProcessResults { Executed = true, ExitCode = 0, Output = "998", Error = "" }, new ProcessInstance.ProcessResults { Executed = true, ExitCode = -1, Output = "", Error = "Sad trombones" } }); var mockLogger = new MockToolLogger(); var user = PosixUserHelper.GetEffectiveUser(mockLogger, mockProcesses); Assert.False(user.HasValue); Assert.Equal( "Error executing \"id -g\" - exit code -1 Sad trombones\nWarning: Unable to get effective group from \"id -g\"\n", mockLogger.Log); } /// <summary> /// Mock for process factory so that we can fake "id" results /// </summary> private class MockIdProcessFactory : IProcessFactory { private readonly ProcessInstance.ProcessResults[] _mockedResults; private int _counter; public MockIdProcessFactory(ProcessInstance.ProcessResults[] mockedResults) { _mockedResults = mockedResults; } public ProcessInstance.ProcessResults RunProcess(ProcessStartInfo info, int timeout = 60000) { if (_counter < _mockedResults.Length) { return _mockedResults[_counter++]; } throw new Exception("Out of mocked process responses"); } } }
123
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace Amazon.Common.DotNetCli.Tools.Test { public class RelativePathTests { [Theory] [InlineData(@"C:\Code\Solution\Project", @"C:\Code\Solution", "../", false)] [InlineData(@"c:\code\solution\project", @"C:\Code\Solution", "../", false)] [InlineData(@"C:\Code\Solution\ProjectA", @"C:\Code\Solution\ProjectB\file.csproj", "../ProjectB/file.csproj", false)] [InlineData(@"C:\Code\Solution\Project", @"D:\Code\Solution", "D:/Code/Solution", true)] [InlineData(@"C:\Code\Solution", @"C:\Code\Solution\Project", "Project", false)] [InlineData(@"C:\Code\Solution", @"C:\Code\Solution\Project\foo.cs", "Project/foo.cs", false)] [InlineData(@"/home/user/Solution/Project", @"/home/user/Solution", "../", false)] [InlineData(@"/home/user/Solution", @"/home/user/Solution/Project", "Project", false)] [InlineData(@"Code\Solution", @"Code\Solution\Project", "Project", true)] [InlineData(@"user/Solution", @"user/Solution/Project", "Project", false)] [InlineData(@"Code\Solution\", @"Code\Solution\Project\", "Project/", true)] [InlineData(@"user/Solution/", @"user/Solution/Project/", "Project/", false)] [InlineData(@"/home/user/Solution/Project", @"/home/user/Solution/", "../", false)] [InlineData(@"/home/user/Solution/", @"/home/user/Solution/Project", "Project", false)] public void ToParentDirectory(string start, string relativeTo, string expected, bool windowsOnly) { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && windowsOnly) return; Assert.Equal(expected, Utilities.RelativePathTo(start, relativeTo)); } } }
37
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Xunit; namespace Amazon.Common.DotNetCli.Tools.Test { public class UtilitiesTests { [Theory] [InlineData("../../../../../testapps/TestFunction", "net6.0")] [InlineData("../../../../../testapps/ServerlessWithYamlFunction", "net6.0")] [InlineData("../../../../../testapps/TestBeanstalkWebApp", "netcoreapp3.1")] public void CheckFramework(string projectPath, string expectedFramework) { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + projectPath); var determinedFramework = Utilities.LookupTargetFrameworkFromProjectFile(projectPath); Assert.Equal(expectedFramework, determinedFramework); } [Fact] public void TestExecuteShellCommandSuccess() { var result = Utilities.ExecuteShellCommand(null, FindDotnetProcess(), "--info"); Assert.Equal(0, result.ExitCode); Assert.Contains("SDKs installed", result.Stdout); } [Fact] public void TestExecuteShellCommandFail() { var result = Utilities.ExecuteShellCommand(null, FindDotnetProcess(), "DoesnotExist.dll"); Assert.Equal(1, result.ExitCode); } [Fact] public void TestParseListSdkOutput() { const string EXAMPLE_OUTPUT = @"1.1.11 [/usr/local/share/dotnet/sdk] 2.1.302 [/usr/local/share/dotnet/sdk] 2.1.403 [/usr/local/share/dotnet/sdk] 2.1.503 [/usr/local/share/dotnet/sdk] 2.2.100 [/usr/local/share/dotnet/sdk] "; var sdkVersion = Amazon.Common.DotNetCli.Tools.DotNetCLIWrapper.ParseListSdkOutput(EXAMPLE_OUTPUT); Assert.Equal(new Version("2.2.100"), sdkVersion); } string FindDotnetProcess() { var dotnetCLI = AbstractCLIWrapper.FindExecutableInPath("dotnet.exe"); if (dotnetCLI == null) dotnetCLI = AbstractCLIWrapper.FindExecutableInPath("dotnet"); return dotnetCLI; } [Theory] [InlineData("../../../../../testapps/TestFunction", null, false)] [InlineData("../../../../../testapps/TestFunction", "", false)] [InlineData("../../../../../testapps/TestFunction", "publishaot=true", true)] [InlineData("../../../../../testapps/TestFunction", "publishAOT=False", false)] [InlineData("../../../../../testapps/TestNativeAotSingleProject", null, true)] [InlineData("../../../../../testapps/TestNativeAotSingleProject", "publishAOT=False", false)] public void TestLookForPublishAotFlag(string projectLocation, string msBuildParameters, bool expected) { var result = Utilities.LookPublishAotFlag(projectLocation, msBuildParameters); Assert.Equal(expected, result); } [Theory] [InlineData("../../../../../testapps/TestFunction", "Library")] [InlineData("../../../../../testapps/TestNativeAotSingleProject", "Exe")] public void TestLookupOutputTypeFromProjectFile(string projectLocation, string expected) { var result = Utilities.LookupOutputTypeFromProjectFile(projectLocation); Assert.Equal(expected, result); } [Theory] [InlineData("../../../../../testapps/TestFunction", null, false)] [InlineData("../../../../../testapps/TestFunction", "", false)] [InlineData("../../../../../testapps/TestFunction", "--self-contained=true", true)] [InlineData("../../../../../testapps/TestFunction", "--self-contained=false", true)] [InlineData("../../../../../testapps/TestFunction", "--self-contained true", true)] [InlineData("../../../../../testapps/TestFunction", "--self-contained false", true)] [InlineData("../../../../../testapps/TestNativeAotSingleProject", null, true)] [InlineData("../../../../../testapps/TestNativeAotSingleProject", "--self-contained false", true)] public void TestHasExplicitSelfContainedFlag(string projectLocation, string msBuildParameters, bool expected) { var result = Utilities.HasExplicitSelfContainedFlag(projectLocation, msBuildParameters); Assert.Equal(expected, result); } } }
103
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Text; namespace Amazon.Common.DotNetCli.Tools.Test.Mocks; public class MockToolLogger : IToolLogger { private readonly StringBuilder _sbLog = new(); public void WriteLine(string text) { _sbLog.Append(text); _sbLog.Append('\n'); } public void WriteLine(string text, params object[] data) { _sbLog.AppendFormat(text, data); _sbLog.Append('\n'); } public string Log => _sbLog.ToString(); }
23
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Xunit; using Amazon.ECS.Tools; using Amazon.Tools.TestHelpers; using Amazon.ECS.Tools.Commands; using Amazon.Common.DotNetCli.Tools.Options; namespace Amazon.ECS.Tools.Test { public class ECSToolsDefaultsReaderTest { [Fact] public void LoadDefaultsDirectly() { var defaults = new ECSToolsDefaults(); defaults.LoadDefaults(TestUtilities.GetTestProjectPath("HelloWorldWebApp"), ECSToolsDefaults.DEFAULT_FILE_NAME); Assert.Equal(defaults["region"], "us-west-2"); Assert.Equal(defaults["container-memory-hard-limit"], 512); } [Fact] public void CommandInferRegionFromDefaults() { var command = new DeployServiceCommand(new TestToolLogger(), TestUtilities.GetTestProjectPath("HelloWorldWebApp"), new string[0]); Assert.Equal("us-west-2", command.GetStringValueOrDefault(command.Region, CommonDefinedCommandOptions.ARGUMENT_AWS_REGION, false)); } [Fact] public void GetTaskCPUFromDefaultsAsInt() { var command = new DeployServiceCommand(new TestToolLogger(), TestUtilities.GetTestProjectPath("HelloWorldWebApp"), new string[0]); // CPU is set in aws-ecs-tools-defaults.json as a number Assert.Equal("256", command.GetStringValueOrDefault(command.TaskDefinitionProperties.TaskCPU, ECSDefinedCommandOptions.ARGUMENT_TD_CPU, false)); // Memory is set in aws-ecs-tools-defaults.json as a string Assert.Equal("512", command.GetStringValueOrDefault(command.TaskDefinitionProperties.TaskMemory, ECSDefinedCommandOptions.ARGUMENT_TD_MEMORY, false)); } } }
52
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Linq; using System.IO; using System.IO.Compression; using System.Threading.Tasks; using Xunit; using Amazon.ElasticBeanstalk.Tools.Commands; using Amazon.Common.DotNetCli.Tools; using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Amazon.ElasticBeanstalk.Tools.Test { public class CreatePackageTests { [Fact] public async Task NoIISSettings() { var outputPackage = Path.GetTempFileName(); var packageCommand = new PackageCommand(new ConsoleToolLogger(), TestUtilities.TestBeanstalkWebAppPath, new string[] { "--output-package", outputPackage }); packageCommand.DisableInteractive = true; await packageCommand.ExecuteAsync(); Assert.Null(packageCommand.LastToolsException); var manifest = ReadManifestFromPackage(outputPackage); var appInManifest = manifest["deployments"]["aspNetCoreWeb"][0]; Assert.NotNull(appInManifest); var appInManifestParameters = appInManifest["parameters"]; Assert.Equal(".", appInManifestParameters["appBundle"].ToString()); Assert.Equal("/", appInManifestParameters["iisPath"].ToString()); Assert.Equal("Default Web Site", appInManifestParameters["iisWebSite"].ToString()); } [Fact] public async Task ExplicitIISSettings() { var outputPackage = Path.GetTempFileName(); var packageCommand = new PackageCommand(new ConsoleToolLogger(), TestUtilities.TestBeanstalkWebAppPath, new string[] { "--output-package", outputPackage, "--iis-website", "The WebSite", "--app-path", "/child" }); packageCommand.DisableInteractive = true; await packageCommand.ExecuteAsync(); var manifest = ReadManifestFromPackage(outputPackage); var appInManifest = manifest["deployments"]["aspNetCoreWeb"][0]; Assert.NotNull(appInManifest); var appInManifestParameters = appInManifest["parameters"]; Assert.Equal(".", appInManifestParameters["appBundle"].ToString()); Assert.Equal("/child", appInManifestParameters["iisPath"].ToString()); Assert.Equal("The WebSite", appInManifestParameters["iisWebSite"].ToString()); } [Fact] public async Task ExpandEnvironmentVariable() { const string envName = "EB_OUTPUT_PACKAGE"; var outputPackage = Path.GetTempFileName(); Environment.SetEnvironmentVariable(envName, outputPackage); try { var packageCommand = new PackageCommand(new ConsoleToolLogger(), TestUtilities.TestBeanstalkWebAppPath, new string[] { "--config-file", "env-eb-config.json" }); await packageCommand.ExecuteAsync(); var manifest = ReadManifestFromPackage(outputPackage); var appInManifest = manifest["deployments"]["aspNetCoreWeb"][0]; Assert.NotNull(appInManifest); var appInManifestParameters = appInManifest["parameters"]; Assert.Equal(".", appInManifestParameters["appBundle"].ToString()); Assert.Equal("/", appInManifestParameters["iisPath"].ToString()); Assert.Equal("Default Web Site", appInManifestParameters["iisWebSite"].ToString()); } finally { Environment.SetEnvironmentVariable(envName, null); } } public JObject ReadManifestFromPackage(string packagePath) { using (var zipStream = File.Open(packagePath, FileMode.Open)) using (var zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Read)) { var entry = zipArchive.Entries.FirstOrDefault(x => string.Equals(x.Name, "aws-windows-deployment-manifest.json")); if (entry == null) throw new Exception("Failed to find aws-windows-deployment-manifest.json in package bundle"); using (var entryReader = new StreamReader(entry.Open())) { return JsonConvert.DeserializeObject(entryReader.ReadToEnd()) as JObject; } } } } }
104
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Linq; using System.IO; using System.Collections.Generic; using System.IO.Compression; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; using Amazon.ElasticBeanstalk.Tools.Commands; using Amazon.Common.DotNetCli.Tools; using Amazon.S3; using Amazon.S3.Model; using Amazon.ElasticBeanstalk; using Amazon.ElasticBeanstalk.Model; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Moq; namespace Amazon.ElasticBeanstalk.Tools.Test { public class DeployTests { [Fact(Skip = "Trouble running in CodeBuild. Need to debug.")] public async Task CreateEnvironmentTest() { var application = "TestApp"; var environment = "TestEnv"; var solutionStack = "TestWindowsStack"; var iamProfile = "arn:aws:fake-profile"; var mockS3Client = new Mock<IAmazonS3>(); var calls = new Dictionary<string, int>(); Action<string> addCall = x => { if (calls.ContainsKey(x)) calls[x] = calls[x] + 1; else calls[x] = 1; }; var mockEbClient = new Mock<IAmazonElasticBeanstalk>(); mockEbClient.Setup(client => client.DescribeApplicationsAsync(It.IsAny<DescribeApplicationsRequest>(), It.IsAny<CancellationToken>())) .Callback<DescribeApplicationsRequest, CancellationToken>((request, token) => { Assert.Equal(application, request.ApplicationNames[0]); }) .Returns((DescribeApplicationsRequest r, CancellationToken token) => { addCall("DescribeApplicationsAsync"); return Task.FromResult(new DescribeApplicationsResponse()); }); mockEbClient.Setup(client => client.CreateStorageLocationAsync(It.IsAny<CancellationToken>())) .Returns((CancellationToken token) => { addCall("CreateStorageLocationAsync"); return Task.FromResult(new CreateStorageLocationResponse {S3Bucket = "TestBucket" }); }); mockEbClient.Setup(client => client.DescribeEventsAsync(It.IsAny<DescribeEventsRequest>(), It.IsAny<CancellationToken>())) .Callback<DescribeEventsRequest, CancellationToken>((request, token) => { Assert.Equal(application, request.ApplicationName); Assert.Equal(environment, request.EnvironmentName); }) .Returns((DescribeEventsRequest r, CancellationToken token) => { addCall("DescribeEventsAsync"); var response = new DescribeEventsResponse { Events = new List<EventDescription> { new EventDescription { ApplicationName = application, EnvironmentName = environment, Message = "Dummy Message", EventDate = DateTime.Now } } }; return Task.FromResult(response); }); mockEbClient.Setup(client => client.CreateApplicationAsync(It.IsAny<CreateApplicationRequest>(), It.IsAny<CancellationToken>())) .Callback<CreateApplicationRequest, CancellationToken>((request, token) => { Assert.Equal(application, request.ApplicationName); }) .Returns((CreateApplicationRequest r, CancellationToken token) => { addCall("CreateApplicationAsync"); return Task.FromResult(new CreateApplicationResponse()); }); mockEbClient.Setup(client => client.CreateEnvironmentAsync(It.IsAny<CreateEnvironmentRequest>(), It.IsAny<CancellationToken>())) .Callback<CreateEnvironmentRequest, CancellationToken>((request, token) => { Assert.Equal(application, request.ApplicationName); Assert.Equal(environment, request.EnvironmentName); Assert.Equal(solutionStack, request.SolutionStackName); var iamSetting = request.OptionSettings.FirstOrDefault(x => string.Equals(x.OptionName, "IamInstanceProfile") && string.Equals(x.Namespace, "aws:autoscaling:launchconfiguration")); Assert.Equal(iamSetting.Value, iamProfile); var xraySetting = request.OptionSettings.FirstOrDefault(x => string.Equals(x.OptionName, "XRayEnabled") && string.Equals(x.Namespace, "aws:elasticbeanstalk:xray")); Assert.Equal(xraySetting.Value.ToLower(), "true"); }) .Returns((CreateEnvironmentRequest r, CancellationToken token) => { addCall("CreateEnvironmentAsync"); return Task.FromResult(new CreateEnvironmentResponse()); }); mockEbClient.Setup(client => client.DescribeEnvironmentsAsync(It.IsAny<DescribeEnvironmentsRequest>(), It.IsAny<CancellationToken>())) .Returns((DescribeEnvironmentsRequest r, CancellationToken token) => { addCall("DescribeEnvironmentsAsync"); return Task.FromResult(new DescribeEnvironmentsResponse { Environments = new List<EnvironmentDescription> { new EnvironmentDescription { ApplicationName = application, EnvironmentName = environment, DateCreated = DateTime.Now.AddMinutes(-1), DateUpdated = DateTime.Now, Status = EnvironmentStatus.Ready } } }); }); var deployCommand = new DeployEnvironmentCommand(new ConsoleToolLogger(), TestUtilities.TestBeanstalkWebAppPath, new string[] { "-app", application, "-env", environment, "--solution-stack", solutionStack, "--instance-profile", iamProfile, "--region", "us-moq-1", "--enable-xray", "true" }); deployCommand.DisableInteractive = true; deployCommand.EBClient = mockEbClient.Object; deployCommand.S3Client = mockS3Client.Object; await deployCommand.ExecuteAsync(); Assert.Null(deployCommand.LastToolsException); Assert.True(calls.ContainsKey("CreateApplicationAsync")); Assert.True(calls.ContainsKey("CreateEnvironmentAsync")); } [Fact(Skip = "Trouble running in CodeBuild. Need to debug.")] public async Task CreateEnvironmentWithPackageTest() { var application = "TestApp"; var environment = "TestEnv"; var solutionStack = "TestWindowsStack"; var iamProfile = "arn:aws:fake-profile"; var mockS3Client = new Mock<IAmazonS3>(); var calls = new Dictionary<string, int>(); Action<string> addCall = x => { if (calls.ContainsKey(x)) calls[x] = calls[x] + 1; else calls[x] = 1; }; var mockEbClient = new Mock<IAmazonElasticBeanstalk>(); mockEbClient.Setup(client => client.DescribeApplicationsAsync(It.IsAny<DescribeApplicationsRequest>(), It.IsAny<CancellationToken>())) .Callback<DescribeApplicationsRequest, CancellationToken>((request, token) => { Assert.Equal(application, request.ApplicationNames[0]); }) .Returns((DescribeApplicationsRequest r, CancellationToken token) => { addCall("DescribeApplicationsAsync"); return Task.FromResult(new DescribeApplicationsResponse()); }); mockEbClient.Setup(client => client.CreateStorageLocationAsync(It.IsAny<CancellationToken>())) .Returns((CancellationToken token) => { addCall("CreateStorageLocationAsync"); return Task.FromResult(new CreateStorageLocationResponse { S3Bucket = "TestBucket" }); }); mockEbClient.Setup(client => client.DescribeEventsAsync(It.IsAny<DescribeEventsRequest>(), It.IsAny<CancellationToken>())) .Callback<DescribeEventsRequest, CancellationToken>((request, token) => { Assert.Equal(application, request.ApplicationName); Assert.Equal(environment, request.EnvironmentName); }) .Returns((DescribeEventsRequest r, CancellationToken token) => { addCall("DescribeEventsAsync"); var response = new DescribeEventsResponse { Events = new List<EventDescription> { new EventDescription { ApplicationName = application, EnvironmentName = environment, Message = "Dummy Message", EventDate = DateTime.Now } } }; return Task.FromResult(response); }); mockEbClient.Setup(client => client.CreateApplicationAsync(It.IsAny<CreateApplicationRequest>(), It.IsAny<CancellationToken>())) .Callback<CreateApplicationRequest, CancellationToken>((request, token) => { Assert.Equal(application, request.ApplicationName); }) .Returns((CreateApplicationRequest r, CancellationToken token) => { addCall("CreateApplicationAsync"); return Task.FromResult(new CreateApplicationResponse()); }); mockEbClient.Setup(client => client.CreateEnvironmentAsync(It.IsAny<CreateEnvironmentRequest>(), It.IsAny<CancellationToken>())) .Callback<CreateEnvironmentRequest, CancellationToken>((request, token) => { Assert.Equal(application, request.ApplicationName); Assert.Equal(environment, request.EnvironmentName); Assert.Equal(solutionStack, request.SolutionStackName); var iamSetting = request.OptionSettings.FirstOrDefault(x => string.Equals(x.OptionName, "IamInstanceProfile") && string.Equals(x.Namespace, "aws:autoscaling:launchconfiguration")); Assert.Equal(iamSetting.Value, iamProfile); var xraySetting = request.OptionSettings.FirstOrDefault(x => string.Equals(x.OptionName, "XRayEnabled") && string.Equals(x.Namespace, "aws:elasticbeanstalk:xray")); Assert.Equal(xraySetting.Value.ToLower(), "true"); }) .Returns((CreateEnvironmentRequest r, CancellationToken token) => { addCall("CreateEnvironmentAsync"); return Task.FromResult(new CreateEnvironmentResponse()); }); mockEbClient.Setup(client => client.DescribeEnvironmentsAsync(It.IsAny<DescribeEnvironmentsRequest>(), It.IsAny<CancellationToken>())) .Returns((DescribeEnvironmentsRequest r, CancellationToken token) => { addCall("DescribeEnvironmentsAsync"); return Task.FromResult(new DescribeEnvironmentsResponse { Environments = new List<EnvironmentDescription> { new EnvironmentDescription { ApplicationName = application, EnvironmentName = environment, DateCreated = DateTime.Now.AddMinutes(-1), DateUpdated = DateTime.Now, Status = EnvironmentStatus.Ready } } }); }); var outputPackage = Path.GetTempFileName().Replace(".tmp", ".zip"); var packageCommand = new PackageCommand(new ConsoleToolLogger(), TestUtilities.TestBeanstalkWebAppPath, new string[] { "--output-package", outputPackage, "--iis-website", "The WebSite", "--app-path", "/child" }); packageCommand.DisableInteractive = true; await packageCommand.ExecuteAsync(); var deployCommand = new DeployEnvironmentCommand(new ConsoleToolLogger(), Path.GetTempPath(), new string[] { "-app", application, "-env", environment, "--solution-stack", solutionStack, "--instance-profile", iamProfile, "--region", "us-moq-1", "--enable-xray", "true", "--package", outputPackage}); deployCommand.DisableInteractive = true; deployCommand.EBClient = mockEbClient.Object; deployCommand.S3Client = mockS3Client.Object; await deployCommand.ExecuteAsync(); Assert.Null(deployCommand.LastToolsException); Assert.True(calls.ContainsKey("CreateApplicationAsync")); Assert.True(calls.ContainsKey("CreateEnvironmentAsync")); } [Fact(Skip = "Trouble running in CodeBuild. Need to debug.")] public async Task UpdateEnvironmentTest() { var application = "TestApp"; var environment = "TestEnv"; var solutionStack = "TestWindowsStack"; var iamProfile = "arn:aws:fake-profile"; var mockS3Client = new Mock<IAmazonS3>(); var calls = new Dictionary<string, int>(); Action<string> addCall = x => { if (calls.ContainsKey(x)) calls[x] = calls[x] + 1; else calls[x] = 1; }; var mockEbClient = new Mock<IAmazonElasticBeanstalk>(); mockEbClient.Setup(client => client.DescribeApplicationsAsync(It.IsAny<DescribeApplicationsRequest>(), It.IsAny<CancellationToken>())) .Callback<DescribeApplicationsRequest, CancellationToken>((request, token) => { Assert.Equal(application, request.ApplicationNames[0]); }) .Returns((DescribeApplicationsRequest r, CancellationToken token) => { addCall("DescribeApplicationsAsync"); return Task.FromResult(new DescribeApplicationsResponse { Applications = new List<ApplicationDescription> { new ApplicationDescription { ApplicationName = application } } }); }); mockEbClient.Setup(client => client.CreateStorageLocationAsync(It.IsAny<CancellationToken>())) .Returns((CancellationToken token) => { addCall("CreateStorageLocationAsync"); return Task.FromResult(new CreateStorageLocationResponse { S3Bucket = "TestBucket" }); }); mockEbClient.Setup(client => client.DescribeEventsAsync(It.IsAny<DescribeEventsRequest>(), It.IsAny<CancellationToken>())) .Callback<DescribeEventsRequest, CancellationToken>((request, token) => { Assert.Equal(application, request.ApplicationName); Assert.Equal(environment, request.EnvironmentName); }) .Returns((DescribeEventsRequest r, CancellationToken token) => { addCall("DescribeEventsAsync"); var response = new DescribeEventsResponse { Events = new List<EventDescription> { new EventDescription { ApplicationName = application, EnvironmentName = environment, Message = "Dummy Message", EventDate = DateTime.Now } } }; return Task.FromResult(response); }); mockEbClient.Setup(client => client.CreateApplicationAsync(It.IsAny<CreateApplicationRequest>(), It.IsAny<CancellationToken>())) .Callback<CreateApplicationRequest, CancellationToken>((request, token) => { Assert.Equal(application, request.ApplicationName); }) .Returns((CreateApplicationRequest r, CancellationToken token) => { addCall("CreateApplicationAsync"); return Task.FromResult(new CreateApplicationResponse()); }); mockEbClient.Setup(client => client.CreateEnvironmentAsync(It.IsAny<CreateEnvironmentRequest>(), It.IsAny<CancellationToken>())) .Returns((CreateEnvironmentRequest r, CancellationToken token) => { addCall("CreateEnvironmentAsync"); return Task.FromResult(new CreateEnvironmentResponse()); }); mockEbClient.Setup(client => client.UpdateEnvironmentAsync(It.IsAny<UpdateEnvironmentRequest>(), It.IsAny<CancellationToken>())) .Callback<UpdateEnvironmentRequest, CancellationToken>((request, token) => { Assert.Equal(application, request.ApplicationName); Assert.Equal(environment, request.EnvironmentName); var xraySetting = request.OptionSettings.FirstOrDefault(x => string.Equals(x.OptionName, "XRayEnabled") && string.Equals(x.Namespace, "aws:elasticbeanstalk:xray")); Assert.Equal(xraySetting.Value.ToLower(), "true"); }) .Returns((UpdateEnvironmentRequest r, CancellationToken token) => { addCall("UpdateEnvironmentAsync"); return Task.FromResult(new UpdateEnvironmentResponse()); }); mockEbClient.Setup(client => client.DescribeEnvironmentsAsync(It.IsAny<DescribeEnvironmentsRequest>(), It.IsAny<CancellationToken>())) .Returns((DescribeEnvironmentsRequest r, CancellationToken token) => { addCall("DescribeEnvironmentsAsync"); return Task.FromResult(new DescribeEnvironmentsResponse { Environments = new List<EnvironmentDescription> { new EnvironmentDescription { ApplicationName = application, EnvironmentName = environment, DateCreated = DateTime.Now.AddMinutes(-1), DateUpdated = DateTime.Now, Status = EnvironmentStatus.Ready } } }); }); var deployCommand = new DeployEnvironmentCommand(new ConsoleToolLogger(), TestUtilities.TestBeanstalkWebAppPath, new string[] { "-app", application, "-env", environment, "--solution-stack", solutionStack, "--instance-profile", iamProfile, "--region", "us-moq-1", "--enable-xray", "true" }); deployCommand.DisableInteractive = true; deployCommand.EBClient = mockEbClient.Object; deployCommand.S3Client = mockS3Client.Object; await deployCommand.ExecuteAsync(); Assert.Null(deployCommand.LastToolsException); Assert.False(calls.ContainsKey("CreateApplicationAsync")); Assert.False(calls.ContainsKey("CreateEnvironmentAsync")); Assert.True(calls.ContainsKey("UpdateEnvironmentAsync")); } } }
421
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; using Xunit; using Amazon.ElasticBeanstalk.Tools.Commands; using Amazon.ElasticBeanstalk.Model; namespace Amazon.ElasticBeanstalk.Tools.Test { public class EBUtilitiesTests { [Fact] public void FindExistingValueNullCollection() { List<ConfigurationOptionSetting> settings = null; Assert.Null(settings.FindExistingValue("ns", "name")); } [Theory] [InlineData("ns1", "name1", "found")] [InlineData("ns1", "name", null)] [InlineData("ns", "name1", null)] [InlineData("ns", "name", null)] public void FindExistingValues(string searchNS, string searchName, string expectedValue) { var ns = "ns1"; var name = "name1"; List<ConfigurationOptionSetting> settings = new List<ConfigurationOptionSetting>() { new ConfigurationOptionSetting {Namespace = ns, OptionName = name, Value = expectedValue } }; var actualValue = settings.FindExistingValue(searchNS, searchName); Assert.Equal(expectedValue, actualValue); } [Theory] [InlineData("./Resources/dotnet31-dependent-runtimeconfig.json", false)] [InlineData("./Resources/self-contained-example-runtimeconfig.json", true)] public void IsSelfContainedPublishTest(string filename, bool isSelfContained) { Assert.Equal(EBUtilities.IsSelfContainedPublish(filename), isSelfContained); } } }
45
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; using Xunit; using Amazon.ElasticBeanstalk.Tools.Commands; namespace Amazon.ElasticBeanstalk.Tools.Test { public class FilterSolutionStacksTest { [Fact] public void EnsureOnlyLatestVersionsAreReturnInputInDecendingOrder() { var availableSolutionStacks = new List<string> { "64bit Windows Server 2012 R2 v2.5.0 running IIS 8.5", "64bit Windows Server 2012 R2 v2.4.0 running IIS 8.5", "64bit Windows Server 2008 R2 v1.2.0 running IIS 7.5", "64bit Windows Server 2008 R2 v1.1.0 running IIS 7.5", "64bit Windows Server 2008 R2 v1.0.0 running IIS 7.5", "64bit Amazon Linux 2 v0.1.1 running Corretto 11 (BETA)", "64bit Amazon Linux 2 v0.1.0 running Corretto 11 (BETA)" }; var filterSolutionStacks = EBBaseCommand.FilterSolutionStackToLatestVersion(availableSolutionStacks); Assert.Equal(3, filterSolutionStacks.Count); Assert.Contains("64bit Windows Server 2012 R2 v2.5.0 running IIS 8.5", filterSolutionStacks); Assert.DoesNotContain("64bit Windows Server 2012 R2 v2.4.0 running IIS 8.5", filterSolutionStacks); Assert.Contains("64bit Windows Server 2008 R2 v1.2.0 running IIS 7.5", filterSolutionStacks); Assert.DoesNotContain("64bit Windows Server 2008 R2 v1.1.0 running IIS 7.5", filterSolutionStacks); Assert.DoesNotContain("64bit Windows Server 2008 R2 v1.0.0 running IIS 7.5", filterSolutionStacks); Assert.Contains("64bit Amazon Linux 2 v0.1.1 running Corretto 11 (BETA)", filterSolutionStacks); Assert.DoesNotContain("64bit Amazon Linux 2 v0.1.0 running Corretto 11 (BETA)", filterSolutionStacks); } [Fact] public void EnsureOnlyLatestVersionsAreReturnInputInAscendingOrder() { var availableSolutionStacks = new List<string> { "64bit Windows Server 2012 R2 v2.4.0 running IIS 8.5", "64bit Windows Server 2012 R2 v2.5.0 running IIS 8.5", "64bit Windows Server 2008 R2 v1.0.0 running IIS 7.5", "64bit Windows Server 2008 R2 v1.1.0 running IIS 7.5", "64bit Windows Server 2008 R2 v1.2.0 running IIS 7.5", "64bit Amazon Linux 2 v0.1.0 running Corretto 11 (BETA)", "64bit Amazon Linux 2 v0.1.1 running Corretto 11 (BETA)" }; var filterSolutionStacks = EBBaseCommand.FilterSolutionStackToLatestVersion(availableSolutionStacks); Assert.Equal(3, filterSolutionStacks.Count); Assert.Contains("64bit Windows Server 2012 R2 v2.5.0 running IIS 8.5", filterSolutionStacks); Assert.DoesNotContain("64bit Windows Server 2012 R2 v2.4.0 running IIS 8.5", filterSolutionStacks); Assert.Contains("64bit Windows Server 2008 R2 v1.2.0 running IIS 7.5", filterSolutionStacks); Assert.DoesNotContain("64bit Windows Server 2008 R2 v1.1.0 running IIS 7.5", filterSolutionStacks); Assert.DoesNotContain("64bit Windows Server 2008 R2 v1.0.0 running IIS 7.5", filterSolutionStacks); Assert.Contains("64bit Amazon Linux 2 v0.1.1 running Corretto 11 (BETA)", filterSolutionStacks); Assert.DoesNotContain("64bit Amazon Linux 2 v0.1.0 running Corretto 11 (BETA)", filterSolutionStacks); } [Fact] public void SolutionStackWithNoVersionIsPresent() { var availableSolutionStacks = new List<string> { "64bit Windows Server 2012 R2 v2.4.0 running IIS 8.5", "64bit Windows Server 2012 R2 v2.5.0 running IIS 8.5", "64bit Windows Server 2008 R2 v1.0.0 running IIS 7.5", "64bit Windows Server 2008 R2 v1.1.0 running IIS 7.5", "Special versionless solution", "64bit Windows Server 2008 R2 v1.2.0 running IIS 7.5", "64bit Amazon Linux 2 v0.1.0 running Corretto 11 (BETA)", "64bit Amazon Linux 2 v0.1.1 running Corretto 11 (BETA)" }; var filterSolutionStacks = EBBaseCommand.FilterSolutionStackToLatestVersion(availableSolutionStacks); Assert.Equal(4, filterSolutionStacks.Count); Assert.Contains("Special versionless solution", filterSolutionStacks); Assert.Contains("64bit Windows Server 2012 R2 v2.5.0 running IIS 8.5", filterSolutionStacks); Assert.DoesNotContain("64bit Windows Server 2012 R2 v2.4.0 running IIS 8.5", filterSolutionStacks); Assert.Contains("64bit Windows Server 2008 R2 v1.2.0 running IIS 7.5", filterSolutionStacks); Assert.DoesNotContain("64bit Windows Server 2008 R2 v1.1.0 running IIS 7.5", filterSolutionStacks); Assert.DoesNotContain("64bit Windows Server 2008 R2 v1.0.0 running IIS 7.5", filterSolutionStacks); Assert.Contains("64bit Amazon Linux 2 v0.1.1 running Corretto 11 (BETA)", filterSolutionStacks); Assert.DoesNotContain("64bit Amazon Linux 2 v0.1.0 running Corretto 11 (BETA)", filterSolutionStacks); } [Fact] public void SolutionStackWithInvalidVersionIsPresent() { var availableSolutionStacks = new List<string> { "64bit Windows Server 2012 R2 v2.4.0 running IIS 8.5", "64bit Windows Server 2012 R2 v2.5.0 running IIS 8.5", "64bit Windows Server 2008 R2 v1.0.0 running IIS 7.5", "64bit Windows Server 2008 R2 v1.1.0 running IIS 7.5", "Special versioning v1.Left.Right solution", "64bit Windows Server 2008 R2 v1.2.0 running IIS 7.5", "64bit Amazon Linux 2 v0.1.0 running Corretto 11 (BETA)", "64bit Amazon Linux 2 v0.1.1 running Corretto 11 (BETA)" }; var filterSolutionStacks = EBBaseCommand.FilterSolutionStackToLatestVersion(availableSolutionStacks); Assert.Equal(4, filterSolutionStacks.Count); Assert.Contains("Special versioning v1.Left.Right solution", filterSolutionStacks); Assert.Contains("64bit Windows Server 2012 R2 v2.5.0 running IIS 8.5", filterSolutionStacks); Assert.DoesNotContain("64bit Windows Server 2012 R2 v2.4.0 running IIS 8.5", filterSolutionStacks); Assert.Contains("64bit Windows Server 2008 R2 v1.2.0 running IIS 7.5", filterSolutionStacks); Assert.DoesNotContain("64bit Windows Server 2008 R2 v1.1.0 running IIS 7.5", filterSolutionStacks); Assert.DoesNotContain("64bit Windows Server 2008 R2 v1.0.0 running IIS 7.5", filterSolutionStacks); Assert.Contains("64bit Amazon Linux 2 v0.1.1 running Corretto 11 (BETA)", filterSolutionStacks); Assert.DoesNotContain("64bit Amazon Linux 2 v0.1.0 running Corretto 11 (BETA)", filterSolutionStacks); } } }
124
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; namespace Amazon.ElasticBeanstalk.Tools.Test { public static class TestUtilities { public static string TestBeanstalkWebAppPath { get { var assembly = typeof(TestUtilities).GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestBeanstalkWebApp"); return fullPath; } } } }
23
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Lambda.Model; using Amazon.Lambda.Tools.Commands; using System; using System.IO; using System.Net.Http; using System.Reflection; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; using static Amazon.Lambda.Tools.Integ.Tests.TestConstants; namespace Amazon.Lambda.Tools.Integ.Tests { public class DeployProjectTests { private readonly ITestOutputHelper _testOutputHelper; public DeployProjectTests(ITestOutputHelper testOutputHelper) { this._testOutputHelper = testOutputHelper; } [Fact] public async Task TestSimpleImageProjectTest() { var assembly = this.GetType().GetTypeInfo().Assembly; var toolLogger = new TestToolLogger(_testOutputHelper); var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ImageBasedProjects/TestSimpleImageProject"); var functionName = "test-simple-image-project-" + DateTime.Now.Ticks; var command = new DeployFunctionCommand(toolLogger, fullPath, new string[0]); command.FunctionName = functionName; command.Region = TEST_REGION; command.Role = await TestHelper.GetTestRoleArnAsync(); command.DockerImageTag = $"{TEST_ECR_REPOSITORY}:simpleimageproject1"; command.DisableInteractive = true; var created = await command.ExecuteAsync(); try { Assert.True(created); toolLogger.ClearBuffer(); var invokeCommand = new InvokeFunctionCommand(toolLogger, fullPath, new string[0]); invokeCommand.FunctionName = command.FunctionName; invokeCommand.Payload = "hello world"; invokeCommand.Region = TEST_REGION; await invokeCommand.ExecuteAsync(); // Make sure waiting works. Assert.Contains("... Waiting", toolLogger.Buffer); Assert.Contains("HELLO WORLD", toolLogger.Buffer); // Update function without changing settings. toolLogger.ClearBuffer(); var updateCommand = new DeployFunctionCommand(toolLogger, fullPath, new string[0]); updateCommand.FunctionName = functionName; updateCommand.DisableInteractive = true; updateCommand.Region = TEST_REGION; updateCommand.DockerImageTag = $"{TEST_ECR_REPOSITORY}:simpleimageproject1"; var updated = await updateCommand.ExecuteAsync(); Assert.True(updated); Assert.DoesNotContain("... Waiting", toolLogger.Buffer); toolLogger.ClearBuffer(); invokeCommand = new InvokeFunctionCommand(toolLogger, fullPath, new string[0]); invokeCommand.FunctionName = command.FunctionName; invokeCommand.Payload = "hello world"; invokeCommand.Region = TEST_REGION; await invokeCommand.ExecuteAsync(); Assert.Contains("HELLO WORLD", toolLogger.Buffer); // Update function with changed settings. toolLogger.ClearBuffer(); updateCommand = new DeployFunctionCommand(toolLogger, fullPath, new string[0]); updateCommand.FunctionName = functionName; updateCommand.MemorySize = 1024; updateCommand.DockerImageTag = $"{TEST_ECR_REPOSITORY}:simpleimageproject1"; updateCommand.Region = TEST_REGION; updateCommand.DisableInteractive = true; updated = await updateCommand.ExecuteAsync(); Assert.True(updated); Assert.Contains("... Waiting", toolLogger.Buffer); toolLogger.ClearBuffer(); invokeCommand = new InvokeFunctionCommand(toolLogger, fullPath, new string[0]); invokeCommand.FunctionName = command.FunctionName; invokeCommand.Payload = "hello world"; invokeCommand.Region = TEST_REGION; await invokeCommand.ExecuteAsync(); Assert.Contains("HELLO WORLD", toolLogger.Buffer); } finally { if (created) { try { await command.LambdaClient.DeleteFunctionAsync(command.FunctionName); } catch { } } } } [Fact] public async Task TestMultiStageBuildWithSupportLibrary() { var assembly = this.GetType().GetTypeInfo().Assembly; var toolLogger = new TestToolLogger(_testOutputHelper); var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ImageBasedProjects/MultiStageBuildWithClassLibraries/TheFunction"); var functionName = "test-multistage-with-support-library-" + DateTime.Now.Ticks; var command = new DeployFunctionCommand(toolLogger, fullPath, new string[0]); command.FunctionName = functionName; command.Region = TEST_REGION; command.Role = await TestHelper.GetTestRoleArnAsync(); command.DockerImageTag = $"{TEST_ECR_REPOSITORY}:multistagetest"; command.DisableInteractive = true; var created = await command.ExecuteAsync(); try { Assert.True(created); toolLogger.ClearBuffer(); var invokeCommand = new InvokeFunctionCommand(toolLogger, fullPath, new string[0]); invokeCommand.FunctionName = command.FunctionName; invokeCommand.Region = TEST_REGION; await invokeCommand.ExecuteAsync(); Assert.Contains("Hello from support library", toolLogger.Buffer); } finally { if (created) { await command.LambdaClient.DeleteFunctionAsync(command.FunctionName); } } } [Fact] public async Task PackageFunctionAsLocalImageThenDeploy() { var assembly = this.GetType().GetTypeInfo().Assembly; var toolLogger = new TestToolLogger(_testOutputHelper); var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ImageBasedProjects/TestSimpleImageProject"); var packageCommand = new PackageCommand(toolLogger, fullPath, new string[0]); packageCommand.Region = TEST_REGION; packageCommand.DockerImageTag = $"{TEST_ECR_REPOSITORY}:packageanddeploy1"; packageCommand.DisableInteractive = true; packageCommand.PackageType = "image"; var packageSuccess = await packageCommand.ExecuteAsync(); Assert.True(packageSuccess); Assert.Contains($"Packaged project as image: \"{packageCommand.DockerImageTag}\"", toolLogger.Buffer); Assert.DoesNotContain("Pushing image to ECR repository", toolLogger.Buffer); var functionName = "test-package-then-deploy-" + DateTime.Now.Ticks; toolLogger.ClearBuffer(); var deployCommand = new DeployFunctionCommand(toolLogger, fullPath, new string[0]); deployCommand.FunctionName = functionName; deployCommand.Region = TEST_REGION; deployCommand.Role = await TestHelper.GetTestRoleArnAsync(); deployCommand.LocalDockerImage = packageCommand.DockerImageTag; deployCommand.DisableInteractive = true; var deploySuccess = await deployCommand.ExecuteAsync(); try { Assert.True(deploySuccess); Assert.DoesNotContain("docker build", toolLogger.Buffer); Assert.Contains($"{TEST_ECR_REPOSITORY}:packageanddeploy1 Push Complete.", toolLogger.Buffer); toolLogger.ClearBuffer(); var invokeCommand = new InvokeFunctionCommand(toolLogger, fullPath, new string[0]); invokeCommand.FunctionName = deployCommand.FunctionName; invokeCommand.Payload = "hello world"; invokeCommand.Region = TEST_REGION; await invokeCommand.ExecuteAsync(); // Make sure waiting works. Assert.Contains("... Waiting", toolLogger.Buffer); Assert.Contains("HELLO WORLD", toolLogger.Buffer); } finally { if (deploySuccess) { await deployCommand.LambdaClient.DeleteFunctionAsync(deployCommand.FunctionName); } } } [Fact] public async Task PackageFunctionAsLocalImageThenDeployWithDifferentECRTag() { var assembly = this.GetType().GetTypeInfo().Assembly; var toolLogger = new TestToolLogger(_testOutputHelper); var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ImageBasedProjects/TestSimpleImageProject"); var packageCommand = new PackageCommand(toolLogger, fullPath, new string[0]); packageCommand.Region = TEST_REGION; packageCommand.DockerImageTag = $"{TEST_ECR_REPOSITORY}:packageanddeploywithdifferenttags1"; packageCommand.DisableInteractive = true; packageCommand.PackageType = "image"; var packageSuccess = await packageCommand.ExecuteAsync(); Assert.True(packageSuccess); Assert.Contains($"Packaged project as image: \"{packageCommand.DockerImageTag}\"", toolLogger.Buffer); Assert.DoesNotContain("Pushing image to ECR repository", toolLogger.Buffer); var functionName = "test-package-then-deploy-differenttags-" + DateTime.Now.Ticks; toolLogger.ClearBuffer(); var deployCommand = new DeployFunctionCommand(toolLogger, fullPath, new string[0]); deployCommand.FunctionName = functionName; deployCommand.Region = TEST_REGION; deployCommand.Role = await TestHelper.GetTestRoleArnAsync(); deployCommand.LocalDockerImage = packageCommand.DockerImageTag; deployCommand.DockerImageTag = $"{TEST_ECR_REPOSITORY}:packageanddeploywithdifferenttags2"; deployCommand.DisableInteractive = true; var deploySuccess = await deployCommand.ExecuteAsync(); try { Assert.True(deploySuccess); Assert.DoesNotContain("docker build", toolLogger.Buffer); Assert.Contains($"{TEST_ECR_REPOSITORY}:packageanddeploywithdifferenttags2 Push Complete.", toolLogger.Buffer); toolLogger.ClearBuffer(); var invokeCommand = new InvokeFunctionCommand(toolLogger, fullPath, new string[0]); invokeCommand.FunctionName = deployCommand.FunctionName; invokeCommand.Payload = "hello world"; invokeCommand.Region = TEST_REGION; await invokeCommand.ExecuteAsync(); // Make sure waiting works. Assert.Contains("... Waiting", toolLogger.Buffer); Assert.Contains("HELLO WORLD", toolLogger.Buffer); } finally { if (deploySuccess) { await deployCommand.LambdaClient.DeleteFunctionAsync(deployCommand.FunctionName); } } } [Fact] public async Task SetAndClearEnvironmentVariables() { var toolLogger = new TestToolLogger(_testOutputHelper); var fullPath = Path.GetFullPath(Path.GetDirectoryName(this.GetType().GetTypeInfo().Assembly.Location) + "../../../../../../testapps/TestHttpFunction"); var functionName = "SetAndClearEnvironmentVariables-" + DateTime.Now.Ticks; // Initial deployment with Function Url enabled and Auth will default to NONE. var command = new DeployFunctionCommand(toolLogger, fullPath, new string[0]); command.FunctionName = functionName; command.Role = await TestHelper.GetTestRoleArnAsync(); command.Runtime = "dotnet6"; command.EphemeralStorageSize = 750; command.EnvironmentVariables = new System.Collections.Generic.Dictionary<string, string> { { "Key1", "Value1" } }; command.DisableInteractive = true; var created = await command.ExecuteAsync(); try { Assert.True(created); var getConfigResponse = await command.LambdaClient.GetFunctionConfigurationAsync(functionName); Assert.Equal(750, getConfigResponse.EphemeralStorage.Size); Assert.Single(getConfigResponse.Environment.Variables); // Redeploy changing the ephemeral size and clearning environment variables. command = new DeployFunctionCommand(toolLogger, fullPath, new string[0]); command.FunctionName = functionName; command.Role = await TestHelper.GetTestRoleArnAsync(); command.Runtime = "dotnet6"; command.EphemeralStorageSize = 800; command.EnvironmentVariables = new System.Collections.Generic.Dictionary<string, string> (); command.DisableInteractive = true; created = await command.ExecuteAsync(); Assert.True(created); getConfigResponse = await command.LambdaClient.GetFunctionConfigurationAsync(functionName); Assert.Equal(800, getConfigResponse.EphemeralStorage.Size); Assert.Null(getConfigResponse.Environment); } finally { try { await command.LambdaClient.DeleteFunctionAsync(functionName); } catch { } } } [Fact] public async Task DeployWithFunctionUrl() { using var httpClient = new HttpClient(); var toolLogger = new TestToolLogger(_testOutputHelper); var fullPath = Path.GetFullPath(Path.GetDirectoryName(this.GetType().GetTypeInfo().Assembly.Location) + "../../../../../../testapps/TestHttpFunction"); var functionName = "DeployWithFunctionUrl-" + DateTime.Now.Ticks; async Task TestFunctionUrl(string functionUrl, bool expectSuccess) { var httpResponse = await httpClient.GetAsync(functionUrl); Assert.Equal(expectSuccess, httpResponse.IsSuccessStatusCode); httpResponse.Dispose(); } async Task TestPublicPermissionStatement(IAmazonLambda lambdaClient, bool expectExist) { if(expectExist) { var policy = (await lambdaClient.GetPolicyAsync(new GetPolicyRequest { FunctionName = functionName })).Policy; Assert.Contains(LambdaConstants.FUNCTION_URL_PUBLIC_PERMISSION_STATEMENT_ID, policy); } else { try { var policy = (await lambdaClient.GetPolicyAsync(new GetPolicyRequest { FunctionName = functionName })).Policy; Assert.DoesNotContain(LambdaConstants.FUNCTION_URL_PUBLIC_PERMISSION_STATEMENT_ID, policy); } catch (ResourceNotFoundException) { // If the last statement is deleted from the policy then a ResourceNotFoundException is thrown which is also proof the statement id has been removed. } } } async Task<DeployFunctionCommand> TestDeployProjectAsync(bool? enableUrl, string authType = null) { var command = new DeployFunctionCommand(toolLogger, fullPath, new string[0]); command.FunctionName = functionName; command.Role = await TestHelper.GetTestRoleArnAsync(); command.Runtime = "dotnet6"; command.DisableInteractive = true; if(enableUrl.HasValue) { command.FunctionUrlEnable = enableUrl; } if (authType != null) { command.FunctionUrlAuthType = authType; } var created = await command.ExecuteAsync(); Assert.True(created); await LambdaUtilities.WaitTillFunctionAvailableAsync(toolLogger, command.LambdaClient, functionName); return command; } // Initial deployment with Function Url enabled and Auth will default to NONE. var command = await TestDeployProjectAsync(enableUrl: true); try { // Ensure initial deployment was successful with function URL and NONE authtype Assert.NotNull(command.FunctionUrlLink); var functionUrl = command.FunctionUrlLink; await TestPublicPermissionStatement(command.LambdaClient, expectExist: true); await TestFunctionUrl(functionUrl, expectSuccess: true); // Redeploy without making any changes to FunctionUrl. Make sure we don't unintended remove function url config // when just updating bits. command = await TestDeployProjectAsync(enableUrl: null); await TestPublicPermissionStatement(command.LambdaClient, expectExist: true); await TestFunctionUrl(functionUrl, expectSuccess: true); // Redeploy turning off Function Url command = await TestDeployProjectAsync(enableUrl: false); Assert.Null(command.FunctionUrlLink); await TestPublicPermissionStatement(command.LambdaClient, expectExist: false); await TestFunctionUrl(functionUrl, expectSuccess: false); // Redeploy turning Function Url back on using AWS_IAM. (Not public command = await TestDeployProjectAsync(enableUrl: true, authType: "AWS_IAM"); Assert.NotNull(command.FunctionUrlLink); await TestPublicPermissionStatement(command.LambdaClient, expectExist: false); // Redeploy switching auth to NONE (Public) command = await TestDeployProjectAsync(enableUrl: true, authType: "NONE"); Assert.NotNull(command.FunctionUrlLink); await TestPublicPermissionStatement(command.LambdaClient, expectExist: true); // Redeploy switching back to AWS_IAM and prove public statement removed. command = await TestDeployProjectAsync(enableUrl: true, authType: "AWS_IAM"); Assert.NotNull(command.FunctionUrlLink); await TestPublicPermissionStatement(command.LambdaClient, expectExist: false); } finally { try { await command.LambdaClient.DeleteFunctionAsync(functionName); } catch { } } } } }
442
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.IO; using System.Reflection; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.Common.DotNetCli.Tools.Commands; using Amazon.Lambda.Tools.Commands; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; using static Amazon.Lambda.Tools.Integ.Tests.TestConstants; namespace Amazon.Lambda.Tools.Integ.Tests { public class DeployServerlessTests : IClassFixture<DeployTestFixture> { private readonly ITestOutputHelper _testOutputHelper; private readonly DeployTestFixture _testFixture; public DeployServerlessTests(DeployTestFixture testFixture, ITestOutputHelper testOutputHelper) { this._testFixture = testFixture; this._testOutputHelper = testOutputHelper; } [Fact] public async Task TestImageFunctionServerlessTemplateExamples() { var assembly = this.GetType().GetTypeInfo().Assembly; var toolLogger = new TestToolLogger(_testOutputHelper); var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ImageBasedProjects/ServerlessTemplateExamples"); var command = new PackageCICommand(toolLogger, fullPath, new string[0]); command.Region = TEST_REGION; command.DisableInteractive = true; command.S3Bucket = this._testFixture.Bucket; command.CloudFormationTemplate = "serverless-resource.template"; command.CloudFormationOutputTemplate = Path.GetTempFileName(); var created = await command.ExecuteAsync(); Assert.True(created); var outputRoot = JsonConvert.DeserializeObject(File.ReadAllText(command.CloudFormationOutputTemplate)) as JObject; { var useDefaultDockerFunction = outputRoot["Resources"]["UseDefaultDockerFunction"]["Properties"] as JObject; Assert.Contains("dkr.ecr", useDefaultDockerFunction["ImageUri"]?.ToString()); Assert.Contains("aws-extensions-tests:usedefaultdockerfunction", useDefaultDockerFunction["ImageUri"]?.ToString()); Assert.EndsWith("usedefaultdocker", useDefaultDockerFunction["ImageUri"]?.ToString()); } { var useDockerMetadata = outputRoot["Resources"]["UseDockerMetadataFunction"]["Properties"] as JObject; Assert.Contains("dkr.ecr", useDockerMetadata["ImageUri"]?.ToString()); Assert.Contains("aws-extensions-tests:usedockermetadatafunction", useDockerMetadata["ImageUri"]?.ToString()); Assert.EndsWith("usedockermetadata", useDockerMetadata["ImageUri"]?.ToString()); } } [Fact] public async Task TestMissingImageTagServerlessMetadata() { var assembly = this.GetType().GetTypeInfo().Assembly; var toolLogger = new TestToolLogger(_testOutputHelper); var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ImageBasedProjects/ServerlessTemplateExamples"); var command = new PackageCICommand(toolLogger, fullPath, new string[0]); command.Region = TEST_REGION; command.DisableInteractive = true; command.S3Bucket = this._testFixture.Bucket; command.CloudFormationTemplate = "serverless-function-missing-image-tag.template"; command.CloudFormationOutputTemplate = Path.GetTempFileName(); var created = await command.ExecuteAsync(); Assert.True(created); var outputRoot = JsonConvert.DeserializeObject(File.ReadAllText(command.CloudFormationOutputTemplate)) as JObject; { var useDefaultDockerFunction = outputRoot["Resources"]["UseDockerMetadataFunction"]["Properties"] as JObject; Assert.Contains("dkr.ecr", useDefaultDockerFunction["ImageUri"]?.ToString()); Assert.Contains("aws-extensions-tests:usedockermetadatafunction", useDefaultDockerFunction["ImageUri"]?.ToString()); Assert.EndsWith("usedockermetadata", useDefaultDockerFunction["ImageUri"]?.ToString()); } } [Fact] public async Task TestMissingDockerFileServerlessMetadata() { var assembly = this.GetType().GetTypeInfo().Assembly; var toolLogger = new TestToolLogger(_testOutputHelper); var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ImageBasedProjects/ServerlessTemplateExamples"); var command = new PackageCICommand(toolLogger, fullPath, new string[0]); command.Region = TEST_REGION; command.DisableInteractive = true; command.S3Bucket = this._testFixture.Bucket; command.CloudFormationTemplate = "serverless-function-missing-dockerfile.template"; command.CloudFormationOutputTemplate = Path.GetTempFileName(); var created = await command.ExecuteAsync(); Assert.False(created); Assert.Contains("Error failed to find file ", toolLogger.Buffer); } [Fact] public async Task TestLambdaResource() { var assembly = this.GetType().GetTypeInfo().Assembly; var toolLogger = new TestToolLogger(_testOutputHelper); var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ImageBasedProjects/ServerlessTemplateExamples"); var command = new PackageCICommand(toolLogger, fullPath, new string[0]); command.Region = TEST_REGION; command.DisableInteractive = true; command.S3Bucket = this._testFixture.Bucket; command.CloudFormationTemplate = "lambda-resource.template"; command.CloudFormationOutputTemplate = Path.GetTempFileName(); var created = await command.ExecuteAsync(); Assert.True(created); var outputRoot = JsonConvert.DeserializeObject(File.ReadAllText(command.CloudFormationOutputTemplate)) as JObject; { var useDefaultDockerFunction = outputRoot["Resources"]["UseDefaultDockerLambdaFunction"]["Properties"] as JObject; Assert.Contains("dkr.ecr", useDefaultDockerFunction["Code"]["ImageUri"]?.ToString()); Assert.Contains("aws-extensions-tests:usedefaultdocker", useDefaultDockerFunction["Code"]["ImageUri"]?.ToString()); } } [Fact] public async Task TestDockerBuildArgsMetadataJsonTemplate() { var assembly = this.GetType().GetTypeInfo().Assembly; var toolLogger = new TestToolLogger(_testOutputHelper); var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ImageBasedProjects/ServerlessTemplateExamples"); var command = new PackageCICommand(toolLogger, fullPath, new string[0]); command.Region = TEST_REGION; command.DisableInteractive = true; command.S3Bucket = this._testFixture.Bucket; command.CloudFormationTemplate = "serverless-resource-dockerbuildargs-json.template"; command.CloudFormationOutputTemplate = Path.GetTempFileName(); var created = await command.ExecuteAsync(); Assert.True(created); Assert.Contains("--build-arg PROJECT_PATH=/src/path-to/project", toolLogger.Buffer); Assert.Contains("--build-arg PROJECT_FILE=project.csproj", toolLogger.Buffer); } [Fact] public async Task TestDockerBuildArgsMetadataYamlTemplate() { var assembly = this.GetType().GetTypeInfo().Assembly; var toolLogger = new TestToolLogger(_testOutputHelper); var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ImageBasedProjects/ServerlessTemplateExamples"); var command = new PackageCICommand(toolLogger, fullPath, new string[0]); command.Region = TEST_REGION; command.DisableInteractive = true; command.S3Bucket = this._testFixture.Bucket; command.CloudFormationTemplate = "serverless-resource-dockerbuildargs-yaml.template"; command.CloudFormationOutputTemplate = Path.GetTempFileName(); var created = await command.ExecuteAsync(); Assert.True(created); Assert.Contains("--build-arg PROJECT_PATH=/src/path-to/project", toolLogger.Buffer); Assert.Contains("--build-arg PROJECT_FILE=project.csproj", toolLogger.Buffer); } [Fact] public async Task TestDeployServerlessECRImageUriNoMetadataYamlTemplate() { var assembly = this.GetType().GetTypeInfo().Assembly; var toolLogger = new TestToolLogger(_testOutputHelper); var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ImageBasedProjects/TestSimpleImageProject"); var pushImageCommand = new PushDockerImageCommand(toolLogger, fullPath, new string[0]) { DisableInteractive = true, Region = TEST_REGION, WorkingDirectory = fullPath, SkipPushToECR = false, PushDockerImageProperties = new BasePushDockerImageCommand<LambdaToolsDefaults>.PushDockerImagePropertyContainer { DockerImageTag = $"{TEST_ECR_REPOSITORY}:deployserverlessimageurinometadata", } }; var pushImageResult = await pushImageCommand.ExecuteAsync(); Assert.Contains("Pushing image to ECR repository", toolLogger.Buffer); Assert.Contains($"{TEST_ECR_REPOSITORY}:deployserverlessimageurinometadata Push Complete.", toolLogger.Buffer); string functionName = $"HelloWorldFunction{DateTime.Now.Ticks}"; string yamlTemplate = @$" AWSTemplateFormatVersion: 2010-09-09 Transform: 'AWS::Serverless-2016-10-31' Description: An AWS Serverless Application. Resources: {functionName}: Type: 'AWS::Serverless::Function' Properties: FunctionName: {functionName} MemorySize: 256 Timeout: 30 Policies: - AWSLambdaBasicExecutionRole PackageType: Image ImageUri: {pushImageCommand.PushedImageUri} ImageConfig: Command: ['TestSimpleImageProject::TestSimpleImageProject.Function::FunctionHandler'] Outputs: {{}} "; var tempFileName = Path.GetTempFileName(); File.WriteAllText(tempFileName, yamlTemplate); var deployServerlessCommand = new DeployServerlessCommand(toolLogger, fullPath, new string[] { "--template", tempFileName }); deployServerlessCommand.DisableInteractive = true; deployServerlessCommand.Region = TEST_REGION; deployServerlessCommand.Configuration = "Release"; deployServerlessCommand.StackName = functionName; deployServerlessCommand.S3Bucket = this._testFixture.Bucket; deployServerlessCommand.WaitForStackToComplete = true; var created = false; try { created = await deployServerlessCommand.ExecuteAsync(); Assert.True(created); using (var cfClient = new AmazonCloudFormationClient(RegionEndpoint.GetBySystemName(TEST_REGION))) { var describeResponse = await cfClient.DescribeStacksAsync(new DescribeStacksRequest { StackName = deployServerlessCommand.StackName }); Assert.Equal(StackStatus.CREATE_COMPLETE, describeResponse.Stacks[0].StackStatus); } toolLogger.ClearBuffer(); var invokeCommand = new InvokeFunctionCommand(toolLogger, fullPath, new string[0]); invokeCommand.FunctionName = functionName; invokeCommand.Payload = "hello world"; invokeCommand.Region = TEST_REGION; await invokeCommand.ExecuteAsync(); Assert.Contains("HELLO WORLD", toolLogger.Buffer); } finally { if (created) { try { var deleteCommand = new DeleteServerlessCommand(toolLogger, fullPath, new string[0]); deleteCommand.StackName = deployServerlessCommand.StackName; deleteCommand.Region = TEST_REGION; await deleteCommand.ExecuteAsync(); } catch { // Bury exception because we don't want to lose any exceptions during the deploy stage. } } File.Delete(tempFileName); } } [Fact] public async Task TestDeployServerlessECRImageUriNoMetadataJsonTemplate() { var assembly = this.GetType().GetTypeInfo().Assembly; var toolLogger = new TestToolLogger(_testOutputHelper); var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ImageBasedProjects/TestSimpleImageProject"); var pushImageCommand = new PushDockerImageCommand(toolLogger, fullPath, new string[0]) { DisableInteractive = true, Region = TEST_REGION, WorkingDirectory = fullPath, SkipPushToECR = false, PushDockerImageProperties = new BasePushDockerImageCommand<LambdaToolsDefaults>.PushDockerImagePropertyContainer { DockerImageTag = $"{TEST_ECR_REPOSITORY}:deployserverlessimageurinometadata", } }; var pushImageResult = await pushImageCommand.ExecuteAsync(); Assert.Contains("Pushing image to ECR repository", toolLogger.Buffer); Assert.Contains($"{TEST_ECR_REPOSITORY}:deployserverlessimageurinometadata Push Complete.", toolLogger.Buffer); string functionName = $"HelloWorldFunction{DateTime.Now.Ticks}"; string jsonTemplate = @$" {{ ""AWSTemplateFormatVersion"": ""2010-09-09"", ""Transform"": ""AWS::Serverless-2016-10-31"", ""Description"": ""An AWS Serverless Application."", ""Resources"": {{ ""{functionName}"": {{ ""Type"": ""AWS::Serverless::Function"", ""Properties"": {{ ""FunctionName"": ""{functionName}"", ""MemorySize"": 256, ""Timeout"": 30, ""Policies"": [ ""AWSLambdaBasicExecutionRole"" ], ""PackageType"": ""Image"", ""ImageUri"": ""{pushImageCommand.PushedImageUri}"", ""ImageConfig"": {{ ""Command"": [ ""TestSimpleImageProject::TestSimpleImageProject.Function::FunctionHandler"" ] }} }} }} }}, ""Outputs"": {{}} }} "; var tempFileName = Path.GetTempFileName(); File.WriteAllText(tempFileName, jsonTemplate); var deployServerlessCommand = new DeployServerlessCommand(toolLogger, fullPath, new string[] { "--template", tempFileName }); deployServerlessCommand.DisableInteractive = true; deployServerlessCommand.Region = TEST_REGION; deployServerlessCommand.Configuration = "Release"; deployServerlessCommand.StackName = functionName; deployServerlessCommand.S3Bucket = this._testFixture.Bucket; deployServerlessCommand.WaitForStackToComplete = true; var created = false; try { created = await deployServerlessCommand.ExecuteAsync(); Assert.True(created); using (var cfClient = new AmazonCloudFormationClient(RegionEndpoint.GetBySystemName(TEST_REGION))) { var describeResponse = await cfClient.DescribeStacksAsync(new DescribeStacksRequest { StackName = deployServerlessCommand.StackName }); Assert.Equal(StackStatus.CREATE_COMPLETE, describeResponse.Stacks[0].StackStatus); } toolLogger.ClearBuffer(); var invokeCommand = new InvokeFunctionCommand(toolLogger, fullPath, new string[0]); invokeCommand.FunctionName = functionName; invokeCommand.Payload = "hello world"; invokeCommand.Region = TEST_REGION; await invokeCommand.ExecuteAsync(); Assert.Contains("HELLO WORLD", toolLogger.Buffer); } finally { if (created) { try { var deleteCommand = new DeleteServerlessCommand(toolLogger, fullPath, new string[0]); deleteCommand.StackName = deployServerlessCommand.StackName; deleteCommand.Region = TEST_REGION; await deleteCommand.ExecuteAsync(); } catch { // Bury exception because we don't want to lose any exceptions during the deploy stage. } } File.Delete(tempFileName); } } } }
392
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.S3; using Amazon.S3.Util; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Amazon.Lambda.Tools.Integ.Tests { public class DeployTestFixture : IDisposable { public string Bucket { get; set; } public IAmazonS3 S3Client { get; set; } public DeployTestFixture() { this.S3Client = new AmazonS3Client(RegionEndpoint.GetBySystemName(TestConstants.TEST_REGION)); this.Bucket = "dotnet-lambda-tests-" + DateTime.Now.Ticks; S3Client.PutBucketAsync(this.Bucket).GetAwaiter().GetResult(); } private bool disposedValue; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { AmazonS3Util.DeleteS3BucketWithObjectsAsync(this.S3Client, this.Bucket).GetAwaiter().GetResult(); this.S3Client.Dispose(); } disposedValue = true; } } public void Dispose() { Dispose(true); } } }
46
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; namespace Amazon.Lambda.Tools.Integ.Tests { public static class TestConstants { public const string TEST_REGION = "us-west-2"; public const string TEST_ECR_REPOSITORY = "aws-extensions-tests"; } }
14
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using Amazon.Common.DotNetCli.Tools; using Amazon.Lambda.Tools.Commands; namespace Amazon.Lambda.Tools.Integ.Tests { public static class TestHelper { const string LAMBDATOOL_TEST_ROLE = "dotnet-lambdatools-test-role"; private static string _roleArn; private static IAmazonIdentityManagementService _iamClient = new AmazonIdentityManagementServiceClient(Amazon.RegionEndpoint.USEast1); static SemaphoreSlim roleLock = new SemaphoreSlim(1, 1); public static async Task<string> GetTestRoleArnAsync() { await roleLock.WaitAsync(TimeSpan.FromMinutes(5)); try { if (!string.IsNullOrEmpty(_roleArn)) return _roleArn; try { _roleArn = (await _iamClient.GetRoleAsync(new GetRoleRequest { RoleName = LAMBDATOOL_TEST_ROLE })).Role.Arn; } catch (Exception e) { if (e is NoSuchEntityException || e.InnerException is NoSuchEntityException) { // Role is not found so create a role with no permissions other then Lambda can assume the role. // The role is deleted and reused in other runs of the test to make the test run faster. _roleArn = RoleHelper.CreateRole(_iamClient, LAMBDATOOL_TEST_ROLE, Constants.LAMBDA_ASSUME_ROLE_POLICY, "arn:aws:iam::aws:policy/PowerUserAccess"); // Wait for new role to propogate await Task.Delay(5000); } else { throw; } } return _roleArn; } finally { roleLock.Release(); } } public static async Task<string> GetPhysicalCloudFormationResourceId(IAmazonCloudFormation cfClient, string stackName, string logicalId) { var response = await cfClient.DescribeStackResourcesAsync(new DescribeStackResourcesRequest() { StackName = stackName, LogicalResourceId = logicalId }); foreach (var resource in response.StackResources) { if (string.Equals(resource.LogicalResourceId, logicalId, StringComparison.OrdinalIgnoreCase)) { return resource.PhysicalResourceId; } } return null; } public static async Task<string> GetOutputParameter(IAmazonCloudFormation cfClient, string stackName, string outputName) { var response = await cfClient.DescribeStacksAsync(new DescribeStacksRequest() { StackName = stackName }); foreach (var output in response.Stacks[0].Outputs) { if (string.Equals(output.OutputKey, outputName, StringComparison.OrdinalIgnoreCase)) { return output.OutputValue; } } return null; } } }
101
aws-extensions-for-dotnet-cli
aws
C#
using System.Text; using Xunit.Abstractions; using Amazon.Common.DotNetCli.Tools; namespace Amazon.Lambda.Tools.Integ.Tests { public class TestToolLogger : IToolLogger { private readonly ITestOutputHelper _testOutputHelper; StringBuilder _buffer = new StringBuilder(); public TestToolLogger(ITestOutputHelper testOutputHelper) { _testOutputHelper = testOutputHelper; } public void WriteLine(string message) { this._buffer.AppendLine(message); _testOutputHelper?.WriteLine(message); } public void WriteLine(string message, params object[] args) { this.WriteLine(string.Format(message, args)); } public void ClearBuffer() { this._buffer.Clear(); } public string Buffer { get { return this._buffer.ToString(); } } } }
38
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO.Compression; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Moq; using Xunit; using Xunit.Abstractions; using Amazon.Lambda; using Amazon.Lambda.Model; using Amazon.Lambda.Tools; using Amazon.Lambda.Tools.Commands; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Amazon.S3.Util; using Amazon.S3.Transfer; namespace Amazon.Lambda.Tools.Test { [Collection("ARM Tests")] public class ArmTests { private readonly ITestOutputHelper _testOutputHelper; public ArmTests(ITestOutputHelper testOutputHelper) { this._testOutputHelper = testOutputHelper; } [Fact] public async Task RunDeployCommand() { var mockClient = new Mock<IAmazonLambda>(); mockClient.Setup(client => client.CreateFunctionAsync(It.IsAny<CreateFunctionRequest>(), It.IsAny<CancellationToken>())) .Callback<CreateFunctionRequest, CancellationToken>((request, token) => { Assert.Single(request.Architectures); Assert.Equal(Architecture.Arm64, request.Architectures[0]); Assert.Equal("linux-arm64", GetRuntimeFromBundle(request.Code.ZipFile)); }) .Returns((CreateFunctionRequest r, CancellationToken token) => { return Task.FromResult(new CreateFunctionResponse()); }); var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestFunction"); var command = new DeployFunctionCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); command.FunctionName = "test-function-" + DateTime.Now.Ticks; command.Handler = "TestFunction::TestFunction.Function::ToUpper"; command.Timeout = 10; command.MemorySize = 512; command.Role = await TestHelper.GetTestRoleArnAsync(); command.Configuration = "Release"; command.Runtime = "dotnet6"; command.Architecture = LambdaConstants.ARCHITECTURE_ARM64; command.DisableInteractive = true; command.LambdaClient = mockClient.Object; var created = await command.ExecuteAsync(); Assert.True(created); } [Fact] public async Task CreateArmPackage() { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestFunction"); var command = new PackageCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); command.DisableInteractive = true; command.Architecture = LambdaConstants.ARCHITECTURE_ARM64; command.OutputPackageFileName = Path.GetTempFileName(); var created = await command.ExecuteAsync(); Assert.True(created); Assert.Equal("linux-arm64", GetRuntimeFromBundle(command.OutputPackageFileName)); File.Delete(command.OutputPackageFileName); } [Fact] public async Task TestServerlessPackage() { var logger = new TestToolLogger(_testOutputHelper); var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestServerlessWebApp"); var command = new PackageCICommand(logger, fullPath, new string[0]); command.Region = "us-west-2"; command.Configuration = "Release"; command.CloudFormationTemplate = "serverless-arm.template"; command.CloudFormationOutputTemplate = Path.Combine(Path.GetTempPath(), "output-serverless-arm.template"); command.S3Bucket = "serverless-package-test-" + DateTime.Now.Ticks; command.DisableInteractive = true; if (File.Exists(command.CloudFormationOutputTemplate)) File.Delete(command.CloudFormationOutputTemplate); await command.S3Client.PutBucketAsync(command.S3Bucket); try { Assert.True(await command.ExecuteAsync()); Assert.True(File.Exists(command.CloudFormationOutputTemplate)); var templateJson = File.ReadAllText(command.CloudFormationOutputTemplate); var templateRoot = JsonConvert.DeserializeObject(templateJson) as JObject; var codeUri = templateRoot["Resources"]["DefaultFunction"]["Properties"]["CodeUri"].ToString(); Assert.False(string.IsNullOrEmpty(codeUri)); var s3Key = codeUri.Split('/').Last(); var transfer = new TransferUtility(command.S3Client); var functionZipPath = Path.GetTempFileName(); await transfer.DownloadAsync(functionZipPath, command.S3Bucket, s3Key); Assert.Equal("linux-arm64", GetRuntimeFromBundle(functionZipPath)); File.Delete(functionZipPath); } finally { await AmazonS3Util.DeleteS3BucketWithObjectsAsync(command.S3Client, command.S3Bucket); } } [Fact] public async Task TestServerlessPackageWithGlobalArchitectures() { var logger = new TestToolLogger(_testOutputHelper); var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestServerlessWebApp"); var command = new PackageCICommand(logger, fullPath, new string[0]); command.Region = "us-west-2"; command.Configuration = "Release"; command.CloudFormationTemplate = "serverless-global-arm.template"; command.CloudFormationOutputTemplate = Path.Combine(Path.GetTempPath(), "output-serverless-global--arm.template"); command.S3Bucket = "serverless-package-test-" + DateTime.Now.Ticks; command.DisableInteractive = true; if (File.Exists(command.CloudFormationOutputTemplate)) File.Delete(command.CloudFormationOutputTemplate); await command.S3Client.PutBucketAsync(command.S3Bucket); try { if(!await command.ExecuteAsync()) { throw new Exception("Failed to publish:\n" + logger.Buffer, command.LastToolsException); } Assert.True(File.Exists(command.CloudFormationOutputTemplate)); var templateJson = File.ReadAllText(command.CloudFormationOutputTemplate); var templateRoot = JsonConvert.DeserializeObject(templateJson) as JObject; var codeUri = templateRoot["Resources"]["DefaultFunction"]["Properties"]["CodeUri"].ToString(); Assert.False(string.IsNullOrEmpty(codeUri)); var s3Key = codeUri.Split('/').Last(); var transfer = new TransferUtility(command.S3Client); var functionZipPath = Path.GetTempFileName(); await transfer.DownloadAsync(functionZipPath, command.S3Bucket, s3Key); Assert.Equal("linux-arm64", GetRuntimeFromBundle(functionZipPath)); File.Delete(functionZipPath); } finally { await AmazonS3Util.DeleteS3BucketWithObjectsAsync(command.S3Client, command.S3Bucket); } } private string GetRuntimeFromBundle(string filePath) { using (var stream = File.OpenRead(filePath)) { return GetRuntimeFromBundle(stream); } } private string GetRuntimeFromBundle(Stream stream) { var zipArchive = new ZipArchive(stream, ZipArchiveMode.Read); var depsJsonEntry = zipArchive.Entries.FirstOrDefault(x => x.Name.EndsWith(".deps.json")); var json = new StreamReader(depsJsonEntry.Open()).ReadToEnd(); var jobj = JsonConvert.DeserializeObject(json) as JObject; var runtimeTaget = jobj["runtimeTarget"] as JObject; var name = runtimeTaget["name"].ToString(); return name.Split('/')[1]; } } }
208
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Xunit; using Amazon.Lambda.Tools.Commands; namespace Amazon.Lambda.Tools.Test { public class CommandLineParserTest { [Fact] public void SingleStringArgument() { Action<CommandOptions> validation = x => { Assert.Equal(1, x.Count); var option = x.FindCommandOption("-c"); Assert.Equal("Release", option.Item2.StringValue); }; var values = CommandLineParser.ParseArguments(DeployFunctionCommand.DeployCommandOptions, new string[] {"-c", "Release" }); validation(values); values = CommandLineParser.ParseArguments(DeployFunctionCommand.DeployCommandOptions, new string[] { "--configuration", "Release" }); validation(values); } [Fact] public void SingleIntArgument() { Action<CommandOptions> validation = x => { Assert.Equal(1, x.Count); var option = x.FindCommandOption("-ft"); Assert.Equal(100, option.Item2.IntValue); }; var values = CommandLineParser.ParseArguments(DeployFunctionCommand.DeployCommandOptions, new string[] { "-ft", "100" }); validation(values); values = CommandLineParser.ParseArguments(DeployFunctionCommand.DeployCommandOptions, new string[] { "--function-timeout", "100" }); validation(values); } [Fact] public void SingleBoolArgument() { Action<CommandOptions> validation = x => { Assert.Equal(1, x.Count); var option = x.FindCommandOption("-fp"); Assert.Equal(true, option.Item2.BoolValue); }; var values = CommandLineParser.ParseArguments(DeployFunctionCommand.DeployCommandOptions, new string[] { "-fp", "true" }); validation(values); values = CommandLineParser.ParseArguments(DeployFunctionCommand.DeployCommandOptions, new string[] { "--function-publish", "true" }); validation(values); } [Fact] public void BuildLambdaDeployCommandWithAllArguments() { var arguments = new List<string>(); arguments.AddRange(new string[] { "-c", "CrazyRelease" }); arguments.AddRange(new string[] { "-f", "netfake" }); arguments.AddRange(new string[] { "--function-name", "MyName" }); arguments.AddRange(new string[] { "--function-description", "MyDescription" }); arguments.AddRange(new string[] { "--function-publish", "true" }); arguments.AddRange(new string[] { "--function-handler", "TheHandler" }); arguments.AddRange(new string[] { "--function-memory-size", "33" }); arguments.AddRange(new string[] { "--function-role", "MyRole" }); arguments.AddRange(new string[] { "--function-timeout", "55" }); arguments.AddRange(new string[] { "--function-runtime", "netcore9.9" }); var command = new DeployFunctionCommand(new ConsoleToolLogger(), ".", arguments.ToArray()); Assert.Equal("CrazyRelease", command.Configuration); Assert.Equal("netfake", command.TargetFramework); Assert.Equal("MyName", command.FunctionName); Assert.Equal("MyDescription", command.Description); Assert.Equal(true, command.Publish); Assert.Equal(33, command.MemorySize); Assert.Equal("MyRole", command.Role); Assert.Equal(55, command.Timeout); Assert.Equal("netcore9.9", command.Runtime); } } }
98
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.IO; using System.Linq; using System.Net; using System.Xml.Linq; using System.Xml.XPath; using Xunit; namespace Amazon.Lambda.Tools.Test { public class ConvertLayerManifestTests { [Fact] public void CheckIfWebProject() { var originalContent = "<Project Sdk=\"Microsoft.NET.Sdk.Web\"></Project>"; var result = LambdaUtilities.ConvertManifestContentToSdkManifest("netcoreapp2.1",originalContent); Assert.True(result.Updated); Assert.False(object.ReferenceEquals(originalContent, result.UpdatedContent)); originalContent = "<Project Sdk=\"Microsoft.NET.Sdk\"></Project>"; result = LambdaUtilities.ConvertManifestContentToSdkManifest("netcoreapp2.1", "<Project Sdk=\"Microsoft.NET.Sdk\"></Project>"); Assert.False(result.Updated); Assert.True(object.ReferenceEquals(originalContent, result.UpdatedContent)); } [Fact] public void ConvertAspNetCoreProject() { var testManifest = File.ReadAllText("./TestFiles/ManifestAspNetCoreProject.xml"); var result = LambdaUtilities.ConvertManifestContentToSdkManifest("netcoreapp2.1",testManifest); Assert.True(result.Updated); Assert.False(object.ReferenceEquals(testManifest, result.UpdatedContent)); var xmlDoc = XDocument.Parse(result.UpdatedContent); Assert.Equal("Microsoft.NET.Sdk", xmlDoc.Root.Attribute("Sdk")?.Value); var packageReferences = xmlDoc.XPathSelectElements("//ItemGroup/PackageReference").ToList(); Func<string, XElement> findRef = (name) => { return packageReferences.FirstOrDefault(x => string.Equals(name, x.Attribute("Include")?.Value, StringComparison.OrdinalIgnoreCase)); }; var netCoreAppRef = packageReferences.FirstOrDefault(x => string.Equals("Microsoft.NETCore.App", x.Attribute("Update")?.Value, StringComparison.OrdinalIgnoreCase)); Assert.NotNull(netCoreAppRef); Assert.Equal("false", netCoreAppRef.Attribute("Publish")?.Value); Assert.NotNull(findRef("Microsoft.AspNetCore.App")); Assert.NotNull(findRef("Amazon.Lambda.AspNetCoreServer")); Assert.NotNull(findRef("AWSSDK.S3")); Assert.NotNull(findRef("AWSSDK.Extensions.NETCore.Setup")); } [Fact] public void Convert31SDKProjectToManifest() { var originalContent = "<Project Sdk=\"Microsoft.NET.Sdk\"></Project>"; var result = LambdaUtilities.ConvertManifestContentToSdkManifest("netcoreapp3.1", originalContent); Assert.True(result.Updated); Assert.Contains("<Project Sdk=\"Microsoft.NET.Sdk\">", result.UpdatedContent); Assert.Contains("<PackagesToPrune Include=\"Microsoft.CSharp\" />", result.UpdatedContent); Assert.DoesNotContain("Microsoft.AspNetCore.App", result.UpdatedContent); } [Fact] public void Convert31SDKWebProjectToManifest() { var originalContent = "<Project Sdk=\"Microsoft.NET.Sdk.Web\"></Project>"; var result = LambdaUtilities.ConvertManifestContentToSdkManifest("netcoreapp3.1", originalContent); Assert.True(result.Updated); Assert.Contains("<Project Sdk=\"Microsoft.NET.Sdk\">", result.UpdatedContent); Assert.Contains("<PackagesToPrune Include=\"Microsoft.CSharp\" />", result.UpdatedContent); Assert.Contains("Microsoft.AspNetCore.App", result.UpdatedContent); } } }
86
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace Amazon.Lambda.Tools.Test { public class ConvertToMapOfFilesTests { [Theory] [InlineData("app.js")] [InlineData("./app.js")] [InlineData("dir/app.js")] [InlineData("./dir/app.js")] public void FileCombinations(string file) { var files = LambdaPackager.ConvertToMapOfFiles(GetTestRoot(), new string[] { file }); Assert.Single(files); Assert.True(files.ContainsKey(file)); Assert.Equal($"{GetTestRoot()}/{file}", files[file]); } [Theory] [InlineData("app.js")] [InlineData("./app.js")] [InlineData("dir/app.js")] [InlineData("./dir/app.js")] public void RootPathWithTrailingSlash(string file) { var files = LambdaPackager.ConvertToMapOfFiles(GetTestRoot() + "/", new string[] { file }); Assert.Single(files); Assert.True(files.ContainsKey(file)); Assert.Equal($"{GetTestRoot()}/{file}", files[file]); } public static string GetTestRoot() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return @"c:/temp"; return "/home/norm/temp"; } } }
53
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Linq; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.Model; using Amazon.Lambda.Tools.Commands; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using Amazon.SQS; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.Common.DotNetCli.Tools; using Xunit.Abstractions; namespace Amazon.Lambda.Tools.Test { public class DeployTest : IClassFixture<DeployTestFixture> { private readonly ITestOutputHelper _testOutputHelper; DeployTestFixture _testFixture; public DeployTest(DeployTestFixture testFixture, ITestOutputHelper testOutputHelper) { this._testFixture = testFixture; this._testOutputHelper = testOutputHelper; } [Fact] public async Task RunDeploymentBuildWithUseContainer() { if (string.Equals(System.Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"), "true", StringComparison.OrdinalIgnoreCase)) { _testOutputHelper.WriteLine("Skipping container build test because test is already running inside a container"); return; } var assembly = this.GetType().GetTypeInfo().Assembly; string expectedValue = "HELLO WORLD"; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + $"../../../../../../testapps/TestFunction"); if (Directory.Exists(fullPath + "/bin/")) { Directory.Delete(fullPath + "/bin/", true); } if (Directory.Exists(fullPath + "/obj/")) { Directory.Delete(fullPath + "/obj/", true); } var command = new DeployFunctionCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); command.FunctionName = "test-function-" + DateTime.Now.Ticks; command.Handler = "TestFunction::TestFunction.Function::ToUpper"; command.Timeout = 10; command.MemorySize = 512; command.Role = await TestHelper.GetTestRoleArnAsync(); command.Configuration = "Release"; command.Runtime = "dotnet6"; command.DisableInteractive = true; command.UseContainerForBuild = true; bool created = false; try { created = await command.ExecuteAsync(); Assert.True(created); await LambdaUtilities.WaitTillFunctionAvailableAsync(new TestToolLogger(_testOutputHelper), command.LambdaClient, command.FunctionName); var invokeRequest = new InvokeRequest { FunctionName = command.FunctionName, LogType = LogType.Tail, Payload = "\"hello world\"" }; var response = await command.LambdaClient.InvokeAsync(invokeRequest); var payload = new StreamReader(response.Payload).ReadToEnd(); Assert.Equal($"\"{expectedValue}\"", payload); // Check that the package size isn't too big which implies stripping the binary worked. var getFunctionRequest = new GetFunctionRequest { FunctionName = command.FunctionName }; GetFunctionResponse getFunctionResponse = await command.LambdaClient.GetFunctionAsync(getFunctionRequest); var codeSize = getFunctionResponse.Configuration.CodeSize; Assert.True(codeSize < 10000000, $"Code size is {codeSize}, which is larger than expected 10000000 bytes (10MB), check that trimming and stripping worked as expected."); } finally { if (created) { await command.LambdaClient.DeleteFunctionAsync(command.FunctionName); } } } [Theory] [InlineData(true, false)] [InlineData(false, false)] [InlineData(true, true)] // [InlineData(false, true)] Ignored since each of these takes over 2 minutes. public async Task RunDeploymentNativeAot(bool multipleProjects, bool customMountLocation) { if (string.Equals(System.Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"), "true", StringComparison.OrdinalIgnoreCase)) { _testOutputHelper.WriteLine("Skipping container build test because test is already running inside a container"); return; } var assembly = this.GetType().GetTypeInfo().Assembly; string expectedValue = multipleProjects ? "MYTEST: HELLO WORLD" : "HELLO WORLD"; var projectLocation = multipleProjects ? "TestNativeAotMultipleProjects/EntryPoint" : "TestNativeAotSingleProject"; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + $"../../../../../../testapps/{projectLocation}"); if (Directory.Exists(fullPath + "/bin/")) { Directory.Delete(fullPath + "/bin/", true); } if (Directory.Exists(fullPath + "/obj/")) { Directory.Delete(fullPath + "/obj/", true); } var command = new DeployFunctionCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); command.FunctionName = "test-function-" + DateTime.Now.Ticks; command.Handler = "ThisDoesntApply"; command.Timeout = 10; command.MemorySize = 512; command.Role = await TestHelper.GetTestRoleArnAsync(); command.Configuration = "Release"; command.TargetFramework = "net7.0"; command.Runtime = "provided.al2"; command.DisableInteractive = true; if (customMountLocation) { command.CodeMountDirectory = "../"; // To test full path the following (skipped to save time): Path.GetFullPath(Path.Combine(fullPath, "../")); } bool created = false; try { created = await command.ExecuteAsync(); Assert.True(created); await LambdaUtilities.WaitTillFunctionAvailableAsync(new TestToolLogger(_testOutputHelper), command.LambdaClient, command.FunctionName); var invokeRequest = new InvokeRequest { FunctionName = command.FunctionName, LogType = LogType.Tail, Payload = "\"hello world\"" }; var response = await command.LambdaClient.InvokeAsync(invokeRequest); var payload = new StreamReader(response.Payload).ReadToEnd(); Assert.Equal($"\"{expectedValue}\"", payload); // Check that the package size isn't too big which implies stripping the binary worked. var getFunctionRequest = new GetFunctionRequest { FunctionName = command.FunctionName }; GetFunctionResponse getFunctionResponse = await command.LambdaClient.GetFunctionAsync(getFunctionRequest); var codeSize = getFunctionResponse.Configuration.CodeSize; Assert.True(codeSize < 10000000, $"Code size is {codeSize}, which is larger than expected 10000000 bytes (10MB), check that trimming and stripping worked as expected."); } finally { if (created) { await command.LambdaClient.DeleteFunctionAsync(command.FunctionName); } } } [Theory] [InlineData(TargetFrameworkMonikers.net60)] [InlineData(TargetFrameworkMonikers.netcoreapp31)] [InlineData(TargetFrameworkMonikers.netcoreapp21)] [InlineData(TargetFrameworkMonikers.netcoreapp20)] [InlineData(TargetFrameworkMonikers.netcoreapp10)] public async Task NativeAotThrowsBeforeNet7(string targetFramework) { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + $"../../../../../../testapps/TestNativeAotSingleProject"); var testLogger = new TestToolLogger(_testOutputHelper); var command = new DeployFunctionCommand(testLogger, fullPath, new string[0]); command.FunctionName = "test-function-" + DateTime.Now.Ticks; command.Handler = "ThisDoesntApply"; command.Timeout = 10; command.MemorySize = 512; command.Role = await TestHelper.GetTestRoleArnAsync(); command.Configuration = "Release"; command.TargetFramework = targetFramework; command.Runtime = "provided.al2"; command.DisableInteractive = true; bool created = false; try { created = await command.ExecuteAsync(); Assert.False(created); Assert.Contains($"Can't use native AOT with target framework less than net7.0, however, provided target framework is {targetFramework}", testLogger.Buffer); } finally { if (created) { await command.LambdaClient.DeleteFunctionAsync(command.FunctionName); } } } [Fact] public async Task RunDeployCommand() { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestFunction"); var command = new DeployFunctionCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); command.FunctionName = "test-function-" + DateTime.Now.Ticks; command.Handler = "TestFunction::TestFunction.Function::ToUpper"; command.Timeout = 10; command.MemorySize = 512; command.Role = await TestHelper.GetTestRoleArnAsync(); command.Configuration = "Release"; command.Runtime = "dotnet6"; command.DisableInteractive = true; var created = await command.ExecuteAsync(); try { Assert.True(created); await LambdaUtilities.WaitTillFunctionAvailableAsync(new TestToolLogger(_testOutputHelper), command.LambdaClient, command.FunctionName); var invokeRequest = new InvokeRequest { FunctionName = command.FunctionName, LogType = LogType.Tail, Payload = "\"hello world\"" }; var response = await command.LambdaClient.InvokeAsync(invokeRequest); var payload = new StreamReader(response.Payload).ReadToEnd(); Assert.Equal("\"HELLO WORLD\"", payload); } finally { if (created) { await command.LambdaClient.DeleteFunctionAsync(command.FunctionName); } } } [Fact] public async Task TestPowerShellLambdaParallelTestCommand() { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestPowerShellParallelTest"); var command = new DeployFunctionCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); command.FunctionName = "test-function-" + DateTime.Now.Ticks; command.Timeout = 10; command.MemorySize = 512; command.Role = await TestHelper.GetTestRoleArnAsync(); command.Configuration = "Release"; command.S3Bucket = this._testFixture.Bucket; command.S3Prefix = "TestPowerShellParallelTest/"; command.Region = "us-east-1"; command.DisableInteractive = true; var created = await command.ExecuteAsync(); try { Assert.True(created); await LambdaUtilities.WaitTillFunctionAvailableAsync(new TestToolLogger(_testOutputHelper), command.LambdaClient, command.FunctionName); var invokeRequest = new InvokeRequest { FunctionName = command.FunctionName, LogType = LogType.Tail, Payload = "{}" }; var response = await command.LambdaClient.InvokeAsync(invokeRequest); var logTail = Encoding.UTF8.GetString(Convert.FromBase64String(response.LogResult)); Assert.Equal(200, response.StatusCode); Assert.Contains("Running against: 1 for SharedVariable: Hello Shared Variable", logTail); Assert.Contains("Running against: 10 for SharedVariable: Hello Shared Variable", logTail); } finally { if (created) { await command.LambdaClient.DeleteFunctionAsync(command.FunctionName); } } } [Fact] public async Task RunDeployCommandWithCustomConfigAndProjectLocation() { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location)); var command = new DeployFunctionCommand(new ConsoleToolLogger(), fullPath, new string[] {"--config-file", "custom-config.json", "--project-location", "../../../../../testapps/TestFunction" }); command.FunctionName = "test-function-" + DateTime.Now.Ticks; command.Handler = "TestFunction::TestFunction.Function::ToUpper"; command.Timeout = 10; command.Role = await TestHelper.GetTestRoleArnAsync(); command.Configuration = "Release"; command.Runtime = "dotnet6"; command.DisableInteractive = true; var created = await command.ExecuteAsync(); try { Assert.True(created); await LambdaUtilities.WaitTillFunctionAvailableAsync(new TestToolLogger(_testOutputHelper), command.LambdaClient, command.FunctionName); var invokeRequest = new InvokeRequest { FunctionName = command.FunctionName, LogType = LogType.Tail, Payload = "\"hello world\"" }; var response = await command.LambdaClient.InvokeAsync(invokeRequest); var payload = new StreamReader(response.Payload).ReadToEnd(); Assert.Equal("\"HELLO WORLD\"", payload); var log = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(response.LogResult)); Assert.Contains("Memory Size: 320 MB", log); } finally { if (created) { await command.LambdaClient.DeleteFunctionAsync(command.FunctionName); } } } [Fact] public async Task DeployWithPackage() { var assembly = this.GetType().GetTypeInfo().Assembly; string packageZip = Path.GetTempFileName() + ".zip"; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestFunction"); var packageCommand = new PackageCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); packageCommand.OutputPackageFileName = packageZip; packageCommand.Configuration = "Release"; await packageCommand.ExecuteAsync(); var deployCommand = new DeployFunctionCommand(new TestToolLogger(_testOutputHelper), Path.GetTempPath(), new string[0]); deployCommand.FunctionName = "test-function-" + DateTime.Now.Ticks; deployCommand.Handler = "TestFunction::TestFunction.Function::ToUpper"; deployCommand.Timeout = 10; deployCommand.MemorySize = 512; deployCommand.Role = await TestHelper.GetTestRoleArnAsync(); deployCommand.Package = packageZip; deployCommand.Runtime = "dotnet6"; deployCommand.Region = "us-east-1"; deployCommand.DisableInteractive = true; var created = await deployCommand.ExecuteAsync(); try { Assert.True(created); await LambdaUtilities.WaitTillFunctionAvailableAsync(new TestToolLogger(_testOutputHelper), deployCommand.LambdaClient, deployCommand.FunctionName); var invokeRequest = new InvokeRequest { FunctionName = deployCommand.FunctionName, LogType = LogType.Tail, Payload = "\"hello world\"" }; var response = await deployCommand.LambdaClient.InvokeAsync(invokeRequest); var payload = new StreamReader(response.Payload).ReadToEnd(); Assert.Equal("\"HELLO WORLD\"", payload); } finally { if(File.Exists(packageZip)) { File.Delete(packageZip); } if (created) { await deployCommand.LambdaClient.DeleteFunctionAsync(deployCommand.FunctionName); } } } [Fact] public async Task RunYamlServerlessDeployCommand() { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ServerlessWithYamlFunction"); var command = new DeployServerlessCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[] { "--template-parameters", "Environment=whatever" }); command.StackName = "ServerlessYamlStackTest-" + DateTime.Now.Ticks; command.S3Bucket = this._testFixture.Bucket; command.WaitForStackToComplete = true; command.DisableInteractive = true; command.ProjectLocation = fullPath; var created = await command.ExecuteAsync(); try { Assert.True(created); // Test if a redeployment happens with different template parameters it works. var renameParameterCommand = new DeployServerlessCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[] { "--template-parameters", "EnvironmentRename=whatever" }); renameParameterCommand.StackName = command.StackName; renameParameterCommand.S3Bucket = this._testFixture.Bucket; renameParameterCommand.WaitForStackToComplete = true; renameParameterCommand.DisableInteractive = true; renameParameterCommand.ProjectLocation = fullPath; renameParameterCommand.CloudFormationTemplate = "rename-params-template.yaml"; var updated = await renameParameterCommand.ExecuteAsync(); Assert.True(updated); } finally { if (created) { var deleteCommand = new DeleteServerlessCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); deleteCommand.StackName = command.StackName; deleteCommand.Region = "us-east-1"; await deleteCommand.ExecuteAsync(); } } } [Fact] public async Task FixIssueOfDLQBeingCleared() { var sqsClient = new AmazonSQSClient(RegionEndpoint.USEast2); var queueUrl = (await sqsClient.CreateQueueAsync("lambda-test-" + DateTime.Now.Ticks)).QueueUrl; var queueArn = (await sqsClient.GetQueueAttributesAsync(queueUrl, new List<string> { "QueueArn" })).QueueARN; try { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestFunction"); var initialDeployCommand = new DeployFunctionCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); initialDeployCommand.FunctionName = "test-function-" + DateTime.Now.Ticks; initialDeployCommand.Handler = "TestFunction::TestFunction.Function::ToUpper"; initialDeployCommand.Timeout = 10; initialDeployCommand.MemorySize = 512; initialDeployCommand.Role = await TestHelper.GetTestRoleArnAsync(); initialDeployCommand.Configuration = "Release"; initialDeployCommand.Runtime = "dotnet6"; initialDeployCommand.DeadLetterTargetArn = queueArn; initialDeployCommand.DisableInteractive = true; var created = await initialDeployCommand.ExecuteAsync(); try { Assert.True(created); var funcConfig = await initialDeployCommand.LambdaClient.GetFunctionConfigurationAsync(initialDeployCommand.FunctionName); Assert.Equal(queueArn, funcConfig.DeadLetterConfig?.TargetArn); var redeployCommand = new DeployFunctionCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); redeployCommand.FunctionName = initialDeployCommand.FunctionName; redeployCommand.Configuration = "Release"; redeployCommand.Runtime = "dotnet6"; redeployCommand.DisableInteractive = true; var redeployed = await redeployCommand.ExecuteAsync(); Assert.True(redeployed); funcConfig = await initialDeployCommand.LambdaClient.GetFunctionConfigurationAsync(initialDeployCommand.FunctionName); Assert.Equal(queueArn, funcConfig.DeadLetterConfig?.TargetArn); redeployCommand = new DeployFunctionCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); redeployCommand.FunctionName = initialDeployCommand.FunctionName; redeployCommand.Configuration = "Release"; redeployCommand.Runtime = "dotnet6"; redeployCommand.DeadLetterTargetArn = ""; redeployCommand.DisableInteractive = true; redeployed = await redeployCommand.ExecuteAsync(); Assert.True(redeployed); funcConfig = await initialDeployCommand.LambdaClient.GetFunctionConfigurationAsync(initialDeployCommand.FunctionName); Assert.Null(funcConfig.DeadLetterConfig?.TargetArn); } finally { if (created) { await initialDeployCommand.LambdaClient.DeleteFunctionAsync(initialDeployCommand.FunctionName); } } } finally { await sqsClient.DeleteQueueAsync(queueUrl); } } [Fact] public async Task DeployStepFunctionWithTemplateSubstitution() { var cfClient = new AmazonCloudFormationClient(RegionEndpoint.USEast2); var s3Client = new AmazonS3Client(RegionEndpoint.USEast2); var bucketName = "deploy-step-functions-" + DateTime.Now.Ticks; await s3Client.PutBucketAsync(bucketName); try { var logger = new TestToolLogger(_testOutputHelper); var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TemplateSubstitutionTestProjects/StateMachineDefinitionStringTest"); var command = new DeployServerlessCommand(logger, fullPath, new string[0]); command.DisableInteractive = true; command.Configuration = "Release"; command.StackName = "DeployStepFunctionWithTemplateSubstitution-" + DateTime.Now.Ticks; command.S3Bucket = bucketName; command.WaitForStackToComplete = true; command.TemplateParameters = new Dictionary<string, string> { { "NonExisting", "Parameter" }, { "StubParameter", "SecretFoo" } }; var created = await command.ExecuteAsync(); try { Assert.True(created); var describeResponse = await cfClient.DescribeStacksAsync(new DescribeStacksRequest { StackName = command.StackName }); Assert.Equal(StackStatus.CREATE_COMPLETE, describeResponse.Stacks[0].StackStatus); Assert.DoesNotContain("SecretFoo", logger.Buffer.ToString()); Assert.Contains("****", logger.Buffer.ToString()); } finally { if (created) { try { var deleteCommand = new DeleteServerlessCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); deleteCommand.StackName = command.StackName; deleteCommand.Region = "us-east-2"; await deleteCommand.ExecuteAsync(); } catch { // Bury exception because we don't want to lose any exceptions during the deploy stage. } } } } finally { await AmazonS3Util.DeleteS3BucketWithObjectsAsync(s3Client, bucketName); } } [Fact] public void ValidateCompatibleLambdaRuntimesAndTargetFrameworks() { // Validate that newer versions of the framework then what the current and possible future lambda runtimes throw an error. LambdaUtilities.ValidateTargetFrameworkAndLambdaRuntime("dotnetcore1.0", "netcoreapp1.0"); LambdaUtilities.ValidateTargetFrameworkAndLambdaRuntime("dotnetcore1.1", "netcoreapp1.0"); LambdaUtilities.ValidateTargetFrameworkAndLambdaRuntime("dotnetcore1.1", "netcoreapp1.1"); LambdaUtilities.ValidateTargetFrameworkAndLambdaRuntime("dotnetcore2.0", "netcoreapp1.0"); Assert.Throws(typeof(LambdaToolsException), (() => LambdaUtilities.ValidateTargetFrameworkAndLambdaRuntime("dotnetcore1.0", "netcoreapp1.1"))); Assert.Throws(typeof(LambdaToolsException), (() => LambdaUtilities.ValidateTargetFrameworkAndLambdaRuntime("dotnetcore1.0", "netcoreapp2.0"))); Assert.Throws(typeof(LambdaToolsException), (() => LambdaUtilities.ValidateTargetFrameworkAndLambdaRuntime("dotnetcore1.1", "netcoreapp2.0"))); } [Fact] public async Task DeployMultiProject() { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/MPDeployServerless/CurrentDirectoryTest"); var command = new DeployServerlessCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[] { }); command.StackName = "DeployMultiProject-" + DateTime.Now.Ticks; command.S3Bucket = this._testFixture.Bucket; command.WaitForStackToComplete = true; command.DisableInteractive = true; command.ProjectLocation = fullPath; var created = await command.ExecuteAsync(); try { Assert.True(created); using (var cfClient = new AmazonCloudFormationClient(RegionEndpoint.USEast1)) { var stack = (await cfClient.DescribeStacksAsync(new DescribeStacksRequest { StackName = command.StackName })).Stacks[0]; var apiUrl = stack.Outputs.FirstOrDefault(x => string.Equals(x.OutputKey, "ApiURL"))?.OutputValue; Assert.NotNull(apiUrl); Assert.Equal("CurrentProjectTest", await GetRestContent(apiUrl, "current")); Assert.Equal("SecondCurrentProjectTest", await GetRestContent(apiUrl, "current2")); Assert.Equal("SiblingProjectTest", await GetRestContent(apiUrl, "sibling")); Assert.Equal("SingleFileNodeFunction", await GetRestContent(apiUrl, "singlenode")); Assert.Equal("DirectoryNodeFunction", await GetRestContent(apiUrl, "directorynode")); } } finally { if (created) { var deleteCommand = new DeleteServerlessCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); deleteCommand.StackName = command.StackName; deleteCommand.Region = "us-east-1"; await deleteCommand.ExecuteAsync(); } } } [Fact] public async Task TestServerlessPackage() { var logger = new TestToolLogger(); var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestServerlessWebApp"); var command = new PackageCICommand(logger, fullPath, new string[0]); command.Region = "us-west-2"; command.Configuration = "Release"; command.CloudFormationTemplate = "serverless.template"; command.CloudFormationOutputTemplate = Path.Combine(Path.GetTempPath(), "output-serverless.template"); command.S3Bucket = "serverless-package-test-" + DateTime.Now.Ticks; command.DisableInteractive = true; if (File.Exists(command.CloudFormationOutputTemplate)) File.Delete(command.CloudFormationOutputTemplate); await command.S3Client.PutBucketAsync(command.S3Bucket); try { Assert.True(await command.ExecuteAsync()); Assert.True(File.Exists(command.CloudFormationOutputTemplate)); } finally { await AmazonS3Util.DeleteS3BucketWithObjectsAsync(command.S3Client, command.S3Bucket); } } [Fact] public async Task TestDeployLargeServerless() { var logger = new TestToolLogger(); var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestServerlessWebApp"); var command = new DeployServerlessCommand(logger, fullPath, new string[0]); command.Region = "us-east-1"; command.Configuration = "Release"; command.CloudFormationTemplate = "large-serverless.template"; command.StackName = "TestDeployLargeServerless-" + DateTime.Now.Ticks; command.S3Bucket = this._testFixture.Bucket; command.WaitForStackToComplete = true; command.ProjectLocation = fullPath; command.DisableInteractive = true; var created = await command.ExecuteAsync(); try { Assert.True(created); } finally { if (created) { var deleteCommand = new DeleteServerlessCommand(new TestToolLogger(_testOutputHelper), fullPath, new string[0]); deleteCommand.StackName = command.StackName; deleteCommand.Region = command.Region; deleteCommand.DisableInteractive = true; await deleteCommand.ExecuteAsync(); } } } public static async Task<string> GetRestContent(string basePath, string resourcePath) { using (var client = new HttpClient()) { var uri = new Uri(new Uri(basePath), resourcePath); var content = await client.GetStringAsync(uri); return content; } } } public class DeployTestFixture : IDisposable { public string Bucket { get; set; } public IAmazonS3 S3Client { get; set; } public DeployTestFixture() { this.S3Client = new AmazonS3Client(RegionEndpoint.USEast1); this.Bucket = "dotnet-lambda-tests-" + DateTime.Now.Ticks; Task.Run(async () => { await S3Client.PutBucketAsync(this.Bucket); }).Wait(); } private bool disposedValue; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { AmazonS3Util.DeleteS3BucketWithObjectsAsync(this.S3Client, this.Bucket).GetAwaiter().GetResult(); this.S3Client.Dispose(); } disposedValue = true; } } public void Dispose() { Dispose(true); } } }
777
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading.Tasks; using Xunit; using Amazon.Lambda.Tools.Commands; namespace Amazon.Lambda.Tools.Test { public class EnvironmentVariableTests { [Fact] public void SingleAppendEnv() { var logger = new TestToolLogger(); var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestServerlessWebApp"); var command = new UpdateFunctionConfigCommand(logger, fullPath, new string[0]); command.EnvironmentVariables = null; command.AppendEnvironmentVariables = new Dictionary<string, string> { { "foo", "bar" } }; var combinedEnv = command.GetEnvironmentVariables(null); Assert.Single(combinedEnv); Assert.Equal("bar", combinedEnv["foo"]); } [Fact] public void CombinedEnvAndAppendEnv() { var logger = new TestToolLogger(); var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestServerlessWebApp"); var command = new UpdateFunctionConfigCommand(logger, fullPath, new string[0]); command.EnvironmentVariables = new Dictionary<string, string> { { "service", "s3" } }; command.AppendEnvironmentVariables = new Dictionary<string, string> { { "foo", "bar" } }; var combinedEnv = command.GetEnvironmentVariables(null); Assert.Equal(2, combinedEnv.Count); Assert.Equal("bar", combinedEnv["foo"]); Assert.Equal("s3", combinedEnv["service"]); } [Fact] public void CombinedEnvAndAppendEnvIgnoreExisting() { var logger = new TestToolLogger(); var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestServerlessWebApp"); var command = new UpdateFunctionConfigCommand(logger, fullPath, new string[0]); command.EnvironmentVariables = new Dictionary<string, string> { { "service", "s3" } }; command.AppendEnvironmentVariables = new Dictionary<string, string> { { "foo", "bar" } }; var combinedEnv = command.GetEnvironmentVariables(new Dictionary<string, string> { { "service", "lambda" } }); Assert.Equal(2, combinedEnv.Count); Assert.Equal("bar", combinedEnv["foo"]); Assert.Equal("s3", combinedEnv["service"]); } [Fact] public void CombinedExistingEnvAndAppendEnv() { var logger = new TestToolLogger(); var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestServerlessWebApp"); var command = new UpdateFunctionConfigCommand(logger, fullPath, new string[0]); command.EnvironmentVariables = null; command.AppendEnvironmentVariables = new Dictionary<string, string> { { "foo", "bar" } }; var combinedEnv = command.GetEnvironmentVariables(new Dictionary<string, string> { { "service", "lambda" } }); Assert.Equal(2, combinedEnv.Count); Assert.Equal("bar", combinedEnv["foo"]); Assert.Equal("lambda", combinedEnv["service"]); } } }
87
aws-extensions-for-dotnet-cli
aws
C#
using System.IO; using System.Reflection; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Xunit; using Amazon.Lambda.Tools.Commands; using Amazon.Tools.TestHelpers; namespace Amazon.Lambda.Tools.Test { public class LambdaToolsDefaultsReaderTest { private string GetTestProjectPath() { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestFunction/"); return fullPath; } [Fact] public void LoadDefaultsDirectly() { var defaults = new LambdaToolsDefaults(); defaults.LoadDefaults(GetTestProjectPath(), LambdaToolsDefaults.DEFAULT_FILE_NAME); Assert.Equal("us-east-2", defaults.Region); Assert.Equal("us-east-2", defaults["region"]); Assert.Equal(true, defaults["disable-version-check"]); Assert.Equal(128, defaults["function-memory-size"]); } [Fact] public void CommandInferRegionFromDefaults() { var command = new DeployFunctionCommand(new ConsoleToolLogger(), GetTestProjectPath(), new string[0]); Assert.Equal("us-east-2", command.GetStringValueOrDefault(command.Region, CommonDefinedCommandOptions.ARGUMENT_AWS_REGION, true)); } } }
43
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Linq; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Net.Http; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; using Amazon.Lambda; using Amazon.Lambda.Model; using Amazon.Lambda.Tools.Commands; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using Amazon.SQS; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.Common.DotNetCli.Tools; using ThirdParty.Json.LitJson; using System.Runtime.InteropServices; using Xunit.Abstractions; namespace Amazon.Lambda.Tools.Test { public class LayerTests : IClassFixture<LayerTestsFixture> { private readonly ITestOutputHelper _testOutputHelper; static string _singleLayerFunctionPath = Path.GetFullPath(Path.GetDirectoryName(typeof(LayerTests).GetTypeInfo().Assembly.Location) + "../../../../../../testapps/TestLayerExample"); static string _serverlessLayerFunctionPath = Path.GetFullPath(Path.GetDirectoryName(typeof(LayerTests).GetTypeInfo().Assembly.Location) + "../../../../../../testapps/TestLayerServerless"); static string _aspnercoreLayerFunctionPath = Path.GetFullPath(Path.GetDirectoryName(typeof(LayerTests).GetTypeInfo().Assembly.Location) + "../../../../../../testapps/TestLayerAspNetCore"); LayerTestsFixture _testFixture; public LayerTests(LayerTestsFixture testFixture, ITestOutputHelper testOutputHelper) { this._testFixture = testFixture; this._testOutputHelper = testOutputHelper; } [Fact] public async Task CreateLayer() { var logger = new TestToolLogger(_testOutputHelper); var command = new PublishLayerCommand(logger, _singleLayerFunctionPath, new string[0]); command.Region = "us-east-1"; command.S3Bucket = this._testFixture.Bucket; command.DisableInteractive = true; command.TargetFramework = "net6.0"; command.LayerName = "DotnetTest-CreateLayer"; command.LayerType = LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE; command.PackageManifest = _singleLayerFunctionPath; try { Assert.True(await command.ExecuteAsync()); Assert.NotNull(command.NewLayerVersionArn); var getResponse = await this._testFixture.LambdaClient.GetLayerVersionAsync(new GetLayerVersionRequest {LayerName = command.NewLayerArn, VersionNumber = command.NewLayerVersionNumber }); Assert.NotNull(getResponse.Description); var data = JsonMapper.ToObject<LayerDescriptionManifest>(getResponse.Description); Assert.Equal(LayerDescriptionManifest.ManifestType.RuntimePackageStore, data.Nlt); Assert.NotNull(data.Dir); Assert.Equal(this._testFixture.Bucket, data.Buc); Assert.NotNull(data.Key); using (var getManifestResponse = await this._testFixture.S3Client.GetObjectAsync(data.Buc, data.Key)) using(var reader = new StreamReader(getManifestResponse.ResponseStream)) { var xml = await reader.ReadToEndAsync(); Assert.Contains("AWSSDK.S3", xml); Assert.Contains("Amazon.Lambda.Core", xml); } } finally { await this._testFixture.LambdaClient.DeleteLayerVersionAsync(new DeleteLayerVersionRequest { LayerName = command.NewLayerArn, VersionNumber = command.NewLayerVersionNumber }); } } [Fact] // This test behaves different depending on the OS the test is running on which means // all code paths are not always being tested. Future work is needed to figure out how to // mock the underlying calls to the dotnet CLI. public async Task AttemptToCreateAnOptmizedLayer() { var logger = new TestToolLogger(_testOutputHelper); var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TestLayerExample"); var command = new PublishLayerCommand(logger, fullPath, new string[] { "--enable-package-optimization", "true"}); command.Region = "us-east-1"; command.S3Bucket = this._testFixture.Bucket; command.DisableInteractive = true; command.TargetFramework = "net6.0"; command.LayerName = "DotnetTest-AttemptToCreateAnOptmizedLayer"; command.LayerType = LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE; command.PackageManifest = fullPath; bool success = false; try { success = await command.ExecuteAsync(); if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Assert.False(success); Assert.Equal(LambdaToolsException.LambdaErrorCode.UnsupportedOptimizationPlatform.ToString(), command.LastToolsException.Code); } else { Assert.True(success); Assert.NotNull(command.NewLayerVersionArn); var getResponse = await this._testFixture.LambdaClient.GetLayerVersionAsync(new GetLayerVersionRequest { LayerName = command.NewLayerArn, VersionNumber = command.NewLayerVersionNumber }); Assert.NotNull(getResponse.Description); var data = JsonMapper.ToObject<LayerDescriptionManifest>(getResponse.Description); Assert.Equal(LayerDescriptionManifest.ManifestType.RuntimePackageStore, data.Nlt); Assert.NotNull(data.Dir); Assert.Equal(this._testFixture.Bucket, data.Buc); Assert.NotNull(data.Key); using (var getManifestResponse = await this._testFixture.S3Client.GetObjectAsync(data.Buc, data.Key)) using (var reader = new StreamReader(getManifestResponse.ResponseStream)) { var xml = await reader.ReadToEndAsync(); Assert.Contains("AWSSDK.S3", xml); Assert.Contains("Amazon.Lambda.Core", xml); } } } finally { if(success) { await this._testFixture.LambdaClient.DeleteLayerVersionAsync(new DeleteLayerVersionRequest { LayerName = command.NewLayerArn, VersionNumber = command.NewLayerVersionNumber }); } } } [Theory(Skip = "Trouble running in CodeBuild. Need to debug.")] [InlineData("")] [InlineData("nuget-store")] public async Task DeployFunctionWithLayer(string optDirectory) { var logger = new TestToolLogger(_testOutputHelper); var publishLayerCommand = await PublishLayerAsync(_singleLayerFunctionPath, optDirectory); try { Assert.NotNull(publishLayerCommand.NewLayerVersionArn); var deployCommand = new DeployFunctionCommand(new TestToolLogger(_testOutputHelper), _singleLayerFunctionPath, new string[0]); deployCommand.FunctionName = "test-layer-function-" + DateTime.Now.Ticks; deployCommand.Region = publishLayerCommand.Region; deployCommand.Handler = "TestLayerExample::TestLayerExample.Function::FunctionHandler"; deployCommand.Timeout = 10; deployCommand.MemorySize = 512; deployCommand.Role = await TestHelper.GetTestRoleArnAsync(); deployCommand.Configuration = "Release"; deployCommand.Runtime = "dotnet6"; deployCommand.LayerVersionArns = new string[] { publishLayerCommand.NewLayerVersionArn }; deployCommand.DisableInteractive = true; var created = await deployCommand.ExecuteAsync(); try { // See if we got back the return which proves we were able to load an assembly from the S3 NuGet package // return new Amazon.S3.Model.ListBucketsRequest().ToString(); await ValidateInvokeAsync(deployCommand.FunctionName, "\"TEST\"", "\"Amazon.S3.Model.ListBucketsRequest\""); var getConfigResponse = await this._testFixture.LambdaClient.GetFunctionConfigurationAsync(new GetFunctionConfigurationRequest { FunctionName = deployCommand.FunctionName }); Assert.NotNull(getConfigResponse.Layers.FirstOrDefault(x => string.Equals(x.Arn, publishLayerCommand.NewLayerVersionArn))); var dotnetSharedSource = getConfigResponse.Environment.Variables[LambdaConstants.ENV_DOTNET_SHARED_STORE]; if(!string.IsNullOrEmpty(optDirectory)) { Assert.Equal($"/opt/{optDirectory}/", dotnetSharedSource); } else { Assert.Equal($"/opt/{LambdaConstants.DEFAULT_LAYER_OPT_DIRECTORY}/", dotnetSharedSource); } var getCodeResponse = await this._testFixture.LambdaClient.GetFunctionAsync(deployCommand.FunctionName); using (var client = new HttpClient()) { var data = await client.GetByteArrayAsync(getCodeResponse.Code.Location); var zipArchive = new ZipArchive(new MemoryStream(data), ZipArchiveMode.Read); Assert.NotNull(zipArchive.GetEntry("TestLayerExample.dll")); Assert.Null(zipArchive.GetEntry("Amazon.Lambda.Core.dll")); Assert.Null(zipArchive.GetEntry("AWSSDK.S3.dll")); } var redeployLayerCommand = await PublishLayerAsync(_singleLayerFunctionPath, optDirectory); var redeployFunctionCommand = new DeployFunctionCommand(new TestToolLogger(_testOutputHelper), _singleLayerFunctionPath, new string[0]); redeployFunctionCommand.FunctionName = deployCommand.FunctionName; redeployFunctionCommand.Region = deployCommand.Region; redeployFunctionCommand.Handler = deployCommand.Handler; redeployFunctionCommand.Timeout = deployCommand.Timeout; redeployFunctionCommand.MemorySize = deployCommand.MemorySize; redeployFunctionCommand.Role = deployCommand.Role; redeployFunctionCommand.Configuration = deployCommand.Configuration; redeployFunctionCommand.TargetFramework = deployCommand.TargetFramework; redeployFunctionCommand.Runtime = deployCommand.Runtime; redeployFunctionCommand.LayerVersionArns = new string[] { redeployLayerCommand.NewLayerVersionArn }; redeployFunctionCommand.DisableInteractive = true; if(!await redeployFunctionCommand.ExecuteAsync()) { throw redeployFunctionCommand.LastToolsException; } await ValidateInvokeAsync(redeployFunctionCommand.FunctionName, "\"TEST\"", "\"Amazon.S3.Model.ListBucketsRequest\""); } finally { await this._testFixture.LambdaClient.DeleteFunctionAsync(new DeleteFunctionRequest { FunctionName = deployCommand.FunctionName }); } } finally { await this._testFixture.LambdaClient.DeleteLayerVersionAsync(new DeleteLayerVersionRequest { LayerName = publishLayerCommand.NewLayerArn, VersionNumber = publishLayerCommand.NewLayerVersionNumber }); } } [Fact] public async Task DeployServerlessWithlayer() { var logger = new TestToolLogger(_testOutputHelper); var templateTilePath = Path.Combine(_serverlessLayerFunctionPath, "serverless.template"); if (File.Exists(templateTilePath)) { File.Delete(templateTilePath); } var publishLayerCommand = await PublishLayerAsync(_serverlessLayerFunctionPath, ""); try { var templateContent = File.ReadAllText(Path.Combine(_serverlessLayerFunctionPath, "fake.template")); templateContent = templateContent.Replace("LAYER_ARN_PLACEHOLDER", publishLayerCommand.NewLayerVersionArn); File.WriteAllText(templateTilePath, templateContent); var command = new DeployServerlessCommand(new TestToolLogger(_testOutputHelper), _serverlessLayerFunctionPath, new string[] { }); command.DisableInteractive = true; command.StackName = "DeployServerlessWithlayer-" + DateTime.Now.Ticks; command.Region = publishLayerCommand.Region; command.S3Bucket = this._testFixture.Bucket; command.WaitForStackToComplete = true; command.DisableInteractive = true; command.ProjectLocation = _serverlessLayerFunctionPath; var created = await command.ExecuteAsync(); try { Assert.True(created); Func<string, Task> testFunctionAsync = async (functionName) => { var lambdaFunctionName = await TestHelper.GetPhysicalCloudFormationResourceId(_testFixture.CFClient, command.StackName, functionName); await ValidateInvokeAsync(lambdaFunctionName, "\"hello\"", "\"HELLO\""); var getConfigResponse = await this._testFixture.LambdaClient.GetFunctionConfigurationAsync(new GetFunctionConfigurationRequest { FunctionName = lambdaFunctionName }); Assert.NotNull(getConfigResponse.Layers.FirstOrDefault(x => string.Equals(x.Arn, publishLayerCommand.NewLayerVersionArn))); var getCodeResponse = await this._testFixture.LambdaClient.GetFunctionAsync(lambdaFunctionName); using (var client = new HttpClient()) { var data = await client.GetByteArrayAsync(getCodeResponse.Code.Location); var zipArchive = new ZipArchive(new MemoryStream(data), ZipArchiveMode.Read); Assert.NotNull(zipArchive.GetEntry("TestLayerServerless.dll")); Assert.Null(zipArchive.GetEntry("Amazon.Lambda.Core.dll")); } }; await testFunctionAsync("TheFunction"); await testFunctionAsync("TheSecondFunctionSameSource"); } finally { if (created) { var deleteCommand = new DeleteServerlessCommand(new TestToolLogger(_testOutputHelper), _serverlessLayerFunctionPath, new string[0]); deleteCommand.DisableInteractive = true; deleteCommand.Region = publishLayerCommand.Region; deleteCommand.StackName = command.StackName; await deleteCommand.ExecuteAsync(); } } } finally { await this._testFixture.LambdaClient.DeleteLayerVersionAsync(new DeleteLayerVersionRequest { LayerName = publishLayerCommand.NewLayerArn, VersionNumber = publishLayerCommand.NewLayerVersionNumber }); if (File.Exists(templateTilePath)) { File.Delete(templateTilePath); } } } [Fact(Skip = "Trouble running in CodeBuild. Need to debug.")] public async Task DeployAspNetCoreWithlayer() { var logger = new TestToolLogger(_testOutputHelper); var templateTilePath = Path.Combine(_aspnercoreLayerFunctionPath, "serverless.template"); if (File.Exists(templateTilePath)) { File.Delete(templateTilePath); } var publishLayerCommand = await PublishLayerAsync(_aspnercoreLayerFunctionPath, ""); try { var getLayerResponse = await this._testFixture.LambdaClient.GetLayerVersionAsync(new GetLayerVersionRequest {LayerName = publishLayerCommand.NewLayerArn, VersionNumber = publishLayerCommand.NewLayerVersionNumber }); Assert.NotNull(getLayerResponse.Description); // Make sure layer does not contain any core ASP.NET Core dependencies. var layerManifest = JsonMapper.ToObject<LayerDescriptionManifest>(getLayerResponse.Description); using (var getManifestResponse = await this._testFixture.S3Client.GetObjectAsync(layerManifest.Buc, layerManifest.Key)) using(var reader = new StreamReader(getManifestResponse.ResponseStream)) { var xml = await reader.ReadToEndAsync(); Assert.False(xml.Contains("Microsoft.AspNetCore")); Assert.False(xml.Contains("runtime")); } var templateContent = File.ReadAllText(Path.Combine(_aspnercoreLayerFunctionPath, "fake.template")); templateContent = templateContent.Replace("LAYER_ARN_PLACEHOLDER", publishLayerCommand.NewLayerVersionArn); File.WriteAllText(templateTilePath, templateContent); var command = new DeployServerlessCommand(new TestToolLogger(_testOutputHelper), _aspnercoreLayerFunctionPath, new string[] { }); command.DisableInteractive = true; command.StackName = "DeployAspNetCoreWithlayer-" + DateTime.Now.Ticks; command.Region = publishLayerCommand.Region; command.S3Bucket = this._testFixture.Bucket; command.WaitForStackToComplete = true; command.DisableInteractive = true; command.ProjectLocation = _aspnercoreLayerFunctionPath; var created = await command.ExecuteAsync(); try { Assert.True(created); var lambdaFunctionName = await TestHelper.GetPhysicalCloudFormationResourceId(_testFixture.CFClient, command.StackName, "AspNetCoreFunction"); var apiUrl = await TestHelper.GetOutputParameter(_testFixture.CFClient, command.StackName, "ApiURL"); using (var client = new HttpClient()) { await client.GetStringAsync(new Uri(new Uri(apiUrl), "api/values")); } var getConfigResponse = await this._testFixture.LambdaClient.GetFunctionConfigurationAsync(new GetFunctionConfigurationRequest { FunctionName = lambdaFunctionName }); Assert.NotNull(getConfigResponse.Layers.FirstOrDefault(x => string.Equals(x.Arn, publishLayerCommand.NewLayerVersionArn))); var getCodeResponse = await this._testFixture.LambdaClient.GetFunctionAsync(lambdaFunctionName); using (var client = new HttpClient()) { var data = await client.GetByteArrayAsync(getCodeResponse.Code.Location); var zipArchive = new ZipArchive(new MemoryStream(data), ZipArchiveMode.Read); Assert.NotNull(zipArchive.GetEntry("TestLayerAspNetCore.dll")); Assert.Null(zipArchive.GetEntry("Amazon.Lambda.Core.dll")); Assert.Null(zipArchive.GetEntry("AWSSDK.S3.dll")); Assert.Null(zipArchive.GetEntry("AWSSDK.Extensions.NETCore.Setup.dll")); Assert.Null(zipArchive.GetEntry("Amazon.Lambda.AspNetCoreServer.dll")); } } finally { if (created) { var deleteCommand = new DeleteServerlessCommand(new TestToolLogger(_testOutputHelper), _aspnercoreLayerFunctionPath, new string[0]); deleteCommand.DisableInteractive = true; deleteCommand.Region = publishLayerCommand.Region; deleteCommand.StackName = command.StackName; await deleteCommand.ExecuteAsync(); } } } finally { await this._testFixture.LambdaClient.DeleteLayerVersionAsync(new DeleteLayerVersionRequest { LayerName = publishLayerCommand.NewLayerArn, VersionNumber = publishLayerCommand.NewLayerVersionNumber }); if (File.Exists(templateTilePath)) { File.Delete(templateTilePath); } } } [Fact] public void MakeSureDirectoryInDotnetSharedStoreValueOnce() { var info = new LayerPackageInfo(); info.Items.Add(new LayerPackageInfo.LayerPackageInfoItem { Directory = LambdaConstants.DEFAULT_LAYER_OPT_DIRECTORY }); info.Items.Add(new LayerPackageInfo.LayerPackageInfoItem { Directory = "Custom/Foo" }); info.Items.Add(new LayerPackageInfo.LayerPackageInfoItem { Directory = LambdaConstants.DEFAULT_LAYER_OPT_DIRECTORY }); var env = info.GenerateDotnetSharedStoreValue(); var tokens = env.Split(':'); Assert.Equal(2, tokens.Length); Assert.Equal(1, tokens.Count(x => x.Equals("/opt/" + LambdaConstants.DEFAULT_LAYER_OPT_DIRECTORY + "/"))); Assert.Equal(1, tokens.Count(x => x.Equals("/opt/Custom/Foo/"))); } private async Task ValidateInvokeAsync(string functionName, string payload, string expectedResult) { var invokeResponse = await this._testFixture.LambdaClient.InvokeAsync(new InvokeRequest { InvocationType = InvocationType.RequestResponse, FunctionName = functionName, Payload = payload, LogType = LogType.Tail }); var content = new StreamReader(invokeResponse.Payload).ReadToEnd(); Assert.Equal(expectedResult, content); } private async Task<PublishLayerCommand> PublishLayerAsync(string projectDirectory, string optDirectory) { var logger = new TestToolLogger(_testOutputHelper); var publishLayerCommand = new PublishLayerCommand(logger, projectDirectory, new string[0]); publishLayerCommand.Region = "us-east-1"; publishLayerCommand.S3Bucket = this._testFixture.Bucket; publishLayerCommand.DisableInteractive = true; publishLayerCommand.LayerName = "Dotnet-IntegTest-"; publishLayerCommand.LayerType = LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE; publishLayerCommand.OptDirectory = optDirectory; publishLayerCommand.TargetFramework = "net6.0"; // publishLayerCommand.PackageManifest = _singleLayerFunctionPath; if(!(await publishLayerCommand.ExecuteAsync())) { throw publishLayerCommand.LastToolsException; } return publishLayerCommand; } } public class LayerTestsFixture : IDisposable { public string Bucket { get; set; } public IAmazonS3 S3Client { get; set; } public IAmazonLambda LambdaClient { get; set; } public IAmazonCloudFormation CFClient { get; set; } public LayerTestsFixture() { this.CFClient = new AmazonCloudFormationClient(RegionEndpoint.USEast1); this.S3Client = new AmazonS3Client(RegionEndpoint.USEast1); this.LambdaClient = new AmazonLambdaClient(RegionEndpoint.USEast1); this.Bucket = "dotnet-lambda-layer-tests-" + DateTime.Now.Ticks; Task.Run(async () => { await S3Client.PutBucketAsync(this.Bucket); // Wait for bucket to exist Thread.Sleep(10000); }).Wait(); } private bool disposedValue; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { AmazonS3Util.DeleteS3BucketWithObjectsAsync(this.S3Client, this.Bucket).Wait(); this.S3Client.Dispose(); } disposedValue = true; } } public void Dispose() { Dispose(true); } } }
535
aws-extensions-for-dotnet-cli
aws
C#
using Xunit; using Amazon.Common.DotNetCli.Tools; using Amazon.Common.DotNetCli.Tools.Options; using Amazon.Lambda.Tools.Commands; namespace Amazon.Lambda.Tools.Test { public class OptionParseTests { [Fact] public void ParseNullCloudFormationParameter() { var parameters = Utilities.ParseKeyValueOption(null); Assert.Equal(0, parameters.Count); parameters = Utilities.ParseKeyValueOption(string.Empty); Assert.Equal(0, parameters.Count); } [Fact] public void ParseSingleCloudFormationParameter() { var parameters = Utilities.ParseKeyValueOption("Table=Blog"); Assert.Equal(1, parameters.Count); Assert.Equal("Blog", parameters["Table"]); parameters = Utilities.ParseKeyValueOption("Table=Blog;"); Assert.Equal(1, parameters.Count); Assert.Equal("Blog", parameters["Table"]); parameters = Utilities.ParseKeyValueOption("\"ConnectionString\"=\"User=foo;Password=test\""); Assert.Equal(1, parameters.Count); Assert.Equal("User=foo;Password=test", parameters["ConnectionString"]); } [Fact] public void ParseTwoCloudFormationParameter() { var parameters = Utilities.ParseKeyValueOption("Table=Blog;Bucket=MyBucket"); Assert.Equal(2, parameters.Count); Assert.Equal("Blog", parameters["Table"]); Assert.Equal("MyBucket", parameters["Bucket"]); parameters = Utilities.ParseKeyValueOption("\"ConnectionString1\"=\"User=foo;Password=test\";\"ConnectionString2\"=\"Password=test;User=foo\""); Assert.Equal(2, parameters.Count); Assert.Equal("User=foo;Password=test", parameters["ConnectionString1"]); Assert.Equal("Password=test;User=foo", parameters["ConnectionString2"]); } [Fact] public void ParseEmptyValue() { var parameters = Utilities.ParseKeyValueOption("ShouldCreateTable=true;BlogTableName="); Assert.Equal(2, parameters.Count); Assert.Equal("true", parameters["ShouldCreateTable"]); Assert.Equal("", parameters["BlogTableName"]); parameters = Utilities.ParseKeyValueOption("BlogTableName=;ShouldCreateTable=true"); Assert.Equal(2, parameters.Count); Assert.Equal("true", parameters["ShouldCreateTable"]); Assert.Equal("", parameters["BlogTableName"]); } [Fact] public void ParseErrors() { Assert.Throws(typeof(ToolsException), () => Utilities.ParseKeyValueOption("=aaa")); } [Fact] public void ParseMSBuildParameters() { var values = CommandLineParser.ParseArguments(DeployFunctionCommand.DeployCommandOptions, new[] {"myfunc", "--region", "us-west-2", "/p:Foo=bar;Version=1.2.3"}); Assert.Equal("myfunc", values.Arguments[0]); Assert.Equal("/p:Foo=bar;Version=1.2.3", values.MSBuildParameters); var param = values.FindCommandOption("--region"); Assert.NotNull(param); Assert.Equal("us-west-2", param.Item2.StringValue); } } }
86
aws-extensions-for-dotnet-cli
aws
C#
using System.Collections.Generic; using System.IO; using System.Reflection; using YamlDotNet.Serialization; using Xunit; namespace Amazon.Lambda.Tools.Test { public class TemplateCodeUpdateYamlTest { static readonly string SERVERLESS_FUNCTION = @" AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: TheServerlessFunction: Type: AWS::Serverless::Function Properties: CodeUri: ./ Handler: lambda.handler MemorySize: 1024 Role: LambdaExecutionRole.Arn Runtime: dotnetcore1.0 Timeout: 30 Events: ProxyApiGreedy: Type: Api Properties: RestApiId: ApiGatewayApi Path: /{proxy+} Method: ANY "; static readonly string LAMBDA_FUNCTION = @" AWSTemplateFormatVersion: '2010-09-09' Resources: TheLambdaFunction: Type: AWS::Lambda::Function Properties: Handler: lambda.handler MemorySize: 1024 Role: LambdaExecutionRole.Arn Runtime: dotnetcore1.0 Timeout: 30 Code: S3Bucket: PlaceHolderObject S3Key: PlaceHolderKey "; static readonly string API_WITH_SWAGGER = @"AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: An AWS Serverless Application. Resources: Api: Type: AWS::Serverless::Api Properties: StageName: prod DefinitionBody: swagger: '2.0' info: version: '2018-04-18T18:37:10Z' title: 'manual-deploy' host: 'prepend.execute-api.region.amazonaws.com' basePath: '/prod' schemes: - 'https' paths: /ride: post: produces: - 'application/json' responses: '200': description: '200 response' schema: $ref: '#/definitions/Empty' headers: Content-Type: type: 'string' definitions: Empty: type: 'object' title: 'Empty Schema'"; const string S3_BUCKET = "myBucket"; const string S3_OBJECT = "myObject"; static readonly string S3_URL = $"s3://{S3_BUCKET}/{S3_OBJECT}"; [Fact] public void ReplaceServerlessApiCodeLocation() { var updateTemplateBody = LambdaUtilities.UpdateCodeLocationInTemplate(SERVERLESS_FUNCTION, S3_BUCKET, S3_OBJECT); var root = new Deserializer().Deserialize(new StringReader(updateTemplateBody)) as IDictionary<object, object>; var resources = root["Resources"] as IDictionary<object, object>; var resource = resources["TheServerlessFunction"] as IDictionary<object, object>; var properties = resource["Properties"] as IDictionary<object, object>; Assert.Equal(S3_URL, properties["CodeUri"]); } [Fact] public void ReplaceLambdaFunctionCodeLocation() { var updateTemplateBody = LambdaUtilities.UpdateCodeLocationInTemplate(LAMBDA_FUNCTION, S3_BUCKET, S3_OBJECT); var root = new Deserializer().Deserialize(new StringReader(updateTemplateBody)) as IDictionary<object, object>; var resources = root["Resources"] as IDictionary<object, object>; var resource = resources["TheLambdaFunction"] as IDictionary<object, object>; var properties = resource["Properties"] as IDictionary<object, object>; var code = properties["Code"] as IDictionary<object, object>; Assert.Equal(S3_BUCKET, code["S3Bucket"]); Assert.Equal(S3_OBJECT, code["S3Key"]); } [Fact] public void ReplaceCodeLocationPreservesSwagger() { var updateTemplateBody = LambdaUtilities.UpdateCodeLocationInTemplate(API_WITH_SWAGGER, S3_BUCKET, S3_OBJECT); Assert.Contains("'200':", updateTemplateBody); } [Fact] public void DeployServerlessWithSwaggerWithTemplateSubstitution() { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../test/Amazon.Lambda.Tools.Test/TestFiles/testtemplate.yaml"); var template = File.ReadAllText(fullPath); //Does not throw an error when parsing template var updateTemplateBody = LambdaUtilities.UpdateCodeLocationInYamlTemplate(template, S3_BUCKET, S3_OBJECT); //validate that functions survive the template update Assert.Contains("DevStack: !Equals [!Ref 'AWS::StackName', dev]", updateTemplateBody); } } }
146
aws-extensions-for-dotnet-cli
aws
C#
using System.Collections.Generic; using System.IO; using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Xunit; using Amazon.Lambda.Tools.TemplateProcessor; using ThirdParty.Json.LitJson; using YamlDotNet.RepresentationModel; using System.Linq; using static Amazon.Lambda.Tools.TemplateProcessor.JsonTemplateParser; using static Amazon.Lambda.Tools.TemplateProcessor.YamlTemplateParser; namespace Amazon.Lambda.Tools.Test { public class TemplateParserTests { [Fact] public void DetermineJsonReader() { Assert.IsType<JsonTemplateParser>(TemplateProcessorManager.CreateTemplateParser("{\"AWSTemplateFormatVersion\" : \"2010-09-09\"}")); Assert.IsType<JsonTemplateParser>(TemplateProcessorManager.CreateTemplateParser("\t\t{\"AWSTemplateFormatVersion\" : \"2010-09-09\"}")); Assert.IsType<JsonTemplateParser>(TemplateProcessorManager.CreateTemplateParser("\n{\"AWSTemplateFormatVersion\" : \"2010-09-09\"}")); } [Fact] public void DetermineYamlReader() { Assert.IsType<YamlTemplateParser>(TemplateProcessorManager.CreateTemplateParser("AWSTemplateFormatVersion: \"2010-09-09\"")); Assert.IsType<YamlTemplateParser>(TemplateProcessorManager.CreateTemplateParser("-")); } [Theory] [MemberData(nameof(GetAndSetValuesOnRootData))] public void GetAndSetValuesOnRoot(IUpdatableResourceDataSource source) { Assert.Equal("/home/code", source.GetValue("CodeUri")); source.SetValue("s3://my-bucket/my-key", "CodeUri"); Assert.Equal("s3://my-bucket/my-key", source.GetValue("CodeUri")); } public static IEnumerable<object[]> GetAndSetValuesOnRootData() { var list = new List<object[]>(); { var rootData = new JsonData(); rootData["CodeUri"] = "/home/code"; var source = new JsonTemplateParser.JsonUpdatableResourceDataSource(null, null, rootData); list.Add(new object[] { source }); } { var rootData = new YamlMappingNode(); rootData.Children.Add("CodeUri", new YamlScalarNode("/home/code")); var source = new YamlTemplateParser.YamlUpdatableResourceDataSource(null, null, rootData); list.Add(new object[] { source }); } return list; } [Theory] [MemberData(nameof(GetAndSetValuesOnChildOnObjectData))] public void GetAndSetValuesOnChildOnObject(IUpdatableResourceDataSource source) { Assert.Equal("/currentProject", source.GetValue("Code", "S3Key")); source.SetValue("my-key", "Code", "S3Key"); Assert.Equal("my-key", source.GetValue("Code", "S3Key")); } public static IEnumerable<object[]> GetAndSetValuesOnChildOnObjectData() { var list = new List<object[]>(); { var codeData = new JsonData(); codeData["S3Bucket"] = ""; codeData["S3Key"] = "/currentProject"; var rootData = new JsonData(); rootData["Code"] = codeData; var source = new JsonTemplateParser.JsonUpdatableResourceDataSource(null, null, rootData); list.Add(new object[] { source }); } { var codeData = new YamlMappingNode(); codeData.Children.Add("S3Bucket", new YamlScalarNode("")); codeData.Children.Add("S3Key", new YamlScalarNode("/currentProject")); var rootData = new YamlMappingNode(); rootData.Children.Add("Code", codeData); var source = new YamlTemplateParser.YamlUpdatableResourceDataSource(null, null, rootData); list.Add(new object[] { source }); } return list; } [Theory] [MemberData(nameof(GetNullValueAndSetValuesOnRootOnObjectData))] public void GetNullValueAndSetValuesOnRootOnObject(IUpdatableResourceDataSource source) { Assert.Null(source.GetValue("CodeUri")); source.SetValue("my-key", "CodeUri"); Assert.Equal("my-key", source.GetValue("CodeUri")); } public static IEnumerable<object[]> GetNullValueAndSetValuesOnRootOnObjectData() { var list = new List<object[]>(); { var rootData = new JsonData(); var source = new JsonTemplateParser.JsonUpdatableResourceDataSource(null, null, rootData); list.Add(new object[] { source }); } { var rootData = new YamlMappingNode(); var source = new YamlTemplateParser.YamlUpdatableResourceDataSource(null, null, rootData); list.Add(new object[] { source }); } return list; } [Theory] [MemberData(nameof(GetNullValueAndSetValuesOnChildOnObjectData))] public void GetNullValueAndSetValuesOnChildOnObject(IUpdatableResourceDataSource source) { Assert.Null(source.GetValue("Code", "S3Key")); source.SetValue("my-key", "Code", "S3Key"); Assert.Equal("my-key", source.GetValue("Code", "S3Key")); } public static IEnumerable<object[]> GetNullValueAndSetValuesOnChildOnObjectData() { var list = new List<object[]>(); { var rootData = new JsonData(); var source = new JsonTemplateParser.JsonUpdatableResourceDataSource(null, null, rootData); list.Add(new object[] { source }); } { var rootData = new YamlMappingNode(); var source = new YamlTemplateParser.YamlUpdatableResourceDataSource(null, null, rootData); list.Add(new object[] { source }); } return list; } [Fact] public void ServerlessFunction_GetCurrentDirectoryForWithNullCodeUri() { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_SERVERLESS_FUNCTION, dataSource); Assert.Equal(".", resource.Fields[0].GetLocalPath()); resource.Fields[0].SetS3Location("my-bucket", "my.zip"); Assert.Equal("s3://my-bucket/my.zip", dataSource.GetValue("CodeUri")); } [Theory] [InlineData(".")] [InlineData("/home")] public void ServerlessFunction_GetLocalPath(string localPath) { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { {"CodeUri", localPath } }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_SERVERLESS_FUNCTION, dataSource); Assert.Equal(localPath, resource.Fields[0].GetLocalPath()); resource.Fields[0].SetS3Location("my-bucket", "my.zip"); Assert.Equal("s3://my-bucket/my.zip", dataSource.GetValue("CodeUri")); } [Fact] public void ServerlessFunction_NotUpdatableBecausePointAtAlreadyS3() { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { {"CodeUri", "s3://my-bucket/my.zip" } }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_SERVERLESS_FUNCTION, dataSource); Assert.Null(resource.Fields[0].GetLocalPath()); } [Fact] public void LambdaFunction_GetCurrentDirectoryForWithNullCode() { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_LAMBDA_FUNCTION, dataSource); Assert.Equal(".", resource.Fields[0].GetLocalPath()); resource.Fields[0].SetS3Location("my-bucket", "my.zip"); Assert.Equal("my-bucket", dataSource.GetValue("Code/S3Bucket")); Assert.Equal("my.zip", dataSource.GetValue("Code/S3Key")); } [Theory] [InlineData(".")] [InlineData("/home")] public void LambdaFunction_GetLocalPath(string localPath) { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { {"Code/S3Key", localPath } }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_LAMBDA_FUNCTION, dataSource); Assert.Equal(localPath, resource.Fields[0].GetLocalPath()); resource.Fields[0].SetS3Location("my-bucket", "my.zip"); Assert.Equal("my-bucket", dataSource.GetValue("Code/S3Bucket")); Assert.Equal("my.zip", dataSource.GetValue("Code/S3Key")); } [Theory] [InlineData(".")] [InlineData("/home")] public void LambdaFunction_GetLocalPathAndEmptyS3Bucket(string localPath) { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { {"Code/S3Bucket", "" }, {"Code/S3Key", localPath } }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_LAMBDA_FUNCTION, dataSource); Assert.Equal(localPath, resource.Fields[0].GetLocalPath()); resource.Fields[0].SetS3Location("my-bucket", "my.zip"); Assert.Equal("my-bucket", dataSource.GetValue("Code/S3Bucket")); Assert.Equal("my.zip", dataSource.GetValue("Code/S3Key")); } [Fact] public void LambdaFunction_NotUpdatableBecausePointAtAlreadyS3() { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { {"Code/S3Bucket", "my-bucket" }, {"Code/S3Key", "my.zip" } }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_LAMBDA_FUNCTION, dataSource); Assert.Null(resource.Fields[0].GetLocalPath()); } [Fact] public void ApiGatewayApi_GetCurrentDirectoryForWithNullCode() { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_SERVERLESS_API, dataSource); Assert.Null(resource.Fields[0].GetLocalPath()); } [Theory] [InlineData("/home/swagger.yml")] public void ApiGatewayApi_GetLocalPathAndEmptyS3Bucket(string localPath) { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { {"BodyS3Location/Key", localPath } }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_APIGATEWAY_RESTAPI, dataSource); Assert.Equal(localPath, resource.Fields[0].GetLocalPath()); resource.Fields[0].SetS3Location("my-bucket", localPath); Assert.Equal("my-bucket", dataSource.GetValue("BodyS3Location/Bucket")); Assert.Equal(localPath, dataSource.GetValue("BodyS3Location/Key")); } [Fact] public void AppSyncGraphQl_GetCurrentDirectoryForWithNullCode() { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_APPSYNC_GRAPHQLSCHEMA, dataSource); Assert.Null(resource.Fields[0].GetLocalPath()); } [Theory] [InlineData("/home/swagger.yml")] public void AppSyncGraphQl_GetLocalPathAndEmptyS3Bucket(string localPath) { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { {"DefinitionS3Location", localPath } }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_APPSYNC_GRAPHQLSCHEMA, dataSource); Assert.Equal(localPath, resource.Fields[0].GetLocalPath()); resource.Fields[0].SetS3Location("my-bucket", "swagger.yml"); Assert.Equal("s3://my-bucket/swagger.yml", dataSource.GetValue("DefinitionS3Location")); } [Fact] public void AppSyncResolver_GetCurrentDirectoryForWithNullCode() { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_APPSYNC_RESOLVER, dataSource); Assert.Null(resource.Fields[0].GetLocalPath()); Assert.Null(resource.Fields[1].GetLocalPath()); } [Fact] public void AppSyncResolver_GetLocalPathAndEmptyS3Bucket() { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { {"ResponseMappingTemplateS3Location", "response.xml" }, {"RequestMappingTemplateS3Location", "request.xml" } }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_APPSYNC_RESOLVER, dataSource); Assert.Equal("response.xml", resource.Fields[0].GetLocalPath()); Assert.Equal("request.xml", resource.Fields[1].GetLocalPath()); resource.Fields[0].SetS3Location("my-bucket", "response.xml-updated"); Assert.Equal("s3://my-bucket/response.xml-updated", dataSource.GetValue("ResponseMappingTemplateS3Location")); resource.Fields[1].SetS3Location("my-bucket", "request.xml-updated"); Assert.Equal("s3://my-bucket/request.xml-updated", dataSource.GetValue("RequestMappingTemplateS3Location")); } [Fact] public void ServerlessApi_GetCurrentDirectoryForWithNullCode() { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_APIGATEWAY_RESTAPI, dataSource); Assert.Null(resource.Fields[0].GetLocalPath()); } [Theory] [InlineData("/home/swagger.yml")] public void ServerlessApi_GetLocalPathAndEmptyS3Bucket(string localPath) { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { {"DefinitionUri", localPath } }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_SERVERLESS_API, dataSource); Assert.Equal(localPath, resource.Fields[0].GetLocalPath()); resource.Fields[0].SetS3Location("my-bucket", "swagger.yml"); Assert.Equal("s3://my-bucket/swagger.yml", dataSource.GetValue("DefinitionUri")); } [Fact] public void ElasticBeanstalkApplicationVersion_GetCurrentDirectoryForWithNullCode() { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_ELASTICBEANSTALK_APPLICATIONVERSION, dataSource); Assert.Null(resource.Fields[0].GetLocalPath()); } [Theory] [InlineData("/home/app.zip")] public void ElasticBeanstalkApplicationVersion_GetLocalPathAndEmptyS3Bucket(string localPath) { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { {"SourceBundle/S3Key", localPath } }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_ELASTICBEANSTALK_APPLICATIONVERSION, dataSource); Assert.Equal(localPath, resource.Fields[0].GetLocalPath()); resource.Fields[0].SetS3Location("my-bucket", localPath); Assert.Equal("my-bucket", dataSource.GetValue("SourceBundle/S3Bucket")); Assert.Equal(localPath, dataSource.GetValue("SourceBundle/S3Key")); } [Fact] public void CloudFormationStack_GetCurrentDirectoryForWithNullCode() { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_CLOUDFORMATION_STACK, dataSource); Assert.Null(resource.Fields[0].GetLocalPath()); } [Theory] [MemberData(nameof(IgnoreResourceWithInlineCodeData))] public void IgnoreResourceWithInlineCode(IUpdatableResourceDataSource source) { var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_LAMBDA_FUNCTION, source); Assert.False(resource.Fields[0].IsCode); } public static IEnumerable<object[]> IgnoreResourceWithInlineCodeData() { const string InlineCode = @"{ 'Fn::Join': ['', [ 'var response = require('cfn-response');', 'exports.handler = function(event, context) {', ' var input = parseInt(event.ResourceProperties.Input);', ' var responseData = {Value: input * 5};', ' response.send(event, context, response.SUCCESS, responseData);', '};' ]]}"; var list = new List<object[]>(); { var codeData = new JsonData(); codeData["ZipFile"] = InlineCode; var rootData = new JsonData(); rootData["Code"] = codeData; var source = new JsonTemplateParser.JsonUpdatableResourceDataSource(null, null, rootData); list.Add(new object[] { source }); } { var codeData = new YamlMappingNode(); codeData.Children.Add("ZipFile", new YamlScalarNode(InlineCode)); var rootData = new YamlMappingNode(); rootData.Children.Add("Code", codeData); var source = new YamlTemplateParser.YamlUpdatableResourceDataSource(null, null, rootData); list.Add(new object[] { source }); } return list; } [Theory] [InlineData("/home/infra.template")] public void CloudFormationStack_GetLocalPathAndEmptyS3Bucket(string localPath) { var dataSource = new FakeUpdatableResourceDataSource( new Dictionary<string, string> { {"TemplateUrl", localPath } }); var resource = new UpdatableResource("TestResource", UpdatableResourceDefinition.DEF_CLOUDFORMATION_STACK, dataSource); Assert.Equal(localPath, resource.Fields[0].GetLocalPath()); resource.Fields[0].SetS3Location("my-bucket", "swagger.yml"); Assert.Equal("s3://my-bucket/swagger.yml", dataSource.GetValue("TemplateUrl")); } [Fact] public void TestGetDictionaryFromResourceForJsonTemplate() { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ImageBasedProjects/ServerlessTemplateExamples"); var cloudFormationTemplate = "serverless-resource-dockerbuildargs-json.template"; string templateBody = File.ReadAllText(Path.Combine(fullPath, cloudFormationTemplate)); var root = JsonMapper.ToObject(templateBody); var firstResource = root["Resources"][0]; var jsonDataSource = new JsonUpdatableResourceDataSource(null, firstResource, null); var valueDictionaryFromResource = jsonDataSource.GetValueDictionaryFromResource("Metadata", "DockerBuildArgs"); Assert.NotNull(valueDictionaryFromResource); Assert.Equal(2, valueDictionaryFromResource.Count); Assert.Equal("/src/path-to/project", valueDictionaryFromResource["PROJECT_PATH"]); Assert.Equal("project.csproj", valueDictionaryFromResource["PROJECT_FILE"]); } [Fact] public void TestGetDictionaryFromResourceForYamlTemplate() { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/ImageBasedProjects/ServerlessTemplateExamples"); var cloudFormationTemplate = "serverless-resource-dockerbuildargs-yaml.template"; string templateBody = File.ReadAllText(Path.Combine(fullPath, cloudFormationTemplate)); YamlStream yamlStream = new YamlStream(); yamlStream.Load(new StringReader(templateBody)); var root = (YamlMappingNode)yamlStream.Documents[0].RootNode; var resourcesKey = new YamlScalarNode("Resources"); var resources = (YamlMappingNode)root.Children[resourcesKey]; var firstResource = (YamlMappingNode)resources.Children.First().Value; var yamlDataSource = new YamlUpdatableResourceDataSource(null, firstResource, null); var valueDictionaryFromResource = yamlDataSource.GetValueDictionaryFromResource("Metadata", "DockerBuildArgs"); Assert.NotNull(valueDictionaryFromResource); Assert.Equal(2, valueDictionaryFromResource.Count); Assert.Equal("/src/path-to/project", valueDictionaryFromResource["PROJECT_PATH"]); Assert.Equal("project.csproj", valueDictionaryFromResource["PROJECT_FILE"]); } public class FakeUpdatableResourceDataSource : IUpdatableResourceDataSource { IDictionary<string, string> Root { get; } IDictionary<string, string> Properties { get; } public FakeUpdatableResourceDataSource(IDictionary<string, string> root, IDictionary<string, string> properties) { this.Root = root; this.Properties = properties; } public FakeUpdatableResourceDataSource(IDictionary<string, string> properties) : this(properties, properties) { } public string GetValueFromRoot(params string[] keyPath) { return GetValue(this.Root, keyPath); } public string[] GetValueListFromRoot(params string[] keyPath) { return GetValueList(this.Root, keyPath); } public string GetValue(params string[] keyPath) { return GetValue(this.Properties, keyPath); } private string GetValue(IDictionary<string, string> values, params string[] keyPath) { var key = string.Join("/", keyPath); if (values.TryGetValue(key, out var value)) return value; return null; } public string[] GetValueList(params string[] keyPath) { return GetValueList(this.Properties, keyPath); } private string[] GetValueList(IDictionary<string, string> values, params string[] keyPath) { var key = string.Join("/", keyPath); if (values.TryGetValue(key, out var value)) return value.Split(','); return null; } public void SetValue(string value, params string[] keyPath) { var key = string.Join("/", keyPath); Properties[key] = value; } public void SetValueList(string[] values, params string[] keyPath) { var key = string.Join("/", keyPath); Properties[key] = string.Join(',', values); } public string GetValueFromResource(params string[] keyPath) { throw new System.NotImplementedException(); } public Dictionary<string, string> GetValueDictionaryFromResource(params string[] keyPath) { throw new System.NotImplementedException(); } } } }
626
aws-extensions-for-dotnet-cli
aws
C#
using System.Collections.Generic; using System.IO; using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Xunit; namespace Amazon.Lambda.Tools.Test { public class TemplateSubsitutionTests { private string GetTestProjectPath(string project) { var assembly = this.GetType().GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/TemplateSubstitutionTestProjects/" + project); return fullPath; } [Fact] public void SubstituteStateMachine() { var fullPath = GetTestProjectPath("StateMachineDefinitionStringTest"); var templateBody = File.ReadAllText(Path.Combine(fullPath, "serverless.template")); var substitutions = new Dictionary<string, string> { {"$.Resources.WorkFlow.Properties.DefinitionString.Fn::Sub", "state-machine.json" } }; var newTemplateBody = LambdaUtilities.ProcessTemplateSubstitions(null, templateBody, substitutions, fullPath); var root = JsonConvert.DeserializeObject(newTemplateBody) as JObject; var value = root.SelectToken("$.Resources.WorkFlow.Properties.DefinitionString.Fn::Sub") as JValue; Assert.NotNull(value); Assert.Equal(value.Type, JTokenType.String); var stateMachineContent = File.ReadAllText(Path.Combine(fullPath, "state-machine.json")); Assert.Equal(stateMachineContent, value.Value); } [Fact] public void SubstituteObject() { var templateBody = "{'Name':'test', 'Data' : {'MyObj': {}}}"; var swapData = "{'Foo' : 'Bar'}"; var substitutions = new Dictionary<string, string> { {"$.Data.MyObj", swapData } }; var newTemplateBody = LambdaUtilities.ProcessTemplateSubstitions(null, templateBody, substitutions, null); var root = JsonConvert.DeserializeObject(newTemplateBody) as JObject; var value = root.SelectToken("$.Data.MyObj") as JObject; Assert.Equal("Bar", value["Foo"].ToString()); } [Fact] public void SubstituteArray() { var templateBody = "{'Name':'test', 'Data' : {'MyArray': []}}"; var swapData = "['Foo', 'Bar']"; var substitutions = new Dictionary<string, string> { {"$.Data.MyArray", swapData } }; var newTemplateBody = LambdaUtilities.ProcessTemplateSubstitions(null, templateBody, substitutions, null); var root = JsonConvert.DeserializeObject(newTemplateBody) as JObject; var value = root.SelectToken("$.Data.MyArray") as JArray; Assert.Equal(2, value.Count); Assert.Equal("Foo", value[0]); Assert.Equal("Bar", value[1]); } [Fact] public void SubstituteBool() { var templateBody = "{'Name':'test', 'Data' : {'MyBool': false}}"; var swapData = "true"; var substitutions = new Dictionary<string, string> { {"$.Data.MyBool", swapData } }; var newTemplateBody = LambdaUtilities.ProcessTemplateSubstitions(null, templateBody, substitutions, null); var root = JsonConvert.DeserializeObject(newTemplateBody) as JObject; var value = root.SelectToken("$.Data.MyBool") as JValue; Assert.Equal(true, value.Value); } [Fact] public void SubstituteInt() { var templateBody = "{'Name':'test', 'Data' : {'MyInt': 0}}"; var swapData = "100"; var substitutions = new Dictionary<string, string> { {"$.Data.MyInt", swapData } }; var newTemplateBody = LambdaUtilities.ProcessTemplateSubstitions(null, templateBody, substitutions, null); var root = JsonConvert.DeserializeObject(newTemplateBody) as JObject; var value = root.SelectToken("$.Data.MyInt") as JValue; Assert.Equal(100L, value.Value); } [Fact] public void SubstituteNullString() { var templateBody = "{'Name':'test', 'Data' : {'MyString': null}}"; var swapData = "100"; var substitutions = new Dictionary<string, string> { {"$.Data.MyString", swapData } }; Assert.Throws<LambdaToolsException>(() => LambdaUtilities.ProcessTemplateSubstitions(null, templateBody, substitutions, null)); } } }
136
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; using Amazon.Common.DotNetCli.Tools; using Amazon.Lambda.Tools.Commands; namespace Amazon.Lambda.Tools.Test { public static class TestHelper { const string LAMBDATOOL_TEST_ROLE = "dotnet-lambdatools-test-role"; private static string _roleArn; private static IAmazonIdentityManagementService _iamClient = new AmazonIdentityManagementServiceClient(Amazon.RegionEndpoint.USEast1); static SemaphoreSlim roleLock = new SemaphoreSlim(1, 1); public static async Task<string> GetTestRoleArnAsync() { await roleLock.WaitAsync(TimeSpan.FromMinutes(5)); try { if (!string.IsNullOrEmpty(_roleArn)) return _roleArn; try { _roleArn = (await _iamClient.GetRoleAsync(new GetRoleRequest { RoleName = LAMBDATOOL_TEST_ROLE })).Role.Arn; } catch (Exception e) { if (e is NoSuchEntityException || e.InnerException is NoSuchEntityException) { // Role is not found so create a role with no permissions other then Lambda can assume the role. // The role is deleted and reused in other runs of the test to make the test run faster. _roleArn = RoleHelper.CreateRole(_iamClient, LAMBDATOOL_TEST_ROLE, Constants.LAMBDA_ASSUME_ROLE_POLICY, "arn:aws:iam::aws:policy/PowerUserAccess"); // Wait for new role to propogate System.Threading.Thread.Sleep(5000); } else { throw; } } return _roleArn; } finally { roleLock.Release(); } } public static async Task<string> GetPhysicalCloudFormationResourceId(IAmazonCloudFormation cfClient, string stackName, string logicalId) { var response = await cfClient.DescribeStackResourcesAsync(new DescribeStackResourcesRequest() { StackName = stackName, LogicalResourceId = logicalId }); foreach (var resource in response.StackResources) { if (string.Equals(resource.LogicalResourceId, logicalId, StringComparison.OrdinalIgnoreCase)) { return resource.PhysicalResourceId; } } return null; } public static async Task<string> GetOutputParameter(IAmazonCloudFormation cfClient, string stackName, string outputName) { var response = await cfClient.DescribeStacksAsync(new DescribeStacksRequest() { StackName = stackName }); foreach (var output in response.Stacks[0].Outputs) { if (string.Equals(output.OutputKey, outputName, StringComparison.OrdinalIgnoreCase)) { return output.OutputValue; } } return null; } } }
101
aws-extensions-for-dotnet-cli
aws
C#
using System.Text; using Amazon.Common.DotNetCli.Tools; using Xunit.Abstractions; namespace Amazon.Lambda.Tools.Test { public class TestToolLogger : IToolLogger { private readonly ITestOutputHelper _testOutputHelper; StringBuilder _buffer = new StringBuilder(); public TestToolLogger() { } public TestToolLogger(ITestOutputHelper testOutputHelper) { _testOutputHelper = testOutputHelper; } public void WriteLine(string message) { this._buffer.AppendLine(message); _testOutputHelper?.WriteLine(message); } public void WriteLine(string message, params object[] args) { this.WriteLine(string.Format(message, args)); } public void ClearBuffer() { this._buffer.Clear(); } public string Buffer { get { return this._buffer.ToString(); } } } }
44
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Xunit; using Amazon.Common.DotNetCli.Tools; using System.Threading.Tasks; using Moq; using Amazon.S3; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; using System.Threading; using Amazon.S3.Model; using Xunit.Abstractions; using System.Linq; using static Amazon.Lambda.Tools.TemplateProcessor.UpdatableResource; namespace Amazon.Lambda.Tools.Test { public class UtilitiesTests { private readonly ITestOutputHelper _testOutputHelper; public UtilitiesTests(ITestOutputHelper testOutputHelper) { this._testOutputHelper = testOutputHelper; } [Theory] [InlineData("dotnetcore2.1", "netcoreapp2.1")] [InlineData("dotnetcore2.0", "netcoreapp2.0")] [InlineData("dotnetcore1.0", "netcoreapp1.0")] public void MapLambdaRuntimeWithFramework(string runtime, string framework) { Assert.Equal(runtime, LambdaUtilities.DetermineLambdaRuntimeFromTargetFramework(framework)); } [Fact] public void MapInvalidLambdaRuntimeWithFramework() { Assert.Null(LambdaUtilities.DetermineLambdaRuntimeFromTargetFramework("not-real")); } [Theory] [InlineData("exactlength", "exactlength", 11)] [InlineData("short", "short", 10)] [InlineData("longlonglong", "longlong", 8)] public void TestGettingLayerDescriptionForNonDotnetLayer(string fullLayer, string displayLayer, int maxLength) { var value = LambdaUtilities.DetermineListDisplayLayerDescription(fullLayer, maxLength); Assert.Equal(displayLayer, value); } [Theory] [InlineData("netcoreapp1.0", LambdaConstants.ARCHITECTURE_X86_64, "rhel.7.2-x64")] [InlineData("netcoreapp1.1", LambdaConstants.ARCHITECTURE_X86_64, "linux-x64")] [InlineData("netcoreapp2.0", LambdaConstants.ARCHITECTURE_X86_64, "rhel.7.2-x64")] [InlineData("netcoreapp2.1", LambdaConstants.ARCHITECTURE_X86_64, "rhel.7.2-x64")] [InlineData("netcoreapp2.2", LambdaConstants.ARCHITECTURE_X86_64, "linux-x64")] [InlineData("netcoreapp3.0", LambdaConstants.ARCHITECTURE_X86_64, "linux-x64")] [InlineData("netcoreapp3.1", LambdaConstants.ARCHITECTURE_X86_64, "linux-x64")] [InlineData("netcoreapp6.0", LambdaConstants.ARCHITECTURE_X86_64, "linux-x64")] [InlineData("netcoreapp3.1", LambdaConstants.ARCHITECTURE_ARM64, "linux-arm64")] [InlineData("netcoreapp6.0", LambdaConstants.ARCHITECTURE_ARM64, "linux-arm64")] [InlineData(null, LambdaConstants.ARCHITECTURE_X86_64, "linux-x64")] [InlineData(null, LambdaConstants.ARCHITECTURE_ARM64, "linux-arm64")] public void TestDetermineRuntimeParameter(string targetFramework, string architecture, string expectedValue) { var runtime = LambdaUtilities.DetermineRuntimeParameter(targetFramework, architecture); Assert.Equal(expectedValue, runtime); } [Theory] [InlineData("repo:old", "repo", "old")] [InlineData("repo", "repo", "latest")] [InlineData("repo:", "repo", "latest")] public void TestSplitImageTag(string imageTag, string repositoryName, string tag) { var tuple = Amazon.Lambda.Tools.Commands.PushDockerImageCommand.SplitImageTag(imageTag); Assert.Equal(repositoryName, tuple.RepositoryName); Assert.Equal(tag, tuple.Tag); } [Theory] [InlineData("Seed", "foo:bar", "1234", "foo:seed-1234-bar")] [InlineData("Seed", "foo", "1234", "foo:seed-1234-latest")] public void TestGenerateUniqueTag(string uniqueSeed, string destinationDockerTag, string imageId, string expected) { var tag = Amazon.Lambda.Tools.Commands.PushDockerImageCommand.GenerateUniqueEcrTag(uniqueSeed, destinationDockerTag, imageId); Assert.Equal(expected, tag); } [Fact] public void TestGenerateUniqueTagWithNullImageId() { var tag = Amazon.Lambda.Tools.Commands.PushDockerImageCommand.GenerateUniqueEcrTag("Seed", "foo:bar", null); Assert.StartsWith("foo:seed-", tag); Assert.EndsWith("-bar", tag); var tokens = tag.Split('-'); var ticks = long.Parse(tokens[1]); var dt = new DateTime(ticks); Assert.Equal(DateTime.UtcNow.Year, dt.Year); } [Theory] [InlineData("ProjectName", "projectname")] [InlineData("Amazon.Lambda_Tools-CLI", "amazon.lambda_tools-cli")] [InlineData("._-Solo", "solo")] [InlineData("Foo@Bar", "foobar")] [InlineData("#$%^&!", null)] [InlineData("a", null)] public void TestGeneratingECRRepositoryName(string projectName, string expectRepositoryName) { string repositoryName; var computed = Amazon.Common.DotNetCli.Tools.Utilities.TryGenerateECRRepositoryName(projectName, out repositoryName); if (expectRepositoryName == null) { Assert.False(computed); } else { Assert.True(computed); Assert.Equal(expectRepositoryName, repositoryName); } } [Fact] public void TestMaxLengthGeneratedRepositoryName() { var projectName = new string('A', 1000); string repositoryName; var computed = Amazon.Common.DotNetCli.Tools.Utilities.TryGenerateECRRepositoryName(projectName, out repositoryName); Assert.True(computed); Assert.Equal(new string('a', 256), repositoryName); } [Theory] [InlineData("Dockerfile.custom", "", "Dockerfile.custom")] [InlineData(@"c:\project\Dockerfile.custom", null, @"c:\project\Dockerfile.custom")] [InlineData("Dockerfile.custom", @"c:\project", "Dockerfile.custom")] [InlineData(@"c:\project\Dockerfile.custom", @"c:\project", "Dockerfile.custom")] [InlineData(@"c:\par1\Dockerfile.custom", @"c:\par1\par2", "../Dockerfile.custom")] public void TestSavingDockerfileInDefaults(string dockerfilePath, string projectLocation, string expected) { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { dockerfilePath = dockerfilePath.Replace(@"c:\", "/").Replace(@"\", "/"); projectLocation = projectLocation?.Replace(@"c:\", "/").Replace(@"\", "/"); expected = expected.Replace(@"c:\", "/").Replace(@"\", "/"); } var rootData = new ThirdParty.Json.LitJson.JsonData(); rootData.SetFilePathIfNotNull("Dockerfile", dockerfilePath, projectLocation); Assert.Equal(expected, rootData["Dockerfile"]); } [Theory] [InlineData("netcoreapp1.0", LambdaConstants.ARCHITECTURE_X86_64, "throws")] [InlineData("netcoreapp1.1", LambdaConstants.ARCHITECTURE_X86_64, "throws")] [InlineData("netcoreapp2.0", LambdaConstants.ARCHITECTURE_X86_64, "throws")] [InlineData("netcoreapp2.1", LambdaConstants.ARCHITECTURE_X86_64, "throws")] [InlineData("netcoreapp2.2", LambdaConstants.ARCHITECTURE_X86_64, "throws")] [InlineData("netcoreapp3.0", LambdaConstants.ARCHITECTURE_X86_64, "throws")] [InlineData("netcoreapp3.1", LambdaConstants.ARCHITECTURE_X86_64, "public.ecr.aws/sam/build-dotnetcore3.1:latest-x86_64")] [InlineData("netcoreapp3.1", "", "public.ecr.aws/sam/build-dotnetcore3.1:latest-x86_64")] [InlineData("netcoreapp3.1", LambdaConstants.ARCHITECTURE_ARM64, "public.ecr.aws/sam/build-dotnetcore3.1:latest-arm64")] [InlineData("net6.0", LambdaConstants.ARCHITECTURE_X86_64, "public.ecr.aws/sam/build-dotnet6:latest-x86_64")] [InlineData("net6.0", null, "public.ecr.aws/sam/build-dotnet6:latest-x86_64")] [InlineData("net6.0", LambdaConstants.ARCHITECTURE_ARM64, "public.ecr.aws/sam/build-dotnet6:latest-arm64")] [InlineData("net7.0", LambdaConstants.ARCHITECTURE_X86_64, "public.ecr.aws/sam/build-dotnet7:latest-x86_64")] [InlineData("net7.0", " ", "public.ecr.aws/sam/build-dotnet7:latest-x86_64")] [InlineData("net7.0", LambdaConstants.ARCHITECTURE_ARM64, "public.ecr.aws/sam/build-dotnet7:latest-arm64")] [InlineData(null, LambdaConstants.ARCHITECTURE_X86_64, "throws")] [InlineData(null, LambdaConstants.ARCHITECTURE_ARM64, "throws")] public void GetDefaultBuildImage(string targetFramework, string architecture, string expectedValue) { if (expectedValue == "throws") { Assert.Throws<LambdaToolsException>(() => LambdaUtilities.GetDefaultBuildImage(targetFramework, architecture, new TestToolLogger(_testOutputHelper))); return; } var containerImageFile = LambdaUtilities.GetDefaultBuildImage(targetFramework, architecture, new TestToolLogger(_testOutputHelper)); Assert.Equal(expectedValue, containerImageFile); } [Theory] [InlineData(null, false)] [InlineData("somelocalpath", false)] [InlineData("123456789012", false)] [InlineData("139480602983.dkr.ecr.us-east-2.amazonaws.com/test-deploy-serverless-image-uri", true)] [InlineData("139480602.dkr.ecr.us-east-2.amazonaws.com/test-deploy-serverless-image-uri", false)] public void TestIsECRImage(string path, bool expectedValue) { bool isECRImage = UpdatableResourceField.IsECRImage(path); Assert.Equal(expectedValue, isECRImage); } [Theory] [InlineData("../../../../../testapps/TestFunction", "net6.0", false, false)] [InlineData("../../../../../testapps/TestFunction", "net6.0", true, true)] [InlineData("../../../../../testapps/TestFunction", "net7.0", true, true)] [InlineData("../../../../../testapps/TestFunction", "net7.0", false, false)] [InlineData("../../../../../testapps/TestFunction", "net5.0", false, false)] [InlineData("../../../../../testapps/TestNativeAotSingleProject", "net7.0", true, false)] [InlineData("../../../../../testapps/TestNativeAotSingleProject", "net7.0", false, false)] [InlineData("../../../../../testapps/TestNativeAotSingleProject", "net6.0", false, false)] [InlineData("../../../../../testapps/TestNativeAotSingleProject", "net6.0", true, true)] [InlineData("../../../../../testapps/TestNativeAotSingleProject", "net5.0", true, true)] public void TestValidateTargetFramework(string projectLocation, string targetFramework, bool isNativeAot, bool shouldThrow) { if (shouldThrow) { Assert.Throws<LambdaToolsException>(() => LambdaUtilities.ValidateTargetFramework(projectLocation, targetFramework, isNativeAot)); } else { // If this throws an exception, the test will fail, hench no assert is necessary LambdaUtilities.ValidateTargetFramework(projectLocation, targetFramework, isNativeAot); } } [Fact] public async Task UseDefaultBucketThatAlreadyExists() { var expectedBucket = $"{LambdaConstants.DEFAULT_BUCKET_NAME_PREFIX}us-west-2-123412341234"; bool getCallerIdentityCallCount = false; var stsClientMock = new Mock<IAmazonSecurityTokenService>(); stsClientMock.Setup(client => client.GetCallerIdentityAsync(It.IsAny<GetCallerIdentityRequest>(), It.IsAny<CancellationToken>())) .Returns((GetCallerIdentityRequest r, CancellationToken token) => { getCallerIdentityCallCount = true; var response = new GetCallerIdentityResponse { Account = "123412341234" }; return Task.FromResult(response); }); bool listBucketsAsyncCallCount = false; bool putBucketCallCount = false; var s3ClientMock = new Mock<IAmazonS3>(); s3ClientMock.SetupGet(client => client.Config).Returns(new AmazonS3Config { RegionEndpoint = RegionEndpoint.USWest2 }); s3ClientMock.Setup(client => client.ListBucketsAsync(It.IsAny<ListBucketsRequest>(), It.IsAny<CancellationToken>())) .Returns(() => { listBucketsAsyncCallCount = true; var response = new ListBucketsResponse { Buckets = { new S3Bucket { BucketName = expectedBucket } } }; return Task.FromResult(response); }); s3ClientMock.Setup(client => client.PutBucketAsync(It.IsAny<PutBucketRequest>(), It.IsAny<CancellationToken>())) .Returns(() => { putBucketCallCount = true; return Task.FromResult(new PutBucketResponse()); }); var logger = new TestToolLogger(); var s3Bucket = await LambdaUtilities.ResolveDefaultS3Bucket(logger, s3ClientMock.Object, stsClientMock.Object); Assert.Equal(expectedBucket, s3Bucket); Assert.True(getCallerIdentityCallCount); Assert.True(listBucketsAsyncCallCount); Assert.False(putBucketCallCount); } [Fact] public async Task CreateDefaultBucket() { var expectedBucket = $"{LambdaConstants.DEFAULT_BUCKET_NAME_PREFIX}us-west-2-123412341234"; bool getCallerIdentityCallCount = false; var stsClientMock = new Mock<IAmazonSecurityTokenService>(); stsClientMock.Setup(client => client.GetCallerIdentityAsync(It.IsAny<GetCallerIdentityRequest>(), It.IsAny<CancellationToken>())) .Returns((GetCallerIdentityRequest r, CancellationToken token) => { getCallerIdentityCallCount = true; var response = new GetCallerIdentityResponse { Account = "123412341234" }; return Task.FromResult(response); }); bool listBucketsAsyncCallCount = false; bool putBucketCallCount = false; var s3ClientMock = new Mock<IAmazonS3>(); s3ClientMock.SetupGet(client => client.Config).Returns(new AmazonS3Config { RegionEndpoint = RegionEndpoint.USWest2 }); s3ClientMock.Setup(client => client.ListBucketsAsync(It.IsAny<ListBucketsRequest>(), It.IsAny<CancellationToken>())) .Returns(() => { listBucketsAsyncCallCount = true; return Task.FromResult(new ListBucketsResponse()); }); s3ClientMock.Setup(client => client.PutBucketAsync(It.IsAny<PutBucketRequest>(), It.IsAny<CancellationToken>())) .Callback<PutBucketRequest, CancellationToken>((request, token) => { Assert.Equal(expectedBucket, request.BucketName); }) .Returns(() => { putBucketCallCount = true; return Task.FromResult(new PutBucketResponse()); }); var logger = new TestToolLogger(); var s3Bucket = await LambdaUtilities.ResolveDefaultS3Bucket(logger, s3ClientMock.Object, stsClientMock.Object); Assert.Equal(expectedBucket, s3Bucket); Assert.True(getCallerIdentityCallCount); Assert.True(listBucketsAsyncCallCount); Assert.True(putBucketCallCount); } } }
325
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; using Amazon.Lambda; using Xunit; using Moq; using Amazon.Lambda.Model; using System.Threading; using System.Threading.Tasks; using YamlDotNet.Core; namespace Amazon.Lambda.Tools.Test { public class WaitTillFunctionAvailableTests { [Fact] public async Task FunctionImmediateAvailable() { var functionName = "fakeFunction"; var mockLambda = new Mock<IAmazonLambda>(); mockLambda.Setup(client => client.GetFunctionConfigurationAsync(It.IsAny<GetFunctionConfigurationRequest>(), It.IsAny<CancellationToken>())) .Callback<GetFunctionConfigurationRequest, CancellationToken>((request, token) => { Assert.Equal(functionName, request.FunctionName); }) .Returns((GetFunctionConfigurationRequest r, CancellationToken token) => { return Task.FromResult(new GetFunctionConfigurationResponse { State = State.Active, LastUpdateStatus = LastUpdateStatus.Successful }); }); var logger = new TestToolLogger(); await LambdaUtilities.WaitTillFunctionAvailableAsync(logger, mockLambda.Object, functionName); Assert.Equal(0, logger.Buffer.Length); } [Fact] public async Task NewFunctionBecomesAvailable() { var functionName = "fakeFunction"; var mockLambda = new Mock<IAmazonLambda>(); var getConfigCallCount = 0; mockLambda.Setup(client => client.GetFunctionConfigurationAsync(It.IsAny<GetFunctionConfigurationRequest>(), It.IsAny<CancellationToken>())) .Callback<GetFunctionConfigurationRequest, CancellationToken>((request, token) => { Assert.Equal(functionName, request.FunctionName); }) .Returns((GetFunctionConfigurationRequest r, CancellationToken token) => { getConfigCallCount++; if(getConfigCallCount < 3) { return Task.FromResult(new GetFunctionConfigurationResponse { State = State.Pending, LastUpdateStatus = LastUpdateStatus.InProgress }); } return Task.FromResult(new GetFunctionConfigurationResponse { State = State.Active, LastUpdateStatus = LastUpdateStatus.Successful }); }); var logger = new TestToolLogger(); await LambdaUtilities.WaitTillFunctionAvailableAsync(logger, mockLambda.Object, functionName); Assert.Contains("An update is currently", logger.Buffer); Assert.Contains("... Waiting", logger.Buffer); } [Fact] public async Task UpdateFunctionBecomesAvailable() { var functionName = "fakeFunction"; var mockLambda = new Mock<IAmazonLambda>(); var getConfigCallCount = 0; mockLambda.Setup(client => client.GetFunctionConfigurationAsync(It.IsAny<GetFunctionConfigurationRequest>(), It.IsAny<CancellationToken>())) .Callback<GetFunctionConfigurationRequest, CancellationToken>((request, token) => { Assert.Equal(functionName, request.FunctionName); }) .Returns((GetFunctionConfigurationRequest r, CancellationToken token) => { getConfigCallCount++; if (getConfigCallCount < 3) { return Task.FromResult(new GetFunctionConfigurationResponse { State = State.Active, LastUpdateStatus = LastUpdateStatus.InProgress }); } return Task.FromResult(new GetFunctionConfigurationResponse { State = State.Active, LastUpdateStatus = LastUpdateStatus.Successful }); }); var logger = new TestToolLogger(); await LambdaUtilities.WaitTillFunctionAvailableAsync(logger, mockLambda.Object, functionName); Assert.Contains("An update is currently", logger.Buffer); Assert.Contains("... Waiting", logger.Buffer); } [Fact] public async Task UpdateFunctionGoesToFailure() { var functionName = "fakeFunction"; var mockLambda = new Mock<IAmazonLambda>(); var getConfigCallCount = 0; mockLambda.Setup(client => client.GetFunctionConfigurationAsync(It.IsAny<GetFunctionConfigurationRequest>(), It.IsAny<CancellationToken>())) .Callback<GetFunctionConfigurationRequest, CancellationToken>((request, token) => { Assert.Equal(functionName, request.FunctionName); }) .Returns((GetFunctionConfigurationRequest r, CancellationToken token) => { getConfigCallCount++; if (getConfigCallCount < 3) { return Task.FromResult(new GetFunctionConfigurationResponse { State = State.Active, LastUpdateStatus = LastUpdateStatus.InProgress }); } return Task.FromResult(new GetFunctionConfigurationResponse { State = State.Active, LastUpdateStatus = LastUpdateStatus.Failed, LastUpdateStatusReason = "Its Bad" }); }); var logger = new TestToolLogger(); await LambdaUtilities.WaitTillFunctionAvailableAsync(logger, mockLambda.Object, functionName); Assert.Contains("An update is currently", logger.Buffer); Assert.Contains("... Waiting", logger.Buffer); Assert.Contains("Warning: function", logger.Buffer); Assert.Contains("Its Bad", logger.Buffer); } } }
166
aws-extensions-for-dotnet-cli
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Xunit; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AWS.Lambda.Tools.Test")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("06804ae7-14e9-494d-a1f7-258ea6432c09")] [assembly: CollectionBehavior(DisableTestParallelization = true)]
23
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Text; using Amazon.Common.DotNetCli.Tools; namespace Amazon.Tools.TestHelpers { public class TestToolLogger : IToolLogger { StringBuilder _buffer = new StringBuilder(); public void WriteLine(string message) { this._buffer.AppendLine(message); } public void WriteLine(string message, params object[] args) { this._buffer.AppendLine(string.Format(message, args)); } public void ClearBuffer() { this._buffer.Clear(); } public string Buffer { get { return this._buffer.ToString(); } } } }
33
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.IO; using System.Reflection; namespace Amazon.Tools.TestHelpers { public static class TestUtilities { public static string GetTestProjectPath(string projectName) { var assembly = typeof(TestUtilities).GetTypeInfo().Assembly; var fullPath = Path.GetFullPath(Path.GetDirectoryName(assembly.Location) + "../../../../../../testapps/"); fullPath = Path.Combine(fullPath, projectName); return fullPath; } } }
18
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace HelloWorldWebApp { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
26
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace HelloWorldWebApp { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } } }
36
aws-extensions-for-dotnet-cli
aws
C#
using System; namespace Supportlibrary { public class Message { public static string Greeting { get { return "Hello from support library"; } } } }
13
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace TheFunction { public class Function { public string FunctionHandler(ILambdaContext context) { context.Logger.LogLine("Hello from support library test"); return Supportlibrary.Message.Greeting; } } }
24
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace UseDefaultDocker { public class Function { public string FunctionHandler(string input, ILambdaContext context) { context.Logger.LogLine("UseDefaultDocker"); return input?.ToUpper(); } } }
24
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace UseDockerMetadata { public class Function { public string FunctionHandler(string input, ILambdaContext context) { context.Logger.LogLine("UseDockerMetadata"); return input?.ToUpper(); } } }
24
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace TestSimpleImageProject { public class Function { public string FunctionHandler(string input, ILambdaContext context) { context.Logger.LogLine("Hello from cloud ToUpper"); return input?.ToUpper(); } } }
24
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace CurrentDirectoryTest { public class Functions { /// <summary> /// Default constructor that Lambda will invoke. /// </summary> public Functions() { } public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context) { var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "CurrentProjectTest", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } } }; return response; } public APIGatewayProxyResponse Get2(APIGatewayProxyRequest request, ILambdaContext context) { var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "SecondCurrentProjectTest", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } } }; return response; } } }
49
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace SiblingProjectTest { public class Function { public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context) { var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "SiblingProjectTest", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } } }; return response; } } }
31
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace ServerlessWithYamlFunction { public class Functions { /// <summary> /// Default constructor that Lambda will invoke. /// </summary> public Functions() { } /// <summary> /// A Lambda function to respond to HTTP Get methods from API Gateway /// </summary> /// <param name="request"></param> /// <returns>The list of blogs</returns> public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context) { context.Logger.LogLine("Get Request\n"); var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "Hello AWS Serverless", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } } }; return response; } } }
45
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; using System.IO; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace StateMachineDefinitionStringTest { public class Functions { /// <summary> /// Default constructor that Lambda will invoke. /// </summary> public Functions() { } /// <summary> /// A Lambda function to respond to HTTP Get methods from API Gateway /// </summary> /// <param name="request"></param> /// <returns>The list of blogs</returns> public Stream Processor(Stream stream, ILambdaContext context) { return stream; } } }
37
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace TestBeanstalkWebApp { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
25
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace TestBeanstalkWebApp { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } } }
36
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TestFunction { public class Function { [Amazon.Lambda.Core.LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] public string ToUpper(string input) { return input?.ToUpper(); } } }
18
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TestFunction { public class ValidateHandlerFunctionSignatures : BaseValidateHandlerFunctionSignatures { public string NoParameters() { return null; } public string OneStringParameters(string one) { return null; } public string TooManyParameters(string one, string two, string three) { return null; } } public class BaseValidateHandlerFunctionSignatures { public string InheritedMethod(string input) { return null; } } }
34
aws-extensions-for-dotnet-cli
aws
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TestFunction")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("11a53c8d-a49b-4477-bfd9-e00c77d1291c")]
20
aws-extensions-for-dotnet-cli
aws
C#
using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; using System.Net; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace TestHttpFunction; public class Function { public APIGatewayHttpApiV2ProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context) { var response = new APIGatewayHttpApiV2ProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = "Making HTTP Calls", Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } } }; return response; } }
25
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using System.IO; namespace TestLayerAspNetCore { /// <summary> /// This class extends from APIGatewayProxyFunction which contains the method FunctionHandlerAsync which is the /// actual Lambda function entry point. The Lambda handler field should be set to /// /// TestLayerAspNetCore::TestLayerAspNetCore.LambdaEntryPoint::FunctionHandlerAsync /// </summary> public class LambdaEntryPoint : // When using an ELB's Application Load Balancer as the event source change // the base class to Amazon.Lambda.AspNetCoreServer.ApplicationLoadBalancerFunction Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction { /// <summary> /// The builder has configuration, logging and Amazon API Gateway already configured. The startup class /// needs to be configured in this method using the UseStartup<>() method. /// </summary> /// <param name="builder"></param> protected override void Init(IWebHostBuilder builder) { builder .UseStartup<Startup>(); } } }
34
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace TestLayerAspNetCore { /// <summary> /// The Main function can be used to run the ASP.NET Core application locally using the Kestrel webserver. /// </summary> public class LocalEntryPoint { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
30
aws-extensions-for-dotnet-cli
aws
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace TestLayerAspNetCore { public class Startup { public const string AppS3BucketKey = "AppS3Bucket"; public Startup(IConfiguration configuration) { Configuration = configuration; } public static IConfiguration Configuration { get; private set; } // This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { // Add S3 to the ASP.NET Core dependency injection framework. services.AddAWSService<Amazon.S3.IAmazonS3>(); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseRouting(); } } }
52