Exemplo n.º 1
0
    def __init__(self, context, main_ep, opt_ep=None):
        """Init MDPBroker instance.
        """
        l = logger.Logger('mq_broker')
        self.log = l.get_logger()
        self.log.info("MDP broker startup...")

        socket = ZmqSocket(context, zmq.ROUTER)
        socket.bind(main_ep)
        self.main_stream = ZMQStream(socket)
        self.main_stream.on_recv(self.on_message)
        if opt_ep:
            socket = ZmqSocket(context, zmq.ROUTER)
            socket.bind(opt_ep)
            self.client_stream = ZMQStream(socket)
            self.client_stream.on_recv(self.on_message)
        else:
            self.client_stream = self.main_stream
        self.log.debug("Socket created...")
        self._workers = {}
        # services contain the worker queue and the request queue
        self._services = {}
        self._worker_cmds = {
            b'\x01': self.on_ready,
            b'\x03': self.on_reply,
            b'\x04': self.on_heartbeat,
            b'\x05': self.on_disconnect,
        }
        self.log.debug("Launch the timer...")
        self.hb_check_timer = PeriodicCallback(self.on_timer, HB_INTERVAL)
        self.hb_check_timer.start()
        self.log.info("MDP broker started")
        return
Exemplo n.º 2
0
    def __init__(self, serialConf):
        l = logger.Logger('x10API')
        self._log = l.get_logger()
        self._retry = 3
        self._lastUnit = -1

        # Mutex for serial port acces
        self._lock = threading.Lock()
        self._timeout = serialConf['timeout']
        self._serialdevice = serial.Serial()

        # Port
        self._serialdevice.setPort(serialConf['port'])

        # Speed
        self._serialdevice.setBaudrate(serialConf['speed'])

        # Timeout
        self._serialdevice.setTimeout(serialConf['timeout'])

        # Parity
        self._serialdevice.setParity(serialConf['parity'])

        # Stop bit
        self._serialdevice.setStopbits(serialConf['stop_bits'])

        # Byte size
        self._serialdevice.setByteSize(serialConf['byte_size'])
        self._open()
Exemplo n.º 3
0
    def __init__(self):
        """
        telldusTool helper
        """

        self.commands =   \
               { "list" :
                  {
                    "cb" : self.list,
                    "desc" : "List devices referenced by the telldus",
                    "min_args" : 0,
                    "usage" : "list [devicetype]"
                  },
                 "info" :
                  {
                    "cb" : self.info,
                    "desc" : "Display device information",
                    "min_args" : 1,
                    "usage" : "info <id>"
                  }
                }

        log = logger.Logger('telldus-helper')
        self._log = log.get_logger('telldus-helper')
       # self._config = Query(self.myxpl, self._log)
        self._log.info("telldusHelper.init : done")
        self._telldusd = Telldusd()
Exemplo n.º 4
0
    def __init__(self):
        """ Init onewire helper
        """

        self.commands =   \
               { "all" :
                  {
                    "cb" : self.all,
                    "desc" : "Show all devices found on onewire network",
                    "min_args" : 1,
                    "usage" : "all <adaptator device>"
                  },
                  "detail" :
                  {
                    "cb" : self.detail,
                    "desc" : "Show detail for a device.",
                    "min_args" : 1,
                    "usage" : "detail <adaptator device> <device id>"
                  },
                  "ds18b20" :
                  {
                    "cb" : self.ds18b20,
                    "desc" : "Show detail for all DS18B20 devices",
                    "min_args" : 1,
                    "usage" : "ds18b20 <adaptator device>"
                  },
                  "ds18s20" :
                  {
                    "cb" : self.ds18s20,
                    "desc" : "Show detail for all DS18S20 devices",
                    "min_args" : 1,
                    "usage" : "ds18s20 <adaptator device>"
                  },
                  "ds2401" :
                  {
                    "cb" : self.ds2401,
                    "desc" : "Show detail for all DS2401 devices",
                    "min_args" : 1,
                    "usage" : "ds2401 <adaptator device>"
                  },
                  "ds2438" :
                  {
                    "cb" : self.ds2438,
                    "desc" : "Show detail for all DS2438 devices",
                    "min_args" : 1,
                    "usage" : "ds2438 <adaptator device>"
                  },
                  "ds2408" :
                  {
                    "cb" : self.ds2408,
                    "desc" : "Show detail for all DS2408/DS2406/DS2405 devices",
                    "min_args" : 1,
                    "usage" : "ds2408 <adaptator device>"
                  }
               }

        log = logger.Logger('onewire-helper')
        self._log = log.get_logger('onewire-helper')
        self.my_ow = None
Exemplo n.º 5
0
    def __init__(self):
        ### init zmq
        zmqc = zmq.Context()

        ### init logger
        loginst = logger.Logger('manager')
        log = loginst.get_logger('manager')

        self.qry = QueryMQ(zmqc, log)
Exemplo n.º 6
0
    def __init__(self):
        """ Init
        """
        # set logger
        l = logger.Logger("testrunner")
        l.set_format_mode("messageOnly")
        self.log = l.get_logger()

        # read the config file
        try:
            cfg = Loader('domogik')
            config = cfg.load()
            conf = dict(config[1])

            # pid dir path
            self._libraries_path = conf['libraries_path']
            self.log.debug("Libraries path is : {0}".format(self._libraries_path))

        except:
            self.log.error(u"Error while reading the configuration file '{0}' : {1}".format(CONFIG_FILE, traceback.format_exc()))
            return


        parser = ArgumentParser(description="Launch all the tests that don't need hardware.")
	parser.add_argument("directory",
                          help="What directory to run")
        parser.add_argument("-a", 
                          "--allow-alter", 
                          dest="allow_alter",
                          action="store_true",
                          help="Launch the tests that can alter the configuration of the plugin or the setup (devices, ...)")
        parser.add_argument("-c", 
                          "--criticity", 
                          dest="criticity", 
                          help="Set the minimum level of criticity to use to filter the tests to execute. low/medium/high. Default is low.")
        self.options = parser.parse_args()
	self.testcases = {}
        self.results = {}

        # options
        self.log.info("Domogik release : {0}".format(DMG_VERSION))
        self.log.info("Running test with the folowing parameters:")
	if self.options.allow_alter:
	    self.log.info("- allow to alter the configuration or setup.")
	if self.options.criticity not in (LOW, MEDIUM, HIGH):
            self.options.criticity = LOW
	self.log.info("- criticity : {0}".format(self.options.criticity))

        # check tests folder
	self.log.info("- path {0}".format(self.options.directory))
        if not self.check_dir():
            return

        # check and load the json file
        self.log.info("- json file {0}".format(self.json_file))
	if not self.load_json():
	    return
Exemplo n.º 7
0
    def __init__(self):
        ### init zmq
        zmqc = zmq.Context()

        ### init logger
        loginst = logger.Logger('butler')
        log = loginst.get_logger('butler')

        self.qry = QueryMQ(zmqc, log, get_sanitized_hostname())
Exemplo n.º 8
0
    def __init__(self):
        """ Init
        """
        l = logger.Logger("testrunner")
        l.set_format_mode("messageOnly")
        self.log = l.get_logger()

        parser = ArgumentParser(
            description="Launch all the tests that don't need hardware.")
        parser.add_argument("directory", help="What directory to run")
        parser.add_argument(
            "-a",
            "--allow-alter",
            dest="allow_alter",
            action="store_true",
            help=
            "Launch the tests that can alter the configuration of the plugin or the setup (devices, ...)"
        )
        parser.add_argument(
            "-c",
            "--criticity",
            dest="criticity",
            help=
            "Set the minimum level of criticity to use to filter the tests to execute. low/medium/high. Default is low."
        )
        self.options = parser.parse_args()
        self.testcases = {}
        self.results = {}

        # options
        self.log.info("Domogik release : {0}".format(DMG_VERSION))
        self.log.info("Running test with the folowing parameters:")
        if self.options.allow_alter:
            self.log.info("- allow to alter the configuration or setup.")
        if self.options.criticity not in (LOW, MEDIUM, HIGH):
            self.options.criticity = LOW
        self.log.info("- criticity : {0}".format(self.options.criticity))

        # check tests folder
        self.log.info("- path {0}".format(self.options.directory))
        if not self.check_dir():
            return False

        # check and load the json file
        self.log.info("- json file {0}".format(self.json_file))
        if not self.load_json():
            return False

        self._run_testcases()
        print self.results
        # TODO : return False is some tests fails
        return True
Exemplo n.º 9
0
        def __init__(self, pipe):
            """
            @param pipe : the Popen instance
            """
            threading.Thread.__init__(self)
            self._pipe = pipe
            self._cbs = []
            log = logger.Logger(self.__class__.__name__)
            self._log = log.get_logger('x10_heyu')

            # for last command
            self._selectedunit = None
            self._last_hashcmd = None
Exemplo n.º 10
0
 def __init__(self, heyuconf, serial_port=0):
     self._serialconf = {
         'speed': 4800,
         'timeout': 15,
         'parity': serial.PARITY_NONE,
         'stop_bits': serial.STOPBITS_ONE,
         'byte_size': serial.EIGHTBITS
     }
     self._serialconf['port'] = serial_port
     l = logger.Logger('x10API')
     self._log = l.get_logger()
     self._housecodes = list('ABCDEFGHIJKLMNOP')
     self._unitcodes = range(1, 17)
     self._heyuconf = heyuconf
     self._controller = X10Controller(self._serialconf)
Exemplo n.º 11
0
    def __init__(self):
        """ Init Teleinfo helper
        """

        self.commands =   \
               { "read" :
                  {
                    "cb" : self.read,
                    "desc" : "Display electric meter informations",
                    "min_args" : 1,
                    "usage" : "read <device path>"
                  }
                }

        log = logger.Logger('teleinfo-helper')
        self._log = log.get_logger('teleinfo-helper')
Exemplo n.º 12
0
    def __init__(self):
        """ Init Caller Id with a modem helper
        """

        self.commands =   \
               { "read" :
                  {
                    "cb" : self.read,
                    "desc" : "Wait for a inbound call event",
                    "min_args" : 1,
                    "usage" : "read <device>"
                  },
                }

        log = logger.Logger('cidmodem-helper')
        self._log = log.get_logger('cidmodem-helper')
Exemplo n.º 13
0
    def __init__(self):
        """ Init Mir:ror helper
        """

        self.commands =   \
               { "read" :
                  {
                    "cb" : self.read,
                    "desc" : "Wait for a Mir:ror event",
                    "min_args" : 1,
                    "usage" : "read <device>"
                  }
                }

        log = logger.Logger('mirror-helper')
        self._log = log.get_logger('mirror-helper')
Exemplo n.º 14
0
    def __init__(self):
        """
        bluez helper
        """

        self.commands =   \
               { "scan" :
                  {
                    "cb" : self.scan,
                    "desc" : "Scan for bluetooth phones, ...",
                    "min_args" : 0,
                    "usage" : "scan"
                  },
                }

        log = logger.Logger('bluez-helper')
        self._log = log.get_logger('bluez-helper')
Exemplo n.º 15
0
def main():
    """
       Main loop for the forwarder
    """
    ctx = DaemonContext()
    ctx.open()

    cfg = Loader('mq').load()
    config = dict(cfg[1])
    log = logger.Logger('mq_forwarder').get_logger()
    log.info("Starting the forwarder")

    try:
        context = zmq.Context(1)

        # Socket facing emitters
        frontend = context.socket(zmq.SUB)
        # Forwarder subscribes to the emitter *pub* port
        sub_addr = "tcp://{0}:{1}".format(\
                   config['ip'], config['pub_port'])
        frontend.bind(sub_addr)
        log.info("Waiting for messages on {0}".format(sub_addr))
        # We want to get all messages from emitters
        frontend.setsockopt(zmq.SUBSCRIBE, "")

        # Socket facing receivers
        backend = context.socket(zmq.PUB)
        # Forwarder publishes to the receiver *sub* port
        pub_addr = "tcp://{0}:{1}".format(\
                   config['ip'], config['sub_port'])
        backend.bind(pub_addr)
        log.info("Sending messages to {0}".format(pub_addr))

        log.info("Forwarding messages...")
        zmq.device(zmq.FORWARDER, frontend, backend)
    except Exception as exp:
        log.error(exp)
        log.error("Bringing down ZMQ device")
        raise Exception("Error with forwarder device")
    finally:
        frontend.close()
        backend.close()
        context.term()
        log.info("Forwarder stopped")
Exemplo n.º 16
0
    def __init__(self):
	self._event = Event()
        self.message = []
        self.commands = \
            { "find" :
                {
                "cb" : self.find,
                "desc" : "Show all nodes found on Z-wave network",
                },
              "info" :
                {
                "cb" : self.info,
                "desc" : "Show node info",
                "min_args" : 1,
                "usage" : "Show info for specified node <node id>",
                }
            }
        log = logger.Logger('zwave-helper')
        self._log = log.get_logger('zwave-helper')
Exemplo n.º 17
0
    def __init__(self):
        """ Init IPX 800 helper
        """

        self.commands =   \
               { "find" :
                  {
                    "cb" : self.find,
                    "desc" : "Find ipx800 relay boards"
                  },
                 "status" :
                  {
                    "cb" : self.status,
                    "desc" : "Display all ipx800 elements status",
                    "min_args" : 1,
                    "usage" : "status <ipx800 ip> <ipx800 model : %s>" % IPX800_MODELS
                  }
                }

        log = logger.Logger('ipx800-helper')
        self._log = log.get_logger('ipx800-helper')
Exemplo n.º 18
0
    def __init__(self):
        """ Init
        """
        l = logger.Logger("package")
        l.set_format_mode("messageOnly")
        self.log = l.get_logger()

        parser = ArgumentParser()
        parser.add_argument(
            "-i",
            "--install",
            dest="install",
            help=
            "Install a package from a path, a zip file or an url to a zip file or to a github repository and branch"
        )
        parser.add_argument(
            "-u",
            "--uninstall",
            dest="uninstall",
            help="Uninstall a package. Example : plugin_rfxcom")
        self.options = parser.parse_args()

        # get install path for packages
        cfg = Loader('domogik')
        config = cfg.load()
        conf = dict(config[1])
        self.pkg_path = os.path.join(conf['libraries_path'], PACKAGES_DIR)

        # install a package
        if self.options.install:
            self.install(self.options.install)

        # uninstall a package
        elif self.options.uninstall:
            self.uninstall(self.options.uninstall)

        # no choice : display the list of installed packages
        else:
            self.list_packages()
Exemplo n.º 19
0
 def __init__(self):
     self._event = Event()
     self.liste_found = []
     self.commands = \
         { "all" :
             {
             "cb" : self.all,
             "desc" : "Show all devices found on plcbus network",
             "min_args" : 2,
             "usage" : "find device for specified  house code <house code> and user code <user code>."
             },
           "detail" :
             {
             "cb" : self.detail,
             "desc" : "Show device detail ",
             "min_args" : 2,
             "usage" : "show status for specified device <device code> and user code <user code>"
             }
         }
     log = logger.Logger('plcbus-helper')
     self._log = log.get_logger('plcbus-helper')
     device = '/dev/plcbus'
     self.api1 = PLCBUSAPI(self._log, device, self._command_cb, self._message_cb)
Exemplo n.º 20
0
 def __init__(self, minute, hour, day, month, daynumber, year):
     '''
     Create a time condition
     Each param can be :
     * an integer (eg : 6, 9, 12)
     * a tuple (eg : (3,9)) : repesents an interval (here between 3 and 9)
     * a list (eg : [4,6,9])
     * a list of tuple (eg : [(4,9),(18,22)] : union of intervals
     * a string (eg : '*', '*/8') : '*' = always, '*/X' = every X time unit
     @param year
     @param month
     @param day
     @param daynumber : 0 - 6 for Monday - Sunday
     @param hour
     @param minute
     '''
     self.year = year
     self.month = month
     self.day = day
     self.hour = hour
     self.minute = minute
     self.daynumber = daynumber
     l = logger.Logger('trigger')
     self._log = l.get_logger('trigger')
Exemplo n.º 21
0
    def __init__(self, name, stop_cb = None, p = None, daemonize = True):
        ''' 
        @param p : An instance of OptionParser. If you want to add extra options to the generic option parser,
        create your own optionparser instance, use parser.addoption 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.
        '''

        # 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("ERROR : this Domogik part must be run with the user defined in /etc/default/domogik as DOMOGIK_USER : %s" % dmg_user)
            sys.exit(1)

        # Then, start the plugin...
        self._threads = []
        self._timers = []
        if name is not None:
            self._plugin_name = name
        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, OptionParser):
            parser = p
        else:
            parser = OptionParser()
        parser.add_option("-V", 
                          "--version", 
                          action="store_true", 
                          dest="display_version", 
                          default=False, 
                          help="Display Domogik version.")
        parser.add_option("-f", 
                          action="store_true", 
                          dest="run_in_foreground", 
                          default=False, 
                          help="Run the plugin in foreground, default to background.")
        (self.options, self.args) = 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:
            createDaemon()
            l = logger.Logger(name)
            self.log = l.get_logger()
            self.log.info("Daemonize plugin %s" % name)
            self.is_daemon = True
        else:
            l = logger.Logger(name)
            self.log = l.get_logger()
            self.is_daemon = False
Exemplo n.º 22
0
    def __init__(self, server_ip, server_port):
        """ Initiate DbHelper, Logs and config
            Then, start HTTP server and give it initialized data
            @param server_ip :  ip of HTTP server
            @param server_port :  port of HTTP server
        """

        XplPlugin.__init__(self, name='rest')
        # logging initialization
        self.log.info("Rest Server initialisation...")
        self.log.debug("locale : %s %s" % locale.getdefaultlocale())

        # logging Queue activities
        log_queue = logger.Logger('rest-queues')
        self.log_queue = log_queue.get_logger('rest-queues')
        self.log_queue.info("Rest's queues activities...")

        # logging data manipulation initialization
        log_dm = logger.Logger('rest-dm')
        self.log_dm = log_dm.get_logger('rest-dm')
        self.log_dm.info("Rest Server Data Manipulation...")

        # API version
        self._rest_api_version = REST_API_VERSION

        # Hosts list
        self._hosts_list = {
            self.get_sanitized_hostname(): {
                "id": self.get_sanitized_hostname(),
                "status": "on",
                "primary": True,
                "last_seen": time.time(),
                "ip": "",
                "interval": "1"
            }
        }

        try:

            ### Config

            # directory data
            cfg = Loader('domogik')
            config = cfg.load()
            conf = dict(config[1])
            self.log_dir_path = conf['log_dir_path']

            # plugin installation path
            if conf.has_key('package_path'):
                self._package_path = conf['package_path']
                self._src_prefix = None
                self.log.info("Set package path to '%s' " % self._package_path)
                print("Set package path to '%s' " % self._package_path)
                self._design_dir = "%s/domogik_packages/design/" % self._package_path
                self.package_mode = True
            else:
                self.log.info("No package path defined in config file")
                self._package_path = None
                self._src_prefix = conf['src_prefix']
                self._design_dir = "%s/share/domogik/design/" % conf[
                    'src_prefix']
                self.package_mode = False

            # HTTP server ip and port
            try:
                cfg_rest = Loader('rest')
                config_rest = cfg_rest.load()
                conf_rest = dict(config_rest[1])
                self.server_ip = conf_rest['rest_server_ip']
                self.server_port = conf_rest['rest_server_port']
            except KeyError:
                # default parameters
                self.server_ip = server_ip
                self.server_port = server_port
            self.log.info("Configuration : ip:port = %s:%s" %
                          (self.server_ip, self.server_port))

            # SSL configuration
            try:
                cfg_rest = Loader('rest')
                config_rest = cfg_rest.load()
                conf_rest = dict(config_rest[1])
                self.use_ssl = conf_rest['rest_use_ssl']
                if self.use_ssl == "True":
                    self.use_ssl = True
                else:
                    self.use_ssl = False
                self.ssl_certificate = conf_rest['rest_ssl_certificate']
            except KeyError:
                # default parameters
                self.use_ssl = USE_SSL
                self.ssl_certificate = SSL_CERTIFICATE
            if self.use_ssl == True:
                self.log.info(
                    "Configuration : SSL support activated (certificate : %s)"
                    % self.ssl_certificate)
            else:
                self.log.info("Configuration : SSL support not activated")

            # File repository
            try:
                cfg_rest = Loader('rest')
                config_rest = cfg_rest.load()
                conf_rest = dict(config_rest[1])
                self.repo_dir = conf_rest['rest_repository']
            except KeyError:
                # default parameters
                self.repo_dir = DEFAULT_REPO_DIR

            # Gloal Queues config
            self.log.debug("Get queues configuration")
            self._config = Query(self.myxpl, self.log)

            self._queue_timeout = self._config.query('rest', 'q-timeout')
            if self._queue_timeout == None:
                self._queue_timeout = QUEUE_TIMEOUT
            self._queue_timeout = float(self._queue_timeout)

            self._queue_package_size = self._config.query('rest', 'q-pkg-size')
            if self._queue_package_size == None:
                self._queue_package_size = QUEUE_PACKAGE_SIZE
            self._queue_package_size = float(self._queue_package_size)

            self._queue_size = self._config.query('rest', 'q-size')
            if self._queue_size == None:
                self._queue_size = QUEUE_SIZE
            self._queue_size = float(self._queue_size)

            self._queue_life_expectancy = self._config.query(
                'rest', 'q-life-exp')
            if self._queue_life_expectancy == None:
                self._queue_life_expectancy = QUEUE_LIFE_EXPECTANCY
            self._queue_life_expectancy = float(self._queue_life_expectancy)

            self._queue_sleep = self._config.query('rest', 'q-sleep')
            if self._queue_sleep == None:
                self._queue_sleep = QUEUE_SLEEP
            self._queue_sleep = float(self._queue_sleep)

            # /command Queues config
            self._queue_command_size = self._config.query('rest', 'q-cmd-size')
            if self._queue_command_size == None:
                self._queue_command_size = QUEUE_COMMAND_SIZE
            self._queue_command_size = float(self._queue_command_size)

            # /event Queues config
            self._event_timeout = self._config.query('rest', 'evt-timeout')
            if self._event_timeout == None:
                self._event_timeout = EVENT_TIMEOUT
            self._event_timeout = float(self._event_timeout)

            self._queue_event_size = self._config.query('rest', 'q-evt-size')
            if self._queue_event_size == None:
                self._queue_event_size = QUEUE_EVENT_SIZE
            self._queue_event_size = float(self._queue_event_size)

            self._queue_event_timeout = self._config.query(
                'rest', 'q-evt-timeout')
            if self._queue_event_timeout == None:
                self._queue_event_timeout = QUEUE_EVENT_TIMEOUT
            self._queue_event_timeout = float(self._queue_event_timeout)

            self._queue_event_life_expectancy = self._config.query(
                'rest', 'q-evt-life-exp')
            if self._queue_event_life_expectancy == None:
                self._queue_event_life_expectancy = QUEUE_EVENT_LIFE_EXPECTANCY
            self._queue_event_life_expectancy = float(
                self._queue_event_life_expectancy)

            # Queues for xPL
            # Queues for packages management
            self._queue_package = Queue(self._queue_package_size)

            # Queues for domogik system actions
            self._queue_system_list = Queue(self._queue_size)
            self._queue_system_detail = Queue(self._queue_size)
            self._queue_system_start = Queue(self._queue_size)
            self._queue_system_stop = Queue(self._queue_size)

            # Queues for /command
            self._queue_command = Queue(self._queue_command_size)

            # Queues for /events/domogik
            self._queue_event_dmg = Queue(self._queue_event_size)

            # Queues for /events/request
            # this queue will be fill by stat manager
            self._event_requests = RequestEvents(
                self.get_stop, self.log, self._event_timeout,
                self._queue_event_size, self._queue_event_timeout,
                self._queue_event_life_expectancy)
            self.add_stop_cb(self._event_requests.set_stop_clean)

            # Queues for /events/domogik
            # this queue will be fill by stat manager
            self._event_dmg = DmgEvents(self.get_stop, self.log,
                                        self._event_timeout,
                                        self._queue_event_size,
                                        self._queue_event_timeout,
                                        self._queue_event_life_expectancy)
            # notice : adding data in queue is made in _add_to_queue_system_list
            self.add_stop_cb(self._event_dmg.set_stop_clean)

            # define listeners for queues
            self.log.debug("Create listeners")
            if self.package_mode == True:
                Listener(self._list_installed_packages, self.myxpl, \
                         {'schema': 'domogik.package',
                          'xpltype': 'xpl-trig',
                          'command' : 'installed-packages-list'})
            Listener(self._add_to_queue_package, self.myxpl, \
                     {'schema': 'domogik.package',
                      'xpltype': 'xpl-trig'})
            Listener(self._add_to_queue_system_list, self.myxpl, \
                     {'schema': 'domogik.system',
                      'xpltype': 'xpl-trig',
                      'command' : 'list'})
            Listener(self._add_to_queue_system_list, self.myxpl, \
                     {'schema': 'domogik.system',
                      'xpltype': 'xpl-trig',
                      'command' : 'enable'})
            Listener(self._add_to_queue_system_list, self.myxpl, \
                     {'schema': 'domogik.system',
                      'xpltype': 'xpl-trig',
                      'command' : 'disable'})
            Listener(self._add_to_queue_system_detail, self.myxpl, \
                     {'schema': 'domogik.system',
                      'xpltype': 'xpl-trig',
                      'command' : 'detail'})
            Listener(self._add_to_queue_system_start, self.myxpl, \
                     {'schema': 'domogik.system',
                      'xpltype': 'xpl-trig',
                      'command' : 'start'})
            Listener(self._add_to_queue_system_stop, self.myxpl, \
                     {'schema': 'domogik.system',
                      'xpltype': 'xpl-trig',
                      'command' : 'stop'})
            Listener(self._add_to_queue_command, self.myxpl, \
                     {'xpltype': 'xpl-trig'})

            # Listener for hosts list
            Listener(self._list_hosts, self.myxpl, \
                     {'schema': 'hbeat.app',
                      'xpltype': 'xpl-stat'})

            # Background process to check if hosts has disappeared
            thr_hbeat = XplTimer(10, \
                                 self._refresh_status_for_list_hosts, \
                                 self.myxpl)
            thr_hbeat.start()

            self._discover_hosts()

            # Enable hbeat
            self.enable_hbeat()

            # Ask for installed packages on all hosts
            # Semaphore init for installed package list update
            self.sema_installed = Semaphore(value=1)
            self._installed_packages = {}
            if self.package_mode == True:
                self._get_installed_packages_from_manager()

            # Launch server, stats
            self.log.info("REST Initialisation OK")
            self.add_stop_cb(self.stop_http)
            self.server = None
            self.start_stats()

            self.start_http()
        except:
            self.log.error("%s" % self.get_exception())
Exemplo n.º 23
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
Exemplo n.º 24
0
 def __init__(self):
     """ Init tool
     """
     log = logger.Logger("package-manager")
     self._log = log.get_logger("package-manager")
Exemplo n.º 25
0
    def __init__(self):
        """ Init
        """
        l = logger.Logger("package")
        l.set_format_mode("messageOnly")
        self.log = l.get_logger()

        parser = ArgumentParser()
        parser.add_argument(
            "-i",
            "--install",
            dest="install",
            help=
            "Install a package from a path, a zip file or an url to a zip file or to a github repository and branch"
        )
        parser.add_argument("-u",
                            "--upgrade",
                            dest="upgrade",
                            help="Upgrade a package (zip and url only).")
        parser.add_argument(
            "-r",
            "--remove",
            dest="uninstall",
            help="Remove (uninstall) a package. Example : plugin_rfxcom")
        parser.add_argument(
            "-d",
            "--refresh-docs",
            dest="refresh_docs",
            action="store_true",
            help=
            "Refresh all packages documentations (usefull when you use the git sources"
        )
        parser.add_argument(
            "-H",
            "--hash",
            dest="hash",
            help=
            "Hash value to check the package integrity. Only for zip files!")
        self.options = parser.parse_args()

        # get install path for packages
        cfg = Loader('domogik')
        config = cfg.load()
        conf = dict(config[1])
        self.pkg_path = os.path.join(conf['libraries_path'], PACKAGES_DIR)
        self.resources_path = os.path.join(conf['libraries_path'],
                                           RESOURCES_DIR)

        # install a package
        if self.options.install:
            if self.options.hash:
                self.install(self.options.install, self.options.hash)
            else:
                self.install(self.options.install)

        # uninstall a package
        elif self.options.uninstall:
            self.uninstall(self.options.uninstall)

        # upgrade a package
        elif self.options.upgrade:
            if self.options.hash:
                self.install(self.options.upgrade,
                             hash=self.options.hash,
                             upgrade=True)
            else:
                self.install(self.options.upgrade, hash=None, upgrade=True)

        # refresh the docs
        elif self.options.refresh_docs:
            self.refresh_docs()

        # no choice : display the list of installed packages
        else:
            self.list_packages()