public ValidationResult Run(ValidationConfig config, ILambdaContext context)
        {
            string snsTopicArn = null;

            try
            {
                LogUtilities.UpdateLogger(context.Logger, null);
                LogUtilities.LogLambdaInfo(context, CommandLineUtilities.InformationalVersion);
                LogUtilities.LogObject("Config", config);
                LogUtilities.Log(new[] { LambdaUrlHelper.UrlBaseEnvironmentVariableName, LambdaUtilities.SnsTopicKey });
                LambdaUtilities.GarbageCollect();
                snsTopicArn = LambdaUtilities.GetEnvironmentVariable(LambdaUtilities.SnsTopicKey);

                config.Validate();
                GenomeAssembly genomeAssembly = GenomeAssemblyHelper.Convert(config.genomeAssembly);

                string nirvanaS3Ref = LambdaUrlHelper.GetRefUrl(genomeAssembly);
                var    refProvider  = ProviderUtilities.GetSequenceProvider(nirvanaS3Ref);

                using (var stream = PersistentStreamUtils.GetReadStream(config.customStrUrl))
                    TryLoadStrFile(stream, genomeAssembly, refProvider);
            }
            catch (Exception exception)
            {
                return(HandleException(config.id, exception, snsTopicArn));
            }

            return(GetSuccessOutput(config.id));
        }
Example #2
0
 public override SyntaxNode TryGetCorrespondingLambdaBody(
     SyntaxNode previousLambdaSyntax,
     SyntaxNode lambdaOrLambdaBodySyntax)
 {
     return(LambdaUtilities.TryGetCorrespondingLambdaBody(
                lambdaOrLambdaBodySyntax, previousLambdaSyntax));
 }
Example #3
0
        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);
        }
Example #4
0
        private static IEnumerable <AnnotationRange> GetAnnotationRanges(NirvanaConfig config, GenomeAssembly genomeAssembly)
        {
            string cachePathPrefix = LambdaUtilities.GetCachePathPrefix(genomeAssembly);

            IntervalForest <IGene>            geneIntervalForest;
            IDictionary <string, IChromosome> refNameToChromosome;
            List <long> blockOffsets;

            using (var tabixStream = PersistentStreamUtils.GetReadStream(config.tabixUrl))
                using (var tabixReader = new BinaryReader(new BlockGZipStream(tabixStream, CompressionMode.Decompress)))
                    using (var referenceStream = PersistentStreamUtils.GetReadStream(LambdaUrlHelper.GetRefUrl(genomeAssembly)))
                        using (var sequenceProvider = new ReferenceSequenceProvider(referenceStream))
                            using (var taProvider = new TranscriptAnnotationProvider(cachePathPrefix, sequenceProvider, null))
                            {
                                long vcfSize       = HttpUtilities.GetLength(config.vcfUrl);
                                int  numPartitions = Math.Max(Math.Min((int)((vcfSize - 1) / MinPartitionSize + 1), MaxNumPartitions), MinNumPartitions);

                                var tabixIndex = Reader.Read(tabixReader, sequenceProvider.RefNameToChromosome);
                                blockOffsets = PartitionUtilities.GetFileOffsets(config.vcfUrl, numPartitions, tabixIndex);

                                IntervalArray <ITranscript>[] transcriptIntervalArrays = taProvider.TranscriptIntervalArrays;
                                geneIntervalForest  = GeneForestGenerator.GetGeneForest(transcriptIntervalArrays);
                                refNameToChromosome = sequenceProvider.RefNameToChromosome;
                            }

            IEnumerable <AnnotationRange> annotationRanges = PartitionUtilities.GenerateAnnotationRanges(blockOffsets, config.vcfUrl, geneIntervalForest, refNameToChromosome);

            return(annotationRanges);
        }
Example #5
0
        /// <summary>
        /// There are a few places where we allow breakpoints on expressions. 
        ///
        /// 1) When the expression is the body of a lambda/method/operator/property/indexer.
        /// 2) The expression is a breakable expression inside a query expression.
        /// 3) The expression is in a for statement initializer, condition or incrementor.
        /// 4) The expression is a foreach initializer.
        /// </summary>
        private static bool IsBreakableExpression(ExpressionSyntax expression)
        {
            if (expression == null || expression.Parent == null)
            {
                return false;
            }

            var parent = expression.Parent;
            switch (parent.Kind())
            {
                case SyntaxKind.ArrowExpressionClause:
                    Debug.Assert(((ArrowExpressionClauseSyntax)parent).Expression == expression);
                    return true;

                case SyntaxKind.ForStatement:
                    var forStatement = (ForStatementSyntax)parent;
                    return
                        forStatement.Initializers.Contains(expression) ||
                        forStatement.Condition == expression ||
                        forStatement.Incrementors.Contains(expression);

                case SyntaxKind.ForEachStatement:
                case SyntaxKind.ForEachComponentStatement:
                    var forEachStatement = (CommonForEachStatementSyntax)parent;
                    return forEachStatement.Expression == expression;

                default:
                    return LambdaUtilities.IsLambdaBodyStatementOrExpression(expression);
            }
        }
Example #6
0
        private static AnnotationResources GetAnnotationResources(AnnotationConfig annotationConfig)
        {
            var    genomeAssembly  = GenomeAssemblyHelper.Convert(annotationConfig.genomeAssembly);
            string cachePathPrefix = LambdaUrlHelper.GetCacheFolder().UrlCombine(genomeAssembly.ToString()).UrlCombine(LambdaUrlHelper.DefaultCacheSource);
            string nirvanaS3Ref    = LambdaUrlHelper.GetRefUrl(genomeAssembly);
            string saManifestUrl   = LambdaUtilities.GetManifestUrl(annotationConfig.supplementaryAnnotations ?? "latest", genomeAssembly);
            var    metrics         = new PerformanceMetrics();

            var annotationResources = new AnnotationResources(nirvanaS3Ref, cachePathPrefix,
                                                              saManifestUrl == null? null: new List <string> {
                saManifestUrl
            },
                                                              annotationConfig.customAnnotations,
                                                              annotationConfig.customStrUrl,
                                                              false,
                                                              false,
                                                              false,
                                                              metrics);

            using (var tabixStream = PersistentStreamUtils.GetReadStream(annotationConfig.tabixUrl))
            {
                annotationResources.InputStartVirtualPosition = GetTabixVirtualPosition(annotationConfig.annotationRange, tabixStream, annotationResources.SequenceProvider.RefNameToChromosome);
            }

            Logger.WriteLine($"Tabix position :{annotationResources.InputStartVirtualPosition}");

            return(annotationResources);
        }
        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);
        }
        private void ValidateTargetFrameworkAndLambdaRuntime()
        {
            string runtimeName   = this.GetStringValueOrDefault(this.Runtime, LambdaDefinedCommandOptions.ARGUMENT_FUNCTION_RUNTIME, true);
            string frameworkName = this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, true);

            LambdaUtilities.ValidateTargetFrameworkAndLambdaRuntime(runtimeName, frameworkName);
        }
Example #9
0
        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"));
        }
Example #10
0
        public BoundLambda(SyntaxNode syntax, BoundBlock body, ImmutableArray <Diagnostic> diagnostics, Binder binder, TypeSymbol delegateType, bool inferReturnType)
            : this(syntax, (LambdaSymbol)binder.ContainingMemberOrLambda, body, diagnostics, binder, delegateType)
        {
            if (inferReturnType)
            {
                this._inferredReturnType = InferReturnType(
                    this.Body,
                    this.Binder,
                    delegateType,
                    this.Symbol.IsAsync,
                    ref this._inferredReturnTypeUseSiteDiagnostics,
                    out this._refKind,
                    out this._inferredFromSingleType);

#if DEBUG
                _hasInferredReturnType = true;
#endif
            }

            Debug.Assert(
                syntax.IsAnonymousFunction() ||                                                                  // lambda expressions
                syntax is ExpressionSyntax && LambdaUtilities.IsLambdaBody(syntax, allowReducedLambdas: true) || // query lambdas
                LambdaUtilities.IsQueryPairLambda(syntax)                                                        // "pair" lambdas in queries
                );
        }
        // ReSharper disable once UnusedMember.Global
        public Stream Run(GeneConfig config, ILambdaContext context)
        {
            string snsTopicArn = null;
            var    runLog      = new StringBuilder();

            try
            {
                LogUtilities.UpdateLogger(context.Logger, runLog);
                LogUtilities.LogLambdaInfo(context, CommandLineUtilities.InformationalVersion);
                LogUtilities.LogObject("Config", config);
                LogUtilities.Log(new[] { LambdaUrlHelper.UrlBaseEnvironmentVariableName, LambdaUtilities.SnsTopicKey });

                LambdaUtilities.GarbageCollect();

                snsTopicArn = LambdaUtilities.GetEnvironmentVariable(LambdaUtilities.SnsTopicKey);

                config.Validate();
                string result = GetGeneAnnotation(config, _saManifestUrl, _saPathPrefix);

                return(LambdaResponse.Create(config.id, LambdaUrlHelper.SuccessMessage, result));
            }
            catch (Exception e)
            {
                return(HandleException(config.id, snsTopicArn, e));
            }
        }
Example #12
0
        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);
        }
Example #13
0
        protected internal sealed override IEnumerable <SyntaxNode> GetDescendants(SyntaxNode node)
        {
            if (node == _oldRoot || node == _newRoot)
            {
                RoslynDebug.Assert(_oldRoot != null);
                RoslynDebug.Assert(_newRoot != null);
                RoslynDebug.Assert(_oldRootChild != null);
                RoslynDebug.Assert(_newRootChild != null);

                var rootChild = (node == _oldRoot) ? _oldRootChild : _newRootChild;

                if (HasLabel(rootChild))
                {
                    yield return(rootChild);
                }

                node = rootChild;
            }

            // TODO: avoid allocation of closure
            foreach (var descendant in node.DescendantNodes(descendIntoChildren: c => !IsLeaf(c) && (c == node || !LambdaUtilities.IsLambdaBodyStatementOrExpression(c))))
            {
                if (!LambdaUtilities.IsLambdaBodyStatementOrExpression(descendant) && HasLabel(descendant))
                {
                    yield return(descendant);
                }
            }
        }
        public void NETCore_2_1_AllWithTooNewVersionNumber()
        {
            var logger      = new TestToolLogger();
            var manifest    = File.ReadAllText(@"ManifestTestFiles/SampleManifest-v2.1.xml");
            var projectFile = File.ReadAllText(@"ManifestTestFiles/NETCore_2_1_AllWithTooNewVersionNumber.xml");


            try
            {
                LambdaUtilities.ValidateMicrosoftAspNetCoreAllReferenceFromProjectContent(logger, "netcoreapp2.1", manifest, projectFile);
                Assert.True(true, "Missing LambdaToolsException thrown");
            }
            catch (LambdaToolsException e)
            {
                Assert.Contains("which is newer than", e.Message);
            }


            projectFile = projectFile.Replace("Microsoft.AspNetCore.All", "Microsoft.AspNetCore.App");
            try
            {
                LambdaUtilities.ValidateMicrosoftAspNetCoreAllReferenceFromProjectContent(logger, "netcoreapp2.1", manifest, projectFile);
                Assert.True(true, "Missing LambdaToolsException thrown");
            }
            catch (LambdaToolsException e)
            {
                Assert.Contains("which is newer than", e.Message);
            }
        }
Example #15
0
        private IEnumerable <SyntaxNode> EnumerateNonRootChildren(SyntaxNode node)
        {
            foreach (var child in node.ChildNodes())
            {
                if (LambdaUtilities.IsLambdaBodyStatementOrExpression(child))
                {
                    continue;
                }

                if (HasLabel(child))
                {
                    yield return(child);
                }
                else
                {
                    foreach (var descendant in child.DescendantNodes(DescendIntoChildren))
                    {
                        if (HasLabel(descendant))
                        {
                            yield return(descendant);
                        }
                    }
                }
            }
        }
        protected override async Task <bool> PerformActionAsync()
        {
            EnsureInProjectDirectory();

            // 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 s3Bucket           = this.GetStringValueOrDefault(this.S3Bucket, LambdaDefinedCommandOptions.ARGUMENT_S3_BUCKET, true);
            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);

            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);

            string zipArchivePath      = null;
            var    configuration       = this.GetStringValueOrDefault(this.Configuration, CommonDefinedCommandOptions.ARGUMENT_CONFIGURATION, true);
            var    targetFramework     = this.GetStringValueOrDefault(this.TargetFramework, CommonDefinedCommandOptions.ARGUMENT_FRAMEWORK, true);
            var    msbuildParameters   = this.GetStringValueOrDefault(this.MSBuildParameters, CommonDefinedCommandOptions.ARGUMENT_MSBUILD_PARAMETERS, false);
            var    disableVersionCheck = this.GetBoolValueOrDefault(this.DisableVersionCheck, LambdaDefinedCommandOptions.ARGUMENT_DISABLE_VERSION_CHECK, false).GetValueOrDefault();
            string publishLocation;

            LambdaPackager.CreateApplicationBundle(this.DefaultConfig, this.Logger, this.WorkingDirectory, projectLocation, configuration, targetFramework, msbuildParameters, disableVersionCheck, out publishLocation, ref zipArchivePath);
            if (string.IsNullOrEmpty(zipArchivePath))
            {
                return(false);
            }

            string s3KeyApplicationBundle;

            using (var stream = new MemoryStream(File.ReadAllBytes(zipArchivePath)))
            {
                s3KeyApplicationBundle = await Utilities.UploadToS3Async(this.Logger, this.S3Client, s3Bucket, s3Prefix, Path.GetFileName(zipArchivePath), stream);
            }

            this.Logger.WriteLine($"Updating CloudFormation template to point to application bundle: s3://{s3Bucket}/{s3KeyApplicationBundle}");
            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 transformedBody = LambdaUtilities.UpdateCodeLocationInTemplate(templateBody, s3Bucket, s3KeyApplicationBundle);

            this.Logger.WriteLine($"Writing updated template: {outputTemplatePath}");
            File.WriteAllText(outputTemplatePath, transformedBody);

            return(true);
        }
        public void FindProjFiles(string projectDirectory)
        {
            var    logger   = new TestToolLogger();
            string manifest = LambdaUtilities.LoadPackageStoreManifest(logger, "netcoreapp2.0");

            LambdaUtilities.ValidateMicrosoftAspNetCoreAllReferenceFromProjectPath(logger, "netcoreapp2.0", manifest, projectDirectory);

            Assert.DoesNotContain("error", logger.Buffer.ToLower());
        }
        public void NETCore_2_0_NotUsingAspNetCore()
        {
            var logger      = new TestToolLogger();
            var manifest    = File.ReadAllText(@"ManifestTestFiles/SampleManifest.xml");
            var projectFile = File.ReadAllText(@"ManifestTestFiles/CurrentAspNetCoreReference.xml");

            LambdaUtilities.ValidateMicrosoftAspNetCoreAllReferenceFromProjectContent(logger, "netcoreapp2.0", manifest, projectFile);

            Assert.DoesNotContain("error", logger.Buffer.ToLower());
        }
Example #19
0
 public int Update(T entity, Expression <Func <T, object> >[] properties)
 {
     DatabaseContext.Entry(entity).State = System.Data.Entity.EntityState.Unchanged;
     foreach (var property in properties)
     {
         var propertyName = LambdaUtilities.GetExpressionText(property);
         DatabaseContext.Entry(entity).Property(propertyName).IsModified = true;
     }
     return(DatabaseContext.SaveChangesWithoutValidation());
 }
Example #20
0
        /// <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)
        {
            var command = new Commands.PackageCommand(this.Logger, location, null);

            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.LayerVersionArns = field.Resource.LambdaLayers;

            // If the project is in the same directory as the CloudFormation template then use any parameters
            // there 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);
            }

            var results = new UpdateResourceResults()
            {
                ZipArchivePath = outputPackage
            };

            if (!string.IsNullOrEmpty(command.NewDotnetSharedStoreValue))
            {
                results.DotnetShareStoreEnv = command.NewDotnetSharedStoreValue;
            }

            return(results);
        }
Example #21
0
        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);
        }
Example #22
0
        public BoundLambda(SyntaxNode syntax, UnboundLambda unboundLambda, BoundBlock body, ImmutableArray <Diagnostic> diagnostics, Binder binder, TypeSymbol delegateType, InferredLambdaReturnType inferredReturnType)
            : this(syntax, unboundLambda, (LambdaSymbol)binder.ContainingMemberOrLambda, body, diagnostics, binder, delegateType)
        {
            InferredReturnType = inferredReturnType;

            Debug.Assert(
                syntax.IsAnonymousFunction() ||                                                                  // lambda expressions
                syntax is ExpressionSyntax && LambdaUtilities.IsLambdaBody(syntax, allowReducedLambdas: true) || // query lambdas
                LambdaUtilities.IsQueryPairLambda(syntax)                                                        // "pair" lambdas in queries
                );
        }
        public void NETCore_2_1_AllWithSupportedVersionNumber()
        {
            var logger      = new TestToolLogger();
            var manifest    = File.ReadAllText(@"ManifestTestFiles/SampleManifest-v2.1.xml");
            var projectFile = File.ReadAllText(@"ManifestTestFiles/NETCore_2_1_AllWithSupportedVersionNumber.xml");

            LambdaUtilities.ValidateMicrosoftAspNetCoreAllReferenceFromProjectContent(logger, "netcoreapp2.1", manifest, projectFile);

            projectFile = projectFile.Replace("Microsoft.AspNetCore.All", "Microsoft.AspNetCore.App");
            LambdaUtilities.ValidateMicrosoftAspNetCoreAllReferenceFromProjectContent(logger, "netcoreapp2.1", manifest, projectFile);
        }
 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")));
 }
Example #25
0
        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);
        }
Example #26
0
        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"]);
        }
        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));
        }
        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));
        }
Example #29
0
        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);
        }
Example #30
0
        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));
        }