PKSN((tcsamcli/__init__.py"""Tc sam cli""" __version__ = "0.0.6" PKSNntcsamcli/__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 jinja2 import Environment, PackageLoader from tclambda.function import LambdaFunction from . import __version__ cloudformation = boto3.client("cloudformation") version_message = "\n".join( [ f"tcsamcli, 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) loader = PackageLoader("tcsamcli", "templates") env = Environment( loader=loader, autoescape=False, keep_trailing_newline=True, trim_blocks=True ) template = env.get_template("template.yaml.j2") output.write( template.render( config=config["Functions"], extra_policies=config.get("ExtraPolicies", []) ) ) @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) 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) ) @cli.command() def env_export(): 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() click.echo(f'TC_{key}_QUEUE="{value}"') click.echo(f'TC_{key}_BUCKET="{result_bucket}"') @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() PKUNWF#tcsamcli/templates/template.yaml.j2AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: > tc-integrations Sample SAM Template for tc-integrations # More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md Globals: Function: Timeout: 3 Environment: Variables: {% for item in config %} TC_{{ item.upper() }}_QUEUE: !Ref {{ item }}Sqs TC_{{ item.upper() }}_BUCKET: !Ref ResultBucket {% endfor %} Resources: ResultBucket: Type: AWS::S3::Bucket Properties: LifecycleConfiguration: Rules: - Id: RemoveAfter30Days ExpirationInDays: 30 Status: Enabled {% for key, data in config.items() %} {{ key }}: Type: AWS::Serverless::Function Properties: CodeUri: {{ data.get("CodeUri") }} Handler: {{ data.get("Handler") }} Runtime: {{ data.get("Runtime") }} MemorySize: {{ data.get("MemorySize") }} Timeout: {{ data.get("Timeout") }} {% if data.get("ReservedConcurrentExecutions") is not none %} ReservedConcurrentExecutions: {{ data["ReservedConcurrentExecutions"] }} {% endif %} Role: !GetAtt LambdaRole.Arn {% if data.get("Tracing") %} Tracing: Active {% else %} Tracing: PassThrough {% endif %} Environment: Variables: {% if data.get("Environment") %} {% for env_key, env_value in data["Environment"].items() %} {{ env_key }}: {{ env_value }} {% endfor %} {% endif %} TC_THIS_QUEUE: !Ref {{ key }}Sqs TC_THIS_BUCKET: !Ref ResultBucket {% if data.get("Events") %} Events: {% for event_name, event_data in data["Events"].items() %} {{ event_name }}: Type: Schedule Properties: Schedule: {{ event_data.get("Schedule") }} Input: '{"function": "{{ event_data.get("Function") }}"}' {% endfor %} {% endif %} {{ key }}Sqs: Type: AWS::SQS::Queue Properties: VisibilityTimeout: {{ data.get("Timeout") }} {{ key }}SqsMapping: Type: AWS::Lambda::EventSourceMapping Properties: BatchSize: {{ data.get("BatchSize", 1) }} Enabled: true EventSourceArn: !GetAtt {{ key }}Sqs.Arn FunctionName: !GetAtt {{ key }}.Arn {% endfor %} LambdaRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: - lambda.amazonaws.com Action: - sts:AssumeRole Policies: - PolicyName: allowLambdaLogs PolicyDocument: Version: '2012-10-17' Statement: {% for extra_policy in extra_policies %} - Effect: {{ extra_policy["Effect"] }} Action: {% for action in extra_policy["Action"] %} - {{ action }} {% endfor %} Resource: {{ extra_policy["Resource"] }} {% endfor %} - Effect: Allow Action: - cloudwatch:PutMetricData Resource: "*" - Effect: "Allow" Action: - "xray:PutTraceSegments" - "xray:PutTelemetryRecords" Resource: "*" - Effect: Allow Action: - logs:* Resource: arn:aws:logs:*:*:* - Effect: Allow Action: - sqs:SendMessage - sqs:ReceiveMessage - sqs:DeleteMessage - sqs:GetQueueAttributes - sqs:ChangeMessageVisibility Resource: {% for item in config %} - !GetAtt {{ item }}Sqs.Arn {% endfor %} - Effect: Allow Action: - s3:* Resource: - !GetAtt ResultBucket.Arn - !Join - "/" - - !GetAtt ResultBucket.Arn - "*" Outputs: {% for item in config %} {{ item }}Queue: Description: "SQS Url" Value: !Ref {{ item }}Sqs {% endfor %} ResultBucket: Description: "S3 bucket" Value: !Ref ResultBucket Region: Description: "AWS region" Value: !Ref AWS::Region PK!H$ /0+tc_sam_cli-0.0.6.dist-info/entry_points.txtN+I/N.,()*I-N̵-I9z񹉙yV@PKLN=.."tc_sam_cli-0.0.6.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.6.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,szd&Y)r$[)T&UrPK!H1S #tc_sam_cli-0.0.6.dist-info/METADATAUmOHbt-+'YJurvBe=I^Np?oٵRӝ.a|Hպ`7F%RD\0(KVEq?W:U)TNȽ7t>Y'& ޲|N@\ Ժ'M' > ." *XA/Y~a7YX˦)!j v΋4*e.RV6.=߉6\:ߝ1K(FU>2j1UTZO(*"z[l{?Ԫ URGw dXzqDlVo‰,45ĴFg0WR i_5 MyHr:IMd͹P՛Dr,${&y;lS}u%whr}y:&3&܊>9 a MrhiܓâMKV`tr66jE=_Nq$'BҐ -D4Dz~TL mϺl_@huO5r4ͻar*l) pODKc$c #:>s LP5n&١v1PK!Hqu!tc_sam_cli-0.0.6.dist-info/RECORD}лv@>a8QP$*"f7eEdpNk,QcR #IQ| ,%OUQ. ]*F~tNwU"et0[',8 ˪XF-aR&z,_r Ҥ۠V@?mSEAT!%>_߳nfT`6}#AV_CCrmpoBf;ẁC]W)6 V4TxYS٣$uze!cc3{F&tMO2 QVJ3\NCO3>ʣ,>O=>N#sor_PKSN((tcsamcli/__init__.pyPKSNnZtcsamcli/__main__.pyPKUNWF#tcsamcli/templates/template.yaml.j2PK!H$ /0+h#tc_sam_cli-0.0.6.dist-info/entry_points.txtPKLN=.."#tc_sam_cli-0.0.6.dist-info/LICENSEPK!HPO N(tc_sam_cli-0.0.6.dist-info/WHEELPK!H1S #(tc_sam_cli-0.0.6.dist-info/METADATAPK!Hqu!-tc_sam_cli-0.0.6.dist-info/RECORDPKl/