From 1f6c9166477c1ba4ee38c69b410700f00a52778b Mon Sep 17 00:00:00 2001 From: sourabh Date: Thu, 25 Feb 2021 16:35:24 +0530 Subject: [PATCH 01/12] adding license file, updating code and template to use destiantion arn along with rolearn --- loggroup-lambda-connector/LICENSE | 201 ++++++++++++++++++ loggroup-lambda-connector/sam/template.yaml | 37 +++- .../src/loggroup-lambda-connector.js | 36 ++-- 3 files changed, 257 insertions(+), 17 deletions(-) create mode 100644 loggroup-lambda-connector/LICENSE 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/sam/template.yaml b/loggroup-lambda-connector/sam/template.yaml index d41e6aa..dead4c4 100644 --- a/loggroup-lambda-connector/sam/template.yaml +++ b/loggroup-lambda-connector/sam/template.yaml @@ -21,7 +21,7 @@ Metadata: - serverless - loggroups - cloudwatch - LicenseUrl: ./LICENSE + LicenseUrl: ../LICENSE Name: sumologic-loggroup-connector ReadmeUrl: ../README.md SemanticVersion: 1.0.4 @@ -29,10 +29,10 @@ Metadata: SpdxLicenseId: Apache-2.0 Parameters: - LambdaARN: + DestinationARN: 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 @@ -50,6 +50,15 @@ Parameters: 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 RoleArn, '' ] + create_pass_role: !Not [ !Condition create_invoke_permission ] + Resources: SumoLogGroupLambdaConnector: @@ -60,10 +69,11 @@ Resources: Runtime: nodejs10.x Environment: Variables: - LAMBDA_ARN: !Ref "LambdaARN" + DESTINATION_ARN: !Ref "DestinationARN" LOG_GROUP_PATTERN: !Ref "LogGroupPattern" USE_EXISTING_LOG_GROUPS: !Ref "UseExistingLogs" LOG_GROUP_TAGS: !Join [",", {"Ref": "LogGroupTags"} ] + ROLE_ARN: !Ref "RoleArn" Policies: - Statement: - Sid: ReadWriteFilterPolicy @@ -86,11 +96,28 @@ 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" + FunctionName: !Ref "DestinationARN" Principal: !Sub 'logs.${AWS::Region}.amazonaws.com' SourceAccount: !Ref AWS::AccountId SourceArn: !Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:*:*' diff --git a/loggroup-lambda-connector/src/loggroup-lambda-connector.js b/loggroup-lambda-connector/src/loggroup-lambda-connector.js index 4cf8e8f..539f726 100644 --- a/loggroup-lambda-connector/src/loggroup-lambda-connector.js +++ b/loggroup-lambda-connector/src/loggroup-lambda-connector.js @@ -5,13 +5,24 @@ async function sleep(waitTimeInMs) { return new Promise((resolve) => setTimeout(resolve, waitTimeInMs)); } -function subscribeToLambda(lambdaLogGroupName, lambdaArn, errorHandler) { - var params = { - destinationArn: lambdaArn, - filterName: 'SumoLGLBDFilter', - filterPattern: '', - logGroupName: lambdaLogGroupName - }; +function subscribeToLambda(lambdaLogGroupName, destinationArn, roleArn, errorHandler) { + if (destinationArn.startsWith("arn:aws:lambda")){ + var params = { + destinationArn: destinationArn, + filterName: 'SumoLGLBDFilter', + filterPattern: '', + logGroupName: lambdaLogGroupName + }; + } else { + var params = { + destinationArn: destinationArn, + filterName: 'SumoLGKinesisFilter', + filterPattern: '', + logGroupName: lambdaLogGroupName, + roleArn: roleArn + }; + } + // handle case where subscription filter exists/case where loggroup generated by target lambda cwl.putSubscriptionFilter(params, errorHandler); } @@ -42,7 +53,8 @@ function filterLogGroups(event, logGroupRegex) { async function subscribeExistingLogGroups(logGroups) { var logGroupName; var logGroupRegex = new RegExp(process.env.LOG_GROUP_PATTERN, "i"); - var lambdaArn = process.env.LAMBDA_ARN; + var destinationArn = process.env.DESTINATION_ARN; + var roleArn = process.env.ROLE_ARN; for (var i = logGroups.length - 1; i >= 0; i--) { logGroupName = logGroups[i].logGroupName; if (logGroupName.match(logGroupRegex)) { @@ -50,7 +62,7 @@ async function subscribeExistingLogGroups(logGroups) { // 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) { + subscribeToLambda(logGroupName, destinationArn, roleArn, (function(inner_logGroupName) { return function (err, data) { if (err) { console.log("Error in subscribing", inner_logGroupName, err); } else { @@ -98,10 +110,10 @@ 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); + subscribeToLambda(logGroupName, env.DESTINATION_ARN, env.ROLE_ARN, errorHandler); } else { - console.log("Unmatched: ", logGroupName, env.LAMBDA_ARN); + console.log("Unmatched: ", logGroupName, env.DESTINATION_ARN); } } From 5ee1361790c0e1d0b3232808bde9fdcf76082cc0 Mon Sep 17 00:00:00 2001 From: sourabh Date: Mon, 1 Mar 2021 15:07:39 +0530 Subject: [PATCH 02/12] adding destinationtype for better control over input values. Updating methodname. Updating test cases. --- loggroup-lambda-connector/sam/template.yaml | 203 +++++++------ .../src/loggroup-lambda-connector.js | 6 +- .../test/requirements.txt | 1 + .../test/test_loggroup_lambda_connector.py | 275 ++++++++++-------- 4 files changed, 266 insertions(+), 219 deletions(-) diff --git a/loggroup-lambda-connector/sam/template.yaml b/loggroup-lambda-connector/sam/template.yaml index dead4c4..3234236 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: 300 + MemorySize: 128 Metadata: AWS::ServerlessRepo::Application: @@ -15,12 +15,12 @@ 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 + - lambda + - sumologic + - autosubscribe + - serverless + - loggroups + - cloudwatch LicenseUrl: ../LICENSE Name: sumologic-loggroup-connector ReadmeUrl: ../README.md @@ -29,53 +29,74 @@ Metadata: SpdxLicenseId: Apache-2.0 Parameters: - DestinationARN: - 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." + + 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' + + DestinationARN: + 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 RoleArn, '' ] - create_pass_role: !Not [ !Condition create_invoke_permission ] + create_invoke_permission: !Equals [ !Ref DestinationType, 'Lambda' ] + create_pass_role: !Equals [ !Ref DestinationType, 'Kinesis' ] + +Rules: + testRoleArn: + RuleCondition: !Equals + - !Ref DestinationType + - Lambda + Assertions: + - Assert: !Equals + - !Ref RoleArn + - '' + AssertDescription: 'If Destination Type is Lambda, than the role ARN should be 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: - DESTINATION_ARN: !Ref "DestinationARN" - LOG_GROUP_PATTERN: !Ref "LogGroupPattern" - USE_EXISTING_LOG_GROUPS: !Ref "UseExistingLogs" - LOG_GROUP_TAGS: !Join [",", {"Ref": "LogGroupTags"} ] - ROLE_ARN: !Ref "RoleArn" - 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: nodejs10.x + Environment: + Variables: + DESTINATION_ARN: !Ref "DestinationARN" + LOG_GROUP_PATTERN: !Ref "LogGroupPattern" + USE_EXISTING_LOG_GROUPS: !Ref "UseExistingLogs" + LOG_GROUP_TAGS: !Join [ ",", { "Ref": "LogGroupTags" } ] + ROLE_ARN: !Ref "RoleArn" + Policies: + - Statement: - Sid: ReadWriteFilterPolicy Effect: Allow Action: @@ -84,46 +105,46 @@ 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 - - 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 "DestinationARN" - Principal: !Sub 'logs.${AWS::Region}.amazonaws.com' - SourceAccount: !Ref AWS::AccountId - SourceArn: !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 + + 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 "DestinationARN" + Principal: !Sub 'logs.${AWS::Region}.amazonaws.com' + SourceAccount: !Ref AWS::AccountId + SourceArn: !Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:*:*' 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 539f726..d6f7d25 100644 --- a/loggroup-lambda-connector/src/loggroup-lambda-connector.js +++ b/loggroup-lambda-connector/src/loggroup-lambda-connector.js @@ -5,7 +5,7 @@ async function sleep(waitTimeInMs) { return new Promise((resolve) => setTimeout(resolve, waitTimeInMs)); } -function subscribeToLambda(lambdaLogGroupName, destinationArn, roleArn, errorHandler) { +function createSubscriptionFilter(lambdaLogGroupName, destinationArn, roleArn, errorHandler) { if (destinationArn.startsWith("arn:aws:lambda")){ var params = { destinationArn: destinationArn, @@ -62,7 +62,7 @@ async function subscribeExistingLogGroups(logGroups) { // sleep time between calls await sleep(1000*(process.env.SUBSCRIBE_DELAY_SECONDS || 2)); // 5 seconds - subscribeToLambda(logGroupName, destinationArn, roleArn, (function(inner_logGroupName) { return function (err, data) { + createSubscriptionFilter(logGroupName, destinationArn, roleArn, (function(inner_logGroupName) { return function (err, data) { if (err) { console.log("Error in subscribing", inner_logGroupName, err); } else { @@ -111,7 +111,7 @@ function processEvents(env, event, errorHandler) { var logGroupName = event.detail.requestParameters.logGroupName; if (filterLogGroups(event, env.LOG_GROUP_PATTERN)) { console.log("Subscribing: ", logGroupName, env.DESTINATION_ARN); - subscribeToLambda(logGroupName, env.DESTINATION_ARN, env.ROLE_ARN, errorHandler); + createSubscriptionFilter(logGroupName, env.DESTINATION_ARN, env.ROLE_ARN, errorHandler); } else { console.log("Unmatched: ", logGroupName, env.DESTINATION_ARN); } 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_loggroup_lambda_connector.py b/loggroup-lambda-connector/test/test_loggroup_lambda_connector.py index 5b3858d..4c01af9 100644 --- a/loggroup-lambda-connector/test/test_loggroup_lambda_connector.py +++ b/loggroup-lambda-connector/test/test_loggroup_lambda_connector.py @@ -1,3 +1,4 @@ +import subprocess import unittest import boto3 from time import sleep @@ -6,66 +7,72 @@ import sys import datetime -BUCKET_PREFIX = "appdevstore" +import cfn_flip +# Modify the name of the bucket prefix for testing +BUCKET_PREFIX = "cf-templates-1qpf3unpuo1hw" +AWS_REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") -class TestLambda(unittest.TestCase): +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) + + # 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_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.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 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,103 +81,73 @@ 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 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 upload_code_in_multiple_regions(): regions = [ "us-east-2", @@ -183,7 +160,7 @@ def upload_code_in_multiple_regions(): "ap-southeast-2", "ap-northeast-1", "ca-central-1", - # "cn-north-1", + # "cn-north-1", "eu-central-1", "eu-west-1", "eu-west-2", @@ -195,16 +172,22 @@ def upload_code_in_multiple_regions(): # create_bucket(region) for region in regions: - upload_code_in_S3(region) + upload_to_s3(region) + + +def get_bucket_name(): + return '%s-%s' % (BUCKET_PREFIX, AWS_REGION) -def get_bucket_name(region): - return '%s-%s' % (BUCKET_PREFIX, region) +def get_account_id(): + client = boto3.client("sts", AWS_REGION) + account_id = client.get_caller_identity()["Account"] + return account_id def create_bucket(region): s3 = boto3.client('s3', region) - bucket_name = get_bucket_name(region) + bucket_name = get_bucket_name() if region == "us-east-1": response = s3.create_bucket(Bucket=bucket_name) else: @@ -215,14 +198,13 @@ def create_bucket(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 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 prod_deploy(): @@ -239,10 +221,53 @@ def prod_deploy(): 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() From 52fcd331b98297a1163aef19395d83523b729d53 Mon Sep 17 00:00:00 2001 From: sourabh Date: Mon, 1 Mar 2021 16:11:26 +0530 Subject: [PATCH 03/12] adding test cases for kinesis firehose. --- .../test/test-template.yaml | 228 ++++++++++++++++++ .../test/test_loggroup_lambda_connector.py | 16 +- 2 files changed, 243 insertions(+), 1 deletion(-) create mode 100644 loggroup-lambda-connector/test/test-template.yaml diff --git a/loggroup-lambda-connector/test/test-template.yaml b/loggroup-lambda-connector/test/test-template.yaml new file mode 100644 index 0000000..6547d44 --- /dev/null +++ b/loggroup-lambda-connector/test/test-template.yaml @@ -0,0 +1,228 @@ +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: + DestinationType: !Ref DestinationType + DestinationARN: !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 \ 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 4c01af9..e3a4768 100644 --- a/loggroup-lambda-connector/test/test_loggroup_lambda_connector.py +++ b/loggroup-lambda-connector/test/test_loggroup_lambda_connector.py @@ -10,7 +10,7 @@ import cfn_flip # Modify the name of the bucket prefix for testing -BUCKET_PREFIX = "cf-templates-1qpf3unpuo1hw" +BUCKET_PREFIX = "appdevstore" AWS_REGION = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") @@ -54,6 +54,20 @@ def test_2_existing_logs(self): self.create_log_group() 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.assert_subscription_filter("SumoLGKinesisFilter") + + def test_4_existing_kinesis(self): + 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.create_log_group() + self.assert_subscription_filter("SumoLGKinesisFilter") + def create_stack_parameters(self, destination, existing, pattern='test'): return [ { From 063a4f221eb8f1f5f49865e4fd31791ccccf89fb Mon Sep 17 00:00:00 2001 From: sourabh Date: Mon, 1 Mar 2021 16:19:55 +0530 Subject: [PATCH 04/12] updating readme --- loggroup-lambda-connector/Readme.md | 28 ++++++++++----------- loggroup-lambda-connector/sam/template.yaml | 2 +- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/loggroup-lambda-connector/Readme.md b/loggroup-lambda-connector/Readme.md index bece205..4fd740b 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 + DestinationType: 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. + DestinationARN: "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,22 +47,17 @@ It has two environment variables } ``` +Kinesis Destination ARN :- This specifies the ARN of the kinesis Stream. + **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 -**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 diff --git a/loggroup-lambda-connector/sam/template.yaml b/loggroup-lambda-connector/sam/template.yaml index 3234236..1d6ebb7 100644 --- a/loggroup-lambda-connector/sam/template.yaml +++ b/loggroup-lambda-connector/sam/template.yaml @@ -33,7 +33,7 @@ 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." + Kinesis - When the destination ARN for subscription filter is an Kinesis or Amazon Kinesis data firehose stream." Default: 'Lambda' AllowedValues: - 'Lambda' From 3bd50f55cf8e94592a9fd3378d13440459c34eda Mon Sep 17 00:00:00 2001 From: sourabh Date: Mon, 1 Mar 2021 21:44:15 +0530 Subject: [PATCH 05/12] updating existing log group test cases. --- loggroup-lambda-connector/sam/template.yaml | 12 +- .../test/loggroup-lambda-cft.json | 208 ------------------ .../test/test-template.yaml | 6 +- .../test/test_loggroup_lambda_connector.py | 80 ++----- 4 files changed, 34 insertions(+), 272 deletions(-) delete mode 100644 loggroup-lambda-connector/test/loggroup-lambda-cft.json diff --git a/loggroup-lambda-connector/sam/template.yaml b/loggroup-lambda-connector/sam/template.yaml index 1d6ebb7..517fd0b 100644 --- a/loggroup-lambda-connector/sam/template.yaml +++ b/loggroup-lambda-connector/sam/template.yaml @@ -70,7 +70,7 @@ Conditions: create_pass_role: !Equals [ !Ref DestinationType, 'Kinesis' ] Rules: - testRoleArn: + testRoleArnWithLambda: RuleCondition: !Equals - !Ref DestinationType - Lambda @@ -79,6 +79,16 @@ Rules: - !Ref RoleArn - '' AssertDescription: 'If Destination Type is Lambda, than the role ARN should be empty.' + testRoleArnWithKinesis: + RuleCondition: !Equals + - !Ref DestinationType + - Kinesis + Assertions: + - Assert: !Not + - !Equals + - !Ref RoleArn + - '' + AssertDescription: 'If Destination Type is Kinesis, than the role ARN can not be kept empty.' Resources: 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/test-template.yaml b/loggroup-lambda-connector/test/test-template.yaml index 6547d44..6d27cb5 100644 --- a/loggroup-lambda-connector/test/test-template.yaml +++ b/loggroup-lambda-connector/test/test-template.yaml @@ -225,4 +225,8 @@ Outputs: roleArn: Description: "Role ARN" Condition: create_pass_role - Value: !GetAtt KinesisLogsRole.Arn \ No newline at end of file + 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 e3a4768..84637a7 100644 --- a/loggroup-lambda-connector/test/test_loggroup_lambda_connector.py +++ b/loggroup-lambda-connector/test/test_loggroup_lambda_connector.py @@ -1,4 +1,5 @@ import subprocess +import time import unittest import boto3 from time import sleep @@ -25,6 +26,7 @@ def setUp(self): # 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")) @@ -48,10 +50,11 @@ def test_1_lambda(self): 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.create_log_group() + self.invoke_lambda() self.assert_subscription_filter("SumoLGLBDFilter") def test_3_kinesis(self): @@ -62,10 +65,11 @@ def test_3_kinesis(self): self.assert_subscription_filter("SumoLGKinesisFilter") 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.create_log_group() + self.invoke_lambda() self.assert_subscription_filter("SumoLGKinesisFilter") def create_stack_parameters(self, destination, existing, pattern='test'): @@ -155,6 +159,18 @@ def _parse_template(self, template_name): 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) @@ -162,56 +178,10 @@ def read_file(file_path): return f.read().strip() -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_to_s3(region) - - def get_bucket_name(): return '%s-%s' % (BUCKET_PREFIX, AWS_REGION) -def get_account_id(): - client = boto3.client("sts", AWS_REGION) - account_id = client.get_caller_identity()["Account"] - return account_id - - -def create_bucket(region): - s3 = boto3.client('s3', region) - bucket_name = get_bucket_name() - 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_to_s3(file_path): print("Uploading %s file in S3 region: %s" % (file_path, AWS_REGION)) s3 = boto3.client('s3', AWS_REGION) @@ -221,20 +191,6 @@ def upload_to_s3(file_path): 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") From 1a819acc6fee63af32c524beab2960d4306852a2 Mon Sep 17 00:00:00 2001 From: sourabh Date: Tue, 2 Mar 2021 13:28:08 +0530 Subject: [PATCH 06/12] updating parameter names for better ordering. --- loggroup-lambda-connector/Readme.md | 4 ++-- loggroup-lambda-connector/sam/template.yaml | 18 +++++++++--------- .../test/test-template.yaml | 4 ++-- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/loggroup-lambda-connector/Readme.md b/loggroup-lambda-connector/Readme.md index 4fd740b..2420303 100644 --- a/loggroup-lambda-connector/Readme.md +++ b/loggroup-lambda-connector/Readme.md @@ -9,9 +9,9 @@ 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, - DestinationType: Lambda - When the destination ARN for subscription filter is an AWS Lambda 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. - DestinationARN: "Enter Destination ARN like Lambda function, Kinesis stream. For more information, visit - https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html + 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. diff --git a/loggroup-lambda-connector/sam/template.yaml b/loggroup-lambda-connector/sam/template.yaml index 517fd0b..70f01a7 100644 --- a/loggroup-lambda-connector/sam/template.yaml +++ b/loggroup-lambda-connector/sam/template.yaml @@ -24,13 +24,13 @@ Metadata: 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: - DestinationType: + 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." @@ -39,7 +39,7 @@ Parameters: - 'Lambda' - 'Kinesis' - DestinationARN: + 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" @@ -66,13 +66,13 @@ Parameters: Description: "Enter AWS IAM Role arn in case the destination is Kinesis Firehose stream." Conditions: - create_invoke_permission: !Equals [ !Ref DestinationType, 'Lambda' ] - create_pass_role: !Equals [ !Ref DestinationType, 'Kinesis' ] + create_invoke_permission: !Equals [ !Ref DestinationArnType, 'Lambda' ] + create_pass_role: !Equals [ !Ref DestinationArnType, 'Kinesis' ] Rules: testRoleArnWithLambda: RuleCondition: !Equals - - !Ref DestinationType + - !Ref DestinationArnType - Lambda Assertions: - Assert: !Equals @@ -81,7 +81,7 @@ Rules: AssertDescription: 'If Destination Type is Lambda, than the role ARN should be empty.' testRoleArnWithKinesis: RuleCondition: !Equals - - !Ref DestinationType + - !Ref DestinationArnType - Kinesis Assertions: - Assert: !Not @@ -100,7 +100,7 @@ Resources: Runtime: nodejs10.x Environment: Variables: - DESTINATION_ARN: !Ref "DestinationARN" + DESTINATION_ARN: !Ref "DestinationArnValue" LOG_GROUP_PATTERN: !Ref "LogGroupPattern" USE_EXISTING_LOG_GROUPS: !Ref "UseExistingLogs" LOG_GROUP_TAGS: !Join [ ",", { "Ref": "LogGroupTags" } ] @@ -148,7 +148,7 @@ Resources: Condition: create_invoke_permission Properties: Action: lambda:InvokeFunction - FunctionName: !Ref "DestinationARN" + 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:*:*' diff --git a/loggroup-lambda-connector/test/test-template.yaml b/loggroup-lambda-connector/test/test-template.yaml index 6d27cb5..02f35b2 100644 --- a/loggroup-lambda-connector/test/test-template.yaml +++ b/loggroup-lambda-connector/test/test-template.yaml @@ -210,8 +210,8 @@ Resources: Properties: TemplateURL: !Sub "https://${BucketName}.s3.amazonaws.com/packaged.yaml" Parameters: - DestinationType: !Ref DestinationType - DestinationARN: !If [ create_invoke_permission, !GetAtt DummyLambda.Arn, !GetAtt KinesisLogsDeliveryStream.Arn ] + 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 ] From 76939433214d96ea46ee279342ac6437ee362b54 Mon Sep 17 00:00:00 2001 From: sourabh Date: Wed, 3 Mar 2021 11:16:52 +0530 Subject: [PATCH 07/12] updating node JS version to 14.x from 10.x --- loggroup-lambda-connector/sam/packaged.yaml | 88 ++++++++++++++++++--- loggroup-lambda-connector/sam/template.yaml | 2 +- 2 files changed, 79 insertions(+), 11 deletions(-) diff --git a/loggroup-lambda-connector/sam/packaged.yaml b/loggroup-lambda-connector/sam/packaged.yaml index 6f5785d..d004392 100644 --- a/loggroup-lambda-connector/sam/packaged.yaml +++ b/loggroup-lambda-connector/sam/packaged.yaml @@ -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,17 +59,57 @@ 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 +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/44a32060109e4c7efa4feed59007b04f Handler: loggroup-lambda-connector.handler - Runtime: nodejs10.x + Runtime: nodejs14.x Environment: Variables: - LAMBDA_ARN: - Ref: LambdaARN + DESTINATION_ARN: + Ref: DestinationArnValue LOG_GROUP_PATTERN: Ref: LogGroupPattern USE_EXISTING_LOG_GROUPS: @@ -68,6 +118,8 @@ Resources: Fn::Join: - ',' - Ref: LogGroupTags + ROLE_ARN: + Ref: RoleArn Policies: - Statement: - Sid: ReadWriteFilterPolicy @@ -90,12 +142,28 @@ 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: diff --git a/loggroup-lambda-connector/sam/template.yaml b/loggroup-lambda-connector/sam/template.yaml index 70f01a7..acf29c7 100644 --- a/loggroup-lambda-connector/sam/template.yaml +++ b/loggroup-lambda-connector/sam/template.yaml @@ -97,7 +97,7 @@ Resources: Properties: CodeUri: ../src/ Handler: "loggroup-lambda-connector.handler" - Runtime: nodejs10.x + Runtime: nodejs14.x Environment: Variables: DESTINATION_ARN: !Ref "DestinationArnValue" From c9ec731bc546d8a5e5776e1677604f4a173c6b9c Mon Sep 17 00:00:00 2001 From: sourabh Date: Fri, 26 Mar 2021 16:08:01 +0530 Subject: [PATCH 08/12] updating the code for existing log groups. Existing is called when user select existing as true in parameters. --- loggroup-lambda-connector/sam/packaged.yaml | 62 +++++++++++++++-- loggroup-lambda-connector/sam/template.yaml | 66 ++++++++++++++++++- .../src/loggroup-lambda-connector.js | 58 ++++++++-------- .../test/test_loggroup_lambda_connector.py | 8 +-- 4 files changed, 156 insertions(+), 38 deletions(-) diff --git a/loggroup-lambda-connector/sam/packaged.yaml b/loggroup-lambda-connector/sam/packaged.yaml index d004392..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: @@ -73,6 +73,10 @@ Conditions: Fn::Equals: - Ref: DestinationArnType - Kinesis + invoke_existing: + Fn::Equals: + - Ref: UseExistingLogs + - 'true' Rules: testRoleArnWithLambda: RuleCondition: @@ -103,17 +107,15 @@ Resources: SumoLogGroupLambdaConnector: Type: AWS::Serverless::Function Properties: - CodeUri: s3://cf-templates-1qpf3unpuo1hw-us-east-1/test-log-group-lambda-connector/44a32060109e4c7efa4feed59007b04f + CodeUri: s3://cf-templates-1qpf3unpuo1hw-us-east-1/test-log-group-lambda-connector/0d12ca7b2219c4fc3fe3cd29d6ba56d0 Handler: loggroup-lambda-connector.handler - Runtime: nodejs14.x + Runtime: nodejs12.x Environment: Variables: DESTINATION_ARN: Ref: DestinationArnValue LOG_GROUP_PATTERN: Ref: LogGroupPattern - USE_EXISTING_LOG_GROUPS: - Ref: UseExistingLogs LOG_GROUP_TAGS: Fn::Join: - ',' @@ -130,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 @@ -170,6 +178,50 @@ Resources: 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 acf29c7..d2a38f1 100644 --- a/loggroup-lambda-connector/sam/template.yaml +++ b/loggroup-lambda-connector/sam/template.yaml @@ -6,7 +6,7 @@ Description: > # More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst Globals: Function: - Timeout: 300 + Timeout: 900 MemorySize: 128 Metadata: @@ -69,6 +69,8 @@ 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 @@ -97,12 +99,11 @@ Resources: Properties: CodeUri: ../src/ Handler: "loggroup-lambda-connector.handler" - Runtime: nodejs14.x + Runtime: nodejs12.x Environment: Variables: DESTINATION_ARN: !Ref "DestinationArnValue" LOG_GROUP_PATTERN: !Ref "LogGroupPattern" - USE_EXISTING_LOG_GROUPS: !Ref "UseExistingLogs" LOG_GROUP_TAGS: !Join [ ",", { "Ref": "LogGroupTags" } ] ROLE_ARN: !Ref "RoleArn" Policies: @@ -115,6 +116,12 @@ Resources: - logs:PutSubscriptionFilter Resource: - !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 @@ -153,6 +160,59 @@ Resources: 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}' + + primerinvoke: + Type: AWS::CloudFormation::CustomResource + Version: "1.0" + Condition: invoke_existing + Properties: + ServiceToken: !GetAtt SumoLogGroupExistingLambdaConnector.Arn + DESTINATION_ARN: !Ref "DestinationArnValue" + LOG_GROUP_PATTERN: !Ref "LogGroupPattern" + ROLE_ARN: !Ref "RoleArn" + Outputs: SumoLogGroupLambdaConnector: diff --git a/loggroup-lambda-connector/src/loggroup-lambda-connector.js b/loggroup-lambda-connector/src/loggroup-lambda-connector.js index d6f7d25..35b9c1c 100644 --- a/loggroup-lambda-connector/src/loggroup-lambda-connector.js +++ b/loggroup-lambda-connector/src/loggroup-lambda-connector.js @@ -1,11 +1,7 @@ var AWS = require("aws-sdk"); 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)); -} -function createSubscriptionFilter(lambdaLogGroupName, destinationArn, roleArn, errorHandler) { +async function createSubscriptionFilter(lambdaLogGroupName, destinationArn, roleArn, errorHandler) { if (destinationArn.startsWith("arn:aws:lambda")){ var params = { destinationArn: destinationArn, @@ -16,7 +12,7 @@ function createSubscriptionFilter(lambdaLogGroupName, destinationArn, roleArn, e } else { var params = { destinationArn: destinationArn, - filterName: 'SumoLGKinesisFilter', + filterName: 'SumoLGLBDFilter', filterPattern: '', logGroupName: lambdaLogGroupName, roleArn: roleArn @@ -24,7 +20,7 @@ function createSubscriptionFilter(lambdaLogGroupName, destinationArn, roleArn, e } // handle case where subscription filter exists/case where loggroup generated by target lambda - cwl.putSubscriptionFilter(params, errorHandler); + await cwl.putSubscriptionFilter(params, errorHandler); } function filterLogGroups(event, logGroupRegex) { @@ -58,11 +54,7 @@ async function subscribeExistingLogGroups(logGroups) { 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 - - createSubscriptionFilter(logGroupName, destinationArn, roleArn, (function(inner_logGroupName) { return function (err, data) { + await createSubscriptionFilter(logGroupName, destinationArn, roleArn, (function(inner_logGroupName) { return function (err, data) { if (err) { console.log("Error in subscribing", inner_logGroupName, err); } else { @@ -75,13 +67,15 @@ async function subscribeExistingLogGroups(logGroups) { } } -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) { @@ -89,15 +83,18 @@ function processExistingLogGroups(token, errorHandler) { reject(err); } else { console.log("fetched logGroups: " + data.logGroups.length + " nextToken: " + data.nextToken); + subscribeExistingLogGroups(data.logGroups); resolve(data); } }); }); var cb = function (data) { - subscribeExistingLogGroups(data.logGroups); - if (data.nextToken) {// if next set of log groups exists - processExistingLogGroups(data.nextToken, errorHandler) + 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"); } }; @@ -106,6 +103,16 @@ 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; @@ -119,7 +126,7 @@ function processEvents(env, event, errorHandler) { } 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); @@ -128,10 +135,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/test_loggroup_lambda_connector.py b/loggroup-lambda-connector/test/test_loggroup_lambda_connector.py index 84637a7..c0df884 100644 --- a/loggroup-lambda-connector/test/test_loggroup_lambda_connector.py +++ b/loggroup-lambda-connector/test/test_loggroup_lambda_connector.py @@ -54,7 +54,7 @@ def test_2_existing_logs(self): 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.invoke_lambda() self.assert_subscription_filter("SumoLGLBDFilter") def test_3_kinesis(self): @@ -62,15 +62,15 @@ def test_3_kinesis(self): print("Testing Stack Creation") self.assertTrue(self.stack_exists(self.stack_name)) self.create_log_group() - self.assert_subscription_filter("SumoLGKinesisFilter") + 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("SumoLGKinesisFilter") + #self.invoke_lambda() + self.assert_subscription_filter("SumoLGLBDFilter") def create_stack_parameters(self, destination, existing, pattern='test'): return [ From dd69fc39b71de976bcb53dabdc8ac9513b1bd2db Mon Sep 17 00:00:00 2001 From: sourabh Date: Fri, 26 Mar 2021 16:33:48 +0530 Subject: [PATCH 09/12] udapting message --- loggroup-lambda-connector/src/loggroup-lambda-connector.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/loggroup-lambda-connector/src/loggroup-lambda-connector.js b/loggroup-lambda-connector/src/loggroup-lambda-connector.js index 35b9c1c..3e34c9e 100644 --- a/loggroup-lambda-connector/src/loggroup-lambda-connector.js +++ b/loggroup-lambda-connector/src/loggroup-lambda-connector.js @@ -94,7 +94,7 @@ function processExistingLogGroups(token, context, errorHandler) { 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); + console.log("All Log Groups are subscribed to Destination Type " + process.env.DESTINATION_ARN); errorHandler(null, "Success"); } }; From a1533e4edb1d1fcb78ed9ceeab99ea55b8166c73 Mon Sep 17 00:00:00 2001 From: sourabh Date: Fri, 26 Mar 2021 23:45:55 +0530 Subject: [PATCH 10/12] adding retry mechanism in case of throttling. Preventing deletion of primer resource. --- loggroup-lambda-connector/sam/template.yaml | 2 + .../src/loggroup-lambda-connector.js | 50 ++++++++++++------- 2 files changed, 34 insertions(+), 18 deletions(-) diff --git a/loggroup-lambda-connector/sam/template.yaml b/loggroup-lambda-connector/sam/template.yaml index d2a38f1..1eae612 100644 --- a/loggroup-lambda-connector/sam/template.yaml +++ b/loggroup-lambda-connector/sam/template.yaml @@ -207,6 +207,8 @@ Resources: Type: AWS::CloudFormation::CustomResource Version: "1.0" Condition: invoke_existing + DeletionPolicy : "Retain" + UpdateReplacePolicy: "Retain" Properties: ServiceToken: !GetAtt SumoLogGroupExistingLambdaConnector.Arn DESTINATION_ARN: !Ref "DestinationArnValue" diff --git a/loggroup-lambda-connector/src/loggroup-lambda-connector.js b/loggroup-lambda-connector/src/loggroup-lambda-connector.js index 3e34c9e..b2ade86 100644 --- a/loggroup-lambda-connector/src/loggroup-lambda-connector.js +++ b/loggroup-lambda-connector/src/loggroup-lambda-connector.js @@ -1,7 +1,8 @@ var AWS = require("aws-sdk"); +const util = require("util"); var cwl = new AWS.CloudWatchLogs({apiVersion: '2014-03-28'}); -async function createSubscriptionFilter(lambdaLogGroupName, destinationArn, roleArn, errorHandler) { +async function createSubscriptionFilter(lambdaLogGroupName, destinationArn, roleArn) { if (destinationArn.startsWith("arn:aws:lambda")){ var params = { destinationArn: destinationArn, @@ -20,7 +21,13 @@ async function createSubscriptionFilter(lambdaLogGroupName, destinationArn, role } // handle case where subscription filter exists/case where loggroup generated by target lambda - await 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) { @@ -46,24 +53,29 @@ function filterLogGroups(event, logGroupRegex) { return false; } -async function subscribeExistingLogGroups(logGroups) { - var logGroupName; +async function subscribeExistingLogGroups(logGroups, counter) { var logGroupRegex = new RegExp(process.env.LOG_GROUP_PATTERN, "i"); var destinationArn = process.env.DESTINATION_ARN; var roleArn = process.env.ROLE_ARN; - for (var i = logGroups.length - 1; i >= 0; i--) { - logGroupName = logGroups[i].logGroupName; - if (logGroupName.match(logGroupRegex)) { - await createSubscriptionFilter(logGroupName, destinationArn, roleArn, (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 { + 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 (counter < 4 && failedLogGroupNames.length > 0) { + console.log("Retrying Subscription for Failed Log Groups due to throttling with counter number as " + counter); + await subscribeExistingLogGroups(failedLogGroupNames, counter + 1); } } @@ -83,12 +95,12 @@ function processExistingLogGroups(token, context, errorHandler) { reject(err); } else { console.log("fetched logGroups: " + data.logGroups.length + " nextToken: " + data.nextToken); - subscribeExistingLogGroups(data.logGroups); resolve(data); } }); }); - var cb = function (data) { + var cb = async function (data) { + await subscribeExistingLogGroups(data.logGroups, 0); 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); @@ -118,7 +130,9 @@ function processEvents(env, event, errorHandler) { var logGroupName = event.detail.requestParameters.logGroupName; if (filterLogGroups(event, env.LOG_GROUP_PATTERN)) { console.log("Subscribing: ", logGroupName, env.DESTINATION_ARN); - createSubscriptionFilter(logGroupName, env.DESTINATION_ARN, env.ROLE_ARN, errorHandler); + createSubscriptionFilter(logGroupName, env.DESTINATION_ARN, env.ROLE_ARN).catch (function (err) { + errorHandler(err, "Error in Subscribing."); + }); } else { console.log("Unmatched: ", logGroupName, env.DESTINATION_ARN); } From 4f144ddee3fc149dfd4432d40b334577b778e492 Mon Sep 17 00:00:00 2001 From: sourabh Date: Thu, 1 Apr 2021 11:28:41 +0530 Subject: [PATCH 11/12] updating read me --- loggroup-lambda-connector/Readme.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/loggroup-lambda-connector/Readme.md b/loggroup-lambda-connector/Readme.md index 2420303..d23afe4 100644 --- a/loggroup-lambda-connector/Readme.md +++ b/loggroup-lambda-connector/Readme.md @@ -49,8 +49,6 @@ Lambda Destination ARN :- This specifies ARN of the Lambda function. Also you ha Kinesis Destination ARN :- This specifies the ARN of the kinesis Stream. -**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 - **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. **ROLE_ARN** : This is used when subscription destination ARN is kinesis firehose stream. @@ -64,7 +62,6 @@ Running the test cases ``` python test_loggroup_lambda_connector.py ``` -Run the above command after building the zip file ## License From 4642e2e2c5e9dda2865a2b901ba221ceb1d3add2 Mon Sep 17 00:00:00 2001 From: sourabh Date: Thu, 1 Apr 2021 12:05:20 +0530 Subject: [PATCH 12/12] changes as per review comments in the GITHUB PR. --- loggroup-lambda-connector/sam/template.yaml | 2 +- .../src/loggroup-lambda-connector.js | 11 ++++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/loggroup-lambda-connector/sam/template.yaml b/loggroup-lambda-connector/sam/template.yaml index 1eae612..bc0ee18 100644 --- a/loggroup-lambda-connector/sam/template.yaml +++ b/loggroup-lambda-connector/sam/template.yaml @@ -203,7 +203,7 @@ Resources: Resource: - !Sub 'arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${SumoLogGroupLambdaConnector}' - primerinvoke: + InvokeLambdaConnector: Type: AWS::CloudFormation::CustomResource Version: "1.0" Condition: invoke_existing diff --git a/loggroup-lambda-connector/src/loggroup-lambda-connector.js b/loggroup-lambda-connector/src/loggroup-lambda-connector.js index b2ade86..6fe170a 100644 --- a/loggroup-lambda-connector/src/loggroup-lambda-connector.js +++ b/loggroup-lambda-connector/src/loggroup-lambda-connector.js @@ -1,6 +1,7 @@ var AWS = require("aws-sdk"); const util = require("util"); var cwl = new AWS.CloudWatchLogs({apiVersion: '2014-03-28'}); +var maxRetryCounter = 3; async function createSubscriptionFilter(lambdaLogGroupName, destinationArn, roleArn) { if (destinationArn.startsWith("arn:aws:lambda")){ @@ -53,7 +54,7 @@ function filterLogGroups(event, logGroupRegex) { return false; } -async function subscribeExistingLogGroups(logGroups, counter) { +async function subscribeExistingLogGroups(logGroups, retryCounter) { var logGroupRegex = new RegExp(process.env.LOG_GROUP_PATTERN, "i"); var destinationArn = process.env.DESTINATION_ARN; var roleArn = process.env.ROLE_ARN; @@ -73,9 +74,9 @@ async function subscribeExistingLogGroups(logGroups, counter) { } }, Promise.resolve()); - if (counter < 4 && failedLogGroupNames.length > 0) { - console.log("Retrying Subscription for Failed Log Groups due to throttling with counter number as " + counter); - await subscribeExistingLogGroups(failedLogGroupNames, counter + 1); + 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); } } @@ -100,7 +101,7 @@ function processExistingLogGroups(token, context, errorHandler) { }); }); var cb = async function (data) { - await subscribeExistingLogGroups(data.logGroups, 0); + 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);