|
| 1 | +""" |
| 2 | +Send SNS notifications after each miniwdl step |
| 3 | +""" |
| 4 | + |
| 5 | +import os |
| 6 | +import json |
| 7 | +from typing import Dict |
| 8 | +from datetime import datetime |
| 9 | +from WDL import values_to_json |
| 10 | +from WDL._util import StructuredLogMessage as _ |
| 11 | + |
| 12 | +import boto3 |
| 13 | + |
| 14 | +sns_client = boto3.client("sns", endpoint_url=os.getenv("AWS_ENDPOINT_URL")) |
| 15 | +topic_arn = os.getenv('STEP_NOTIFICATION_TOPIC_ARN') |
| 16 | + |
| 17 | + |
| 18 | +def process_outputs(outputs: Dict): |
| 19 | + """process outputs dict into string to be passed into SQS""" |
| 20 | + # only stringify for now |
| 21 | + return json.dumps(outputs) |
| 22 | + |
| 23 | + |
| 24 | +def send_message(attr, body): |
| 25 | + """send message to SNS""" |
| 26 | + sns_resp = sns_client.publish( |
| 27 | + TopicArn=topic_arn, |
| 28 | + Message=body, |
| 29 | + MessageAttributes=attr, |
| 30 | + ) |
| 31 | + return sns_resp |
| 32 | + |
| 33 | + |
| 34 | +def task(cfg, logger, run_id, run_dir, task, **recv): |
| 35 | + """ |
| 36 | + on completion of any task sends a message to sns with the output files |
| 37 | + """ |
| 38 | + log = logger.getChild("sns_step_notification") |
| 39 | + |
| 40 | + # ignore inputs |
| 41 | + recv = yield recv |
| 42 | + # ignore command/runtime/container |
| 43 | + recv = yield recv |
| 44 | + |
| 45 | + log.info(_("sending message to sns")) |
| 46 | + |
| 47 | + if topic_arn: |
| 48 | + message_attributes = { |
| 49 | + "WorkflowName": {"DataType": "String", "StringValue": run_id[0]}, |
| 50 | + "TaskName": {"DataType": "String", "StringValue": run_id[-1]}, |
| 51 | + "ExecutionId": { |
| 52 | + "DataType": "String", |
| 53 | + "StringValue": "execution_id_to_be_passed_in", |
| 54 | + }, |
| 55 | + } |
| 56 | + |
| 57 | + outputs = process_outputs(values_to_json(recv["outputs"])) |
| 58 | + message_body = { |
| 59 | + "version": "0", |
| 60 | + "id": "0", |
| 61 | + "detail-type": "Step Functions Execution Step Notification", |
| 62 | + "source": "aws.batch", |
| 63 | + "account": "", |
| 64 | + "time": datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ"), |
| 65 | + "resources": [], |
| 66 | + "detail": outputs, |
| 67 | + } |
| 68 | + send_message(message_attributes, json.dumps(message_body)) |
| 69 | + |
| 70 | + yield recv |
| 71 | + |
| 72 | + |
| 73 | +def workflow(cfg, logger, run_id, run_dir, workflow, **recv): |
| 74 | + log = logger.getChild("sns_step_notification") |
| 75 | + |
| 76 | + # ignore inputs |
| 77 | + recv = yield recv |
| 78 | + |
| 79 | + log.info(_("ignores workflow calls")) |
| 80 | + yield recv |
0 commit comments