Example #1
0
    def start(self):
        """ to call to start the plugin
            @return : None if ko
                      the pid if ok
        """
        ### Check if the plugin is not already launched
        # notice that this test is not really needed as the plugin also test this in startup...
        # but the plugin does it before the MQ is initiated, so the error message won't go overt the MQ.
        # By doing it now, the error will go to the UI through the 'error' MQ messages (sended by self.log.error)
        res, pid_list = is_already_launched(self.log, self.name)
        if res:
            return 0

        ### Actions for test mode
        test_mode = self._config.query(self.name, "test_mode")
        test_option = self._config.query(self.name, "test_option")
        test_args = ""
        if test_mode == True: 
            self.log.info("The plugin {0} is requested to be launched in TEST mode. Option is {1}".format(self.name, test_option))
            test_args = "-T {0}".format(test_option)

        ### Try to start the plugin
        self.log.info(u"Request to start plugin : {0} {1}".format(self.name, test_args))
        pid = self.exec_component(py_file = "{0}/plugin_{1}/bin/{2}.py {3}".format(self._packages_directory, self.name, self.name, test_args), \
                                  env_pythonpath = self._libraries_directory)
        pid = pid

        # There is no need to check if it is successfully started as the plugin will send over the MQ its status the UI will get the information in this way

        self.set_pid(pid)
        return pid
Example #2
0
    def start(self):
        """ to call to start the component
            @return : None if ko
                      the pid if ok
        """
        ### Check if the component is not already launched
        # notice that this test is not really needed as the plugin also test this in startup...
        # but the plugin does it before the MQ is initiated, so the error message won't go overt the MQ.
        # By doing it now, the error will go to the UI through the 'error' MQ messages (sended by self.log.error)
        res, pid_list = is_already_launched(self.log, self.name)
        if res:
            return 0

        ### Start the component
        self.log.info(u"Request to start core component : {0}".format(self.name))
        pid = self.exec_component("domogik.bin")
        self.set_pid(pid)
        if pid != 0:
            # Notice : we whould not need to do this as this information should be provided by the MQ plugin.status.
            # But as the IOLoop is not started when core components are launched with -r, -d or -x options, we don't
            # have the plugin.status message.
            self.set_status(STATUS_ALIVE)
       
        # no need to add a step to check if the component is started as the status is given to the user directly by the pub/sub 'plugin.status'

        return pid
Example #3
0
def check_domogik_is_running():
    """ a function to check if domogik is running, and so if the tests can be done
    """
    ret = True
    to_check = ['dmg_hub', 'dmg_broker', 'dmg_forwarder']
    for chk in to_check:
        status = is_already_launched(None, chk, False)
        if not status[0]:
            print("ERROR : component {0} is not running".format(chk))
            ret = False
        else:
            print("component {0} is running".format(chk))

    to_check = ['rest', 'xplgw', 'dbmgr', 'manager', 'admin', 'scenario']
    for chk in to_check:
        status = is_already_launched(None, chk, False)
        if not status[0]:
            print("ERROR : component {0} is not running".format(chk))
            ret = False
        else:
            print("component {0} is running".format(chk))
    return ret
Example #4
0
def check_domogik_is_running():
    """ a function to check if domogik is running, and so if the tests can be done
    """
    ret = True
    to_check = ['dmg_hub', 'dmg_broker', 'dmg_forwarder']
    for chk in to_check:
        status = is_already_launched(None, "core", chk, False)
        if not status[0]:
            print("ERROR : component {0} is not running".format(chk))
            ret = False
        else:
            print("component {0} is running".format(chk))

    to_check = ['xplgw', 'dbmgr', 'manager', 'admin', 'scenario']
    for chk in to_check:
        status = is_already_launched(None, "core", chk, False)
        if not status[0]:
            print("ERROR : component {0} is not running".format(chk))
            ret = False
        else:
            print("component {0} is running".format(chk))
    return ret
Example #5
0
def check_domogik_is_running():
    """ a function to check if domogik is running, and so if the tests can be done
    """
    ret = True
    to_check = ["dmg_hub", "dmg_broker", "dmg_forwarder"]
    for chk in to_check:
        status = is_already_launched(None, "core", chk, False)
        if not status[0]:
            print("ERROR : component {0} is not running".format(chk))
            ret = False
        else:
            print("component {0} is running".format(chk))

    to_check = ["rest", "xplgw", "dbmgr", "manager", "admin", "scenario"]
    for chk in to_check:
        status = is_already_launched(None, "core", chk, False)
        if not status[0]:
            print("ERROR : component {0} is not running".format(chk))
            ret = False
        else:
            print("component {0} is running".format(chk))
    return ret
Example #6
0
 def _check_if_stopped(self):
     """ Check if the plugin is stopped. If not, kill it
     """
     self._stop.wait(WAIT_AFTER_STOP_REQUEST)
     self.log.debug("Check if the plugin {0} has stopped it self. Else there will be a bloodbath".format(self.name))
     res, pid_list = is_already_launched(self.log, self.name)
     if res:
         for the_pid in pid_list:
             self.log.info(u"Try to kill pid {0}...".format(the_pid))
             os.kill(int(the_pid), signal.SIGKILL)
             # TODO : add one more check ?
             # do a while loop over is_already.... ?
         self.log.info(u"The plugin {0} should be killed now (kill -9)".format(self.name))
     else:
         self.log.info(u"The plugin {0} has stopped itself properly.".format(self.name))
Example #7
0
    def __init__(self, name, stop_cb = None, p = None, daemonize = True, log_prefix= ""):
        ''' 
        @param p : An instance of ArgumentParser. If you want to add extra options to the generic option parser,
        create your own ArgumentParser instance, use parser.add_argument and then pass your parser instance as parameter.
        Your options/params will then be available on self.options and self.args
        @param daemonize : If set to False, force the instance *not* to daemonize, even if '-f' is not passed
        on the command line. If set to True (default), will check if -f was added.
        @param log_prefix : If set, use this prefix when creating the log file in Logger()
        '''
        ### First, check if the user is allowed to launch the plugin. The user must be the same as the one defined
        # in the file /etc/default/domogik : DOMOGIK_USER
        Default = DefaultLoader()
        dmg_user = Default.get("DOMOGIK_USER")
        logname = pwd.getpwuid(os.getuid())[0]
        if dmg_user != logname:
            print(u"ERROR : this Domogik part must be run with the user defined in /etc/default/domogik as DOMOGIK_USER : %s" % dmg_user)
            sys.exit(1)

        if name is not None:
            self._plugin_name = name

        l = logger.Logger(name, use_filename = "{0}{1}".format(log_prefix, name))
        self.log = l.get_logger()

        ### Check if the plugin is not already launched
        # notice that when the plugin is launched from the manager, this call is not done as the manager already does this test before starting a plugin
        res, pid_list = is_already_launched(self.log, name)
        if res:
            sys.exit(2)

        ### Create a file to handle the return code
        # this is used by the function set_return_code and get_return_code
        # this is needed as a Domogik process is forked, there is no way to send from a class a return code from the child to the parent.
        try: 
            self.return_code_filename = "{0}/{1}_return_code_{2}".format(FIFO_DIR, self._plugin_name, os.getpid())
            # just touch the file to create it
            open(self.return_code_filename, 'a').close()
        except:
            self.log.error("Error while creating return_code file '{0}' : {1}".format(self.return_code_filename, traceback.format_exc()))
            sys.exit(3)

        ### Start the plugin...
        self._threads = []
        self._timers = []
        self._stop = threading.Event()
        self._lock_add_thread = threading.Semaphore()
        self._lock_add_timer = threading.Semaphore()
        self._lock_add_cb = threading.Semaphore()
        if stop_cb is not None:
            self._stop_cb = [stop_cb]
        else:
            self._stop_cb = []

        ### options management
        if p is not None and isinstance(p, ArgumentParser):
            parser = p
        else:
            parser = ArgumentParser()
        parser.add_argument("-V", 
                          "--version", 
                          action="store_true", 
                          dest="display_version", 
                          default=False, 
                          help="Display Domogik version.")
        parser.add_argument("-f", 
                          action="store_true", 
                          dest="run_in_foreground", 
                          default=False, 
                          help="Run the plugin in foreground, default to background.")
        parser.add_argument("-T", 
                          dest="test_option", 
                          default=None,
                          help="Test option.")
        self.options = parser.parse_args()
        if self.options.display_version:
            __import__("domogik")
            global_release = sys.modules["domogik"].__version__
            print(global_release)
            sys.exit(0)
        elif not self.options.run_in_foreground and daemonize:
            self.log.info(u"Starting the plugin in background...")
            ctx = DaemonContext()
            ctx.files_preserve = l.get_fds([name])
            ctx.open()
            self.log.info(u"Daemonize plugin %s" % name)
            self.is_daemon = True
        else:
            #l = logger.Logger(name)
            #self.log = l.get_logger()
            self.is_daemon = False
Example #8
0
    def __init__(self,
                 name,
                 stop_cb=None,
                 p=None,
                 daemonize=True,
                 log_prefix="",
                 log_on_stdout=True):
        ''' 
        @param p : An instance of ArgumentParser. If you want to add extra options to the generic option parser,
        create your own ArgumentParser instance, use parser.add_argument and then pass your parser instance as parameter.
        Your options/params will then be available on self.options and self.args
        @param daemonize : If set to False, force the instance *not* to daemonize, even if '-f' is not passed
        on the command line. If set to True (default), will check if -f was added.
        @param log_prefix : If set, use this prefix when creating the log file in Logger()
        @param log_on_stdout : if set to True, allow to read logs on both stdout and log file
        '''
        ### First, check if the user is allowed to launch the plugin. The user must be the same as the one defined
        # in the file /etc/default/domogik : DOMOGIK_USER
        Default = DefaultLoader()
        dmg_user = Default.get("DOMOGIK_USER")
        logname = pwd.getpwuid(os.getuid())[0]
        if dmg_user != logname:
            print(
                u"ERROR : this Domogik part must be run with the user defined in /etc/default/domogik as DOMOGIK_USER : %s"
                % dmg_user)
            sys.exit(1)

        if name is not None:
            self._plugin_name = name

        l = logger.Logger(name,
                          use_filename="{0}{1}".format(log_prefix, name),
                          log_on_stdout=log_on_stdout)
        self.log = l.get_logger()

        ### Check if the plugin is not already launched
        # notice that when the plugin is launched from the manager, this call is not done as the manager already does this test before starting a plugin
        # TODO : improve ? currently, as it is not used, we set the type of the client to None
        # in case the 'is_already_launched function would use it a day, we should find a way to get the client type
        res, pid_list = is_already_launched(self.log, None, name)
        if res:
            sys.exit(2)

        ### Create a file to handle the return code
        # this is used by the function set_return_code and get_return_code
        # this is needed as a Domogik process is forked, there is no way to send from a class a return code from the child to the parent.
        try:
            self.return_code_filename = "{0}/{1}_return_code_{2}".format(
                FIFO_DIR, self._plugin_name, os.getpid())
            # just touch the file to create it
            open(self.return_code_filename, 'a').close()
        except:
            self.log.error(
                "Error while creating return_code file '{0}' : {1}".format(
                    self.return_code_filename, traceback.format_exc()))
            sys.exit(3)

        ### Start the plugin...
        self._threads = []
        self._timers = []
        self._stop = threading.Event()
        self._lock_add_thread = threading.Semaphore()
        self._lock_add_timer = threading.Semaphore()
        self._lock_add_cb = threading.Semaphore()
        if stop_cb is not None:
            self._stop_cb = [stop_cb]
        else:
            self._stop_cb = []

        ### options management
        if p is not None and isinstance(p, ArgumentParser):
            parser = p
        else:
            parser = ArgumentParser()
        parser.add_argument("-V",
                            "--version",
                            action="store_true",
                            dest="display_version",
                            default=False,
                            help="Display Domogik version.")
        parser.add_argument(
            "-f",
            action="store_true",
            dest="run_in_foreground",
            default=False,
            help="Run the plugin in foreground, default to background.")
        parser.add_argument("-T",
                            dest="test_option",
                            default=None,
                            help="Test option.")
        self.options = parser.parse_args()
        if self.options.display_version:
            __import__("domogik")
            global_release = sys.modules["domogik"].__version__
            print(global_release)
            sys.exit(0)
        elif not self.options.run_in_foreground and daemonize:
            self.log.info(u"Starting the plugin in background...")
            ctx = DaemonContext()
            ctx.files_preserve = l.get_fds([name])
            ctx.open()
            self.log.info(u"Daemonize plugin %s" % name)
            self.is_daemon = True
        else:
            #l = logger.Logger(name)
            #self.log = l.get_logger()
            self.is_daemon = False