예제 #1
0
    def start_http(self):
        """ Start HTTP Server
        """
        self.log.info(u"Start HTTP Server on %s:%s..." % (self.interfaces, self.port))
        # logger
        for log in self.log.handlers:
            admin_app.logger.addHandler(log)
        admin_app.zmq_context = self.zmq
        admin_app.db = DbHelper()
        admin_app.datatypes = self.datatypes
        
	tapp = Application([
		(r"/ws", AdminWebSocket),
                (r".*", FallbackHandler, dict(fallback=WSGIContainer(admin_app)))
	])

	# create the server
        # for ssl, extra parameter to HTTPServier init
        if self.use_ssl is True:
            ssl_options = {
                 "certfile": self.cert_file,
                 "keyfile": self.key_file,
            }
	    self.http_server = HTTPServer(tapp, ssl_options=ssl_options)
        else:
            self.http_server = HTTPServer(tapp)
	# listen on the interfaces
	if self.interfaces != "":
	    intf = self.interfaces.split(',')
	    for ip in get_ip_for_interfaces(intf):
	        self.http_server.listen(int(self.port), address=ip)
        else:
            self.http_server.bind(int(self.port))
            self.http_server.start(1)
        return
예제 #2
0
파일: admin.py 프로젝트: altenide/domogik
    def start_http(self):
        """ Start HTTP Server
        """
        self.log.info(u"Start HTTP Server on %s:%s..." % (self.interfaces, self.port))
        # logger
        for log in self.log.handlers:
            admin_app.logger.addHandler(log)
        admin_app.zmq_context = self.zmq
        admin_app.db = DbHelper()
        admin_app.datatypes = self.datatypes
        
	tapp = Application([
		(r"/ws", AdminWebSocket),
                (r".*", FallbackHandler, dict(fallback=WSGIContainer(admin_app)))
	])

	# create the server
        # for ssl, extra parameter to HTTPServier init
        if self.use_ssl is True:
            ssl_options = {
                 "certfile": self.cert_file,
                 "keyfile": self.key_file,
            }
	    self.http_server = HTTPServer(tapp, ssl_options=ssl_options)
        else:
            self.http_server = HTTPServer(tapp)
	# listen on the interfaces
	if self.interfaces != "":
	    intf = self.interfaces.split(',')
	    for ip in get_ip_for_interfaces(intf):
	        self.http_server.listen(int(self.port), address=ip)
        else:
            self.http_server.bind(int(self.port))
            self.http_server.start(1)
        return
예제 #3
0
def test_user_config_file(user_home, user_entry):
    info("Check user config file contents")
    import ConfigParser
    config = ConfigParser.ConfigParser()
    config.read("/etc/domogik/domogik.cfg")

    #check [domogik] section
    dmg = dict(config.items('domogik'))
    database = dict(config.items('database'))
    admin = dict(config.items('admin'))
    butler = dict(config.items('butler'))
    backup = dict(config.items('backup'))
    ok("Config file correctly loaded")

    info("Parse [domogik] section")
    import domogik

    #Check ix xpl port is not used
    _check_port_availability("0.0.0.0", 3865, udp = True)
    ok("xPL hub IP/port is not bound by anything else")

    parent_conn, child_conn = Pipe()
    p = Process(target=_test_user_can_write, args=(child_conn, dmg['log_dir_path'],user_entry,))
    p.start()
    p.join()
    assert parent_conn.recv(), "The directory %s for log does not exist or does not have right permissions" % dmg['log_dir_path']

    assert dmg['log_level'] in ['debug','info','warning','error','critical'], "The log_level parameter does not have a good value. Must \
            be one of debug,info,warning,error,critical"
    ### obsolete
    #if not os.path.isdir(dmg['src_prefix'] + '/share/domogik'):
    #    try:
    #        f = os.listdir("%s/share/domogik" % dmg['src_prefix'])
    #        f.close()
    #    except OSError:
    #        fail("Can't access %s/share/domogik. Check %s is available for domogik user (if you are in development mode, be sure the directory which contains the sources is available for domogik user)." % (dmg['src_prefix'],dmg['src_prefix']))
    #        exit()
    ok("[domogik] section seems good")

    # check [database] section
    info("Parse [database] section")
    assert database['type'] == 'mysql', "Only mysql database type is supported at the moment"

    uid = user_entry.pw_uid
    os.setreuid(0,uid)
    old_home = os.environ['HOME']
    os.environ['HOME'] = user_home
    from domogik.common.database import DbHelper
    d = DbHelper()
    os.setreuid(0,0)
    os.environ['HOME'] = old_home
    assert d.get_engine() != None, "Engine is not set, it seems something went wrong during connection to the database"

    ok("[database] section seems good")

    # Check [admin] section
    info("Parse [admin] section")
    for ipadd in get_ip_for_interfaces(admin['interfaces'].split(",")):
        _check_port_availability(ipadd, admin['port'])
    ok("Admin server IP/port is not bound by anything else")
예제 #4
0
    def start_http(self):
        """ Start HTTP Server
        """
        self.log.info(u"Start HTTP Server on {0}:{1}...".format(
            self.interfaces, self.port))
        # logger
        for log in self.log.handlers:
            admin_app.logger.addHandler(log)
        admin_app.zmq_context = self.zmq
        admin_app.db = DbHelper()
        admin_app.datatypes = self.datatypes
        admin_app.clean_json = self.clean_json
        admin_app.rest_auth = self.rest_auth
        admin_app.apiversion = REST_API_VERSION
        admin_app.use_ssl = self.use_ssl
        admin_app.interfaces = self.interfaces
        admin_app.port = self.port
        admin_app.hostname = self.get_sanitized_hostname()
        admin_app.resources_directory = self.get_resources_directory()
        admin_app.packages_directory = self.get_packages_directory()
        admin_app.publish_directory = self.get_publish_directory(
        )  # publish directory for all packages

        publisher = Publisher()
        tapp = Application([(r"/ws", Subscription, dict(publisher=publisher)),
                            (r".*", FallbackHandler,
                             dict(fallback=WSGIContainer(admin_app)))])

        # create the server
        # for ssl, extra parameter to HTTPServier init
        if self.use_ssl is True:
            ssl_options = {
                "certfile": self.cert_file,
                "keyfile": self.key_file,
            }
            print(ssl_options)
            self.http_server = HTTPServer(tapp, ssl_options=ssl_options)
        else:
            self.http_server = HTTPServer(tapp)

# listen on the interfaces
        if self.interfaces != "":
            # value can be : lo, eth0, ...
            # or also : '*' to catch all interfaces, whatever they are
            intf = self.interfaces.split(',')
            self.log.info(
                "The admin will be available on the below addresses : ")
            num_int = 0
            for ip in get_ip_for_interfaces(intf, log=self.log):
                self.log.info(" - {0}:{1} [BIND]".format(ip, self.port))
                self.http_server.listen(int(self.port), address=ip)
                num_int += 1
            if num_int == 0:
                self.log.error(
                    "The admin is not configured to use any working network interface! Please check configuration!!!!!!"
                )
        else:
            self.http_server.bind(int(self.port))
            self.http_server.start(0)
        yield [publisher.publishToMQ(), publisher.publishToWS()]
예제 #5
0
파일: helpers.py 프로젝트: Basilic/domogik
def get_rest_url():
    """ Return the REST server url (constructed from the configuration file of the host)
    """
    cfg = Loader('rest')
    config = cfg.load()
    conf = dict(config[1])
    # we return the url related to the first declared interface in domogik.cfg
    intf = conf['interfaces'].split(",")[0]
    ip = get_ip_for_interfaces([intf])[0]
    return "http://{0}:{1}/".format(ip, conf['port'])
예제 #6
0
def get_rest_url():
    """ Return the REST server url (constructed from the configuration file of the host)
    """
    cfg = Loader('rest')
    config = cfg.load()
    conf = dict(config[1])
    # we return the url related to the first declared interface in domogik.cfg
    intf = conf['interfaces'].split(",")[0]
    ip = get_ip_for_interfaces([intf])[0]
    return "http://{0}:{1}/".format(ip, conf['port'])
예제 #7
0
파일: admin.py 프로젝트: domogik/domogik
    def start_http(self):
        """ Start HTTP Server
        """
        self.log.info(u"Start HTTP Server on {0}:{1}...".format(self.interfaces, self.port))
        # logger
        for log in self.log.handlers:
            admin_app.logger.addHandler(log)
        admin_app.zmq_context = self.zmq
        admin_app.db = DbHelper()
        admin_app.datatypes = self.datatypes
        admin_app.clean_json = self.clean_json
        admin_app.rest_auth = self.rest_auth
        admin_app.apiversion = REST_API_VERSION
        admin_app.use_ssl = self.use_ssl
        admin_app.interfaces = self.interfaces
        admin_app.port = self.port
        admin_app.hostname = self.get_sanitized_hostname()
        admin_app.resources_directory = self.get_resources_directory()
        admin_app.packages_directory = self.get_packages_directory()
        admin_app.publish_directory = self.get_publish_directory() # publish directory for all packages
        
        publisher = Publisher()
        tapp = Application([
            (r"/ws", Subscription, dict(publisher=publisher)),
            (r".*", FallbackHandler, dict(fallback=WSGIContainer(admin_app)))
            ])

	# create the server
        # for ssl, extra parameter to HTTPServier init
        if self.use_ssl is True:
            ssl_options = {
                 "certfile": self.cert_file,
                 "keyfile": self.key_file,
            }
            print(ssl_options)
            self.http_server = HTTPServer(tapp, ssl_options=ssl_options)
        else:
            self.http_server = HTTPServer(tapp)
	# listen on the interfaces
        if self.interfaces != "":
            # value can be : lo, eth0, ...
            # or also : '*' to catch all interfaces, whatever they are
            intf = self.interfaces.split(',')
            self.log.info("The admin will be available on the below addresses : ")
            num_int = 0
            for ip in get_ip_for_interfaces(intf, log = self.log):
                self.log.info(" - {0}:{1} [BIND]".format(ip, self.port))
                self.http_server.listen(int(self.port), address=ip)
                num_int += 1
            if num_int == 0:
                self.log.error("The admin is not configured to use any working network interface! Please check configuration!!!!!!")
        else:
            self.http_server.bind(int(self.port))
            self.http_server.start(0)
        yield [publisher.publishToMQ(), publisher.publishToWS()]
예제 #8
0
    def scan(self):
        if self.nm != None:
            while not self._stop.isSet():
                self.log.debug(u"Result of nmap scan: ")
                for int_ip in get_ip_for_interfaces():
                    try:
                        the_ip_tab = int_ip.split(".")
                        if the_ip_tab[0] == "127":
                            continue
                        the_ip = "{0}.{1}.{2}.0".format(
                            the_ip_tab[0], the_ip_tab[1], the_ip_tab[2])
                        result = self.nm.scan(hosts='{0}/24'.format(the_ip),
                                              arguments='-n -sP')
                        for host in result['scan']:
                            status = result['scan'][host]['status']['state']
                            self.log.debug(u"{0} is {1}".format(host, status))
                            try:
                                ipv4 = result['scan'][host]['addresses'][
                                    'ipv4']
                                self.log.debug(u"- ipv4 : {0}".format(ipv4))
                            except KeyError:
                                pass
                            try:
                                vendor = result['scan'][host]['vendor']
                                self.log.debug(
                                    u"- vendor : {0}".format(vendor))
                            except KeyError:
                                pass

                            self.cb_device_detected({
                                "device_type":
                                "ping.ping",
                                "reference":
                                "",
                                "global": [],
                                "xpl": [{
                                    "key": "device",
                                    "value": host
                                }],
                                "xpl_commands": {},
                                "xpl_stats": {}
                            })
                    except KeyError:
                        # surely a nmap error :)
                        # skipping for this turn
                        self.log.warning(u"Nmap : no result for the scan...")
                        pass

                # sleep for 5 minutes
                time.sleep(5 * 60)
예제 #9
0
    def start_http(self):
        """ Start HTTP Server
        """
        self.log.info(u"Start HTTP Server on %s:%s..." %
                      (self.interfaces, self.port))
        # logger
        for log in self.log.handlers:
            urlHandler.logger.addHandler(log)
        # db access
        urlHandler.db = DbHelper()
        # needed for status
        urlHandler.apiversion = self._rest_api_version
        urlHandler.use_ssl = self.use_ssl
        urlHandler.hostname = self.get_sanitized_hostname()
        urlHandler.clean_json = self.clean_json
        urlHandler.zmq_context = self.zmq
        # handler for getting the paths
        urlHandler.resources_directory = self.get_resources_directory()

        # create the server
        # for ssl, extra parameter to HTTPServier init
        if self.use_ssl:
            ssl_options = {
                "certfile": self.cert_file,
                "keyfile": self.key_file,
            }
            self.http_server = HTTPServer(WSGIContainer(urlHandler),
                                          ssl_options=ssl_options)
        else:
            self.http_server = HTTPServer(WSGIContainer(urlHandler))

# listen on the interfaces
        if self.interfaces != "":
            intf = self.interfaces.split(',')
            self.log.info(
                "REST server will be available on the below addresses : ")
            num_int = 0
            for ip in get_ip_for_interfaces(intf, log=self.log):
                self.log.info(" - {0}:{1} [BIND]".format(ip, self.port))
                self.http_server.listen(int(self.port), address=ip)
                num_int += 1
            if num_int == 0:
                self.log.error(
                    "The rest server is not configured to use any working network interface! Please check configuration!!!!!!"
                )
        else:
            self.http_server.bind(int(self.port))
            self.http_server.start(1)
        return
예제 #10
0
 def scan(self):
     if self.nm != None:
         while not self._stop.isSet():
             self.log.debug(u"Result of nmap scan: ")
             for int_ip in get_ip_for_interfaces():
                 try:
                     the_ip_tab = int_ip.split(".")
                     if the_ip_tab[0] == "127":
                         continue
                     the_ip = "{0}.{1}.{2}.0".format(the_ip_tab[0], the_ip_tab[1], the_ip_tab[2])
                     result = self.nm.scan(hosts='{0}/24'.format(the_ip), arguments='-n -sP')
                     for host in result['scan']:
                         status = result['scan'][host]['status']['state']
                         self.log.debug(u"{0} is {1}".format(host, status))
                         try:
                             ipv4 = result['scan'][host]['addresses']['ipv4']
                             self.log.debug(u"- ipv4 : {0}".format(ipv4))
                         except KeyError:
                             pass
                         try:
                             vendor = result['scan'][host]['vendor']
                             self.log.debug(u"- vendor : {0}".format(vendor))
                         except KeyError:
                             pass
 
                         self.cb_device_detected({
                             "device_type" : "ping.ping",
                             "reference" : "",
                             "global" : [],
                             "xpl" : [
                                 {
                                     "key" : "device",
                                     "value" : host
                                 }
                             ],
                             "xpl_commands" : {},
                             "xpl_stats" : {}
                         })
                 except KeyError:
                     # surely a nmap error :)
                     # skipping for this turn
                     self.log.warning(u"Nmap : no result for the scan...")
                     pass
 
             # sleep for 5 minutes
             time.sleep(5 * 60)
예제 #11
0
파일: rest.py 프로젝트: Nico0084/domogik
    def start_http(self):
        """ Start HTTP Server
        """
        self.log.info(u"Start HTTP Server on %s:%s..." % (self.interfaces, self.port))
        # logger
        for log in self.log.handlers:
            urlHandler.logger.addHandler(log)
        # db access
        urlHandler.db = DbHelper()
        # needed for status
        urlHandler.apiversion = self._rest_api_version
        urlHandler.use_ssl = self.use_ssl
        urlHandler.hostname = self.get_sanitized_hostname()
        urlHandler.clean_json = self.clean_json
        urlHandler.zmq_context = self.zmq
        # handler for getting the paths
        urlHandler.resources_directory = self.get_resources_directory()
        
	# create the server
        # for ssl, extra parameter to HTTPServier init
        if self.use_ssl:
            ssl_options = {
                 "certfile": self.cert_file,
                 "keyfile": self.key_file,
            }
	    self.http_server = HTTPServer(WSGIContainer(urlHandler), ssl_options=ssl_options)
        else:
            self.http_server = HTTPServer(WSGIContainer(urlHandler))
	# listen on the interfaces
	if self.interfaces != "":
	    intf = self.interfaces.split(',')
            self.log.info("REST server will be available on the below addresses : ")
            num_int = 0
	    for ip in get_ip_for_interfaces(intf, log = self.log):
                self.log.info(" - {0}:{1} [BIND]".format(ip, self.port))
	        self.http_server.listen(int(self.port), address=ip)
                num_int += 1
            if num_int == 0:
                self.log.error("The rest server is not configured to use any working network interface! Please check configuration!!!!!!")
        else:
            self.http_server.bind(int(self.port))
            self.http_server.start(1)
        return
예제 #12
0
파일: admin.py 프로젝트: Nico0084/domogik
    def start_http(self):
        """ Start HTTP Server
        """
        self.log.info(u"Start HTTP Server on %s:%s..." % (self.interfaces, self.port))
        # logger
        for log in self.log.handlers:
            admin_app.logger.addHandler(log)
        admin_app.zmq_context = self.zmq
        admin_app.db = DbHelper()
        admin_app.datatypes = self.datatypes
        
	tapp = Application([
		(r"/ws", AdminWebSocket),
        (r".*", FallbackHandler, dict(fallback=WSGIContainer(admin_app)))
	])

	# create the server
        # for ssl, extra parameter to HTTPServier init
        if self.use_ssl is True:
            ssl_options = {
                 "certfile": self.cert_file,
                 "keyfile": self.key_file,
            }
	    self.http_server = HTTPServer(tapp, ssl_options=ssl_options)
        else:
            self.http_server = HTTPServer(tapp)
	# listen on the interfaces
	if self.interfaces != "":
            # value can be : lo, eth0, ...
            # or also : '*' to catch all interfaces, whatever they are
	    intf = self.interfaces.split(',')
            self.log.info("The admin will be available on the below addresses : ")
            num_int = 0
	    for ip in get_ip_for_interfaces(intf, log = self.log):
                self.log.info(" - {0}:{1} [BIND]".format(ip, self.port))
	        self.http_server.listen(int(self.port), address=ip)
                num_int += 1
            if num_int == 0:
                self.log.error("The admin is not configured to use any working network interface! Please check configuration!!!!!!")
        else:
            self.http_server.bind(int(self.port))
            self.http_server.start(1)
        return
예제 #13
0
def rest():

    cfg = Loader('rest')
    config = cfg.load()
    conf = dict(config[1])
    ### get REST ip and port
    port = conf['port']                          
    interfaces = conf['interfaces']                          
    intf = interfaces.split(',')
    print intf
    # get the first ip of the first interface declared
    ip = get_ip_for_interfaces(intf)[0]


    r = requests.get("http://{0}:{1}/map".format(ip, port))

    return render_template('rest.html',
        mactive="rest",
        urls = r.json(),
        )
예제 #14
0
    def start_http(self):
        """ Start HTTP Server
        """
        self.log.info(u"Start HTTP Server on %s:%s..." % (self.interfaces, self.port))
        # logger
        for log in self.log.handlers:
            urlHandler.logger.addHandler(log)
        # db access
        urlHandler.db = DbHelper()
        # needed for status
        urlHandler.apiversion = self._rest_api_version
        urlHandler.use_ssl = self.use_ssl
        urlHandler.hostname = self.get_sanitized_hostname()
        urlHandler.clean_json = self.clean_json
        # reload statsmanager helper
        urlHandler.reload_stats = self.reload_stats
        urlHandler.zmq_context = self.zmq
        # handler for getting the paths
        urlHandler.resources_directory = self.get_resources_directory()
        
	# create the server
        # for ssl, extra parameter to HTTPServier init
        if self.use_ssl:
            ssl_options = {
                 "certfile": self.cert_file,
                 "keyfile": self.key_file,
            }
	    self.http_server = HTTPServer(WSGIContainer(urlHandler), ssl_options=ssl_options)
        else:
            self.http_server = HTTPServer(WSGIContainer(urlHandler))
	# listen on the interfaces
	if self.interfaces != "":
	    intf = self.interfaces.split(',')
	    for ip in get_ip_for_interfaces(intf):
	        self.http_server.listen(int(self.port), address=ip)
        else:
            self.http_server.bind(int(self.port))
            self.http_server.start(1)
        return
예제 #15
0
def test_user_config_file(user_home, user_entry):
    info("Check user config file contents")
    import ConfigParser
    config = ConfigParser.ConfigParser()
    config.read("/etc/domogik/domogik.cfg")

    #check [domogik] section
    dmg = dict(config.items('domogik'))
    database = dict(config.items('database'))
    rest = dict(config.items('rest'))
    ok("Config file correctly loaded")

    info("Parse [domogik] section")
    import domogik

    #Check ix xpl port is not used
    _check_port_availability("0.0.0.0", 3865, udp=True)
    ok("xPL hub IP/port is not bound by anything else")

    parent_conn, child_conn = Pipe()
    p = Process(target=_test_user_can_write,
                args=(
                    child_conn,
                    dmg['log_dir_path'],
                    user_entry,
                ))
    p.start()
    p.join()
    assert parent_conn.recv(
    ), "The directory %s for log does not exist or does not have right permissions" % dmg[
        'log_dir_path']

    assert dmg['log_level'] in [
        'debug', 'info', 'warning', 'error', 'critical'
    ], "The log_level parameter does not have a good value. Must \
            be one of debug,info,warning,error,critical"

    ### obsolete
    #if not os.path.isdir(dmg['src_prefix'] + '/share/domogik'):
    #    try:
    #        f = os.listdir("%s/share/domogik" % dmg['src_prefix'])
    #        f.close()
    #    except OSError:
    #        fail("Can't access %s/share/domogik. Check %s is available for domogik user (if you are in development mode, be sure the directory which contains the sources is available for domogik user)." % (dmg['src_prefix'],dmg['src_prefix']))
    #        exit()
    ok("[domogik] section seems good")

    # check [database] section
    info("Parse [database] section")
    assert database[
        'type'] == 'mysql', "Only mysql database type is supported at the moment"

    uid = user_entry.pw_uid
    os.setreuid(0, uid)
    old_home = os.environ['HOME']
    os.environ['HOME'] = user_home
    from domogik.common.database import DbHelper
    d = DbHelper()
    os.setreuid(0, 0)
    os.environ['HOME'] = old_home
    assert d.get_engine(
    ) != None, "Engine is not set, it seems something went wrong during connection to the database"

    ok("[database] section seems good")

    # Check [rest] section
    info("Parse [rest] section")
    for ipadd in get_ip_for_interfaces(rest['interfaces'].split(",")):
        _check_port_availability(ipadd, rest['port'])
    ok("Rest server IP/port is not bound by anything else")
예제 #16
0
    def __init__(self, interfaces_list=None, port=0, broadcast="255.255.255.255", plugin = None, nohub = False, source = None):
        """
        Create a new manager instance
        @param interfaces_list : interfaces to listen to (default real ip address)
        @param port : port to listen to (default 0)
        @param plugin : The plugin associated with this xpl instance
        @param nohub : Don't start the hub discovery
        """
        if interfaces_list == None:
            interfaces_list = '*'  # all interfaces

        self.p = plugin
        if source == None:
            source = "domogik-%s.%s" % (self.p.get_plugin_name(), self.p.get_sanitized_hostname())
        # Define maximum xPL message size
        self._buff = 1500
        # Define xPL base port
        self._source = source
        self._listeners = []
        #Not really usefull
        #self.port = port
        # Initialise the socket
        self._UDPSock = socket(AF_INET, SOCK_DGRAM)
        #Set broadcast flag
        self._UDPSock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
        self._broadcast = broadcast

        #xPL plugins only needs to connect on local xPL Hub on localhost
        addr_list = []
        intf = interfaces_list.split(',')
        self.p.log.info("Configured interface(s) : {0}".format(intf))
        self.p.log.info("The xpl connection may be done on the below addresses (only one will be used): ")
        num_int = 0
        for ip in get_ip_for_interfaces(intf, log = self.p.log):
            self.p.log.info(" - {0}:{1}".format(ip, port))
            addr_list.append((ip, port))
            num_int += 1
        if num_int == 0:
            self.p.log.error("The xpl plugin is not configured to use any working network interface! Please check configuration!!!!!!")
        # if there is more than one interface available, skip lo and take the first one in the list
        if len(addr_list) > 1:
            for addr in addr_list:
                if addr[0].split(".")[0] == "127":
                    self.p.log.info("Several interfaces available : skipping 'lo'")
                    continue
                else:
                    self.p.log.info("One interface selected : ip = {0}".format(addr[0]))
                    self.p.log.info("Skipping the other ones. The full list was : {0}".format(addr_list))
                    break
        else:
            addr = addr_list[0]

        #UID for the fragment management
        self._fragment_uid = 1
        self._sent_fragments_buffer = {}
        self._received_fragments_buffer = {}

        #Define locks
        self._lock_send = threading.Semaphore()
        self._lock_list = threading.Semaphore()

        # plugin status
        # 0 = strating (xpl hub discovery)
        # 1 = config (xpl config phase)
        # 2 = running (plugin ready for receiving xpl commands)
        self._status = 0
        # status (starting, config, started)
        self._lock_status = threading.Semaphore()

        # hbeat detected
        self._foundhub = threading.Event()
        self._nohub_mandatory = nohub
        if nohub == True:
            self._foundhub.set()
        else:
            self._foundhub.clear()

        try:
            self.p.log.info("Binding to {0} [BIND]...".format(addr))
            self._UDPSock.bind(addr)
        except:
            # Something is already running on this port
            self.p.log.error("Can't bind to the interface {0}, port {1}. Error is : {2}".format(ip, port, traceback.format_exc()))
            exit(1)
        else:
            self.p.add_stop_cb(self.leave)
            self.port = self._UDPSock.getsockname()[1]
            #Get the port number assigned by the system
            self._ip, self._port = self._UDPSock.getsockname()
            self.p.log.debug("xPL plugin %s socket bound to %s, port %s" \
                            % (self.p.get_plugin_name(), self._ip, self._port))
            self._h_timer = None

      
            if self._nohub_mandatory == True:
                # no xPL hub is requested for the plugin to start by the developper
                # This means that we don't search for a xPL hub...
                # but as we are in a xPL plugin, we still send a hbeat each 5 minutes to
                # be seen by a hub, if there is a hub :)
                self.p.log.info("Plugin configure to have the xPL hub as optionnal! The hub won't be searched but a hbeat message will be sent each 5 minutes")
                self._SendHeartbeat()
                self._h_timer = XplTimer(60 * STATUS_HBEAT_XPL, self._SendHeartbeat, self)
                self._h_timer.start()

            else:
                # a xPL hub is requested for the plugin to start by the developper
                # This means that if we don't find a xPL hub, the plugin will not start !
                self.p.log.info("Plugin configure to have the xPL hub as mandatory!")
                msg = "HUB discovery > starting"
                self.p.log.info(msg)
    
                self._SendHeartbeat()

            #And finally we start network listener in a thread
            self._stop_thread = False
            self._network = threading.Thread(None, self._run_thread_monitor,
                    "thread-monitor", (), {})
            self.p.register_thread(self._network)
            self._network.start()
            self.p.log.debug("xPL thread started for %s " % self.p.get_plugin_name())

        # start hbeat discovery
        self.hub_discovery()
        self._foundhub.wait()
예제 #17
0
    def __init__(self,
                 interfaces_list=None,
                 port=0,
                 broadcast="255.255.255.255",
                 plugin=None,
                 nohub=False,
                 source=None):
        """
        Create a new manager instance
        @param interfaces_list : interfaces to listen to (default real ip address)
        @param port : port to listen to (default 0)
        @param plugin : The plugin associated with this xpl instance
        @param nohub : Don't start the hub discovery
        """
        if interfaces_list == None:
            interfaces_list = '*'  # all interfaces

        self.p = plugin
        if source == None:
            source = "domogik-%s.%s" % (self.p.get_plugin_name(),
                                        self.p.get_sanitized_hostname())
        # Define maximum xPL message size
        self._buff = 1500
        # Define xPL base port
        self._source = source
        self._listeners = []
        #Not really usefull
        #self.port = port
        # Initialise the socket
        self._UDPSock = socket(AF_INET, SOCK_DGRAM)
        #Set broadcast flag
        self._UDPSock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
        self._broadcast = broadcast

        #xPL plugins only needs to connect on local xPL Hub on localhost
        addr_list = []
        intf = interfaces_list.split(',')
        self.p.log.info("Configured interface(s) : {0}".format(intf))
        self.p.log.info(
            "The xpl connection may be done on the below addresses (only one will be used): "
        )
        num_int = 0
        for ip in get_ip_for_interfaces(intf, log=self.p.log):
            self.p.log.info(" - {0}:{1}".format(ip, port))
            addr_list.append((ip, port))
            num_int += 1
        if num_int == 0:
            self.p.log.error(
                "The xpl plugin is not configured to use any working network interface! Please check configuration!!!!!!"
            )
        # if there is more than one interface available, skip lo and take the first one in the list
        if len(addr_list) > 1:
            for addr in addr_list:
                if addr[0].split(".")[0] == "127":
                    self.p.log.info(
                        "Several interfaces available : skipping 'lo'")
                    continue
                else:
                    self.p.log.info("One interface selected : ip = {0}".format(
                        addr[0]))
                    self.p.log.info(
                        "Skipping the other ones. The full list was : {0}".
                        format(addr_list))
                    break
        else:
            addr = addr_list[0]

        #UID for the fragment management
        self._fragment_uid = 1
        self._sent_fragments_buffer = {}
        self._received_fragments_buffer = {}

        #Define locks
        self._lock_send = threading.Semaphore()
        self._lock_list = threading.Semaphore()

        # plugin status
        # 0 = strating (xpl hub discovery)
        # 1 = config (xpl config phase)
        # 2 = running (plugin ready for receiving xpl commands)
        self._status = 0
        # status (starting, config, started)
        self._lock_status = threading.Semaphore()

        # hbeat detected
        self._foundhub = threading.Event()
        self._nohub_mandatory = nohub
        if nohub == True:
            self._foundhub.set()
        else:
            self._foundhub.clear()

        try:
            self.p.log.info("Binding to {0} [BIND]...".format(addr))
            self._UDPSock.bind(addr)
        except:
            # Something is already running on this port
            self.p.log.error(
                "Can't bind to the interface {0}, port {1}. Error is : {2}".
                format(ip, port, traceback.format_exc()))
            exit(1)
        else:
            self.p.add_stop_cb(self.leave)
            self.port = self._UDPSock.getsockname()[1]
            #Get the port number assigned by the system
            self._ip, self._port = self._UDPSock.getsockname()
            self.p.log.debug("xPL plugin %s socket bound to %s, port %s" \
                            % (self.p.get_plugin_name(), self._ip, self._port))
            self._h_timer = None

            if self._nohub_mandatory == True:
                # no xPL hub is requested for the plugin to start by the developper
                # This means that we don't search for a xPL hub...
                # but as we are in a xPL plugin, we still send a hbeat each 5 minutes to
                # be seen by a hub, if there is a hub :)
                self.p.log.info(
                    "Plugin configure to have the xPL hub as optionnal! The hub won't be searched but a hbeat message will be sent each 5 minutes"
                )
                self._SendHeartbeat()
                self._h_timer = XplTimer(60 * STATUS_HBEAT_XPL,
                                         self._SendHeartbeat, self)
                self._h_timer.start()

            else:
                # a xPL hub is requested for the plugin to start by the developper
                # This means that if we don't find a xPL hub, the plugin will not start !
                self.p.log.info(
                    "Plugin configure to have the xPL hub as mandatory!")
                msg = "HUB discovery > starting"
                self.p.log.info(msg)

                self._SendHeartbeat()

            #And finally we start network listener in a thread
            self._stop_thread = False
            self._network = threading.Thread(None, self._run_thread_monitor,
                                             "thread-monitor", (), {})
            self.p.register_thread(self._network)
            self._network.start()
            self.p.log.debug("xPL thread started for %s " %
                             self.p.get_plugin_name())

        # start hbeat discovery
        self.hub_discovery()
        self._foundhub.wait()