def start_httpd(broker, client): securityObject = security.Security() cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS) cherrypy.tree.mount(CommandsApi(broker, securityObject), '/commands', conf) server = Server() server.socket_port = config.HTTPD_PUBLIC_PORT server.socket_host = '0.0.0.0' server.subscribe() cherrypy.config.update({'server.socket_host': '0.0.0.0'}) cherrypy.tree.mount(ClientsApi(securityObject), '/clients', conf) cherrypy.engine.start() cherrypy.engine.block()
def main(argv=None): if not argv: argv = sys.argv if len(argv) < 2: usage(argv) load_dotenv_vars() env = Env() config_uri = argv[1] wsgi_app = get_app(config_uri) setup_logging(config_uri) import cherrypy cherrypy.tree.graft(wsgi_app, '/') cherrypy.server.unsubscribe() from cherrypy._cpserver import Server server = Server() server.socket_host = env.host server.socket_port = env.port server.thread_pool = 10 server.subscribe() cherrypy.engine.start() cherrypy.engine.block()
def __init__(self, normalizer, svc_cfg): self.logger = c.logger cherrypy.config.update('{0}/{1}'.format(os.getcwd(), c.SVC_WEBHOOK_CONF)) for module in c.conf.SERVICES.Webhook.Modules: handler = getattr(sys.modules[__name__], module + 'WebHookHandler') cherrypy.tree.mount(handler(normalizer=normalizer, svc_cfg=svc_cfg), script_name='/' + module.lower(), config='{0}/{1}'.format(os.getcwd(), '{0}{1}{2}'.format(c.SVC_WEBHOOK_PATH, module.lower(), '.conf'))) self._webhook_server = Server() self._webhook_server.socket_host = c.conf.SERVICES.Webhook.ServiceBindAddress self._webhook_server.socket_port = c.conf.SERVICES.Webhook.ServiceListenPort self._webhook_server.subscribe() self.logger.info(Tools.create_log_msg(logmsg.WEBHOOK_SERVICE, None, logmsg.WEBHOOK_LISTEN.format(self._webhook_server.socket_host, self._webhook_server.socket_port))) cherrypy.engine.start() cherrypy.engine.block()
def __init__(self, source_plugin, plugin_cfg): self.logger = c.logger self._phs_server = Server() self._phs_server.socket_host = c.conf.SERVICES.Phs.ServiceBindAddress self._phs_server.socket_port = c.conf.SERVICES.Phs.ServiceListenPort self.device_type = None self.service_chain = None self.deviceIP = None self.sn_nr = None if c.conf.SERVICES.Phs.EnableSSL: self.logger.info( Tools.create_log_msg(logmsg.PHS_SERVICE, None, logmsg.PHS_SSL_ENABLED)) self._phs_server.ssl_module = 'builtin' if os.path.isfile(c.conf.SERVICES.Phs.SSLCertificate): self._phs_server.ssl_certificate = c.conf.SERVICES.Phs.SSLCertificate else: self.logger.info( Tools.create_log_msg(logmsg.PHS_SERVICE, None, logmsg.PHS_SSL_NO_CERT)) if os.path.isfile(c.conf.SERVICES.Phs.SSLPrivateKey): self._phs_server.ssl_private_key = c.conf.SERVICES.Phs.SSLPrivateKey else: self.logger.info( Tools.create_log_msg(logmsg.PHS_SERVICE, None, logmsg.PHS_SSL_NO_KEY)) self._phs_server.subscribe() self._source_plugin = source_plugin self._plugin_cfg = plugin_cfg self.logger.info( Tools.create_log_msg( logmsg.PHS_SERVICE, None, logmsg.PHS_LISTEN.format(self._phs_server.socket_host, self._phs_server.socket_port)))
def __init__(self): self._host = c.conf.YAPT.WebUiAddress self._port = int(c.conf.YAPT.OobaUiPort) self._current_dir = os.path.dirname(os.path.abspath(__file__)) yapt_rest_server = Server() yapt_rest_server.socket_host = self._host yapt_rest_server.socket_port = self._port yapt_rest_server.subscribe()
def run(): config = { 'server.socket_host': '0.0.0.0', 'server.socket_port': app.config['PORT'], 'engine.autoreload.on': app.config['AUTO_RELOAD'], 'log.screen': app.config['DEBUG'], 'log.error_file': os.path.join(app.config['LOGS_DIR'], 'error.log') } cherrypy.config.update(config) cherrypy.tree.graft(app, '/') https_server = Server() https_server.socket_host = '0.0.0.0' https_server.socket_port = app.config['PORT_SECURE'] https_server.ssl_module = 'pyopenssl' https_server.ssl_certificate = app.config['SSL_PATH']['crt'] https_server.ssl_private_key = app.config['SSL_PATH']['key'] https_server.subscribe() cherrypy.engine.start() cherrypy.engine.block()
def __init__(self): self._host = c.conf.YAPT.WebUiAddress self._port = int(c.conf.YAPT.WebUiPort) self._scheme = 'ws' Plugin(cherrypy.engine).subscribe() AMQP(cherrypy.engine).subscribe() cherrypy.tools.websocket = WebSocketTool() yapt_server = Server() yapt_server.socket_host = self._host yapt_server.socket_port = self._port yapt_server.max_request_body_size = 838860800 yapt_server.subscribe()
def _get_root_start(): # # Set up path to db file db_path = os.path.abspath(os.path.join(os.curdir, rasp_settings.db_file)) rasphome.database.set_db_path('sqlite:///%s' % db_path) # # Set up Admin User name and Default admin user # noinspection PyArgumentList create_init_db() # # Set up Sqlalchemy Plugin and Tool rasphome.database.SAEnginePlugin(cherrypy.engine).subscribe() cherrypy.tools.db = rasphome.database.SATool() # # Activate additional SSL Server from cherrypy._cpserver import Server server = Server() server.socket_host = '0.0.0.0' server.socket_port = rasp_settings.https_port server.ssl_certificate = './cert.pem' server.ssl_private_key = './privatekey.pem' server.subscribe() # # Do other config config = { 'global' : { 'server.socket_host' : '0.0.0.0', 'server.socket_port' : rasp_settings.http_port }, '/' : { 'tools.auth_basic.on': True, 'tools.auth_basic.realm': 'earth', 'tools.auth_basic.checkpassword': rasphome.authorization.checkpassword(), 'tools.db.on' : True, 'request.dispatch': cherrypy.dispatch.MethodDispatcher() } } # # Set up Api root = rasphome.api.Root() root.backend = rasphome.api.Backend_api() root.monitor = rasphome.api.Monitor_api() root.node = rasphome.api.Node_api() root.room = rasphome.api.Room_api() root.user = rasphome.api.User_api() setUpLogger() return root, config
def __init__(self): _backendp = BackendClientProcessor( exchange='', routing_key=c.AMQP_RPC_BACKEND_QUEUE) self._setattr_url_map(args=_backendp) _host = c.conf.YAPT.WebUiAddress _port = int(c.conf.YAPT.RestApiPort) yapt_rest_server = Server() yapt_rest_server.socket_host = _host yapt_rest_server.socket_port = _port yapt_rest_server.subscribe() cherrypy.tools.cors_tool = cherrypy.Tool('before_request_body', cors_tool, name='cors_tool', priority=50)
def __init__(self, sh, port=None, threads=8, ip='', updates_allowed='True', user="******", password="", hashed_password="", language="", developer_mode="no", pypi_timeout=5): self.logger = logging.getLogger(__name__) self._user = user self._password = password self._hashed_password = hashed_password if self._password is not None and self._password != "" and self._hashed_password is not None and self._hashed_password != "": self.logger.warning("BackendServer: Both 'password' and 'hashed_password' given. Ignoring 'password' and using 'hashed_password'!") self._password = None if self._password is not None and self._password != "" and (self._hashed_password is None or self._hashed_password == ""): self.logger.warning("BackendServer: Giving plaintext password in configuration is insecure. Consider using 'hashed_password' instead!") self._hashed_password = None if (self._password is not None and self._password != "") or (self._hashed_password is not None and self._hashed_password != ""): self._basic_auth = True else: self._basic_auth = False self._sh = sh if self.is_int(port): self.port = int(port) else: self.port = 8383 if port is not None: self.logger.error("BackendServer: Invalid value '"+str(port)+"' configured for attribute 'port' in plugin.conf, using '"+str(self.port)+"' instead") if self.is_int(threads): self.threads = int(threads) else: self.threads = 8 self.logger.error("BackendServer: Invalid value '"+str(threads)+"' configured for attribute 'thread' in plugin.conf, using '"+str(self.threads)+"' instead") if ip == '': ip = self.get_local_ip_address() self.logger.debug("BackendServer: Using local ip address '{0}'".format(ip)) else: pass # if not self.is_ip(ip): # self.logger.error("BackendServer: Invalid value '"+str(ip)+"' configured for attribute ip in plugin.conf, using '"+str('0.0.0.0')+"' instead") # ip = '0.0.0.0' language = language.lower() if language != '': if not load_translation(language): self.logger.warning("BackendServer: Language '{0}' not found, using standard language instead".format(language)) self.developer_mode = self.my_to_bool(developer_mode, 'developer_mode', False) self.updates_allowed = self.my_to_bool(updates_allowed, 'updates_allowed', True) if self.is_int(pypi_timeout): self.pypi_timeout = int(pypi_timeout) else: self.pypi_timeout = 5 if pypi_timeout is not None: self.logger.error("BackendServer: Invalid value '" + str(pypi_timeout) + "' configured for attribute 'pypi_timeout' in plugin.conf, using '" + str(self.pypi_timeout) + "' instead") current_dir = os.path.dirname(os.path.abspath(__file__)) self.logger.debug("BackendServer running from '{}'".format(current_dir)) config = {'global': { 'engine.autoreload.on': False, 'tools.staticdir.debug': True, 'tools.trailing_slash.on': False }, '/': { 'tools.auth_basic.on': self._basic_auth, 'tools.auth_basic.realm': 'earth', 'tools.auth_basic.checkpassword': self.validate_password, 'tools.staticdir.root': current_dir, }, '/static': { 'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, 'static') } } from cherrypy._cpserver import Server self._server = Server() self._server.socket_host = ip self._server.socket_port = int(self.port) self._server.thread_pool = self.threads self._server.subscribe() self._cherrypy = cherrypy self._cherrypy.config.update(config) self._cherrypy.tree.mount(Backend(self, self.updates_allowed, language, self.developer_mode, self.pypi_timeout), '/', config = config)
class BackendServer(SmartPlugin): ALLOW_MULTIINSTANCE = False PLUGIN_VERSION='1.3.5' def my_to_bool(self, value, attr='', default=False): try: result = self.to_bool(value) except: result = default self.logger.error("BackendServer: Invalid value '"+str(value)+"' configured for attribute "+attr+" in plugin.conf, using '"+str(result)+"' instead") return result def get_local_ip_address(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("10.10.10.10", 80)) return s.getsockname()[0] def __init__(self, sh, port=None, threads=8, ip='', updates_allowed='True', user="******", password="", hashed_password="", language="", developer_mode="no", pypi_timeout=5): self.logger = logging.getLogger(__name__) self._user = user self._password = password self._hashed_password = hashed_password if self._password is not None and self._password != "" and self._hashed_password is not None and self._hashed_password != "": self.logger.warning("BackendServer: Both 'password' and 'hashed_password' given. Ignoring 'password' and using 'hashed_password'!") self._password = None if self._password is not None and self._password != "" and (self._hashed_password is None or self._hashed_password == ""): self.logger.warning("BackendServer: Giving plaintext password in configuration is insecure. Consider using 'hashed_password' instead!") self._hashed_password = None if (self._password is not None and self._password != "") or (self._hashed_password is not None and self._hashed_password != ""): self._basic_auth = True else: self._basic_auth = False self._sh = sh if self.is_int(port): self.port = int(port) else: self.port = 8383 if port is not None: self.logger.error("BackendServer: Invalid value '"+str(port)+"' configured for attribute 'port' in plugin.conf, using '"+str(self.port)+"' instead") if self.is_int(threads): self.threads = int(threads) else: self.threads = 8 self.logger.error("BackendServer: Invalid value '"+str(threads)+"' configured for attribute 'thread' in plugin.conf, using '"+str(self.threads)+"' instead") if ip == '': ip = self.get_local_ip_address() self.logger.debug("BackendServer: Using local ip address '{0}'".format(ip)) else: pass # if not self.is_ip(ip): # self.logger.error("BackendServer: Invalid value '"+str(ip)+"' configured for attribute ip in plugin.conf, using '"+str('0.0.0.0')+"' instead") # ip = '0.0.0.0' language = language.lower() if language != '': if not load_translation(language): self.logger.warning("BackendServer: Language '{0}' not found, using standard language instead".format(language)) self.developer_mode = self.my_to_bool(developer_mode, 'developer_mode', False) self.updates_allowed = self.my_to_bool(updates_allowed, 'updates_allowed', True) if self.is_int(pypi_timeout): self.pypi_timeout = int(pypi_timeout) else: self.pypi_timeout = 5 if pypi_timeout is not None: self.logger.error("BackendServer: Invalid value '" + str(pypi_timeout) + "' configured for attribute 'pypi_timeout' in plugin.conf, using '" + str(self.pypi_timeout) + "' instead") current_dir = os.path.dirname(os.path.abspath(__file__)) self.logger.debug("BackendServer running from '{}'".format(current_dir)) config = {'global': { 'engine.autoreload.on': False, 'tools.staticdir.debug': True, 'tools.trailing_slash.on': False }, '/': { 'tools.auth_basic.on': self._basic_auth, 'tools.auth_basic.realm': 'earth', 'tools.auth_basic.checkpassword': self.validate_password, 'tools.staticdir.root': current_dir, }, '/static': { 'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(current_dir, 'static') } } from cherrypy._cpserver import Server self._server = Server() self._server.socket_host = ip self._server.socket_port = int(self.port) self._server.thread_pool = self.threads self._server.subscribe() self._cherrypy = cherrypy self._cherrypy.config.update(config) self._cherrypy.tree.mount(Backend(self, self.updates_allowed, language, self.developer_mode, self.pypi_timeout), '/', config = config) def run(self): self.logger.debug("BackendServer: rest run") self._server.start() #self._cherrypy.engine.start() self.logger.debug("BackendServer: engine started") #cherrypy.engine.block() self.alive = True def stop(self): self.logger.debug("BackendServer: shutting down") self._server.stop() #self._cherrypy.engine.exit() self.logger.debug("BackendServer: engine exited") self.alive = False def parse_item(self, item): pass def parse_logic(self, logic): pass def update_item(self, item, caller=None, source=None, dest=None): pass def validate_password(self, realm, username, password): if username != self._user or password is None or password == "": return False if self._hashed_password is not None: return Utils.check_hashed_password(password, self._hashed_password) elif self._password is not None: return password == self._password return False
import cherrypy from cherrypy._cpserver import Server import endpoints #* Server Setup cherrypy.server.unsubscribe() dispatchServer = Server() dispatchServer.socket_port = 4000 dispatchServer.subscribe() if __name__ == "__main__": endpoints.init() cherrypy.engine.start() cherrypy.engine.block()
return "OK" parts = path.split("/") assert parts[0] == "" assert parts[1] == ".well-known" assert parts[2] == "acme-challenge" token = parts[3] start_response("200 OK", []) return tokens.get(token, "") from cherrypy._cpserver import Server cherrypy.server.unsubscribe( ) # don't start default http server that listens on some socket cherrypy.config.update({"/": {}}) server = Server(exos_vr="ALL") server._socket_host = "::" server.socket_port = 80 server.thread_pool = 7 server.subscribe() cherrypy.tree.graft(httpd_service, "/") cherrypy.engine.start() server.start() cherrypy.engine.block()
class PhoneHomeServer(object): def __init__(self, source_plugin, plugin_cfg): self.logger = c.logger self._phs_server = Server() self._phs_server.socket_host = c.conf.SERVICES.Phs.ServiceBindAddress self._phs_server.socket_port = c.conf.SERVICES.Phs.ServiceListenPort self.device_type = None self.service_chain = None self.deviceIP = None self.sn_nr = None if c.conf.SERVICES.Phs.EnableSSL: self.logger.info( Tools.create_log_msg(logmsg.PHS_SERVICE, None, logmsg.PHS_SSL_ENABLED)) self._phs_server.ssl_module = 'builtin' if os.path.isfile(c.conf.SERVICES.Phs.SSLCertificate): self._phs_server.ssl_certificate = c.conf.SERVICES.Phs.SSLCertificate else: self.logger.info( Tools.create_log_msg(logmsg.PHS_SERVICE, None, logmsg.PHS_SSL_NO_CERT)) if os.path.isfile(c.conf.SERVICES.Phs.SSLPrivateKey): self._phs_server.ssl_private_key = c.conf.SERVICES.Phs.SSLPrivateKey else: self.logger.info( Tools.create_log_msg(logmsg.PHS_SERVICE, None, logmsg.PHS_SSL_NO_KEY)) self._phs_server.subscribe() self._source_plugin = source_plugin self._plugin_cfg = plugin_cfg self.logger.info( Tools.create_log_msg( logmsg.PHS_SERVICE, None, logmsg.PHS_LISTEN.format(self._phs_server.socket_host, self._phs_server.socket_port))) @cherrypy.expose def init(self, **params): self.deviceIP = cherrypy.request.headers['Remote-Addr'] self.sn_nr = params['uid'] status, data = Tools.get_config( lookup_type=c.CONFIG_LOOKUP_TYPE_GET_DEVICE_CFG, serialnumber=self.sn_nr, deviceOsshId=None) if status: try: self.device_type = data['yapt']['device_type'] self.service_chain = data['yapt']['service_chain'] except KeyError as ke: self.logger.info('{0} {1}'.format( logmsg.PHS_SERVICE + ':', logmsg.PHS_CONF_KEY_ERROR.format(ke.message))) return _boostrap_init_file = c.conf.SERVICES.Phs.InitConfPath + self.device_type + '.xml' if os.path.isfile(_boostrap_init_file): response = None try: env = Environment(autoescape=select_autoescape(['xml']), loader=FileSystemLoader( c.conf.SERVICES.Phs.InitConfPath), trim_blocks=True, lstrip_blocks=True) response = env.get_template(self.device_type + '.xml').render( serial=self.sn_nr) except (TemplateNotFound, IOError) as err: self.logger.info( Tools.create_log_msg( logmsg.PHS_SERVICE, self.sn_nr, logmsg.PHS_TEMPLATE_ERROR.format( err.errno, err.strerror, err.filename))) return response else: self.logger.info( Tools.create_log_msg( logmsg.PHS_SERVICE, self.sn_nr, logmsg.PHS_BOOSTRAP_FILE_FAILED.format( _boostrap_init_file))) else: self.logger.info( Tools.create_log_msg(logmsg.PHS_SERVICE, self.sn_nr, logmsg.PHS_DEV_CONF_FAILED)) @cherrypy.expose def activation(self, **params): pass @cherrypy.expose def notification(self, **params): cherrypy.response.status = 201 body = cherrypy.request.body.read() xml_body = etree.fromstring(body) ns_orig = 'http://juniper.net/zerotouch-bootstrap-server' for item in xml_body.iter('{' + ns_orig + '}notification-type'): if item.text == c.PHS_NOTIFICATION_CONF_APPLIED: self.logger.info( Tools.create_log_msg(logmsg.PHS_SERVICE, self.sn_nr, logmsg.PHS_STAGE1_SUCCESS).format( params['uid'])) elif item.text == c.PHS_NOTIFICATION_CONF_FAILED: self.logger.info( Tools.create_log_msg( logmsg.PHS_SERVICE, self.sn_nr, logmsg.PHS_STAGE1_FAILED.format(params['uid']))) elif item.text == c.PHS_NOTIFICATION_BOOTSTRAP_COMPLETED: self.logger.info( Tools.create_log_msg( logmsg.PHS_SERVICE, self.sn_nr, logmsg.PHS_BOOTSTRAP_SUCCESS.format(params['uid']))) if c.SERVICEPLUGIN_OSSH in self.service_chain: self.logger.info( Tools.create_log_msg( logmsg.PHS_SERVICE, self.sn_nr, logmsg.PHS_SEC_SVC.format(c.SERVICEPLUGIN_OSSH, c.SERVICEPLUGIN_OSSH))) return else: sample_device = self._source_plugin.run_normalizer( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), device=self.deviceIP) # NFX JDM facts return empty serial number so we have to add it here if self.device_type == 'nfx': sample_device.deviceSerial = self.sn_nr message = AMQPMessage( message_type=c.AMQP_MSG_TYPE_DEVICE_ADD, payload=sample_device, source=c.AMQP_PROCESSOR_SVC) self._source_plugin.send_message(message=message) elif item.text == c.PHS_NOTIFICATION_BOOTSTRAP_FAILED: self.logger.info( Tools.create_log_msg( logmsg.PHS_SERVICE, self.sn_nr, logmsg.PHS_BOOSTRAP_FAILED.format(params['uid'])))
import cherrypy from cherrypy._cpserver import Server class Hello(object): @cherrypy.expose def index(self): return 'OK' if __name__ == '__main__': port = 8081 for i in range(10): port += 1 server = Server() server.socket_port = port server.subscribe() cherrypy.quickstart(Hello(), '/')