def start(event):
    result = process_instance.create(event)
    if result and "operation_instance" in result:
        log("Running container")
        run_container(result["operation_instance"], event.name)
        log(''
            "--------------------------------------------------------------------------------------------------------------------\n\n"
            )
 def on_post(self, request, response):
     log('Create process instance to event: {event}', event=request.media)
     event = Event(**request.media)
     result = process_instance.create(event)
     if result and "process_instance" in result:
         response.body = json.dumps(result["process_instance"])
         response.status = falcon.HTTP_CREATED
     else:
         response.body = json.dumps(
             {"error": "Cannot create process instance"})
         response.status = falcon.HTTP_INTERNAL_SERVER_ERROR
示例#3
0
def run_container(operation_instance, event_name):
    delete_container = os.getenv('REMOVE_CONTAINER_AFTER_EXECUTION', "True") == "True"
    """
    """
    log("**********************************************************")
    log('Executing process app. instance id={process_instance_id} image={image}', process_instance_id=operation_instance["processInstanceId"], image=operation_instance["image"])
    log(f'Container will be removed after execution? {delete_container}')
    log("**********************************************************")

    #ports = None
    #if settings.ENABLE_CONTAINER_DEBUG:
    ports = {"9229":str(random.randrange(7000, 7999, 2))}

    container = client.containers.run(
        operation_instance['image'],
        environment={
            "INSTANCE_ID": operation_instance["processInstanceId"],
            "PROCESS_ID": operation_instance["processId"],
            "SYSTEM_ID": operation_instance["systemId"],
            "EVENT": event_name
        },
        network='plataforma_network',
        stdout=True,
        ports=ports,
        remove=delete_container,
        labels={
            "instance_id": operation_instance["processInstanceId"]
        }
    )
def create_reproduction_instance(reproduction_instance):
    """creates a new reproduction execution instance.
    """
    log("Create reproduction instance {reproduction_instance}",
        reproduction_instance=reproduction_instance)
    result = persist([{
        "systemId": reproduction_instance['systemId'],
        "processId": reproduction_instance['processId'],
        "originalId": reproduction_instance['originalId'],
        "instanceId": reproduction_instance['instanceId'],
        "owner": reproduction_instance['owner'],
        "externalId": reproduction_instance['externalId'],
        "start_date": str(datetime.datetime.now()),
        "_metadata": {
            "type": "reproduction",
            "changeTrack": "create",
        }
    }])
    if not result.has_error and result.data:
        return result.data[0]
示例#5
0
 def process(self, event):
     """
     Process receives an event an tries to get a subcribed operation.
     """
     print(event)
     log("============================================================================================")
     log('Processing event {event}', event=event.name)
     log("\n")
     if events.Event().is_reproduction(event):
         reproduction.dispatch(event)
     elif events.Event().is_reprocessing(event):
         reprocessing.start(event)
     else:
         execution.start(event)
     log("============================================================================================\n")
示例#6
0
def create(event):
    """
    creates a new process instance based on event
    """
    if event.version:
        operation = coreapi.get_operation_by_event_and_version(
            event, event.version)
    else:
        operation = coreapi.get_operation_by_event(event)

    if not operation:
        log(f"Event {event.name} with version {event.version} has no subscribers"
            )
        return

    if event.instanceId:
        log(f"Event {event.name} already have a instance id={event.instanceId}"
            )
        process_instance = coreapi.get_process_instance_by_instance_id(
            event.instanceId)
    else:
        log(f"Creating new process instance to respond event {event.name}")
        process_instance = coreapi.create_process_instance(operation, event)
        event.instanceId = process_instance["id"]
        event.version = operation["version"]
        event.image = operation["image"]
        event.timestamp = process_instance["startExecution"]
        if not process_memory.create_memory(process_instance, event):
            log("""Could not create process memory. Event: {event} Process Instance: {process_instance}. Process aborted.""",
                process_instance=process_instance,
                event=event)
            return

    if not process_instance:
        log("""Could not create process instance. Event: {event} Data: {operation}. Process aborted.""",
            event=event,
            operation=operation)
        return

    log(f"event scope is {event.scope}")
    if event.scope in {"execution", "reprocessing"}:
        operation_instance = coreapi.create_operation_instance(
            operation, event.name, process_instance["id"])
    elif event.scope == "reproduction":
        # recupera a operation que foi executada para uma determinada instancia do processo
        log(f"instance id={process_instance['id']} event={event.name}")
        reproduction_instance = coreapi.get_reproduction_by_instance_id(
            process_instance["id"])
        operation_instance = coreapi.get_operation_instance_by_instance_id_and_event(
            reproduction_instance["originalId"], event.name)
        operation_instance.pop("id")
        operation_instance["processInstanceId"] = process_instance["id"]
        coreapi.create_operation_instance(operation_instance, event.name,
                                          process_instance["id"])
    else:
        log(f"Scope {event.scope} not supported")
        return
    result = {}
    if process_instance:
        result["process_instance"] = process_instance
    if operation_instance:
        result["operation_instance"] = operation_instance
    return result
示例#7
0
def dispatch(event):
    if not "instanceId" in event.reproduction:
        log(f"Reproduction event should have field instanceId on section reproduction"
            )
        return False
    original_instance = get_process_instance_by_instance_id(
        event.reproduction["instanceId"])
    if original_instance == None:
        log(f"Instance {event.reproduction['instanceId']} not found in process memory"
            )
        return False

    original_event = first_commit(original_instance["id"])

    if original_event == None:
        log(f"Origin event not found for instance {original_instance['id']}")
        return False
    original_event = original_event["event"]
    name = original_event.pop("name")
    original_event["scope"] = "reproduction"
    process_instance = create_process_instance(original_instance,
                                               Event(name, **original_event))

    if process_instance == None:
        log(f"Cannot create a new instance from origin {original_instance['id']} and event {name}"
            )
        return False

    if not clone(original_instance["id"], process_instance["id"]):
        log(f"Cannot clone origin process memory from instance {original_instance['id']} and event {name}"
            )
        return False

    original_event["instanceId"] = process_instance["id"]
    log(f"Dispatching reproduction event {name}")

    original_event["name"] = name
    emit_event(original_event)

    reproduction = original_instance.copy()
    reproduction["originalId"] = original_instance["id"]
    reproduction["instanceId"] = process_instance["id"]
    reproduction["owner"] = event.reproduction["owner"]
    if "externalId" in event.reproduction:
        reproduction["externalId"] = event.reproduction["externalId"]
    else:
        reproduction["externalId"] = ""

    rep_instance = create_reproduction_instance(reproduction)
    if rep_instance == None:
        log(f"Cannot create reproduction instance on API Core")
        return False
    log(f"Created reproduction instance on API Core id={rep_instance['id']}")

    return True
def start(event):
    operation = coreapi.get_operation_by_event_and_version(
        event, event.version)
    if not operation:
        log("""event {event} has no subscribers""", event=event)
        return
    original_instance_id = event.reprocessing["instance_id"]
    original_instance = coreapi.get_process_instance_by_instance_id(
        original_instance_id)
    log(f"Creating new process instance to respond event {event.name}")
    log("""event {event}""", event=event)
    process_instance = coreapi.create_process_instance(original_instance,
                                                       event)

    event.instanceId = process_instance["id"]
    if not process_memory.create_memory(process_instance, event):
        log("""Could not create process memory. Event: {event} Process Instance: {process_instance}. Process aborted.""",
            process_instance=process_instance,
            event=event)
        return

    if not process_instance:
        log("""Could not create process instance. Event: {event} Process aborted.""",
            event=event)
        return

    log(f"event scope is {event.scope}")
    log(f"running image {operation['image']} for event {event.name} with version {event.version}"
        )
    operation_instance = coreapi.create_operation_instance(
        operation, event.name, process_instance["id"])
    run_container(operation_instance, event.name)
示例#9
0
def test_logger():
    logger = logging.getLogger()

    with mock.patch.object(logger, 'error') as mock_log:
        log("message")
        mock_log.assert_called_once_with('message')
 def __init__(self, **kwargs):
     log(self.MESSAGE, **kwargs)