diff --git a/loggroup-lambda-connector/LICENSE b/loggroup-lambda-connector/LICENSE new file mode 100644 index 0000000..ba07b59 --- /dev/null +++ b/loggroup-lambda-connector/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2021 Sumo Logic Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/loggroup-lambda-connector/Readme.md b/loggroup-lambda-connector/Readme.md index bece205..d23afe4 100644 --- a/loggroup-lambda-connector/Readme.md +++ b/loggroup-lambda-connector/Readme.md @@ -9,10 +9,13 @@ Made with ❤️ by Sumo Logic. Available on the [AWS Serverless Application Rep 3. Select Show apps that create custom IAM roles or resource policies check box. 4. Click the sumologic-loggroup-connector,link, and then click Deploy. 5. In the Configure application parameters panel, - LambdaARN: "Enter ARN for target lambda function" All loggroups matching the pattern are subscribed to this function + DestinationArnType: Lambda - When the destination ARN for subscription filter is an AWS Lambda Function. + Kinesis - When the destination ARN for subscription filter is an Kinesis or Amazon Kinesis data firehose stream. + DestinationArnValue: "Enter Destination ARN like Lambda function, Kinesis stream. For more information, visit - https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html LogGroupPattern: "Enter regex for matching logGroups" UseExistingLogs: "Select true for subscribing existing logs" - LogGroupTags: "Enter comma separated keyvalue pairs for filtering logGroups using tags. Ex KeyName1=string,KeyName2=string. Supported only when UseExistingLogs is set to false." + LogGroupTags: "Enter comma separated keyvalue pairs for filtering logGroups using tags. Ex KeyName1=string,KeyName2=string. Supported only when UseExistingLogs is set to false. + RoleArn: Enter AWS IAM Role arn in case the destination is Kinesis Firehose stream." 6. Click Deploy. @@ -25,7 +28,9 @@ It has two environment variables Test - will match testlogroup, logtestgroup and LogGroupTest ``` -**LAMBDA_ARN**: This specifies ARN of the lambda functions. Also you have to specify FunctionName attribute in your lambda function so that AWS does not generate random function name. This is to avoid making changes to the lambda function configuration in case your lambda function gets created again. +**DESTINATION_ARN**: This specifies ARN of the Destination to Subscribe the log group. + +Lambda Destination ARN :- This specifies ARN of the Lambda function. Also you have to specify FunctionName attribute in your lambda function so that AWS does not generate random function name. This is to avoid making changes to the lambda function configuration in case your lambda function gets created again. ``` { @@ -42,29 +47,21 @@ It has two environment variables } ``` -**USE_EXISTING_LOGS**: This is used for subscribing existing log groups. By setting this parameter to true and invoking the function manually, all the existing log groups matching the pattern will be subscribed to lambda function with `LAMBDA_ARN` as arn +Kinesis Destination ARN :- This specifies the ARN of the kinesis Stream. -**LogGroupTags**: This is used for filtering out loggroups based on tags.Only loggroups which match any one of the key value pairs will be subscribed to the lambda function. This works only for new loggroups not existing loggroups. +**LOG_GROUP_TAGS**: This is used for filtering out loggroups based on tags.Only loggroups which match any one of the key value pairs will be subscribed to the lambda function. This works only for new loggroups not existing loggroups. -### For Developers +**ROLE_ARN** : This is used when subscription destination ARN is kinesis firehose stream. -Installing Dependencies -``` - npm install -``` +### For Developers -Building zip file -``` - npm run build -``` -Upload the generated loggroup-lambda-connector.zip in S3 bucket(don't forget to change bucket name and key in cloudformation template) +Installing Dependencies. Test cases requires [SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html), [BOTO3](https://pypi.org/project/boto3/), [CFN FLIP](https://pypi.org/project/cfn-flip/) and Requests python packages. Running the test cases ``` python test_loggroup_lambda_connector.py ``` -Run the above command after building the zip file ## License diff --git a/loggroup-lambda-connector/sam/packaged.yaml b/loggroup-lambda-connector/sam/packaged.yaml index 6f5785d..2da0692 100644 --- a/loggroup-lambda-connector/sam/packaged.yaml +++ b/loggroup-lambda-connector/sam/packaged.yaml @@ -6,7 +6,7 @@ Description: '"Lambda Function for automatic subscription of any Sumo Logic lamb ' Globals: Function: - Timeout: 300 + Timeout: 900 MemorySize: 128 Metadata: AWS::ServerlessRepo::Application: @@ -21,17 +21,27 @@ Metadata: - serverless - loggroups - cloudwatch - LicenseUrl: s3://appdevstore/LoggroupConnector/v1.0.4/5122657d5b9a0d3713e24d3a33eae431 + LicenseUrl: s3://cf-templates-1qpf3unpuo1hw-us-east-1/test-log-group-lambda-connector/6092dd6c323e33634657102f570628e0 Name: sumologic-loggroup-connector - ReadmeUrl: s3://appdevstore/LoggroupConnector/v1.0.4/c98f2c0d986a3f55fbea539688ee6a2e - SemanticVersion: 1.0.4 + ReadmeUrl: s3://cf-templates-1qpf3unpuo1hw-us-east-1/test-log-group-lambda-connector/946832fcaabeea8d4fa5580eb13fd90c + SemanticVersion: 1.0.5 SourceCodeUrl: https://github.com/SumoLogic/sumologic-aws-lambda/loggroup-lambda-connector SpdxLicenseId: Apache-2.0 Parameters: - LambdaARN: + DestinationArnType: + Type: String + Description: Lambda - When the destination ARN for subscription filter is an AWS + Lambda Function. Kinesis - When the destination ARN for subscription filter + is an Kinesis or Amazon Kinesis data firehose stream. + Default: Lambda + AllowedValues: + - Lambda + - Kinesis + DestinationArnValue: Type: String Default: arn:aws:lambda:us-east-1:123456789000:function:TestLambda - Description: Enter ARN for target lambda function + Description: Enter Destination ARN like Lambda function, Kinesis stream. For more + information, visit - https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html LogGroupPattern: Type: String Default: Test @@ -49,25 +59,69 @@ Parameters: Description: Enter comma separated keyvalue pairs for filtering logGroups using tags. Ex KeyName1=string,KeyName2=string. This is optional leave it blank if tag based filtering is not needed. + RoleArn: + Type: String + Default: '' + Description: Enter AWS IAM Role arn in case the destination is Kinesis Firehose + stream. +Conditions: + create_invoke_permission: + Fn::Equals: + - Ref: DestinationArnType + - Lambda + create_pass_role: + Fn::Equals: + - Ref: DestinationArnType + - Kinesis + invoke_existing: + Fn::Equals: + - Ref: UseExistingLogs + - 'true' +Rules: + testRoleArnWithLambda: + RuleCondition: + Fn::Equals: + - Ref: DestinationArnType + - Lambda + Assertions: + - Assert: + Fn::Equals: + - Ref: RoleArn + - '' + AssertDescription: If Destination Type is Lambda, than the role ARN should be + empty. + testRoleArnWithKinesis: + RuleCondition: + Fn::Equals: + - Ref: DestinationArnType + - Kinesis + Assertions: + - Assert: + Fn::Not: + - Fn::Equals: + - Ref: RoleArn + - '' + AssertDescription: If Destination Type is Kinesis, than the role ARN can not + be kept empty. Resources: SumoLogGroupLambdaConnector: Type: AWS::Serverless::Function Properties: - CodeUri: s3://appdevstore/LoggroupConnector/v1.0.4/8822c7aea452b5df042a0d22e4ecd99d + CodeUri: s3://cf-templates-1qpf3unpuo1hw-us-east-1/test-log-group-lambda-connector/0d12ca7b2219c4fc3fe3cd29d6ba56d0 Handler: loggroup-lambda-connector.handler - Runtime: nodejs10.x + Runtime: nodejs12.x Environment: Variables: - LAMBDA_ARN: - Ref: LambdaARN + DESTINATION_ARN: + Ref: DestinationArnValue LOG_GROUP_PATTERN: Ref: LogGroupPattern - USE_EXISTING_LOG_GROUPS: - Ref: UseExistingLogs LOG_GROUP_TAGS: Fn::Join: - ',' - Ref: LogGroupTags + ROLE_ARN: + Ref: RoleArn Policies: - Statement: - Sid: ReadWriteFilterPolicy @@ -78,6 +132,12 @@ Resources: - logs:PutSubscriptionFilter Resource: - Fn::Sub: arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:* + - Sid: InvokePolicy + Effect: Allow + Action: + - lambda:InvokeFunction + Resource: + - Fn::Sub: arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:* Events: LambdaTrigger: Type: CloudWatchEvent @@ -90,18 +150,78 @@ Resources: - logs.amazonaws.com eventName: - CreateLogGroup + sumoIAMPassRolePolicy: + Type: AWS::IAM::Policy + Condition: create_pass_role + Properties: + PolicyName: KinesisFirehoseLogsPolicy + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: + - iam:PassRole + Resource: + Ref: RoleArn + Roles: + - Ref: SumoLogGroupLambdaConnectorRole SumoCWLambdaInvokePermission: Type: AWS::Lambda::Permission + Condition: create_invoke_permission Properties: Action: lambda:InvokeFunction FunctionName: - Ref: LambdaARN + Ref: DestinationArnValue Principal: Fn::Sub: logs.${AWS::Region}.amazonaws.com SourceAccount: Ref: AWS::AccountId SourceArn: Fn::Sub: arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:*:* + SumoLogGroupExistingLambdaConnector: + Type: AWS::Serverless::Function + Condition: invoke_existing + Properties: + InlineCode: "var aws = require('aws-sdk');\nvar response = require('cfn-response');\n\ + \nexports.handler = function(event, context) {\n var lambda = new aws.Lambda();\n\ + \ var payload = {\"existingLogs\": \"true\", \"token\": \"\"};\n var\ + \ responseStatus = \"FAILED\";\n var responseData = {};\n lambda.invoke(\n\ + \ {\n InvocationType: 'Event',\n FunctionName: process.env.FUNCTION_NAME,\n\ + \ Payload: JSON.stringify(payload),\n }, function(err, invokeResult)\ + \ {\n if (err) {\n responseData = {Error: \"Invoke call\ + \ failed\"};\n console.log(responseData.Error + \":\\n\", err);\n\ + \ }\n else {\n responseStatus = \"SUCCESS\";\n\ + \ }\n response.send(event, context, responseStatus, responseData);\n\ + \ });\n};\n" + Handler: index.handler + Runtime: nodejs12.x + Environment: + Variables: + FUNCTION_NAME: + Ref: SumoLogGroupLambdaConnector + Policies: + - Statement: + - Sid: InvokePolicy + Effect: Allow + Action: + - lambda:InvokeFunction + Resource: + - Fn::Sub: arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${SumoLogGroupLambdaConnector} + primerinvoke: + Type: AWS::CloudFormation::CustomResource + Version: '1.0' + Condition: invoke_existing + Properties: + ServiceToken: + Fn::GetAtt: + - SumoLogGroupExistingLambdaConnector + - Arn + DESTINATION_ARN: + Ref: DestinationArnValue + LOG_GROUP_PATTERN: + Ref: LogGroupPattern + ROLE_ARN: + Ref: RoleArn Outputs: SumoLogGroupLambdaConnector: Description: SumoLogGroupLambdaConnector Function ARN diff --git a/loggroup-lambda-connector/sam/template.yaml b/loggroup-lambda-connector/sam/template.yaml index d41e6aa..bc0ee18 100644 --- a/loggroup-lambda-connector/sam/template.yaml +++ b/loggroup-lambda-connector/sam/template.yaml @@ -5,9 +5,9 @@ Description: > # More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst Globals: - Function: - Timeout: 300 - MemorySize: 128 + Function: + Timeout: 900 + MemorySize: 128 Metadata: AWS::ServerlessRepo::Application: @@ -15,57 +15,99 @@ Metadata: Description: Lambda Function for automatic subscription of any Sumo Logic lambda function with loggroups matching an input pattern. HomePageUrl: https://github.com/SumoLogic/sumologic-aws-lambda Labels: - - lambda - - sumologic - - autosubscribe - - serverless - - loggroups - - cloudwatch - LicenseUrl: ./LICENSE + - lambda + - sumologic + - autosubscribe + - serverless + - loggroups + - cloudwatch + LicenseUrl: ../LICENSE Name: sumologic-loggroup-connector ReadmeUrl: ../README.md - SemanticVersion: 1.0.4 + SemanticVersion: 1.0.5 SourceCodeUrl: https://github.com/SumoLogic/sumologic-aws-lambda/loggroup-lambda-connector SpdxLicenseId: Apache-2.0 Parameters: - LambdaARN: - Type : String - Default: "arn:aws:lambda:us-east-1:123456789000:function:TestLambda" - Description: "Enter ARN for target lambda function" - - LogGroupPattern: - Type : String - Default: "Test" - Description: "Enter regex for matching logGroups" - - UseExistingLogs: - Type : String - Default: "false" - AllowedValues : ["true", "false"] - Description: "Select true for subscribing existing logs" - - LogGroupTags: - Type: CommaDelimitedList - Default: "" - Description: "Enter comma separated keyvalue pairs for filtering logGroups using tags. Ex KeyName1=string,KeyName2=string. This is optional leave it blank if tag based filtering is not needed." + + DestinationArnType: + Type: String + Description: "Lambda - When the destination ARN for subscription filter is an AWS Lambda Function. + Kinesis - When the destination ARN for subscription filter is an Kinesis or Amazon Kinesis data firehose stream." + Default: 'Lambda' + AllowedValues: + - 'Lambda' + - 'Kinesis' + + DestinationArnValue: + Type: String + Default: "arn:aws:lambda:us-east-1:123456789000:function:TestLambda" + Description: "Enter Destination ARN like Lambda function, Kinesis stream. For more information, visit - https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html" + + LogGroupPattern: + Type: String + Default: "Test" + Description: "Enter regex for matching logGroups" + + UseExistingLogs: + Type: String + Default: "false" + AllowedValues: [ "true", "false" ] + Description: "Select true for subscribing existing logs" + + LogGroupTags: + Type: CommaDelimitedList + Default: "" + Description: "Enter comma separated keyvalue pairs for filtering logGroups using tags. Ex KeyName1=string,KeyName2=string. This is optional leave it blank if tag based filtering is not needed." + + RoleArn: + Type: String + Default: "" + Description: "Enter AWS IAM Role arn in case the destination is Kinesis Firehose stream." + +Conditions: + create_invoke_permission: !Equals [ !Ref DestinationArnType, 'Lambda' ] + create_pass_role: !Equals [ !Ref DestinationArnType, 'Kinesis' ] + + invoke_existing: !Equals [ !Ref UseExistingLogs, 'true' ] + +Rules: + testRoleArnWithLambda: + RuleCondition: !Equals + - !Ref DestinationArnType + - Lambda + Assertions: + - Assert: !Equals + - !Ref RoleArn + - '' + AssertDescription: 'If Destination Type is Lambda, than the role ARN should be empty.' + testRoleArnWithKinesis: + RuleCondition: !Equals + - !Ref DestinationArnType + - Kinesis + Assertions: + - Assert: !Not + - !Equals + - !Ref RoleArn + - '' + AssertDescription: 'If Destination Type is Kinesis, than the role ARN can not be kept empty.' Resources: - SumoLogGroupLambdaConnector: - Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Properties: - CodeUri: ../src/ - Handler: "loggroup-lambda-connector.handler" - Runtime: nodejs10.x - Environment: - Variables: - LAMBDA_ARN: !Ref "LambdaARN" - LOG_GROUP_PATTERN: !Ref "LogGroupPattern" - USE_EXISTING_LOG_GROUPS: !Ref "UseExistingLogs" - LOG_GROUP_TAGS: !Join [",", {"Ref": "LogGroupTags"} ] - Policies: - - Statement: + SumoLogGroupLambdaConnector: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + CodeUri: ../src/ + Handler: "loggroup-lambda-connector.handler" + Runtime: nodejs12.x + Environment: + Variables: + DESTINATION_ARN: !Ref "DestinationArnValue" + LOG_GROUP_PATTERN: !Ref "LogGroupPattern" + LOG_GROUP_TAGS: !Join [ ",", { "Ref": "LogGroupTags" } ] + ROLE_ARN: !Ref "RoleArn" + Policies: + - Statement: - Sid: ReadWriteFilterPolicy Effect: Allow Action: @@ -74,29 +116,107 @@ Resources: - logs:PutSubscriptionFilter Resource: - !Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:*' - Events: - LambdaTrigger: - Type: CloudWatchEvent - Properties: - Pattern: - source: - - aws.logs - detail: - eventSource: - - logs.amazonaws.com - eventName: - - CreateLogGroup - SumoCWLambdaInvokePermission: - Type: AWS::Lambda::Permission - Properties: - Action: lambda:InvokeFunction - FunctionName: !Ref "LambdaARN" - Principal: !Sub 'logs.${AWS::Region}.amazonaws.com' - SourceAccount: !Ref AWS::AccountId - SourceArn: !Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:*:*' + - Sid: InvokePolicy + Effect: Allow + Action: + - lambda:InvokeFunction + Resource: + - !Sub 'arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:*' + Events: + LambdaTrigger: + Type: CloudWatchEvent + Properties: + Pattern: + source: + - aws.logs + detail: + eventSource: + - logs.amazonaws.com + eventName: + - CreateLogGroup + + sumoIAMPassRolePolicy: + Type: AWS::IAM::Policy + Condition: create_pass_role + Properties: + PolicyName: "KinesisFirehoseLogsPolicy" + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: + - iam:PassRole + Resource: !Ref RoleArn + Roles: + - Ref: SumoLogGroupLambdaConnectorRole + + SumoCWLambdaInvokePermission: + Type: AWS::Lambda::Permission + Condition: create_invoke_permission + Properties: + Action: lambda:InvokeFunction + FunctionName: !Ref "DestinationArnValue" + Principal: !Sub 'logs.${AWS::Region}.amazonaws.com' + SourceAccount: !Ref AWS::AccountId + SourceArn: !Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:*:*' + + SumoLogGroupExistingLambdaConnector: + Type: AWS::Serverless::Function + Condition: invoke_existing + Properties: + InlineCode: | + var aws = require('aws-sdk'); + var response = require('cfn-response'); + + exports.handler = function(event, context) { + var lambda = new aws.Lambda(); + var payload = {"existingLogs": "true", "token": ""}; + var responseStatus = "FAILED"; + var responseData = {}; + lambda.invoke( + { + InvocationType: 'Event', + FunctionName: process.env.FUNCTION_NAME, + Payload: JSON.stringify(payload), + }, function(err, invokeResult) { + if (err) { + responseData = {Error: "Invoke call failed"}; + console.log(responseData.Error + ":\n", err); + } + else { + responseStatus = "SUCCESS"; + } + response.send(event, context, responseStatus, responseData); + }); + }; + Handler: "index.handler" + Runtime: nodejs12.x + Environment: + Variables: + FUNCTION_NAME: !Ref SumoLogGroupLambdaConnector + Policies: + - Statement: + - Sid: InvokePolicy + Effect: Allow + Action: + - lambda:InvokeFunction + Resource: + - !Sub 'arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${SumoLogGroupLambdaConnector}' + + InvokeLambdaConnector: + Type: AWS::CloudFormation::CustomResource + Version: "1.0" + Condition: invoke_existing + DeletionPolicy : "Retain" + UpdateReplacePolicy: "Retain" + Properties: + ServiceToken: !GetAtt SumoLogGroupExistingLambdaConnector.Arn + DESTINATION_ARN: !Ref "DestinationArnValue" + LOG_GROUP_PATTERN: !Ref "LogGroupPattern" + ROLE_ARN: !Ref "RoleArn" Outputs: - SumoLogGroupLambdaConnector: - Description: "SumoLogGroupLambdaConnector Function ARN" - Value: !GetAtt SumoLogGroupLambdaConnector.Arn + SumoLogGroupLambdaConnector: + Description: "SumoLogGroupLambdaConnector Function ARN" + Value: !GetAtt SumoLogGroupLambdaConnector.Arn diff --git a/loggroup-lambda-connector/src/loggroup-lambda-connector.js b/loggroup-lambda-connector/src/loggroup-lambda-connector.js index 4cf8e8f..6fe170a 100644 --- a/loggroup-lambda-connector/src/loggroup-lambda-connector.js +++ b/loggroup-lambda-connector/src/loggroup-lambda-connector.js @@ -1,19 +1,34 @@ var AWS = require("aws-sdk"); +const util = require("util"); var cwl = new AWS.CloudWatchLogs({apiVersion: '2014-03-28'}); -async function sleep(waitTimeInMs) { - console.log("sleeping for " + waitTimeInMs + " ms..."); - return new Promise((resolve) => setTimeout(resolve, waitTimeInMs)); -} +var maxRetryCounter = 3; + +async function createSubscriptionFilter(lambdaLogGroupName, destinationArn, roleArn) { + if (destinationArn.startsWith("arn:aws:lambda")){ + var params = { + destinationArn: destinationArn, + filterName: 'SumoLGLBDFilter', + filterPattern: '', + logGroupName: lambdaLogGroupName + }; + } else { + var params = { + destinationArn: destinationArn, + filterName: 'SumoLGLBDFilter', + filterPattern: '', + logGroupName: lambdaLogGroupName, + roleArn: roleArn + }; + } -function subscribeToLambda(lambdaLogGroupName, lambdaArn, errorHandler) { - var params = { - destinationArn: lambdaArn, - filterName: 'SumoLGLBDFilter', - filterPattern: '', - logGroupName: lambdaLogGroupName - }; // handle case where subscription filter exists/case where loggroup generated by target lambda - cwl.putSubscriptionFilter(params, errorHandler); + try { + await util.promisify(cwl.putSubscriptionFilter.bind(cwl))(params); + console.log("Successfully subscribed logGroup: ", lambdaLogGroupName); + } catch (err) { + console.log("Error in subscribing", lambdaLogGroupName, err); + throw err; + } } function filterLogGroups(event, logGroupRegex) { @@ -39,37 +54,41 @@ function filterLogGroups(event, logGroupRegex) { return false; } -async function subscribeExistingLogGroups(logGroups) { - var logGroupName; +async function subscribeExistingLogGroups(logGroups, retryCounter) { var logGroupRegex = new RegExp(process.env.LOG_GROUP_PATTERN, "i"); - var lambdaArn = process.env.LAMBDA_ARN; - for (var i = logGroups.length - 1; i >= 0; i--) { - logGroupName = logGroups[i].logGroupName; - if (logGroupName.match(logGroupRegex)) { - - // sleep time between calls - await sleep(1000*(process.env.SUBSCRIBE_DELAY_SECONDS || 2)); // 5 seconds - - subscribeToLambda(logGroupName, lambdaArn, (function(inner_logGroupName) { return function (err, data) { - if (err) { - console.log("Error in subscribing", inner_logGroupName, err); - } else { - console.log("Successfully subscribed logGroup: ", inner_logGroupName); - } - };})(logGroupName)); - } else { + var destinationArn = process.env.DESTINATION_ARN; + var roleArn = process.env.ROLE_ARN; + const failedLogGroupNames = []; + await logGroups.reduce(async (previousPromise, nextLogGroup) => { + await previousPromise; + const { logGroupName } = nextLogGroup; + if (!logGroupName.match(logGroupRegex)) { console.log("Unmatched logGroup: ", logGroupName); + return Promise.resolve(); + } else { + return createSubscriptionFilter(logGroupName, destinationArn, roleArn).catch( function (err) { + if (err && err.code == "ThrottlingException") { + failedLogGroupNames.push({logGroupName: logGroupName}); + } + }); } + }, Promise.resolve()); + + if (retryCounter <= maxRetryCounter && failedLogGroupNames.length > 0) { + console.log("Retrying Subscription for Failed Log Groups due to throttling with counter number as " + retryCounter); + await subscribeExistingLogGroups(failedLogGroupNames, retryCounter + 1); } } -function processExistingLogGroups(token, errorHandler) { - - var params = { - limit: 50, - // logGroupNamePrefix: '', - nextToken: token - }; +function processExistingLogGroups(token, context, errorHandler) { + var params = {limit: 50}; + if (token) { + params = { + limit: 50, + // logGroupNamePrefix: '', + nextToken: token + }; + } var p = new Promise(function(resolve, reject) { cwl.describeLogGroups(params, function(err, data) { if (err) { @@ -81,11 +100,14 @@ function processExistingLogGroups(token, errorHandler) { } }); }); - var cb = function (data) { - subscribeExistingLogGroups(data.logGroups); - if (data.nextToken) {// if next set of log groups exists - processExistingLogGroups(data.nextToken, errorHandler) + var cb = async function (data) { + await subscribeExistingLogGroups(data.logGroups, 1); + if (data.nextToken) {// if next set of log groups exists, invoke next instance of lambda + console.log("Log Groups remaining...Calling the lambda again with token " + data.nextToken); + invoke_lambda(context, data.nextToken, errorHandler); + console.log("Lambda invoke complete with token " + data.nextToken); } else { + console.log("All Log Groups are subscribed to Destination Type " + process.env.DESTINATION_ARN); errorHandler(null, "Success"); } }; @@ -94,20 +116,32 @@ function processExistingLogGroups(token, errorHandler) { }); } +function invoke_lambda(context, token, errorHandler) { + var lambda = new AWS.Lambda(); + var payload = {"existingLogs": "true", "token": token}; + lambda.invoke({ + InvocationType: 'Event', + FunctionName: context.functionName, + Payload: JSON.stringify(payload), + }, errorHandler); +} + function processEvents(env, event, errorHandler) { var logGroupName = event.detail.requestParameters.logGroupName; if (filterLogGroups(event, env.LOG_GROUP_PATTERN)) { - console.log("Subscribing: ", logGroupName, env.LAMBDA_ARN); - subscribeToLambda(logGroupName, env.LAMBDA_ARN, errorHandler); + console.log("Subscribing: ", logGroupName, env.DESTINATION_ARN); + createSubscriptionFilter(logGroupName, env.DESTINATION_ARN, env.ROLE_ARN).catch (function (err) { + errorHandler(err, "Error in Subscribing."); + }); } else { - console.log("Unmatched: ", logGroupName, env.LAMBDA_ARN); + console.log("Unmatched: ", logGroupName, env.DESTINATION_ARN); } } exports.handler = function (event, context, callback) { - console.log("Invoking Log Group connector function") + console.log("Invoking Log Group connector function"); function errorHandler(err, msg) { if (err) { console.log(err, msg); @@ -116,10 +150,9 @@ exports.handler = function (event, context, callback) { callback(null, "Success"); } } - if (process.env.USE_EXISTING_LOG_GROUPS == "true") { - processExistingLogGroups(null, errorHandler); + if (event.existingLogs == "true") { + processExistingLogGroups(event.token, context, errorHandler); } else { processEvents(process.env, event, errorHandler); } - }; diff --git a/loggroup-lambda-connector/test/loggroup-lambda-cft.json b/loggroup-lambda-connector/test/loggroup-lambda-cft.json deleted file mode 100644 index 5a296ff..0000000 --- a/loggroup-lambda-connector/test/loggroup-lambda-cft.json +++ /dev/null @@ -1,208 +0,0 @@ -{ - "AWSTemplateFormatVersion": "2010-09-09", - "Outputs": { - "SumoLogGroupLambdaConnector": { - "Description": "SumoLogGroupLambdaConnector Function ARN", - "Value": { - "Fn::GetAtt": [ - "SumoLogGroupLambdaConnector", - "Arn" - ] - }, - "Export" : { - "Name" : { "Fn::Join": [ "-", [ "SumoLogGroupLambdaConnectorArn", { "Fn::Select" : [ "2", {"Fn::Split" : [ "/" , { "Ref": "AWS::StackId" } ]}] } ] ] } - } - } - }, - "Mappings" : { - "RegionMap" : { - "us-east-1": {"bucketname": "appdevzipfiles-us-east-1"}, - "us-east-2": {"bucketname": "appdevzipfiles-us-east-2"}, - "us-west-1": {"bucketname": "appdevzipfiles-us-west-1"}, - "us-west-2": {"bucketname": "appdevzipfiles-us-west-2"}, - "ap-south-1": {"bucketname": "appdevzipfiles-ap-south-1"}, - "ap-northeast-2": {"bucketname": "appdevzipfiles-ap-northeast-2"}, - "ap-southeast-1": {"bucketname": "appdevzipfiles-ap-southeast-1"}, - "ap-southeast-2": {"bucketname": "appdevzipfiles-ap-southeast-2"}, - "ap-northeast-1": {"bucketname": "appdevzipfiles-ap-northeast-1"}, - "ca-central-1": {"bucketname": "appdevzipfiles-ca-central-1"}, - "eu-central-1": {"bucketname": "appdevzipfiles-eu-central-1"}, - "eu-west-1": {"bucketname": "appdevzipfiles-eu-west-1"}, - "eu-west-2": {"bucketname": "appdevzipfiles-eu-west-2"}, - "eu-west-3": {"bucketname": "appdevzipfiles-eu-west-3"}, - "sa-east-1": {"bucketname": "appdevzipfiles-sa-east-1"} - } - }, - "Resources": { - "SumoLogGroupLambdaConnector": { - "Type": "AWS::Lambda::Function", - "Properties": { - "Code": { - "S3Bucket": {"Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "bucketname"]}, - "S3Key": "loggroup-lambda-connector.zip" - }, - "Tags": [ - { - "Value": "SAM", - "Key": "lambda:createdBy" - } - ], - "MemorySize": 128, - "Environment": { - "Variables": { - "LOG_GROUP_PATTERN": { - "Ref": "LogGroupPattern" - }, - "USE_EXISTING_LOG_GROUPS": { - "Ref": "UseExistingLogs" - }, - "LAMBDA_ARN": { - "Ref": "LambdaARN" - } - } - }, - "Handler": "loggroup-lambda-connector.handler", - "Role": { - "Fn::GetAtt": [ - "SumoLogGroupLambdaConnectorRole", - "Arn" - ] - }, - "Timeout": 300, - "Runtime": "nodejs10.x" - } - }, - "SumoLogGroupLambdaConnectorRole": { - "Type": "AWS::IAM::Role", - "Properties": { - "ManagedPolicyArns": [ - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" - ], - "Policies": [ - { - "PolicyName": { "Fn::Join": [ "-", [ "SumoLogGroupLambdaConnectorPolicy", { "Fn::Select" : [ "2", {"Fn::Split" : [ "/" , { "Ref": "AWS::StackId" } ]}] } ] ] }, - "PolicyDocument": { - "Statement": [ - { - "Action": [ - "logs:DescribeLogGroups", - "logs:DescribeLogStreams", - "logs:PutSubscriptionFilter" - ], - "Resource": [ - { - "Fn::Sub": "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:*" - } - ], - "Effect": "Allow", - "Sid": "ReadWriteFilterPolicy" - } - ] - } - } - ], - "AssumeRolePolicyDocument": { - "Version": "2012-10-17", - "Statement": [ - { - "Action": [ - "sts:AssumeRole" - ], - "Effect": "Allow", - "Principal": { - "Service": [ - "lambda.amazonaws.com" - ] - } - } - ] - } - } - }, - "SumoCWLambdaInvokePermission": { - "Type": "AWS::Lambda::Permission", - "Properties": { - "Action": "lambda:InvokeFunction", - "SourceAccount": { - "Ref": "AWS::AccountId" - }, - "Principal": { - "Fn::Sub": "logs.${AWS::Region}.amazonaws.com" - }, - "FunctionName": { - "Ref": "LambdaARN" - }, - "SourceArn": { - "Fn::Sub": "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:*:*" - } - } - }, - "SumoLogGroupLambdaConnectorLambdaTrigger": { - "Type": "AWS::Events::Rule", - "Properties": { - "EventPattern": { - "source": [ - "aws.logs" - ], - "detail": { - "eventName": [ - "CreateLogGroup" - ], - "eventSource": [ - "logs.amazonaws.com" - ] - } - }, - "Targets": [ - { - "Id": "SumoLogGroupLambdaConnectorLambdaTriggerLambdaTarget", - "Arn": { - "Fn::GetAtt": [ - "SumoLogGroupLambdaConnector", - "Arn" - ] - } - } - ] - } - }, - "SumoLogGroupLambdaConnectorLambdaTriggerPermission": { - "Type": "AWS::Lambda::Permission", - "Properties": { - "Action": "lambda:invokeFunction", - "Principal": "events.amazonaws.com", - "FunctionName": { - "Ref": "SumoLogGroupLambdaConnector" - }, - "SourceArn": { - "Fn::GetAtt": [ - "SumoLogGroupLambdaConnectorLambdaTrigger", - "Arn" - ] - } - } - } - }, - "Description": "\"Lambda Function for automatic subscription of any Sumo Logic lambda function with loggroups matching an input pattern.\"\n", - "Parameters": { - "UseExistingLogs": { - "Default": "false", - "Type": "String", - "Description": "Select true for subscribing existing logs", - "AllowedValues": [ - "true", - "false" - ] - }, - "LambdaARN": { - "Default": "arn:aws:lambda:us-east-1:123456789000:function:TestLambda", - "Type": "String", - "Description": "Enter ARN for target lambda function" - }, - "LogGroupPattern": { - "Default": "Test", - "Type": "String", - "Description": "Enter regex for matching logGroups" - } - } -} diff --git a/loggroup-lambda-connector/test/requirements.txt b/loggroup-lambda-connector/test/requirements.txt index 4aa09d7..6e204ce 100644 --- a/loggroup-lambda-connector/test/requirements.txt +++ b/loggroup-lambda-connector/test/requirements.txt @@ -1,2 +1,3 @@ requests==2.20.0 boto3==1.5.1 +cfn-flip>=1.2.3 \ No newline at end of file diff --git a/loggroup-lambda-connector/test/test-template.yaml b/loggroup-lambda-connector/test/test-template.yaml new file mode 100644 index 0000000..02f35b2 --- /dev/null +++ b/loggroup-lambda-connector/test/test-template.yaml @@ -0,0 +1,232 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: 'AWS::Serverless-2016-10-31' +Description: "Template to test lambda log group connector and create a Lambda function, delivery stream and aws role." + +Parameters: + DestinationType: + Type: String + Description: "Lambda - When the destination ARN for subscription filter is an AWS Lambda Function. + Kinesis - When the destination ARN for subscription filter is an Kinesis or Amazon Kinesis data firehose stream." + Default: 'Lambda' + AllowedValues: + - 'Lambda' + - 'Kinesis' + + LogGroupPattern: + Type: String + Default: "Test" + Description: "Enter regex for matching logGroups" + + UseExistingLogs: + Type: String + Default: "false" + AllowedValues: [ "true", "false" ] + Description: "Select true for subscribing existing logs" + + BucketName: + Type: String + Default: "" + Description: "Provide the bucket name where packaged.yaml is pushed." + +Conditions: + create_invoke_permission: !Equals [ !Ref DestinationType, 'Lambda' ] + create_pass_role: !Equals [ !Ref DestinationType, 'Kinesis' ] + +Resources: + + LambdaRole: + Type: AWS::IAM::Role + Condition: create_invoke_permission + Metadata: + cfn_nag: + rules_to_suppress: + - id: W11 + reason: "Operations are performed across resources." + Properties: + AssumeRolePolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Principal: + Service: lambda.amazonaws.com + Action: sts:AssumeRole + Path: / + Policies: + - PolicyName: AwsObservabilityLambdaExecutePolicies + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: + - logs:CreateLogGroup + - logs:CreateLogStream + - logs:PutLogEvents + Resource: '*' + + DummyLambda: + Type: AWS::Lambda::Function + Condition: create_invoke_permission + Properties: + Code: + ZipFile: | + print("success") + Handler: index.lambda_handler + MemorySize: 128 + Runtime: python3.7 + Timeout: 60 + Role: !GetAtt LambdaRole.Arn + + FirehoseLogsRole: + Type: AWS::IAM::Role + Condition: create_pass_role + Properties: + AssumeRolePolicyDocument: + Version: '2012-10-17' + Statement: + - Sid: 'FirehoseAssumeRole' + Effect: Allow + Principal: + Service: firehose.amazonaws.com + Action: sts:AssumeRole + Condition: + StringEquals: + sts:ExternalId: !Ref "AWS::AccountId" + + AttachBucketPolicyToFirehoseLogsRole: + Type: AWS::IAM::Policy + Condition: create_pass_role + Properties: + PolicyName: "S3BucketPermissionPolicy" + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: + - s3:AbortMultipartUpload + - s3:GetBucketLocation + - s3:GetObject + - s3:ListBucket + - s3:ListBucketMultipartUploads + - s3:PutObject + Resource: + - !Sub "arn:aws:s3:::${BucketName}" + - !Sub "arn:aws:s3:::${BucketName}/*" + Roles: + - Ref: FirehoseLogsRole + + KinesisLogsRole: + Type: AWS::IAM::Role + Condition: create_pass_role + Properties: + AssumeRolePolicyDocument: + Version: '2012-10-17' + Statement: + - Sid: 'LogsAssumeRole' + Effect: Allow + Principal: + Service: !Sub "logs.${AWS::Region}.amazonaws.com" + Action: sts:AssumeRole + + KinesisLogsRolePolicy: + Type: AWS::IAM::Policy + Condition: create_pass_role + Properties: + PolicyName: "KinesisFirehoseLogsPolicy" + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: + - firehose:PutRecord + - firehose:PutRecordBatch + - kinesis:PutRecord + - kinesis:PutRecordBatch + Resource: !Sub "arn:aws:firehose:${AWS::Region}:${AWS::AccountId}:*" + - Effect: Allow + Action: + - iam:PassRole + Resource: !Sub "arn:aws:iam::${AWS::AccountId}:role/${KinesisLogsRole}" + Roles: + - Ref: KinesisLogsRole + + KinesisLogsDeliveryStream: + Type: AWS::KinesisFirehose::DeliveryStream + Condition: create_pass_role + Properties: + DeliveryStreamName: !Sub + - "Kinesis-Logs-${StackID}" + - StackID: !Select + - 0 + - !Split + - "-" + - !Select + - 2 + - !Split ["/", !Ref "AWS::StackId"] + DeliveryStreamType: DirectPut + HttpEndpointDestinationConfiguration: + RoleARN: !GetAtt FirehoseLogsRole.Arn + EndpointConfiguration: + Url: "https://localhost.com" + Name: !Sub "${AWS::StackName}-sumologic-logs-endpoint" + RequestConfiguration: + ContentEncoding: GZIP + CloudWatchLoggingOptions: + Enabled: false + BufferingHints: + IntervalInSeconds: 60 + SizeInMBs: 4 + RetryOptions: + DurationInSeconds: 60 + S3BackupMode: FailedDataOnly + S3Configuration: + BucketARN: !Sub "arn:aws:s3:::${BucketName}" + CompressionFormat: UNCOMPRESSED + ErrorOutputPrefix: "SumoLogic-Kinesis-Failed-Logs/" + RoleARN: !GetAtt FirehoseLogsRole.Arn + CloudWatchLoggingOptions: + Enabled: false + + KinesisLogsFirehoseRolePolicy: + Type: AWS::IAM::Policy + Condition: create_pass_role + Properties: + PolicyName: "KinesisLogsLogStreamPermissionPolicy" + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: + - kinesis:DescribeStream + - kinesis:GetShardIterator + - kinesis:GetRecords + - kinesis:ListShards + Resource: + - !GetAtt KinesisLogsDeliveryStream.Arn + Roles: + - Ref: FirehoseLogsRole + + LogGroupConnector: + Type: AWS::CloudFormation::Stack + Properties: + TemplateURL: !Sub "https://${BucketName}.s3.amazonaws.com/packaged.yaml" + Parameters: + DestinationArnType: !Ref DestinationType + DestinationArnValue: !If [ create_invoke_permission, !GetAtt DummyLambda.Arn, !GetAtt KinesisLogsDeliveryStream.Arn ] + LogGroupPattern: !Ref LogGroupPattern + UseExistingLogs: !Ref UseExistingLogs + RoleArn: !If [ create_invoke_permission, "", !GetAtt KinesisLogsRole.Arn ] + +Outputs: + + destinationArn: + Description: "Destination ARN" + Value: !If [ create_invoke_permission, !GetAtt DummyLambda.Arn, !GetAtt KinesisLogsDeliveryStream.Arn ] + + roleArn: + Description: "Role ARN" + Condition: create_pass_role + Value: !GetAtt KinesisLogsRole.Arn + + LambdaARN: + Description: "Role ARN" + Value: !GetAtt LogGroupConnector.Outputs.SumoLogGroupLambdaConnector \ No newline at end of file diff --git a/loggroup-lambda-connector/test/test_loggroup_lambda_connector.py b/loggroup-lambda-connector/test/test_loggroup_lambda_connector.py index 5b3858d..c0df884 100644 --- a/loggroup-lambda-connector/test/test_loggroup_lambda_connector.py +++ b/loggroup-lambda-connector/test/test_loggroup_lambda_connector.py @@ -1,3 +1,5 @@ +import subprocess +import time import unittest import boto3 from time import sleep @@ -6,66 +8,89 @@ import sys import datetime +import cfn_flip + +# Modify the name of the bucket prefix for testing BUCKET_PREFIX = "appdevstore" +AWS_REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") class TestLambda(unittest.TestCase): - ''' fail case newlgrp success case testlggrp already exists subscription filter idempotent ''' - ZIP_FILE = 'loggroup-lambda-connector.zip' - AWS_REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") - FILTER_NAME = 'SumoLGLBDFilter' def setUp(self): - self.config = { - 'AWS_REGION_NAME': self.AWS_REGION - } - self.LOG_GROUP_NAME = 'testloggroup-%s' % ( - datetime.datetime.now().strftime("%d-%m-%y-%H-%M-%S")) - # aws_access_key_id aws_secret_access_key - self.stack_name = "TestLogGrpConnectorStack-%s" % ( - datetime.datetime.now().strftime("%d-%m-%y-%H-%M-%S")) - self.cf = boto3.client('cloudformation', - self.config['AWS_REGION_NAME']) - self.template_name = 'loggroup-lambda-cft.json' - self.template_data = self._parse_template(self.template_name) - # replacing prod zipfile location to test zipfile location - self.template_data = self.template_data.replace("appdevzipfiles", BUCKET_PREFIX, 1) - RUNTIME = "nodejs%s" % os.environ.get("NODE_VERSION", "10.x") - self.template_data = self.template_data.replace("nodejs10.x", RUNTIME) - - def get_account_id(self): - client = boto3.client("sts", self.config['AWS_REGION_NAME']) - account_id = client.get_caller_identity()["Account"] - return account_id + # Set Up AWS Clients + self.log_group_client = boto3.client('logs', AWS_REGION) + self.cf = boto3.client('cloudformation', AWS_REGION) + self.lambda_cl = boto3.client('lambda', AWS_REGION) + + # AWS Resource Names + self.log_group_name = 'testloggroup-%s' % (datetime.datetime.now().strftime("%d-%m-%y-%H-%M-%S")) + self.stack_name = "TestLogGrpConnectorStack-%s" % (datetime.datetime.now().strftime("%d-%m-%y-%H-%M-%S")) + + self.bucket_name = get_bucket_name() + self.outputs = {} + # Read template + self.template_data = read_file("test/test-template.yaml") def tearDown(self): if self.stack_exists(self.stack_name): - self.delete_stack() - self.delete_log_group(self.LOG_GROUP_NAME) + self.delete_stack(self.stack_name) + self.delete_log_group() - def test_lambda(self): - upload_code_in_S3(self.config['AWS_REGION_NAME']) - self.create_stack() + def test_1_lambda(self): + self.create_stack(self.stack_name, self.template_data, self.create_stack_parameters("Lambda", "false")) print("Testing Stack Creation") self.assertTrue(self.stack_exists(self.stack_name)) - self.create_log_group(self.LOG_GROUP_NAME) - self.assertTrue(self.check_subscription_filter_exists( - self.LOG_GROUP_NAME, self.FILTER_NAME)) - - def test_existing_logs(self): - upload_code_in_S3(self.config['AWS_REGION_NAME']) - self.template_data = self.template_data.replace("false", "true", 1) - self.create_stack() + self.create_log_group() + self.assert_subscription_filter("SumoLGLBDFilter") + + def test_2_existing_logs(self): + self.create_log_group() + self.create_stack(self.stack_name, self.template_data, self.create_stack_parameters("Lambda", "true")) + print("Testing Stack Creation") + self.assertTrue(self.stack_exists(self.stack_name)) + #self.invoke_lambda() + self.assert_subscription_filter("SumoLGLBDFilter") + + def test_3_kinesis(self): + self.create_stack(self.stack_name, self.template_data, self.create_stack_parameters("Kinesis", "false")) print("Testing Stack Creation") self.assertTrue(self.stack_exists(self.stack_name)) - self.create_log_group(self.LOG_GROUP_NAME) - self.assertTrue(self.check_subscription_filter_exists( - self.LOG_GROUP_NAME, self.FILTER_NAME)) + self.create_log_group() + self.assert_subscription_filter("SumoLGLBDFilter") + + def test_4_existing_kinesis(self): + self.create_log_group() + self.create_stack(self.stack_name, self.template_data, self.create_stack_parameters("Kinesis", "true")) + print("Testing Stack Creation") + self.assertTrue(self.stack_exists(self.stack_name)) + #self.invoke_lambda() + self.assert_subscription_filter("SumoLGLBDFilter") + + def create_stack_parameters(self, destination, existing, pattern='test'): + return [ + { + 'ParameterKey': 'DestinationType', + 'ParameterValue': destination + }, + { + 'ParameterKey': 'LogGroupPattern', + 'ParameterValue': pattern + }, + { + 'ParameterKey': 'UseExistingLogs', + 'ParameterValue': existing + }, + { + 'ParameterKey': 'BucketName', + 'ParameterValue': self.bucket_name + } + ] def stack_exists(self, stack_name): stacks = self.cf.list_stacks()['StackSummaries'] @@ -74,175 +99,145 @@ def stack_exists(self, stack_name): continue if stack_name == stack['StackName'] and stack['StackStatus'] == 'CREATE_COMPLETE': print("%s stack exists" % stack_name) + stack_data = self.cf.describe_stacks(StackName=self.stack_name) + outputs_stacks = stack_data["Stacks"][0]["Outputs"] + for output in outputs_stacks: + self.outputs[output["OutputKey"]] = output["OutputValue"] return True return False - def create_stack(self): + def create_stack(self, stack_name, template_data, parameters): params = { - 'StackName': self.stack_name, - 'TemplateBody': self.template_data, - 'Capabilities': ['CAPABILITY_IAM'] + 'StackName': stack_name, + 'TemplateBody': template_data, + 'Capabilities': ['CAPABILITY_IAM', 'CAPABILITY_AUTO_EXPAND'], + 'Parameters': parameters } stack_result = self.cf.create_stack(**params) - print('Creating {}'.format(self.stack_name), stack_result) + print('Creating {}'.format(stack_name), stack_result) waiter = self.cf.get_waiter('stack_create_complete') print("...waiting for stack to be ready...") - waiter.wait(StackName=self.stack_name) + waiter.wait(StackName=stack_name) - def delete_stack(self): + def delete_stack(self, stack_name): params = { - 'StackName': self.stack_name + 'StackName': stack_name } stack_result = self.cf.delete_stack(**params) - print('Deleting {}'.format(self.stack_name), stack_result) + print('Deleting {}'.format(stack_name), stack_result) waiter = self.cf.get_waiter('stack_delete_complete') print("...waiting for stack to be removed...") - waiter.wait(StackName=self.stack_name) + waiter.wait(StackName=stack_name) - def delete_log_group(self, log_group_name): - cwlclient = boto3.client('logs', self.config['AWS_REGION_NAME']) - response = cwlclient.delete_log_group(logGroupName=log_group_name) + def delete_log_group(self): + response = self.log_group_client.delete_log_group(logGroupName=self.log_group_name) print("deleting log group", response) - def create_log_group(self, log_group_name): - cwlclient = boto3.client('logs', self.config['AWS_REGION_NAME']) - response = cwlclient.create_log_group(logGroupName=log_group_name) + def create_log_group(self): + response = self.log_group_client.create_log_group(logGroupName=self.log_group_name) print("creating log group", response) - def check_subscription_filter_exists(self, log_group_name, filter_name): + def assert_subscription_filter(self, filter_name): sleep(60) - cwlclient = boto3.client('logs', self.config['AWS_REGION_NAME']) - response = cwlclient.describe_subscription_filters( - logGroupName=log_group_name, + response = self.log_group_client.describe_subscription_filters( + logGroupName=self.log_group_name, filterNamePrefix=filter_name ) print("testing subscription filter exists", response) - if len(response['subscriptionFilters']) > 0 and response['subscriptionFilters'][0]['filterName'] == filter_name: - return True - else: - return False - - def add_dummy_lambda(self, template_data): - template_data = eval(template_data) - test_lambda_name = "TestLambda-%s" % ( - datetime.datetime.now().strftime("%d-%m-%y-%H-%M-%S")) - template_data['Resources']["SumoCWLambdaInvokePermission"]["DependsOn"] = ["TestLambda"] - template_data['Resources']["TestLambda"] = { - "Type": "AWS::Lambda::Function", - "DependsOn": [ - "SumoLogGroupLambdaConnectorRole" - ], - "Properties": { - "Code": { - "ZipFile": {"Fn::Join": ["", [ - "exports.handler = function(event, context) {", - "console.log('Success');", - "};" - ]]} - }, - "Role": { - "Fn::GetAtt": [ - "SumoLogGroupLambdaConnectorRole", - "Arn" - ] - }, - "FunctionName": test_lambda_name, - "Timeout": 300, - "Handler": "index.handler", - "Runtime": "nodejs10.x", - "MemorySize": 128 - } - } - - lambda_arn = "arn:aws:lambda:%s:%s:function:%s" % ( - self.config["AWS_REGION_NAME"], self.get_account_id(), - test_lambda_name) - template_data["Parameters"]["LambdaARN"]["Default"] = lambda_arn - template_data = str(template_data) - return template_data - - def _parse_template(self, template): - with open(template) as template_fileobj: - template_data = template_fileobj.read() - - template_data = self.add_dummy_lambda(template_data) + # Add multiple assert for name, destination arn, role arn. + assert len(response['subscriptionFilters']) > 0 + assert response['subscriptionFilters'][0]['filterName'] == filter_name + assert response['subscriptionFilters'][0]['logGroupName'] == self.log_group_name + assert response['subscriptionFilters'][0]['destinationArn'] == self.outputs["destinationArn"] + if "roleArn" in self.outputs: + assert response['subscriptionFilters'][0]['roleArn'] == self.outputs["roleArn"] + + def _parse_template(self, template_name): + output_file = cfn_flip.to_json(read_file(template_name)) + template_data = json.loads(output_file) print("Validating cloudformation template") self.cf.validate_template(TemplateBody=template_data) return template_data + def invoke_lambda(self): + lambda_arn = self.outputs["LambdaARN"] + output = self.lambda_cl.invoke( + FunctionName=lambda_arn, + InvocationType='Event', + LogType='None', + Payload=bytes(json.dumps({"value": "test"}), "utf-8") + ) + if output["StatusCode"] != 202: + raise Exception("Failed to invoke Lambda") + time.sleep(60) + + +def read_file(file_path): + file_path = os.path.join(os.path.dirname(os.getcwd()), file_path) + with open(file_path, "r") as f: + return f.read().strip() + + +def get_bucket_name(): + return '%s-%s' % (BUCKET_PREFIX, AWS_REGION) + + +def upload_to_s3(file_path): + print("Uploading %s file in S3 region: %s" % (file_path, AWS_REGION)) + s3 = boto3.client('s3', AWS_REGION) + bucket_name = get_bucket_name() + key = os.path.basename(file_path) + filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), file_path) + s3.upload_file(os.path.join(__file__, filename), bucket_name, key, ExtraArgs={'ACL': 'public-read'}) -def upload_code_in_multiple_regions(): - regions = [ - "us-east-2", - "us-east-1", - "us-west-1", - "us-west-2", - "ap-south-1", - "ap-northeast-2", - "ap-southeast-1", - "ap-southeast-2", - "ap-northeast-1", - "ca-central-1", - # "cn-north-1", - "eu-central-1", - "eu-west-1", - "eu-west-2", - "eu-west-3", - "sa-east-1" - ] - - # for region in regions: - # create_bucket(region) - - for region in regions: - upload_code_in_S3(region) - - -def get_bucket_name(region): - return '%s-%s' % (BUCKET_PREFIX, region) - - -def create_bucket(region): - s3 = boto3.client('s3', region) - bucket_name = get_bucket_name(region) - if region == "us-east-1": - response = s3.create_bucket(Bucket=bucket_name) - else: - response = s3.create_bucket(Bucket=bucket_name, - CreateBucketConfiguration={ - 'LocationConstraint': region - }) - print("Creating bucket", region, response) - - -def upload_code_in_S3(region): - print("Uploading zip file in S3 region: %s" % region) - s3 = boto3.client('s3', region) - bucket_name = get_bucket_name(region) - key = os.path.basename(TestLambda.ZIP_FILE) - filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), TestLambda.ZIP_FILE) - s3.upload_file(os.path.join(__file__, filename), bucket_name, key, - ExtraArgs={'ACL': 'public-read'}) - - -def prod_deploy(): - global BUCKET_PREFIX - BUCKET_PREFIX = 'appdevzipfiles' - upload_code_in_multiple_regions() - print("Uploading template file in S3") - s3 = boto3.client('s3', "us-east-1") - filename = os.path.join('test', 'loggroup-lambda-cft.json') - bucket_name = "appdev-cloudformation-templates" - key = os.path.basename(filename) - s3.upload_file(filename, bucket_name, key, - ExtraArgs={'ACL': 'public-read'}) - print("Deployment Successfull: ALL files copied to Sumocontent") + +def create_sam_package_and_upload(): + template_file_path = os.path.join(os.path.dirname(os.getcwd()), "sam/template.yaml") + packaged_template_path = os.path.join(os.path.dirname(os.getcwd()), "sam/packaged.yaml") + + # Create packaged template + run_command(["sam", "package", "--template-file", template_file_path, + "--output-template-file", packaged_template_path, "--s3-bucket", get_bucket_name(), + "--s3-prefix", "test-log-group-lambda-connector"]) + # Upload the packaged template to S3 + upload_to_s3(packaged_template_path) + + +def _run(command, input=None, check=False, **kwargs): + if sys.version_info >= (3, 5): + return subprocess.run(command, capture_output=True) + if input is not None: + if 'stdin' in kwargs: + raise ValueError('stdin and input arguments may not both be used.') + kwargs['stdin'] = subprocess.PIPE + + process = subprocess.Popen(command, **kwargs) + try: + stdout, stderr = process.communicate(input) + except: + process.kill() + process.wait() + raise + retcode = process.poll() + if check and retcode: + raise subprocess.CalledProcessError( + retcode, process.args, output=stdout, stderr=stderr) + return retcode, stdout, stderr + + +def run_command(cmdargs): + resp = _run(cmdargs) + if len(resp.stderr.decode()) > 0: + # traceback.print_exc() + raise Exception("Error in run command %s cmd: %s" % (resp, cmdargs)) + return resp.stdout if __name__ == '__main__': if len(sys.argv) > 1: BUCKET_PREFIX = sys.argv.pop() - + create_sam_package_and_upload() # upload_code_in_multiple_regions() + # Run the test cases unittest.main()