Coverage for janitoo.threads.http : 37%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# -*- coding: utf-8 -*-
Server files using the http protocol
"""
This file is part of Janitoo.
Janitoo is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
Janitoo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with Janitoo. If not, see <http://www.gnu.org/licenses/>.
"""
############################################################## #Check that we are in sync with the official command classes #Must be implemented for non-regression
##############################################################
return HttpThread(options) else:
return HttpResourceComponent(**kwargs)
""" """ logger.debug("[%s] - Request page for %s", self.__class__.__name__, path) logger.debug("[%s] - Serve files from %s", self.__class__.__name__, self.server.root_directory + path) return SimpleHTTPRequestHandler.translate_path(self, self.server.root_directory + path)
"""Handle requests in a separate thread.""" HTTPServer.__init__(self, server_address, RequestHandlerClass) self.root_directory = root_directory
"""The Rdd cache thread
Implement a cache.
""" """Initialise the cache thread
Manage a cache for the rrd.
A timer in a separated thread will pickle the cache to disk every 30 seconds.
An other thread will update the rrd every hours
:param options: The options used to start the worker. :type clientid: str """ self.section = section BaseThread.__init__(self, options=options) self.host = "localhost" self.port = 8081 self._server = None
""" """ if host is not None: self.host = host if port is not None: self.port = port
"""Launch before entering the run loop. The node manager is available. """ dirname='.' if 'home_dir' in self.options.data and self.options.data['home_dir'] is not None: dirname = self.options.data['home_dir'] dirname = os.path.join(dirname, 'public') os.makedirs(dirname) #~ os.chdir(dirname) if dirname.endswith("/"): dirname = dirname[:-1] logger.debug("[%s] - dirname %s", self.__class__.__name__, dirname) self._server = ThreadedHTTPServer((self.host, self.port), ThreadedHTTPHandler, root_directory=dirname)
"""Launch after finishing the run loop. The node manager is still available. """ pass
"""Launch after finishing the run loop. The node manager is still available. """ self._server.serve_forever()
"""Called when configuration is finished. """ BaseThread.config_timeout_callback(self) if self._server is not None: self._server.shutdown() self._server = None
"""Stop the thread """ BaseThread.stop(self) self._server.shutdown() self._server = None
"""Run the loop """ self._stopevent.clear() #~ self.boot() self.trigger_reload() logger.debug("[%s] - Wait for the thread reload event for initial startup", self.__class__.__name__) while not self._reloadevent.isSet() and not self._stopevent.isSet(): self._reloadevent.wait(0.50) logger.debug("[%s] - Entering the thread loop", self.__class__.__name__) while not self._stopevent.isSet(): self._reloadevent.clear() self.pre_loop() except: logger.exception('[%s] - Exception in pre_loop', self.__class__.__name__) self._stopevent.set() while not self._reloadevent.isSet() and not self._stopevent.isSet(): self.loop() try: self.post_loop() except: logger.exception('[%s] - Exception in post_loop', self.__class__.__name__)
"""A pseudo-bus to manage RRDTools """ """ :param int bus_id: the SMBus id (see Raspberry Pi documentation) :param kwargs: parameters transmitted to :py:class:`smbus.SMBus` initializer """ JNTBus.__init__(self, **kwargs) self._lock = threading.Lock() self._server = None if 'home_dir' in self.options.data and self.options.data['home_dir'] is not None: directory = os.path.join(dirname, 'public')
uuid="host" self.values[uuid] = self.value_factory['config_string'](options=self.options, uuid=uuid, node_uuid=self.uuid, help='The host or IP to use for the server', label='Host', default='localhost', )
uuid="port" self.values[uuid] = self.value_factory['config_integer'](options=self.options, uuid=uuid, node_uuid=self.uuid, help='The port', label='Port', default=8081, )
uuid="actions" self.values[uuid] = self.value_factory['action_list'](options=self.options, uuid=uuid, node_uuid=self.uuid, help='The action on the HTTP server', label='Actions', list_items=['start', 'stop', 'reload'], set_data_cb=self.set_action, is_writeonly = True, cmd_class=COMMAND_WEB_CONTROLLER, genre=0x01, )
"""Return the resource path
""" return "%s:%s/%%s" % (self.values["host"].data, self.values["port"].data)
"""Check that the component is 'available'
""" #~ print "it's me %s : %s" % (self.values['upsname'].data, self._ups_stats_last) if self._server is not None: return False
"""Act on the server """ if data == "start": if self.mqttc is not None: self.start(self.mqttc) elif data == "stop": self.stop() elif data == "reload": if self._server is not None: self._server.trigger_reload()
JNTBus.start(self, mqttc, trigger_thread_reload_cb) self._server = HttpServerThread("http_server", self.options.data) self._server.config(host=self.values["host"].data, port=self.values["port"].data) self._server.start()
if self._server is not None: self._server.stop() self._server = None JNTBus.stop(self)
""" A resource ie /rrd """
""" """ name = kwargs.pop('name', "HTTP resource") product_name = kwargs.pop('product_name', "HTTP resource") product_type = kwargs.pop('product_type', "Software") product_manufacturer = kwargs.pop('product_manufacturer', "Janitoo") product_name=product_name, product_type=product_type, product_manufacturer="Janitoo", **kwargs) self.path = path if 'home_dir' in self.options.data and self.options.data['home_dir'] is not None: dirname = self.options.data['home_dir'] dirname = os.path.join(dirname, "public") dirname = os.path.join(dirname, self.path) self.deploy_resource(dirname)
"""Start the component.
""" JNTComponent.start(self, mqttc) return True
"""Stop the component.
""" JNTComponent.stop(self)
""" """ pass
"""Check that the component is 'available'
""" dirname='.' if 'home_dir' in self.options.data and self.options.data['home_dir'] is not None: dirname = self.options.data['home_dir'] return os.path.exists(dirname)
""" A resource ie /rrd """
""" """ oid = kwargs.pop('oid', 'http.basic') product_name = kwargs.pop('product_name', "HTTP basic resource") name = kwargs.pop('name', "Http basic resource") HttpResourceComponent.__init__(self, path, oid=oid, bus=bus, addr=addr, name=name, product_name=product_name, **kwargs) uuid="resource" node_uuid=self.uuid, help='The http resource: host:port', label='Resource', get_data_cb=self.get_resource, genre=0x01, cmd_class=COMMAND_WEB_RESOURCE, ) #~ config_value = self.values[uuid].create_config_value(help='The resource path', label='resource', type=0x08) #~ self.values[config_value.uuid] = config_value poll_value = self.values[uuid].create_poll_value(default=1800) self.values[poll_value.uuid] = poll_value
""" """ #~ print self._bus.get_resource_path() % self.path return self._bus.get_resource_path() % '%s/' % self.path
""" """ for subdir in DEPLOY_DIRS: try: source = os.path.join(self.resource_filename('public'), self.path, subdir) if os.path.isdir(source): if not os.path.exists(os.path.join(destination,subdir)): os.makedirs(os.path.join(destination,subdir)) copy_tree(source, os.path.join(destination,subdir), preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0) except: try: source = os.path.join(self.resource_filename('public'), "html") logger.debug('[%s] - public html source = %s', self.__class__.__name__, source) if os.path.isdir(source): src_files = os.listdir(source) for file_name in src_files: try: full_file_name = os.path.join(source, file_name) if (os.path.isfile(full_file_name)): shutil.copy(full_file_name, destination) except: logger.exception('[%s] - Exception in deploy_resource', self.__class__.__name__) except: logger.exception('[%s] - Exception in deploy_resource', self.__class__.__name__)
""" A resource ie /rrd """
""" """ oid = kwargs.pop('oid', 'http.doc') product_name = kwargs.pop('product_name', "HTTP documentation resource") name = kwargs.pop('name', "Http documentation resource") HttpResourceComponent.__init__(self, path=os.path.join('doc',path), oid=oid, bus=bus, addr=addr, name=name, product_name=product_name, **kwargs) uuid="key" node_uuid=self.uuid, help='The key of documentation (ie controller.audiovideo.installation, node.audiovideo.samsung_ue46, ...))', label='Key doc.', get_data_cb=self.get_key, is_readonly=True, genre=0x01, cmd_class=COMMAND_DOC_RESOURCE, ) self.configs_instances = self.values[uuid].instances #~ print self.configs_instances poll_value = self.values[uuid].create_poll_value(default=1800) self.values[poll_value.uuid] = poll_value uuid="resource" self.values[uuid] = self.value_factory['sensor_string'](options=self.options, uuid=uuid, node_uuid=self.uuid, help='The http documentation : host:port/path', label='Documentation', get_data_cb=self.get_resource, genre=0x01, cmd_class=COMMAND_WEB_RESOURCE, ) config_value = self.values[uuid].create_config_value(help='The resource path', label='resource', type=0x08) self.values[config_value.uuid] = config_value self.values[config_value.uuid].instances = self.configs_instances poll_value = self.values[uuid].create_poll_value(default=1800) self.values[poll_value.uuid] = poll_value
""" """ try: source = self.resource_filename('docs') logger.debug('[%s] - doc source = %s', self.__class__.__name__, source) if os.path.isdir(source): #~ if os.path.isfile(source): copy_tree(source, destination, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0) except: logger.exception('[%s] - Exception in deploy_resource', self.__class__.__name__)
""" """ pass
""" """ #~ print self._bus.get_resource_path() % self.path pass
"""The Http thread
""" """Build the bus """ self.section = 'http' self.bus = HttpBus(options=self.options, oid=self.section, product_name="Http server") |