"""CLI functions to run decider, worker and exec processes.""" import argparse from datetime import datetime from datetime import timedelta import importlib import json import time import boto.swf.layer2 as swf from garcon import activity from garcon import decider def execute_flow(flow, context, output_file=None, **kwargs): """Launch the workflow execution. Args: flow (module): Garcon flow module. context (str): Initial context parsed from JSON. output_file: Optional path to file to store all args as well as workflow_id and run_id. kwargs: Extensible call API. """ start_kwargs = dict( workflow_id=flow.workflow_id(json.loads(context)), input=context) if hasattr(flow, 'timeout'): start_kwargs.update(execution_start_to_close_timeout=str(flow.timeout)) execution = swf.WorkflowType( name=flow.name, domain=flow.domain, version=flow.version, task_list=flow.name).start(**start_kwargs) if output_file: with open(output_file, 'w') as out_file: start_kwargs.update(run_id=execution.runId) json.dump(start_kwargs, out_file) if json.loads(context).get('wait_until_complete') == 'True': print('Polling until Workflow is complete') max_time = datetime.now() + timedelta(seconds=flow.timeout) while datetime.now() < max_time: current_exec = swf.Layer1().describe_workflow_execution( domain=flow.domain, workflow_id=execution.workflowId, run_id=execution.runId) if current_exec['executionInfo'].get( 'executionStatus') != 'CLOSED': time.sleep(10) else: if current_exec['executionInfo'].get( 'closeStatus') == 'COMPLETED': return execution else: raise Exception( 'Workflow with runId {runId} in domain {domain} ' 'failed'.format( runId=execution.runId, domain=flow.domain)) else: return execution def run_decider(flow, **kwargs): """Launch the SWF decider process. Args: flow (module): Garcon flow module. kwargs (dict): Extensible call API. """ worker = decider.DeciderWorker(flow) while True: worker.run() time.sleep(1) def run_activity_worker(flow, **kwargs): """Launch the activity worker process. Args: flow (module): Garcon flow module. kwargs (dict): Extensible call API. """ worker = activity.ActivityWorker(flow) worker.run() _COMMANDS = {'exec': execute_flow, 'decider': run_decider, 'worker': run_activity_worker} def garcon(*args): """Entry point for the Garcon command line integration. Args: args (tuple): Args for the flow. """ parser = argparse.ArgumentParser(description='Garcon command line util') parser.add_argument('cmd', choices=_COMMANDS.keys(), help='garcon command') parser.add_argument('flow', help='name of the flow') parser.add_argument('-c', '--context', help='initial context [json]') parser.add_argument('-o', '--output_file', help='full path to output file, if applicable') # parse cli args (allows easy unit testing) args = parser.parse_args(args) if args else parser.parse_args() # import the flow module flow = importlib.import_module( '.{}.flow'.format(args.flow), 'swf_monitoring.flows') flow_class = getattr(flow, 'Flow', None) flow = flow_class() # execute command args.context = args.context or '{}' _COMMANDS[args.cmd](flow=flow, context=args.context, output_file=args.output_file)