Example #1
0
import logging

import rafcon
from yaml_configuration.config import config_path
import rafcon.utils.filesystem as filesystem

from rafcon.core.config import global_config
import rafcon.core.singleton as core_singletons
from rafcon.core.storage import storage
from rafcon.core.states.state import StateExecutionStatus

from rafcon.utils import plugins
from rafcon.utils import resources
from rafcon.utils import log

logger = log.get_logger("rafcon.start.core")

_user_abort = False


def pre_setup_plugins():
    """Loads plugins and calls the pre init hooks
    """
    plugins.load_plugins()
    plugins.run_pre_inits()


def post_setup_plugins(parser_result):
    """Calls the post init hubs

    :param dict parser_result: Dictionary with the parsed arguments
Example #2
0
"""

from gi.repository import GObject
from gi.repository import Gtk
from builtins import str

from rafcon.gui import singleton as gui_singletons
from rafcon.gui.controllers.utils.extended_controller import ExtendedController
from rafcon.gui.helpers.label import react_to_event
from rafcon.gui.helpers.meta_data import check_gaphas_state_machine_meta_data_consistency
from rafcon.gui.models.state_machine_manager import StateMachineManagerModel
from rafcon.gui.models.signals import MetaSignalMsg, StateTypeChangeSignalMsg, ActionSignalMsg
from rafcon.gui.singleton import global_gui_config
from rafcon.utils import log

logger = log.get_logger(__name__)

# TODO Comment


class ModificationHistoryTreeController(ExtendedController):
    string_substitution_dict = {
    }  # will be used to substitute strings for better and shorter tree columns

    def __init__(self, model, view):
        """Constructor
        :param model StateMachineModel should be exchangeable
        """
        assert isinstance(model, StateMachineManagerModel)

        ExtendedController.__init__(self, model, view)
Example #3
0
 def name(self, name):
     # Important: fset is calling the setter of the property "name" of the State base class
     # this will also trigger the name validity checks defined in the base class setter method
     # and its decorator function of the observable pattern
     State.name.fset(self, name)
     self.logger = log.get_logger(self.name)
Example #4
0
from rafcon.core.states.hierarchy_state import HierarchyState
import rafcon.core.singleton as core_singletons
from rafcon.core.execution.execution_status import StateMachineExecutionStatus

# utils
from rafcon.gui.utils import wait_for_gui
import rafcon.utils.filesystem as filesystem
from rafcon.utils import plugins, installation
from rafcon.utils.i18n import setup_l10n
from rafcon.utils import resources, log

from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GLib

logger = log.get_logger("rafcon.start.gui")


def data_files_version_up_to_date():
    install_file_path = os.path.join(resources.xdg_user_data_folder, "rafcon",
                                     "installed")
    if not os.path.isfile(install_file_path):
        return False
    with open(install_file_path, 'r') as file_pointer:
        install_version = file_pointer.read().strip()
        return install_version == rafcon.__version__


def update_data_files_version():
    install_file_folder = os.path.join(resources.xdg_user_data_folder,
                                       "rafcon")
Example #5
0
def client_interaction(main_window_controller, global_monitoring_manager,
                       queue_dict, state_machine_id):
    import rafcon.core.singleton as core_singletons  # be careful, could be replaced before
    import rafcon.gui.singleton as gui_singletons
    from monitoring.monitoring_execution_engine import MonitoringExecutionEngine
    from rafcon.core.execution.execution_status import StateMachineExecutionStatus
    from rafcon.core.execution.execution_engine import ExecutionEngine
    from monitoring.model.network_model import network_manager_model
    from monitoring.monitoring_manager import MonitoringManager
    from rafcon.utils import log

    client_controller = gui_singletons.main_window_controller.get_controller(
        'monitoring_manager_ctrl')

    assert isinstance(global_monitoring_manager, MonitoringManager)
    remote_execution_engine = core_singletons.state_machine_execution_engine
    assert isinstance(remote_execution_engine, MonitoringExecutionEngine)

    logger = log.get_logger("Interacting client1")
    sleep_time = 0.01
    logger.info("Start interacting with server\n\n")

    for id, queue in queue_dict.items():
        assert isinstance(queue, multiprocessing.queues.Queue)

    while not global_monitoring_manager.endpoint_initialized:
        logger.warning("global_monitoring_manager not initialized yet!")
        time.sleep(sleep_time)

    while len(network_manager_model.connected_ip_port) < 1:
        time.sleep(sleep_time)

    while not global_monitoring_manager.endpoint.registered_to_server:
        time.sleep(sleep_time)

    #######################################################
    print("\n\n\nTEST1 stop - start - wait_for_stop")
    #######################################################

    queue_dict[CLIENT_TO_SERVER].put("start_test_1")

    # step 1: stop sm and synchronize
    queue_element = queue_dict[SERVER_TO_CLIENT].get(
    )  # synchronize, when to start stepping
    assert queue_element == "started"
    print("received: ", queue_element)
    # test stop start
    remote_execution_engine.stop()
    queue_element = queue_dict[SERVER_TO_CLIENT].get()
    assert queue_element == "stop_received"
    print("received: ", queue_element)

    # step 2: start sm and synchronize
    remote_execution_engine.start(state_machine_id)
    queue_element = queue_dict[SERVER_TO_CLIENT].get(
    )  # synchronize, when to start stepping
    assert queue_element == "restarted"
    print("received: ", queue_element)

    # step 3: synchronize with stopping of execution engine
    queue_element = queue_dict[SERVER_TO_CLIENT].get()
    assert queue_element == "successfully stopped the state machine"
    print("received: ", queue_element)
    queue_dict[MAIN_QUEUE].put(STOP_START_SUCCESSFUL)

    # queue_dict[KILL_CLIENT1_QUEUE].get()
    # os._exit(0)
    # return

    #######################################################
    print("\n\n\nTEST2 disconnect -> run sm -> connect -> run sm")
    #######################################################

    queue_dict[CLIENT_TO_SERVER].put("start_test_2")

    # step 1
    queue_element = queue_dict[SERVER_TO_CLIENT].get()
    assert queue_element == "disconnect_me_and_run"
    print("received: ", queue_element)

    address = None
    for addr in network_manager_model.connected_ip_port:
        global_monitoring_manager.disconnect(addr)
        address = addr

    while global_monitoring_manager.endpoint.registered_to_server:
        time.sleep(sleep_time)

    # TODO: why is this in a while loop here?
    while not isinstance(remote_execution_engine, ExecutionEngine):
        remote_execution_engine = core_singletons.state_machine_execution_engine
        time.sleep(sleep_time)

    # the start command won't do anything
    remote_execution_engine.start(state_machine_id)
    while remote_execution_engine.status.execution_mode is not StateMachineExecutionStatus.STARTED:
        time.sleep(sleep_time)

    queue_dict[CLIENT_TO_SERVER].put("disconnected_and_executed")

    # joining and stopping the execution engine won't do anything
    remote_execution_engine.join()
    remote_execution_engine.stop()

    # step 2
    queue_element = queue_dict[SERVER_TO_CLIENT].get()
    assert queue_element == "reconnect_me_and_run"
    print("received: ", queue_element)

    global_monitoring_manager.reconnect(address)
    while not global_monitoring_manager.endpoint.registered_to_server:
        time.sleep(sleep_time)
    while not network_manager_model.get_connected_status(
            address) == "connected":
        time.sleep(sleep_time)
    print("status connected")

    while not isinstance(remote_execution_engine, MonitoringExecutionEngine):
        remote_execution_engine = core_singletons.state_machine_execution_engine
        time.sleep(sleep_time)

    print("sm monitoring")
    remote_execution_engine.start(state_machine_id)
    while remote_execution_engine.status.execution_mode is not StateMachineExecutionStatus.STARTED:
        time.sleep(sleep_time)
    print("sm started")

    queue_dict[CLIENT_TO_SERVER].put("reconnected_and_executed")
    queue_element = queue_dict[SERVER_TO_CLIENT].get()
    assert queue_element == "succeeded"
    print("received: ", queue_element)

    # stop is executed by the server itself, but it is not forwarded to the remote server!
    # TODO: forward it

    queue_dict[MAIN_QUEUE].put(DISCONNECTED_RUN_SUCCESSFUL)
    print("client disconnection test succeeded")

    # queue_dict[KILL_CLIENT1_QUEUE].get()
    # os._exit(0)
    # return

    #######################################################
    print("\n\n\nclient TEST3 disable -> run sm -> enable -> run sm")
    #######################################################

    queue_dict[CLIENT_TO_SERVER].put("start_test_3")

    queue_element = queue_dict[SERVER_TO_CLIENT].get()
    assert queue_element == "you_are_disabled"
    print("client received: ", queue_element)

    for address in network_manager_model.connected_ip_port:
        while not network_manager_model.get_connected_status(
                address) == "disabled":
            time.sleep(sleep_time)

    print("start remote_execution_engine 1")

    # since the engine changed to local after disabling, we need to import it again
    remote_execution_engine = core_singletons.state_machine_execution_engine
    while not isinstance(remote_execution_engine, ExecutionEngine):
        time.sleep(sleep_time)

    print("start remote_execution_engine 2")
    remote_execution_engine.start(state_machine_id)

    print("wait for started")
    while remote_execution_engine.status.execution_mode is not StateMachineExecutionStatus.STARTED:
        time.sleep(sleep_time)

    print("wait for stopped")
    while not remote_execution_engine.finished_or_stopped():
        time.sleep(sleep_time)

    print("stop engine")
    remote_execution_engine.stop()
    if not remote_execution_engine.finished_or_stopped():
        remote_execution_engine.join()

    print("disabled run stopped")
    queue_dict[CLIENT_TO_SERVER].put("reached end")

    global_monitoring_manager.reinitialize(
        network_manager_model.connected_ip_port)

    for address in network_manager_model.connected_ip_port:
        # TODO: reconnect does not work
        # global_monitoring_manager.reconnect(address)
        while not network_manager_model.get_connected_status(
                address) == "connected":
            print("network_manager_model.get_connected_status(address)",
                  network_manager_model.get_connected_status(address))
            time.sleep(0.5)

    queue_dict[CLIENT_TO_SERVER].put("enabled_again")

    while not isinstance(remote_execution_engine, MonitoringExecutionEngine):
        remote_execution_engine = core_singletons.state_machine_execution_engine
        time.sleep(sleep_time)

    remote_execution_engine.start(state_machine_id)
    print("started enabled sm")
    while remote_execution_engine.status.execution_mode is not StateMachineExecutionStatus.STARTED:
        time.sleep(sleep_time)
    print("start enabled run")
    queue_dict[CLIENT_TO_SERVER].put("started_execution")

    queue_element = queue_dict[SERVER_TO_CLIENT].get()
    assert queue_element == "succeeded"
    print("client received: ", queue_element)

    remote_execution_engine.stop()
    remote_execution_engine.join()

    queue_dict[MAIN_QUEUE].put(DISABLED_RUN_SUCCESSFUL)

    # queue_dict[KILL_CLIENT1_QUEUE].get()
    # os._exit(0)
    # return

    #######################################################
    print(
        "client TEST4 change client ID in config -> apply -> check connected client ID"
    )
    #######################################################

    queue_dict[CLIENT_TO_SERVER].put("start_test_4")

    queue_element = queue_dict[SERVER_TO_CLIENT].get()
    assert queue_element == "ready_to_change_config"
    print("client received: ", queue_element)

    network_manager_model.set_config_value('CLIENT_ID', 'apply_test_client_id')
    while not client_controller.global_network_config.get_config_value(
            'CLIENT_ID') == 'apply_test_client_id':
        time.sleep(sleep_time)
    global_monitoring_manager.endpoint.registered_to_server = False
    global_monitoring_manager.reinitialize(
        network_manager_model.connected_ip_port)

    while not global_monitoring_manager.endpoint_initialized:
        logger.warning("global_monitoring_manager not initialized yet!")
        time.sleep(sleep_time)

    logger.info("Wait until registered to server")
    while not global_monitoring_manager.endpoint:
        time.sleep(sleep_time)
    while not global_monitoring_manager.endpoint.registered_to_server:
        time.sleep(sleep_time)
    # here is a function needed which ensures that the client is disconnected and reconnected again
    queue_dict[CLIENT_TO_SERVER].put("on_apply_button_clicked")

    queue_element = queue_dict[SERVER_TO_CLIENT].get()
    assert queue_element == "succeeded"
    print("client received: ", queue_element)

    while not isinstance(remote_execution_engine, MonitoringExecutionEngine):
        # import rafcon.core.singleton as core_singletons
        remote_execution_engine = core_singletons.state_machine_execution_engine
        time.sleep(sleep_time)
    queue_dict[MAIN_QUEUE].put(APPLY_CONFIG_SUCCESSFUL)

    queue_dict[KILL_CLIENT1_QUEUE].get()  # synchronize to main process
    os._exit(0)
Example #6
0
import os
from os.path import join

# core elements
import rafcon.core.singleton
from rafcon.core.storage import storage
from rafcon.core.config import global_config

# test environment elements
from tests import utils as testing_utils
import pytest

from rafcon.utils import log
logger = log.get_logger("start-no-gui")


def setup_function(_):
    # set the test_libraries path temporarily to the correct value
    global_config.set_config_value("LIBRARY_RECOVERY_MODE", True)
    testing_utils.rewind_and_set_libraries({
        "unit_test_state_machines":
        join(testing_utils.TEST_ASSETS_PATH, "unit_test_state_machines")
    })


def get_test_state_machine(name):
    return storage.load_state_machine_from_path(
        testing_utils.get_test_sm_path(
            join("unit_test_state_machines", "faulty_libraries", name)))

Example #7
0
    import sys
    import logging

    # Apply defaults to logger of gtkmvc3
    for handler in logging.getLogger('gtkmvc3').handlers:
        logging.getLogger('gtkmvc3').removeHandler(handler)
    stdout = logging.StreamHandler(sys.stdout)
    stdout.setFormatter(
        logging.Formatter(
            "%(asctime)s: %(levelname)-8s - %(name)s:  %(message)s"))
    stdout.setLevel(logging.DEBUG)
    logging.getLogger('gtkmvc3').addHandler(stdout)


setup_logger()
logger = log.get_logger("Resave state machines script")


def trigger_gui_signals(*args):
    sm_manager_model = args[0]
    main_window_controller = args[1]
    setup_config = args[2]
    state_machine = args[3]
    menubar_ctrl = main_window_controller.get_controller('menu_bar_controller')
    try:
        sm_manager_model.selected_state_machine_id = state_machine.state_machine_id
        gui_helper_state_machine.save_state_machine_as(
            path=setup_config['target_path'][0])
        while state_machine.marked_dirty:
            time.sleep(0.1)
    except:
Example #8
0
def start_server(interacting_function, queue_dict):
    import sys
    import os

    import rafcon
    from rafcon.utils import log
    from rafcon.utils import plugins

    from rafcon.core.config import global_config
    import rafcon.core.singleton as core_singletons
    from rafcon.core.storage import storage as global_storage
    # needed for yaml parsing
    from rafcon.core.states.hierarchy_state import HierarchyState
    from rafcon.core.states.execution_state import ExecutionState
    from rafcon.core.states.preemptive_concurrency_state import PreemptiveConcurrencyState
    from rafcon.core.states.barrier_concurrency_state import BarrierConcurrencyState

    from rafcon.core.start import signal_handler, register_signal_handlers
    register_signal_handlers(signal_handler)

    logger = log.get_logger("start-no-gui")
    logger.info("initialize RAFCON ... ")

    plugins.load_plugins()
    plugins.run_pre_inits()

    global_config.load(path=os.path.dirname(os.path.abspath(__file__)))

    # Initialize libraries
    core_singletons.library_manager.initialize()

    import testing_utils
    state_machine = global_storage.load_state_machine_from_path(
        testing_utils.get_test_sm_path(
            os.path.join("unit_test_state_machines",
                         "99_bottles_of_beer_monitoring")))
    sm_id = rafcon.core.singleton.state_machine_manager.add_state_machine(
        state_machine)

    sm_thread = threading.Thread(target=check_for_sm_finished,
                                 args=[
                                     state_machine,
                                 ])
    sm_thread.start()

    setup_config = dict()
    setup_config["net_config_path"] = os.path.abspath(path=os.path.join(
        os.path.dirname(os.path.abspath(__file__)), "server"))

    plugins.run_post_inits(setup_config)

    if "twisted" in sys.modules:
        print("################# twisted found #######################")
        interacting_thread = threading.Thread(target=interacting_function,
                                              args=[queue_dict, sm_id])
        interacting_thread.start()
        from twisted.internet import reactor
        reactor.run()
    else:
        logger.error(
            "Server: Twisted is not in sys.modules or twisted is not working! Exiting program ... !"
        )
        import os
        os._exit(0)

    state_machine.root_state.join()

    rafcon.core.singleton.state_machine_execution_engine.stop()
    logger.info("State machine execution finished!")
Example #9
0
 def __init__(self):
     self.logger = log.get_logger(type(self).__name__)
     self.execution_engine = rafcon.core.singleton.state_machine_execution_engine
     self.register_observer()
Example #10
0
def interacting_function_client1(main_window_controller,
                                 global_monitoring_manager, queue_dict):
    from rafcon.utils import log
    logger = log.get_logger("Interacting client1")

    logger.info("Start interacting with server\n\n")

    for id, queue in queue_dict.iteritems():
        assert isinstance(queue, multiprocessing.queues.Queue)

    while not global_monitoring_manager.endpoint_initialized:
        logger.warn("global_monitoring_manager not initialized yet!")
        time.sleep(0.01)

    import rafcon.core.singleton as core_singletons
    remote_execution_engine = core_singletons.state_machine_execution_engine

    # tell the server that client 1 is ready
    queue_dict[CLIENT1_TO_SERVER_QUEUE].put("ready")
    queue_dict[SERVER_TO_CLIENT1_QUEUE].get(
    )  # synchronize, when to start stepping

    # test stepping
    # print "client: cp0"
    remote_execution_engine.step_mode(
    )  # this will trigger a step into = triggers decimate
    custom_assert(queue_dict[SERVER_TO_CLIENT1_QUEUE].get(), TestSteps[0])

    # print "client: cp1"
    remote_execution_engine.step_over()  # triggers count
    custom_assert(queue_dict[SERVER_TO_CLIENT1_QUEUE].get(), TestSteps[1])

    # print "client: cp2"
    remote_execution_engine.step_into()  # triggers sing
    custom_assert(queue_dict[SERVER_TO_CLIENT1_QUEUE].get(), TestSteps[2])

    # print "client: cp3"
    remote_execution_engine.backward_step()  # backward triggers sing
    custom_assert(queue_dict[SERVER_TO_CLIENT1_QUEUE].get(), TestSteps[3])
    queue_dict[MAIN_QUEUE].put(STEPPING_SUCCESSFUL)

    # print "client: cp4"
    remote_execution_engine.step_out()  # triggers run until end
    custom_assert(queue_dict[SERVER_TO_CLIENT1_QUEUE].get(), TestSteps[4])

    # start execution test
    remote_execution_engine.start()
    custom_assert(queue_dict[SERVER_TO_CLIENT1_QUEUE].get(), TestSteps[5])
    queue_dict[MAIN_QUEUE].put(STOP_START_SUCCESSFUL)

    # run-until test
    remote_execution_engine.run_to_selected_state(
        "GLSUJY/SFZGMH")  # run to decimate bottles inclusively
    custom_assert(queue_dict[SERVER_TO_CLIENT1_QUEUE].get(), TestSteps[6])
    remote_execution_engine.stop()
    custom_assert(queue_dict[SERVER_TO_CLIENT1_QUEUE].get(), TestSteps[7])
    queue_dict[MAIN_QUEUE].put(RUN_UNTIL_SUCCESSFUL)

    # start from test
    # directly start with decimate bottles and jump over the sing state
    remote_execution_engine.start(start_state_path="GLSUJY/NDIVLD")
    custom_assert(queue_dict[SERVER_TO_CLIENT1_QUEUE].get(), TestSteps[8])

    print "client: send sync message to server\n"
    queue_dict[CLIENT1_TO_SERVER_QUEUE].put("sync")
    print "client: wait for sync message from server\n"
    queue_dict[SERVER_TO_CLIENT1_QUEUE].get()
    print "client: tell the main queue that tests were successful\n"
    queue_dict[MAIN_QUEUE].put(START_FROM_SUCCESSFUL)
    print "client: wait for kill command from main queue\n"
    # set a timeout of 3 seconds
    queue_dict[KILL_CLIENT1_QUEUE].get(3)
    os._exit(0)
Example #11
0
def start_client(interacting_function, queue_dict):
    from rafcon.gui.config import global_gui_config
    import os

    from rafcon.utils.i18n import setup_l10n
    setup_l10n()
    from rafcon.gui.controllers.main_window import MainWindowController
    from rafcon.gui.views.main_window import MainWindowView
    import rafcon.gui.singleton as gui_singletons
    from rafcon.gui.runtime_config import global_runtime_config
    from rafcon.gui.start import signal_handler

    import rafcon
    from rafcon.utils import log
    from rafcon.utils import plugins

    from rafcon.core.config import global_config
    from rafcon.core.storage import storage as global_storage
    from rafcon.core.state_machine import StateMachine
    from rafcon.core.states.hierarchy_state import HierarchyState
    import rafcon.core.singleton as core_singletons
    from rafcon.core.start import setup_environment

    # load all plugins specified in the RAFCON_PLUGIN_PATH
    plugins.load_plugins()
    from tests import utils as testing_utils

    # check if twisted is imported
    if "twisted" in sys.modules:
        from twisted.internet import gtk3reactor
        # needed for GLib.idle_add, and signals
        gtk3reactor.install()
        from twisted.internet import reactor
    else:
        print("Twisted not imported! Thus the gkt2reatcor is not installed!")
        exit()

    plugins.run_pre_inits()

    setup_logger()
    logger = log.get_logger("start")
    logger.info("RAFCON launcher")

    setup_environment()

    signal.signal(signal.SIGINT, signal_handler)

    global_config.load(path=os.path.dirname(os.path.abspath(__file__)))
    global_gui_config.load(path=os.path.dirname(os.path.abspath(__file__)))
    global_runtime_config.load(path=os.path.dirname(os.path.abspath(__file__)))

    setup_config = dict()
    setup_config["net_config_path"] = os.path.abspath(path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                                        "client"))

    # Initialize library
    core_singletons.library_manager.initialize()

    # Create the GUI
    main_window_view = MainWindowView()

    state_machine = global_storage.load_state_machine_from_path(
        testing_utils.get_test_sm_path(os.path.join("unit_test_state_machines", "99_bottles_of_beer_monitoring")))

    sm_id = rafcon.core.singleton.state_machine_manager.add_state_machine(state_machine)
    # the active_state_machine_id must be set here, as the state machine can be active (e.g. if the server started the sm already)
    # although it is not yet started on the client
    rafcon.core.singleton.state_machine_manager.active_state_machine_id = sm_id

    sm_manager_model = gui_singletons.state_machine_manager_model
    main_window_controller = MainWindowController(sm_manager_model, main_window_view)

    plugins.run_post_inits(setup_config)

    import threading
    # this is not recognized by pycharm as the module is loaded in plugins.load_plugins()
    from monitoring.monitoring_manager import global_monitoring_manager
    interacting_thread = threading.Thread(target=interacting_function, args=[main_window_controller,
                                                                             global_monitoring_manager,
                                                                             queue_dict,
                                                                             sm_id])
    testing_utils.wait_for_gui()
    interacting_thread.start()

    # check if twisted is imported
    if "twisted" in sys.modules:
        reactor.run()
    else:
        logger.error("Client: Twisted is not in sys.modules or twisted is not working! Exiting program ... !")
        os._exit(0)

    logger.info("Joined root state")

    # If there is a running state-machine, wait for it to be finished before exiting
    sm = core_singletons.state_machine_manager.get_active_state_machine()
    if sm:
        sm.root_state.join()

    logger.info("Exiting ...")

    # this is a ugly process shutdown method but works if gtk or twisted process are still blocking
    os._exit(0)
Example #12
0
def interacting_function_client1(main_window_controller,
                                 global_monitoring_manager, queue_dict):
    import rafcon.core.singleton as core_singletons  # be careful, could be replaced before
    remote_execution_engine = core_singletons.state_machine_execution_engine
    from rafcon.utils import log
    logger = log.get_logger("Interacting client1")
    sleep_time = 0.01
    logger.info("Start interacting with server\n\n")

    for id, queue in queue_dict.iteritems():
        assert isinstance(queue, multiprocessing.queues.Queue)

    while not global_monitoring_manager.endpoint_initialized:
        logger.warn("global_monitoring_manager not initialized yet!")
        time.sleep(sleep_time)
    """
    TEST1 disconnect -> run sm -> connect -> run sm
    """
    queue_dict[SERVER_TO_CLIENT].get()  # synchronize, when to start stepping
    # test stop start
    remote_execution_engine.stop()
    queue_dict[SERVER_TO_CLIENT].get()
    remote_execution_engine.start()
    queue_dict[SERVER_TO_CLIENT].get()
    queue_dict[MAIN_QUEUE].put(STOP_START_SUCCESSFUL)

    from monitoring.controllers import client_controller
    from rafcon.core.execution.execution_status import StateMachineExecutionStatus
    from rafcon.core.execution.execution_engine import ExecutionEngine
    from monitoring.monitoring_execution_engine import MonitoringExecutionEngine
    from monitoring.model.network_model import network_manager_model
    """
    TEST2 disconnect -> run sm -> connect -> run sm
    """
    queue_dict[SERVER_TO_CLIENT].get()

    for address in network_manager_model.connected_ip_port:
        global_monitoring_manager.disconnect(address)

    while global_monitoring_manager.endpoint.registered_to_server:
        time.sleep(sleep_time)

    # import rafcon.core.singleton as core_singletons
    # remote_execution_engine = core_singletons.state_machine_execution_engine
    while not isinstance(remote_execution_engine, ExecutionEngine):
        remote_execution_engine = core_singletons.state_machine_execution_engine
        time.sleep(sleep_time)

    remote_execution_engine.start()
    while remote_execution_engine.status.execution_mode is not StateMachineExecutionStatus.STARTED:
        time.sleep(sleep_time)

    remote_execution_engine.join()
    # while remote_execution_engine.status.execution_mode is not StateMachineExecutionStatus.STOPPED:
    #     time.sleep(0.01)
    queue_dict[CLIENT_TO_SERVER].put("disconnected_and_executed")

    remote_execution_engine.stop()
    if not remote_execution_engine.finished_or_stopped():
        remote_execution_engine.join()

    queue_dict[SERVER_TO_CLIENT].get()
    global_monitoring_manager.reconnect(address)

    while not global_monitoring_manager.endpoint.registered_to_server:
        time.sleep(sleep_time)

    while not network_manager_model.get_connected_status(
            address) == "connected":
        time.sleep(sleep_time)
    print "status connected"

    # import rafcon.core.singleton as core_singletons
    while not isinstance(remote_execution_engine, MonitoringExecutionEngine):
        remote_execution_engine = core_singletons.state_machine_execution_engine
        time.sleep(sleep_time)

    print "sm monitoring"
    remote_execution_engine.start()
    while remote_execution_engine.status.execution_mode is not StateMachineExecutionStatus.STARTED:
        time.sleep(sleep_time)
    print "sm started"

    queue_dict[CLIENT_TO_SERVER].put("reconnected_and_executed")
    queue_dict[SERVER_TO_CLIENT].get()

    remote_execution_engine.stop()
    if not remote_execution_engine.finished_or_stopped():
        remote_execution_engine.join()

    queue_dict[MAIN_QUEUE].put(DISCONNECTED_RUN_SUCCESSFUL)
    print "client disconnection test succeeded"
    """
    TEST3 disable -> run sm -> enable -> run sm
    """
    queue_dict[SERVER_TO_CLIENT].get()
    print "client disabled test begin"
    for address in network_manager_model.connected_ip_port:
        while not network_manager_model.get_connected_status(
                address) == "disabled":
            time.sleep(sleep_time)

    # since the engine changed to local after disabling, we need to import it again
    # import rafcon.core.singleton as core_singletons
    remote_execution_engine = core_singletons.state_machine_execution_engine
    while not isinstance(remote_execution_engine, ExecutionEngine):
        time.sleep(sleep_time)

    remote_execution_engine.start()

    while remote_execution_engine.status.execution_mode is not StateMachineExecutionStatus.STARTED:
        time.sleep(sleep_time)

    while not remote_execution_engine.finished_or_stopped():
        time.sleep(sleep_time)

    remote_execution_engine.stop()
    if not remote_execution_engine.finished_or_stopped():
        remote_execution_engine.join()

    print "disabled run stopped"
    queue_dict[CLIENT_TO_SERVER].put("reached end")
    queue_dict[SERVER_TO_CLIENT].get()
    print "ended disabled run"
    # for address in network_manager_model.connected_ip_port:
    #     while not network_manager_model.get_connected_status(address) == "connected":
    #         time.sleep(0.01)

    # since the engine changed to remote after enabling, we need to import it again

    while not isinstance(remote_execution_engine, MonitoringExecutionEngine):
        remote_execution_engine = core_singletons.state_machine_execution_engine
        time.sleep(sleep_time)

    remote_execution_engine.start()
    print "started enabled sm"
    while remote_execution_engine.status.execution_mode is not StateMachineExecutionStatus.STARTED:
        time.sleep(sleep_time)
    print "start enabled run"
    queue_dict[CLIENT_TO_SERVER].put("started execution")
    queue_dict[SERVER_TO_CLIENT].get()

    remote_execution_engine.stop()
    if not remote_execution_engine.finished_or_stopped():
        remote_execution_engine.join()

    queue_dict[MAIN_QUEUE].put(DISABLED_RUN_SUCCESSFUL)
    """
    TEST4 change client ID in config -> apply -> check connected client ID
    """
    queue_dict[SERVER_TO_CLIENT].get()
    network_manager_model.set_config_value('CLIENT_ID', 'apply_test_client_id')
    while not client_controller.global_network_config.get_config_value(
            'CLIENT_ID') == 'apply_test_client_id':
        time.sleep(sleep_time)
    global_monitoring_manager.endpoint.registered_to_server = False
    global_monitoring_manager.reinitialize(
        network_manager_model.connected_ip_port)

    while not global_monitoring_manager.endpoint_initialized:
        logger.warn("global_monitoring_manager not initialized yet!")
        time.sleep(sleep_time)

    logger.info("Wait until registered to server")
    while not global_monitoring_manager.endpoint:
        time.sleep(sleep_time)
    while not global_monitoring_manager.endpoint.registered_to_server:
        time.sleep(sleep_time)
    # here is a function needed which ensures that the client is disconnected and reconnected again
    queue_dict[CLIENT_TO_SERVER].put("on_apply_button clicked")
    queue_dict[SERVER_TO_CLIENT].get()

    while not isinstance(remote_execution_engine, MonitoringExecutionEngine):
        # import rafcon.core.singleton as core_singletons
        remote_execution_engine = core_singletons.state_machine_execution_engine
        time.sleep(sleep_time)
    queue_dict[MAIN_QUEUE].put(APPLY_CONFIG_SUCCESSFUL)

    queue_dict[KILL_CLIENT1_QUEUE].get()  # synchronize to main process
    os._exit(0)
Example #13
0
# Copyright (C) 2016-2018 DLR
#
# All rights reserved. This program and the accompanying materials are made
# available under the terms of the Eclipse Public License v1.0 which
# accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Franz Steinmetz <*****@*****.**>
# Sebastian Brunner <*****@*****.**>

import os
from rafcon.utils import log
from rafcon.utils.constants import RAFCON_TEMP_PATH_BASE
logger = log.get_logger("profiler")

_profilers = {}


def start(name):
    if not name:
        return
    try:
        import profiling.tracing
        _profilers[name] = profiling.tracing.TracingProfiler()
        _profilers[name].start()
        logger.debug("The profiler has been started")
    except ImportError:
        _profilers[name] = None
        logger.error(
            "Cannot run profiler due to missing Python package 'profiling'")