PKVWNϣ((tcsamcli/__init__.py"""Tc sam cli""" __version__ = "0.0.9" PKVNRw{ootcsamcli/__main__.py#!/usr/bin/env python import json import sys from operator import itemgetter import click import toml import boto3 import samcli import sh import tclambda import tclambda.auto_functions from tclambda.function import LambdaFunction from . import __version__, template_builder cloudformation = boto3.client("cloudformation") version_message = "\n".join( [ f"tc-sam-cli, version {__version__}", f"tclambda, version {tclambda.__version__}", f"aws-sam-cli, version {samcli.__version__}", ] ) @click.group() @click.version_option(message=version_message) def cli(): pass @cli.command() @click.option("--output", type=click.File("w"), default=sys.stdout) def generate_template(output): with open("tc-sam.toml") as f: config = toml.load(f) template_builder.build_template(config, stream=output) @cli.command() @click.option( "--no-build", is_flag=True, default=False, help="Skip building the packages." ) def deploy(**kwargs): with open("tc-sam.toml") as f: config = toml.load(f) stack_name = config["Default"]["StackName"] s3_bucket = config["Default"]["S3CodeBucket"] template_file = ".aws-sam/packaged.yaml" try: if not kwargs.get("no_build"): sh.sam.build(_fg=True, template="template.json") sh.sam.package( s3_bucket=s3_bucket, output_template_file=template_file, _fg=True ) sh.sam.deploy( template_file=template_file, stack_name=stack_name, capabilities="CAPABILITY_IAM", _fg=True, ) except Exception: pass @cli.command() @click.argument("module") @click.option("--input-file", type=click.File("r")) @click.option("--function-name") @click.option("--args", type=json.loads, default="[]") @click.option("--kwargs", type=json.loads, default="{}") @click.option("--delay", type=float, default=5) def invoke(module, input_file, function_name, args, kwargs, delay): lf = getattr(tclambda.auto_functions, module) if input_file: data = json.load(input_file) function_name = data["function_name"] args = data.get("args", []) kwargs = data.get("kwargs", {}) result = getattr(lf, function_name)(*args, **kwargs) click.echo_via_pager( json.dumps(result.result(delay=delay), indent=2, sort_keys=True) ) def environmental_variables(): with open("tc-sam.toml") as f: config = toml.load(f) stack_name = config["Default"]["StackName"] response = cloudformation.describe_stacks(StackName=stack_name) stack = response["Stacks"][0] outputs = dict(map(itemgetter("OutputKey", "OutputValue"), stack["Outputs"])) result_bucket = outputs["ResultBucket"] for key, value in outputs.items(): if key.endswith("Queue"): key = key[: -len("Queue")].upper() yield key, value, result_bucket @cli.command() @click.option("--env-vars", is_flag=True) def env_export(env_vars): environmental_dict = {} for key, queue, result_bucket in environmental_variables(): environmental_dict[f"TC_{key}_QUEUE"] = f"{queue}" environmental_dict[f"TC_{key}_BUCKET"] = f"{result_bucket}" if env_vars: with open("tc-sam.toml") as f: config = toml.load(f) obj = {} for function in config["Functions"].keys(): obj[function] = {} obj[function].update(environmental_dict) obj[function]["TC_THIS_QUEUE"] = environmental_dict[ f"TC_{function.upper()}_QUEUE" ] obj[function]["TC_THIS_BUCKET"] = environmental_dict[ f"TC_{function.upper()}_BUCKET" ] click.echo(json.dumps(obj, indent=2, sort_keys=True)) else: for key, value in environmental_dict.items(): click.echo(f'{key}="{value}"') @cli.command() def ping(): with open("tc-sam.toml") as f: config = toml.load(f) stack_name = config["Default"]["StackName"] response = cloudformation.describe_stacks(StackName=stack_name) stack = response["Stacks"][0] outputs = dict(map(itemgetter("OutputKey", "OutputValue"), stack["Outputs"])) result_bucket = outputs["ResultBucket"] pings = [] for key, value in outputs.items(): if key.endswith("Queue"): key = key[: -len("Queue")].upper() lf = LambdaFunction(value, result_bucket) result = lf.ping() pings.append((key, result)) click.secho(f"Ping {key}") for key, ping in pings: try: if ping.result(delay=0.5) == "pong": click.secho(f"Pong {key}", fg="green") else: click.secho(f"No pong {key}: {ping.result()}") except TimeoutError as e: click.secho(f"Timeout {key}: {e}") except Exception as e: click.secho(f"Error {key}: {e}") if __name__ == "__main__": cli() PK{NR6·tcsamcli/template_builder.pyimport json def build_template(config, stream): template_object = { "AWSTemplateFormatVersion": "2010-09-09", "Description": "tc-integrations\nSample SAM Template for tc-integrations\n", "Globals": { "Function": { "Environment": {"Variables": generate_environmental_variables(config)}, "Timeout": 3, } }, "Outputs": generate_outputs(config), "Resources": generate_resources(config), "Transform": "AWS::Serverless-2016-10-31", } json.dump(template_object, stream, indent=2, sort_keys=True) def generate_environmental_variables(config, **defaults): functions = config["Functions"] env_vars = {"TC_THIS_BUCKET": {"Ref": "ResultBucket"}} for function in functions: env_vars[f"TC_{function.upper()}_QUEUE"] = {"Ref": f"{function}Sqs"} env_vars[f"TC_{function.upper()}_BUCKET"] = {"Ref": f"ResultBucket"} env_vars.update(defaults) return env_vars def generate_outputs(config): functions = config["Functions"] return { f"{function}Queue": {"Description": "SQSUrl", "Value": f"{function}Sqs"} for function in functions } def generate_resources(config): functions = config["Functions"] resources = {} resources["ResultBucket"] = { "Properties": { "LifecycleConfiguration": { "Rules": [ { "ExpirationInDays": "30", "Id": "RemoveAfter30Days", "Status": "Enabled", } ] } }, "Type": "AWS::S3::Bucket", } resources["LambdaRole"] = generate_lambda_role(config) for function, function_data in functions.items(): resources.update( { function: { "Properties": generate_function_properties(function, function_data), "Type": "AWS::Serverless::Function", }, f"{function}Sqs": { "Properties": {"VisibilityTimeout": function_data.get("Timeout")}, "Type": "AWS::SQS::Queue", }, f"{function}SqsMapping": { "Properties": { "BatchSize": function_data.get("BatchSize", 1), "Enabled": "true", "EventSourceArn": {"Fn::GetAtt": [f"{function}Sqs", "Arn"]}, "FunctionName": {"Fn::GetAtt": [function, "Arn"]}, }, "Type": "AWS::Lambda::EventSourceMapping", }, } ) return resources def generate_lambda_role(config): functions = config["Functions"] policy_statements = [ {"Action": ["cloudwatch:PutMetricData"], "Effect": "Allow", "Resource": "*"}, { "Action": ["xray:PutTraceSegments", "xray:PutTelemetryRecords"], "Effect": "Allow", "Resource": "*", }, {"Action": ["logs:*"], "Effect": "Allow", "Resource": "arn:aws:logs:*:*:*"}, { "Action": [ "sqs:SendMessage", "sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes", "sqs:ChangeMessageVisibility", ], "Effect": "Allow", "Resource": [ {"Fn::GetAtt": [f"{function}Sqs", "Arn"]} for function in functions ], }, { "Action": ["s3:*"], "Effect": "Allow", "Resource": [ {"Fn::GetAtt": ["ResultBucket", "Arn"]}, {"Fn::Join": ["/", [{"Fn::GetAtt": ["ResultBucket", "Arn"]}, "*"]]}, ], }, ] policy_statements.extend(config.get("ExtraPolicies", [])) return { "Properties": { "AssumeRolePolicyDocument": { "Statement": [ { "Action": ["sts:AssumeRole"], "Effect": "Allow", "Principal": {"Service": ["lambda.amazonaws.com"]}, } ], "Version": "2012-10-17", }, "Policies": [ { "PolicyDocument": { "Statement": policy_statements, "Version": "2012-10-17", }, "PolicyName": "allowLambdaLogs", } ], }, "Type": "AWS::IAM::Role", } def generate_function_properties(function, function_data): properties = { "CodeUri": function_data.get("CodeUri"), "Environment": { "Variables": generate_function_environmental_variables( function, function_data ) }, "Handler": function_data.get("Handler"), "MemorySize": function_data.get("MemorySize"), "Role": {"Fn::GetAtt": ["LambdaRole", "Arn"]}, "Runtime": "python3.7", "Timeout": function_data.get("Timeout"), "Tracing": "Active" if function_data.get("Tracing") else "PassThrough", } if function_data.get("ReservedConcurrentExecutions") is not None: properties["ReservedConcurrentExecutions"] = function_data.get( "ReservedConcurrentExecutions" ) if function_data.get("Events"): properties.setdefault("Events", {}) for event_name, event_data in function_data["Events"].items(): properties["Events"][event_name] = { "Type": "Schedule", "Properties": { "Schedule": event_data.get("Schedule"), "Input": json.dumps({"function": event_data.get("Function")}), }, } if function_data.get("Api"): properties.setdefault("Events", {}) for event_name, event_data in function_data["Api"].items(): properties["Events"][event_name] = { "Type": "Api", "Properties": { "Path": event_data.get("Path"), "Method": event_data.get("Method"), }, } return properties def generate_function_environmental_variables(function, function_data): env_vars = {"TC_THIS_QUEUE": {"Ref": f"{function}Sqs"}} env_vars.update(function_data.get("Environment", {})) return env_vars PK!H$ /0+tc_sam_cli-0.0.9.dist-info/entry_points.txtN+I/N.,()*I-N̵-I9z񹉙yV@PKLN=.."tc_sam_cli-0.0.9.dist-info/LICENSEMIT License Copyright (c) 2019 Trustcruit AB Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!HPO tc_sam_cli-0.0.9.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,szd&Y)r$[)T&UrPK!H] #tc_sam_cli-0.0.9.dist-info/METADATAV[OF~_q*ua@U#eUiAKBvmV==ޙq sI;0OaU.Ree)6p?%MYrAR5c\m{Q4hașƺ4EOa#v!3QYt}]^XܸBP.DY~% DɥAnաeۜ$}i KJ?ÏTa\.kN<CNVΤܧb!1qX\ A?_5AF9umB{x\F /KYWFmHu-3R$zDq#UfZ٧aJzz~4AUvwReӜ3{z g /g !$i6X a`eY+j=tZu?MowzEЖ2vͽE\Bx@,ͺwkZ#\_"#x&{,m439o '16L|7bn"$>tVԊ/KOt.^-t<:7 e !X)aqFQpɗ/u>vnqV7&󙹩zoc AXt{݃_zOeJam8\^CaT镑\aguX?;kS9]{"f;l(JmAG,EP?G;+ 5kAEBТˎˊww:AFW[6vy-\5/Km8ƛíe݊w]clxak_ZwC''>n9x7YFgNJO&Z[xEy۩Q\!*AS:$"㹣sI s:Lګ & 0bN~ZQ UwOٗv~7=@oNk\^ s|j\"@g.b 0O%/hpb4V)+!l3m>cChGy꩏]'R=@腰P#oѳC[muM~)FBm=Vu\xqD[ғpjאָ~ᆺB^3DbC9n 䠝`;ҀÑ~ǧ/i}UmypB+|(Fk_