Esempio n. 1
0
class StepDeclVar(StepBase):
    def __init__(self, name, value, uuid=None):
        super().__init__()
        self.__name = name
        self.__value = value
        self.__logger = Logger("Step", "DeclareVarible")
        self.__uuid = uuid

    def run(self):
        if self.__uuid:
            if self.vars.is_varible_exist(self.__name):
                self.vars[("Variables", self.__name)]["ID"] = self.__uuid
                self.vars[("Variables", self.__name)]["OP"] = "="
            else:
                self.vars[("Variables", self.__name)] = {
                    "ID": self.__uuid,
                    "OP": "="
                }
        else:
            self.__logger.log(
                "Info", "Store ({},'{}')".format(self.__name, self.__value))
            self.vars[("Variables", self.__name)] = {"Value": self.__value}
        return True

    def what(self):
        return StepType.VAR
Esempio n. 2
0
class ApiCommand():
    def __init__(self, lib_path, func_name):
        self.__func_name = func_name
        self.__lib_path = lib_path
        self.__ret_type = None
        self.__args_type_list = []
        self.__logger = Logger("Library", "Command")
        self.__function = None

    def set_return_type(self, type_):
        self.__ret_type = type_

    def add_argument(self, arg):
        # arg = (Name, Type)
        self.__args_type_list.append(arg)

    def load(self):
        try:
            return _get_lib_cmd(_load_library_file(self.__lib_path),
                                self.__func_name, self.__ret_type,
                                self.__args_type_list)
        except Exception as ex:
            self.__logger.log("Error", str(ex))
            return None

    def __str__(self):
        _args_text = ",".join(self.__args_type_list)
        return "Library={},Function={} {}({})".format(self.__lib_path,
                                                      self.__ret_type,
                                                      self.__func_name,
                                                      _args_text)
Esempio n. 3
0
class LibConfigFileReader():
    def __init__(self, path):
        self.__cfg_path = path
        self.__cmds = {}
        self.__logger = Logger("Library", "Loader")

    def read(self):
        root = ElementTree.parse(self.__cfg_path).getroot()
        for lib in root:
            specReader = LibSpecReader(lib.attrib['SpecPath'])
            self.__cmds[lib.attrib['Name']] = specReader.read()
        self.__logger.log("Debug", str(self))
        return self.__cmds

    def serialize(self):
        _serialized_cmds = {}
        for _lib in self.__cmds:
            _serialized_cmds[_lib] = {}
            for _api_cmd in self.__cmds[_lib]:
                _serialized_cmds[_lib][_api_cmd] =\
                    str(self.__cmds[_lib][_api_cmd])
        return _serialized_cmds

    def __str__(self):
        return json.dumps(self.serialize(), indent=4)
Esempio n. 4
0
class RunHookAction(Action):
    def __init__(self, params_json):
        self.__logger = Logger("Actions", "RunHookAction")
        self.__params_json = params_json

    def run(self):
        _hook_path = self._hook_path = self.__params_json['HookPath']
        self.__logger.log("Debug", "Running hook: {}", _hook_path)
        run_hook(_hook_path)
Esempio n. 5
0
def _traverse(tree, rule_names, indent=0):
    _logger = Logger("Hook", "Execute", "TreverseScript")
    if tree.getText() == "<EOF>":
        return
    elif isinstance(tree, TerminalNodeImpl):
        _logger.log("Info", "{0}TOKEN='{1}'".format("  " * indent,
                                                    tree.getText()))
    else:
        _logger.log(
            "Info", "{0}{1}".format("  " * indent,
                                    rule_names[tree.getRuleIndex()]))
        for child in tree.children:
            _traverse(child, rule_names, indent + 1)
Esempio n. 6
0
def _execute(steps):
    _logger = Logger("Hook", "Execute", "Main")
    _data = StepsData()
    for _step in steps:
        _step.set_step_data(_data)
        try:
            _logger.log("Info", "Start: {}", _step.what())
            if not _step.run():
                _logger.log("Info", "End(Failure): {}", _step.what())
                break
            _logger.log("Info", "End(Success): {}", _step.what())
        except Exception as ex:
            _logger.log("Info", "End(Error): {}", str(ex))
            break
    _logger.log("Info", "Stack Data: {}", str(_data))
Esempio n. 7
0
class Service(asyncore.dispatcher):
    def __init__(self, host):
        asyncore.dispatcher.__init__(self)
        self.__logger = Logger("Service", "Dispatcher")
        self.create_socket()
        self.set_reuse_addr()
        self.__env = Environment()
        self.bind((host, int(self.__env["port"])))
        self.listen(5)

    def handle_close(self):
        self.__logger.log("Debug", "Service: Connection Closed")

    def handle_accept(self):
        pair = self.accept()
        if pair is not None:
            sock, addr = pair
            self.__logger.log("Debug", "Incoming request" ": {}", repr(addr))
            handler = ServiceHandler(sock=sock)
Esempio n. 8
0
class StepRunCommand(StepBase):
    def __init__(self, *args, **kwargs):
        super().__init__()
        self.__args = args
        self.__cmd_name = kwargs["name"] if "name" in kwargs else None
        self.__uuid = kwargs["uuid"] if "uuid" in kwargs else None
        self.__logger = Logger("Step", "RunCommand")

    def run(self):
        _cmd = self.vars.get_first_command(self.__cmd_name)
        _ret = _cmd(*self.__args)
        if self.__uuid is not None and _ret is not None:
            self.vars[("Variables", self.vars.get_varible_by_uuid(
                self.__uuid))]["Value"] = _ret
            self.__logger.log("Info", "Command Return : Var = {},"
                              "Value = {}",
                              self.vars.get_varible_by_uuid(self.__uuid), _ret)
        return True

    def what(self):
        return StepType.EXECUTE
Esempio n. 9
0
class LibsSingleton(metaclass=Singleton):
    def __init__(self):
        self.__env_singleton = Environment()
        self.__logger = Logger("LibrariesSingleton")
        self.__lib_cfg_reader = None
        self.__cmds = None

    def __setitem__(self, key, value):
        raise GeneralException(ErrorCodes.CANT_EDIT_SPEC_FILE,
                               "Cannot edit lib spec file.")

    def __getitem__(self, key):
        return self.__cmds[key[0]][key[1]]

    def load_command(self, library, command):
        self.__logger.log(
            "Info", "Trying to load {} from {}.".format(command, library))
        if library not in self.__cmds:
            self.__logger.log("Error",
                              "Library {} doesn't exist.".format(library))
            return False
        if command not in self.__cmds[library]:
            self.__logger.log("Error",
                              "Command {} doesn't exist.".format(command))
            return False
        return self.__cmds[library][command].load()

    def init(self):
        self.__lib_cfg_reader = LibConfigFileReader(
            self.__env_singleton['lib_spec_file'])
        self.__cmds = self.__lib_cfg_reader.read()
Esempio n. 10
0
def _handle_tasks():
    while True:
        __logger = Logger("Service", "TaskHandler")
        try:
            action = Action.create(TASK_QUEUE.get(block=True, timeout=3))
        except Exception as ex:
            if IS_FINISH:
                break
            else:
                continue
        try:
            action.run()
        except AntlrExcption as ex:
            __logger.log(logging.ERROR, str(ex))
        __logger.log("Info", "Task is done...")
        TASK_QUEUE.task_done()
        __logger.log("Info", "Waiting for the next task...")
    if IS_FINISH:
        __logger.log("Debug", "Main thread signed to exit.")
Esempio n. 11
0
class Application:
    def __init__(self):
        self.__environment = Environment()
        self.__arg_reader = ArgReader()
        self.__arg_reader.parse()
        self.__environment.read()
        self.__lib_spec_reader = None
        self.__logger = None
        self.__service = None

    def run(self):
        self.__lib_spec_reader = LibsSingleton()
        self.__logger = Logger("Application")
        self.__logger.log("Info", "HookRunner is running.")
        self.__lib_spec_reader.init()
        self.__service = ServiceThread('localhost')
        self.__service.start()
        self.__logger.log("Info", "Server is ready...")
        self.__logger.log(
            "Info", "Is ServerThread alive?"
            " {status}".format(status=str(self.__service.is_alive())))
        self.__logger.log("Info", "On any input server will close.")
        input()
        self.__service.stop()
Esempio n. 12
0
class ServiceThread(Thread):
    def __init__(self, host):
        global IS_FINISH
        Thread.__init__(self)
        self.__logger = Logger("Service", "MainThread")
        self.__service = Service(host)
        IS_FINISH = False
        self.__task_handler = Thread(target=_handle_tasks)

    def run(self):
        self.__task_handler.start()
        asyncore.loop()

    def stop(self):
        global IS_FINISH
        IS_FINISH = True
        self.__task_handler.join()
        self.__logger.log("Debug", "Closing all connections...")
        asyncore.close_all()
        self.__logger.log("Debug", "Waiting for service"
                          " dispatcher to close...")
        self.__service.close()
        self.__logger.log("Debug", "Service dispatcher closed...")
        self.join()
Esempio n. 13
0
class TestAction(Action):
    def __init__(self, params_json):
        self.__logger = Logger("Actions", "TestActions")

    def run(self):
        self.__logger.log("Debug", "Test action is running.")
Esempio n. 14
0
class MainInterpreterListener(HookInterpreterListener):
    def __init__(self):
        HookInterpreterListener.__init__(self)
        self.__logger = Logger("Interpreter", "Listener")
        self.__steps = []
        self.__out = StringIO()
        self.__err = StringIO()

    def get_steps(self):
        return self.__steps

    def enterPrimaryExpression(self, ctx):
        pass

    def exitPrimaryExpression(self, ctx):
        pass

    def enterIncludeSentence(self, ctx):
        _desc = (StepType.INCLUDE, _get_step_description(StepType.INCLUDE))
        _lib = ctx.Identifier(0).getText()
        _func = ctx.Identifier(1).getText()
        self.__steps.append(StepInclude(_lib, _func))
        self.__logger.log("Info", "Found step: " "{}.", str(_desc))

    def exitIncludeSentence(self, ctx):
        pass

    def enterValue(self, ctx):
        pass

    def exitValue(self, ctx):
        pass

    def enterValues(self, ctx):
        pass

    def exitValues(self, ctx):
        pass

    def enterFunctionCall(self, ctx):
        _desc = (StepType.EXECUTE, _get_step_description(StepType.EXECUTE))
        args = [] if ctx.values() is None else _read_arguments(ctx.values())
        _ctx_uuid = ctx.uuid if hasattr(ctx, "uuid") else None
        self.__steps.append(
            StepRunCommand(*args,
                           name=ctx.Identifier(0).getText(),
                           uuid=_ctx_uuid))
        self.__logger.log("Info", "Found step: {}", str(_desc))

    def exitFunctionCall(self, ctx):
        pass

    def enterAssigmentWithOutDecl(self, ctx):
        _name = ctx.value(0).getText()
        if ctx.value(1):
            _value = ctx.value(1).getText()
        else:
            _value = None
        _desc = (StepType.ASSIGNMENT,
                 _get_step_description(StepType.ASSIGNMENT))
        if not ctx.value(0).Identifier():
            # TODO:Error
            pass
        if hasattr(ctx, '_decl'):
            if not ctx.AssigmentOpreator().getText() != "=":
                # TODO:Error
                pass
            if ctx.functionCall():
                _func_uuid = uuid4()
                ctx.functionCall().uuid = _func_uuid
                self.__steps.append(StepDeclVar(_name, "", _func_uuid))
            elif _value:
                _value_as_id = ctx.value(1).Identifier()
                _value_as_num = ctx.value(1).Digits()
                if _value_as_id or _value_as_num:
                    self.__steps.append(StepDeclVar(_name, _value))
                else:
                    self.__steps.append(StepDeclVar(_name, _value[1:-1]))
        if ctx.functionCall():
            _func_uuid = uuid4()
            ctx.functionCall().uuid = _func_uuid
            self.__steps.append(
                StepAssignment(_name, _func_uuid, AssignmentType.FUNCTION,
                               ctx.AssigmentOpreator().getText()))
        elif _value:
            _op = ctx.AssigmentOpreator().getText()
            _value_as_id = ctx.value(1).Identifier()
            if _value_as_id:
                self.__steps.append(
                    StepAssignment(_name, _value, AssignmentType.VARIBLE, _op))
            else:
                self.__steps.append(
                    StepAssignment(_name, _value, AssignmentType.VALUE, _op))
        self.__logger.log("Info", "Found step: {}.", str(_desc))

    def exitAssigmentWithOutDecl(self, ctx):
        pass

    def enterAssigmentWithDecl(self, ctx):
        ctx.assigmentWithOutDecl()._decl = True

    def exitAssigmentWithDecl(self, ctx):
        pass

    def enterMultiAssingment(self, ctx):
        pass

    def exitMultiAssingment(self, ctx):
        pass