def start(self, config_path, non_block=False): self.status = ServerStatus.Starting self.publish('on_before_server_start', {'server':self, 'context':self.context}) self.context.load_settings(abspath(join(self.root_dir, config_path))) self.cache = Cache(size=1000, age="5s", log=cherrypy.log) self.context.load_apps() self.apps = self.context.apps self.app_paths = self.context.app_paths self.app_modules = self.context.app_modules if self.context.settings.Ion.as_bool('debug'): logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) logging.getLogger('sqlalchemy.orm.unitofwork').\ setLevel(logging.DEBUG) self.import_template_filters() self.import_controllers() if self.context.settings.Ion.pid_file: p = PIDFile(cherrypy.engine, self.context.settings.Ion.pid_file) p.subscribe() self.run_server(non_block) self.status = ServerStatus.Started self.publish('on_after_server_start', {'server':self, 'context':self.context})
def start(self, blocking=True): """Configure and start the server.""" self.configure() config['engine'] = engine WebSocketPlugin(engine).subscribe() cherrypy.tools.websocket = WebSocketTool() base_url = config.get('ws_base_url', '/websocket') wsconfig = {'/ws' :{ 'tools.websocket.on': True, 'tools.websocket.handler_cls': DBSWebSocketHandler }} tree.mount(self, base_url, wsconfig) # mount WebSocket service obj = DataService() tree.mount(obj, '/dbs') # mount another data service print "Applications:", pformat(tree.apps) print "Configuration:", pformat(self.config) pid = PIDFile(engine, self.pid) pid.subscribe() engine.start() print "### number of threads with web engine %s" \ % threading.active_count() if blocking: engine.block()
def start(self, blocking=True): """Configure and start the server.""" self.configure() url_base = self.config['web_server']['url_base'] config = self.config.get('web_server', {}) config['engine'] = engine obj = DASWebService(self.config) tree.mount(obj, url_base) # mount web server self.setup_kws_server() print "### DAS web server, PID=%s" % self.pid print pformat(tree.apps) print pformat(self.config) pid = PIDFile(engine, self.pid) pid.subscribe() engine.start() print "### DAS server runs with %s threads" \ % threading.active_count() threads = threading.enumerate() threads.sort() for thr in threads: print thr if blocking: engine.block()
def start(self, blocking=True): """Configure and start the server.""" self.configure() url_base = self.config['web_server']['url_base'] config = self.config.get('web_server', {}) config['engine'] = engine # import DASWebServices after we run self.configure which register secmodv2 from DAS.web.das_web_srv import DASWebService obj = DASWebService(self.config) tree.mount(obj, url_base) # mount web server self.setup_kws_server() print("### DAS web server, PID=%s" % self.pid) print(pformat(tree.apps)) print(pformat(self.config)) pid = PIDFile(engine, self.pid) pid.subscribe() engine.start() print("### DAS server runs with %s threads" \ % threading.active_count()) threads = threading.enumerate() try: threads.sort() except: pass for thr in threads: print(thr) if blocking: engine.block()
def start_cherrypy(app, host=None, port=None, ssl_cert_file=None, ssl_key_file=None, is_dev_env=None): if not is_dev_env: cherrypy.config.update({'environment': 'production'}) cherrypy.config.update(config.get_cherrypy_config()) cherrypy.config.update({ 'log.screen': False, 'server.socket_port': port, 'server.socket_host': host, 'server.ssl_certificate': ssl_cert_file, 'server.ssl_private_key': ssl_key_file }) app_logged = TransLogger(app.wsgi_app, setup_console_handler=False) cherrypy.tree.graft(app_logged, '/') if not is_dev_env: Daemonizer(cherrypy.engine).subscribe() PIDFile(cherrypy.engine, os.path.join(util.get_user_directory(), PID_FILE_NAME)).subscribe() cherrypy.engine.start() cherrypy.engine.block()
def run(self, daemon=False, pidfile='', log_screen=False, access_log='', error_log=''): if os.name != 'nt' and daemon: Daemonizer(cherrypy.engine).subscribe() if not pidfile: pidfile = DEFAULT_PIDFILE if pidfile: PIDFile(cherrypy.engine, pidfile).subscribe() cherrypy.config.update({ 'server.socket_host': self.host, 'server.socket_port': self.port, 'server.thread_pool': 30, 'engine.autoreload.on': False, 'checker.on': False, 'tools.log_headers.on': False, 'log.screen': log_screen, 'log.access_file': access_log, 'log.error_file': error_log, }) cherrypy.log('Mounting static dir to %s' % settings.STATIC_URL) self.mount_static(settings.STATIC_URL, settings.STATIC_ROOT) cherrypy.log('Mounting media dir to %s' % settings.MEDIA_URL) self.mount_static(settings.MEDIA_URL, settings.MEDIA_ROOT) self.add_favicon(FAVICON) cherrypy.log('Loading and serving ChemManager application') cherrypy.tree.graft(application, '/') if not daemon: self._subscribe_handlers() cherrypy.engine.start() cherrypy.engine.block()
def main(): #cherrypy.config.update({'error_page.404': error_page_404}) cherrypy.config.update('webapiner.ini') print cherrypy.__version__ core = AppCore() WebSocketPlugin(cherrypy.engine).subscribe() cherrypy.engine.json_rpc = JSONRPCHanlder(cherrypy.engine, core) cherrypy.engine.json_rpc.subscribe() cherrypy.tools.websocket = WebSocketTool() http_conf = {'/': {'tools.staticdir.on': False}} rest_conf = { '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher() } } cherrypy.tree.mount(RESTHandler(), "/api/REST/", config=rest_conf) cherrypy.tree.mount(HTTPHandler(), "/api/HTTP/", config=http_conf) PIDFile(cherrypy.engine, os.path.join(current_dir, "webapiner.pid")).subscribe() cherrypy.engine.subscribe("start", core.inito) cherrypy.engine.subscribe("stop", core.destroy) cherrypy.quickstart(Root(), '/', 'webapiner.ini')
def run(): cur_dir = os.path.abspath(os.path.dirname(__file__)) port = 8444 if "ASTRE_PORT" in os.environ: port = int(os.environ["ASTRE_PORT"]) cherrypy.config.update({ "environment": "production", "log.screen": True, "log.error_file": "astre.log", "server.socket_port": port, "server.ssl_module": "builtin", "server.ssl_private_key": os.path.join(cur_dir, "key.pem"), "server.ssl_certificate": os.path.join(cur_dir, "cert.pem") }) PIDFile(cherrypy.engine, '/tmp/astre.pid').subscribe() Daemonizer(cherrypy.engine).subscribe() cherrypy.quickstart(Root())
def runServer(config): PIDFile(cherrypy.engine, config.get('Server', 'PIDFile')).subscribe() configCherryPyDict = {} stderrFile = config.get('Logs', 'stderr') configCherryPyDict['log.error_file'] = stderrFile configCherryPyDict['log.screen'] = False stdoutFile = config.get('Logs', 'stdout') configCherryPyDict['log.access_file'] = stdoutFile configCherryPyDict['log.screen'] = False #Check if KeyPair is installed try: keyPair = M2Crypto.RSA.load_key(config.get("SSL", "KeyPair")) except: raise AssertionError("Copy KeyPair.pem to MDM directory") mapper = cherrypy.dispatch.RoutesDispatcher() mapper.connect('wp', caseInsensitive("/wp"), controller=discovery.Discovery(config), action='index') mapper.connect('healthCheck', caseInsensitive("/healthCheck"), controller=HealthCheck(), action='index') mapper.connect('discovery', caseInsensitive("/EnrollmentServer/Discovery.svc"), controller=discovery.Discovery(config), action='index') mapper.connect('enrollment', caseInsensitive("/EnrollmentServer/Enrollment.svc"), controller=enrollment.Enrollment(config), action='index') mapper.connect('omadm', caseInsensitive("/omadm/WindowsPhone.ashx"), controller=omaDM.OMADM(config), action='index') mapper.connect('pushSender', caseInsensitive("/push"), controller=pushSender.PushSender(config), action='index') mapper.connect('notFound', '{dummy:/(.*)}', NotFound(), action='index') configCherryPyDict['server.socket_host'] = config.get("Server", "Host") configCherryPyDict['server.socket_port'] = config.getint("Server", "Port") configCherryPyDict['server.thread_pool'] = config.getint( "Server", "ThreadPool") if config.getboolean("SSL", "TurnedOn"): configCherryPyDict['server.ssl_module'] = 'pyopenssl' configCherryPyDict['server.ssl_certificate'] = config.get( "SSL", "Certificate") configCherryPyDict['server.ssl_private_key'] = config.get("SSL", "Key") configCherryPyDict['server.ssl_certificate_chain'] = config.get( "SSL", "CertificateChain") cherrypy.config.update(configCherryPyDict) config = {"/": {"request.dispatch": mapper}} cherrypy.quickstart(None, config=config)
def _daemonize(self): """ Drop privileges, daemonize with :class:`cherrypy.process.plugins.Daemonizer` and write a PID file with :class:`cherrypy.process.plugins.PIDFile`. """ self._drop_privileges() Daemonizer(cherrypy.engine).subscribe() PIDFile(cherrypy.engine, Bcfg2.Options.setup.daemon).subscribe() return True
class CherrypyServer(object): """Handles server config, startup and termination. """ def __init__(self, port=8080, ip='0.0.0.0', pidfilename=None, app=None, show_log=False): self._server = wsgiserver.CherryPyWSGIServer( (ip, port), app ) if pidfilename is not None: self._pidfile = PIDFile(cherrypy.engine, pidfilename) self._pidfile.subscribe() if show_log: cherrypy.log.screen = True print("CherrypyServer running at %s:%s" % (ip, port)) def start(self): """Starts the server and stop it automatically if KeyboardInterrupt. """ try: self._server.start() except KeyboardInterrupt: self._server.stop() def stpo(self): """Stops the server.""" self._server.stop() @property def server(self): """Return the server""" return self._server @property def pidfile(self): return self.pidfile
def create_pidfile(args): # Create the filename for this instance's PID file. if not args.pidfile: if args.test: args.pidfile = "/tmp/captive_portal." else: args.pidfile = "/var/run/captive_portal." full_pidfile = args.pidfile + args.interface logging.debug("Name of PID file is: %s", full_pidfile) # If a PID file already exists for this network interface, ABEND. if os.path.exists(full_pidfile): logging.error("A pidfile already exists for network interface %s.", full_pidfile) logging.error("Is a daemon already running on this interface?") exit(5) # Write the PID file of this instance to the PID file. logging.debug("Creating pidfile for network interface %s.", str(args.interface)) logging.debug("PID of process is %s.", str(os.getpid())) pid = PIDFile(cherrypy.engine, full_pidfile) pid.subscribe()
def run(): cherrypy.config.update({ "environment": "production", "log.screen": True, "log.error_file": "sunset.log", "server.socket_host": "0.0.0.0", "server.socket_port": 8080, }) PIDFile(cherrypy.engine, '/tmp/sunset.pid').subscribe() Daemonizer(cherrypy.engine).subscribe() cherrypy.quickstart(Root())
def _daemonize(self): """ Drop privileges with :class:`cherrypy.process.plugins.DropPrivileges`, daemonize with :class:`cherrypy.process.plugins.Daemonizer`, and write a PID file with :class:`cherrypy.process.plugins.PIDFile`. """ DropPrivileges(cherrypy.engine, uid=Bcfg2.Options.setup.daemon_uid, gid=Bcfg2.Options.setup.daemon_gid, umask=int(Bcfg2.Options.setup.umask, 8)).subscribe() Daemonizer(cherrypy.engine).subscribe() PIDFile(cherrypy.engine, Bcfg2.Options.setup.daemon).subscribe() return True
def create_pidfile(args): # Create the filename for this instance's PID file. if not args.pidfile: if args.test: args.pidfile = '/tmp/captive_portal.' else: args.pidfile = '/var/run/captive_portal.' full_pidfile = args.pidfile + args.interface logging.debug("Name of PID file is: %s", full_pidfile) # If a PID file already exists for this network interface, ABEND. if os.path.exists(full_pidfile): logging.error("A pidfile already exists for network interface %s.", full_pidfile) logging.error("Is a daemon already running on this interface?") exit(5) # Write the PID file of this instance to the PID file. logging.debug("Creating pidfile for network interface %s.", str(args.interface)) logging.debug("PID of process is %s.", str(os.getpid())) pid = PIDFile(cherrypy.engine, full_pidfile) pid.subscribe()
def _daemonize(self): """ Drop privileges with :class:`cherrypy.process.plugins.DropPrivileges`, daemonize with :class:`cherrypy.process.plugins.Daemonizer`, and write a PID file with :class:`cherrypy.process.plugins.PIDFile`. """ DropPrivileges(cherrypy.engine, uid=self.setup['daemon_uid'], gid=self.setup['daemon_gid'], umask=int(self.setup['umask'], 8)).subscribe() Daemonizer(cherrypy.engine).subscribe() PIDFile(cherrypy.engine, self.setup['daemon']).subscribe() return True
def start_server(address='127.0.0.1', port=8000): if not os.path.abspath(os.getcwd()).endswith("python_challenge/web"): os.chdir('./web') cherrypy.tree.mount(web.webui.XforceForm(address, port), "", config='cpy_app.cfg') #cherrypy.tree.mount(webapp, "") cherrypy.engine.start() pidfile = tempfile.TemporaryFile(prefix='xfipchk', suffix='.pid') PIDFile(cherrypy.engine, pidfile).subscribe() cherrypy.engine.block()
def run(): cherrypy.config.update({ "environment": "production", "log.screen": True, "server.socket_port": 8443, "server.ssl_module": "builtin", "server.ssl_private_key": key_path, "server.ssl_certificate": cert_path }) Daemonizer(cherrypy.engine).subscribe() PIDFile(cherrypy.engine, 'sunset.pid').subscribe() cherrypy.quickstart(Root())
def run(): cur_dir = os.path.abspath(os.path.dirname(__file__)) cherrypy.config.update({ "environment": "production", "log.screen": True, "server.socket_port": 8444, "server.ssl_module": "builtin", "server.ssl_private_key": os.path.join(cur_dir, "key.pem"), "server.ssl_certificate": os.path.join(cur_dir, "cert.pem") }) PIDFile(cherrypy.engine, 'astre.pid').subscribe() cherrypy.quickstart(Root())
def start(self, blocking=True): """Configure and start the server.""" self.configure() url_base = self.config['web_server']['url_base'] config = self.config.get('web_server', {}) config['engine'] = engine obj = DASWebService(self.config) tree.mount(obj, url_base) # mount web server # DBS/Phedex Service if self.config.has_key('dbs_phedex') and \ self.config['dbs_phedex']['urls']: uri = self.config['mongodb']['dburi'] urls = {} for url in self.config['dbs_phedex']['urls']: if url.find('phedex') != -1: urls['phedex'] = url else: urls['dbs'] = url expire = self.config['dbs_phedex'].get('expire', 3600) obj = DBSPhedexService(uri, urls, expire) tree.mount(obj, '/dbs_phedex') print "### DAS web server mounted /dbs_phedex service" print "### DAS web server, PID=%s, #threads=%s" \ % (self.pid, threading.active_count()) # for thr in threading.enumerate(): # print thr print pformat(tree.apps) print pformat(self.config) pid = PIDFile(engine, self.pid) pid.subscribe() engine.start() print "### number of threads with web engine %s" \ % threading.active_count() if blocking: engine.block()
def main(): import sys from optparse import OptionParser parser = OptionParser() parser = OptionParser(usage="usage: %prog [options] server_dir [scheduler_id]") parser.add_option("--foreground", action="store_true", dest="foreground") parser.add_option("--removelock", action="store_true", dest="removelock") (options, args)=parser.parse_args() if len(args) not in (1, 2): parser.error("incorrect number of arguments") config.load_config(args[0]) try: sched_id=args[1] except: sched_id=config.sched_id else: config.set_sched_id(sched_id) if options.removelock: statistics.DBLogPlugin(cherrypy.engine, sched_id=config.sched_id).subscribe() LockPlugin(cherrypy.engine, forcelock=True).subscribe() cherrypy.engine.start() cherrypy.engine.block() from cherrypy.process.plugins import Daemonizer, PIDFile, DropPrivileges # DropPrivileges(cherrypy.engine, umask=0022, uid=1044, gid=1000).subscribe() LockPlugin(cherrypy.engine).subscribe() sched_type = config.get('Scheduler', 'type') SchedulerPlugin(cherrypy.engine, importlib.import_module('.interfaces.' + sched_type, __name__)).subscribe() PIDFile(cherrypy.engine, config.get('Scheduler', 'pid_file')).subscribe() cherrypy.engine.signal_handler.subscribe() statistics.DBLogPlugin(cherrypy.engine, sched_id=config.sched_id).subscribe() cherrypy.server.unsubscribe() if not options.foreground: cherrypy.process.plugins.Daemonizer(cherrypy.engine).subscribe() cherrypy.engine.start() cherrypy.engine.block()
def __init__(self, port=8080, ip='0.0.0.0', pidfilename=None, app=None, show_log=False): self._server = wsgiserver.CherryPyWSGIServer( (ip, port), app ) if pidfilename is not None: self._pidfile = PIDFile(cherrypy.engine, pidfilename) self._pidfile.subscribe() if show_log: cherrypy.log.screen = True print("CherrypyServer running at %s:%s" % (ip, port))
def setup_server(): """Setup CherryPy server""" LOGGER.info('Setting up CherryPy server') # Set the PID file path try: if cfg.pidfile: from cherrypy.process.plugins import PIDFile PIDFile(cherrypy.engine, cfg.pidfile).subscribe() except AttributeError: pass # Add an extra server server = _cpserver.Server() server.socket_host = '127.0.0.1' server.socket_port = 52854 server.subscribe() # Configure default server cherrypy.config.update({ 'server.socket_host': cfg.host, 'server.socket_port': cfg.port, 'server.thread_pool': 10 }) application = django.core.wsgi.get_wsgi_application() cherrypy.tree.graft(application, cfg.server_dir) config = { '/': { 'tools.staticdir.root': '%s/static' % cfg.file_root, 'tools.staticdir.on': True, 'tools.staticdir.dir': '.' } } cherrypy.tree.mount(None, django.conf.settings.STATIC_URL, config) if not cfg.no_daemon: Daemonizer(cherrypy.engine).subscribe() cherrypy.engine.signal_handler.subscribe()
def main(args=sys.argv): from calibre.db.legacy import LibraryDatabase parser = option_parser() opts, args = parser.parse_args(args) if opts.daemonize and not iswindows: daemonize() if opts.pidfile is not None: from cherrypy.process.plugins import PIDFile PIDFile(cherrypy.engine, opts.pidfile).subscribe() cherrypy.log.screen = True from calibre.utils.config import prefs if opts.with_library is None: opts.with_library = prefs['library_path'] if not opts.with_library: print('No saved library path. Use the --with-library option' ' to specify the path to the library you want to use.') return 1 db = LibraryDatabase(os.path.expanduser(opts.with_library)) server = LibraryServer(db, opts, show_tracebacks=opts.develop) server.start() return 0
def daemonize(user, group, pidfile=None): if os.name == 'posix' and os.getuid() == 0: from cherrypy.process.plugins import DropPrivileges import grp import pwd try: uid = pwd.getpwnam(user)[2] gid = grp.getgrnam(group)[2] except KeyError: cherrypy.log.error( 'Cannot find user `{0}` or group `{1}`'.format(user, group), 'DAEMONIZE', logging.FATAL ) raise cherrypy.drop_privileges = DropPrivileges( cherrypy.engine, uid=uid, gid=gid).subscribe() from cherrypy.process.plugins import PIDFile, Daemonizer if pidfile: PIDFile(cherrypy.engine, pidfile).subscribe() Daemonizer(cherrypy.engine).subscribe()
def configure(cfgfile): with open_text(*_CONFIG_SPEC) as fh: cfg = salmagundi.config.configure(cfgfile, fh, create_properties=False, converters=_CONVERTERS) _logging(cfg) _storage_path(cfg) _index_url(cfg) _project_url(cfg) _ssl(cfg) host, port = cfg['server', 'host'] cherrypy.config.update({ 'response.headers.Server': f'{PROG_NAME}/{__version__}', 'server.socket_host': host, 'server.socket_port': port, 'engine.autoreload.on': False, 'request.show_tracebacks': PYPP_DEBUG, 'request.show_mismatched_params': PYPP_DEBUG, }) if PYPP_DEBUG: cherrypy.engine.signal_handler.handlers['SIGUSR2'] =\ lambda: cherrypy.engine.restart() if cfg['server', 'daemonize']: Daemonizer(cherrypy.engine).subscribe() cherrypy.engine.signal_handler.handlers['SIGUSR1'] = None if os.getuid() == 0: uid, gid = _user_group(cfg) if uid: DropPrivileges(cherrypy.engine, uid=uid, gid=gid).subscribe() else: cherrypy.log("running as 'root'", 'WARNING') if cfg['server', 'pidfile']: PIDFile(cherrypy.engine, cfg['server', 'pidfile']).subscribe() rv = {opt: cfg['pypackproxy', opt] for opt in cfg.options('pypackproxy')} rv['proxies'] = _proxies(cfg) rv['user-agent'] = f'{PROG_NAME}/{__version__}' return rv
def run(self): from cherrypy.process.plugins import Daemonizer from cherrypy.process.plugins import PIDFile import cherrypy import os os.environ["DJANGO_SETTINGS_MODULE"] = "ImageResize.settings" from django.core.handlers.wsgi import WSGIHandler from django.core.management import call_command import django django.setup(set_prefix=False) call_command("migrate", interactive=False) call_command("collectstatic", interactive=False) engine = cherrypy.engine autoreload = engine.autoreload autoreload.stop() autoreload.unsubscribe() cherrypy.config.update({ 'server.socket_host': self.HOST, 'server.socket_port': self.PORT, 'engine.autoreload_on': False, 'log.screen': True }) from django.conf import settings self.mount_static(settings.STATIC_URL, settings.STATIC_ROOT) cherrypy.log("Loading and serving Django application") cherrypy.tree.graft(WSGIHandler()) Daemonizer(engine).subscribe() PIDFile(cherrypy.engine, 'app.pid').subscribe() engine.start()
def daemonize(self): if not _daemon_conf.on: return if os.name == 'posix' and os.getuid() == 0: from cherrypy.process.plugins import DropPrivileges import grp, pwd try: uid = pwd.getpwnam(_daemon_conf.user)[2] gid = grp.getgrnam(_daemon_conf.group)[2] except KeyError: cherrypy.log.error( 'Cannot find user "{0}" or group "{1}"'.format( _daemon_conf.user, _daemon_conf.group), 'SERVER', logging.FATAL) raise cherrypy.drop_privileges = DropPrivileges(cherrypy.engine, uid=uid, gid=gid).subscribe() from cherrypy.process.plugins import PIDFile, Daemonizer if _daemon_conf.pid_file: PIDFile(cherrypy.engine, _daemon_conf.pid_file).subscribe() Daemonizer(cherrypy.engine).subscribe()
def start(): cherrypy.engine.autoreload.stop() cherrypy.engine.autoreload.unsubscribe() settings = { 'global': { 'server.socket_port': 2080, 'server.socket_host': '0.0.0.0', 'server.socket_file': '', 'server.socket_queue_size': 100, 'server.protocol_version': 'HTTP/1.1', 'server.log_to_screen': True, 'server.log_file': '', 'server.reverse_dns': False, 'server.thread_pool': 200, 'server.environment': 'production', 'engine.timeout_monitor.on': False } } d = Daemonizer(cherrypy.engine) d.subscribe() PIDFile(cherrypy.engine, pidfile).subscribe() cherrypy.config.update(settings) cherrypy.tree.mount(ZookeeperAdmin(), '/') cherrypy.engine.start()
pidfile = '/var/run/captive_portal.' pidfile = pidfile + interface if debug: print "DEBUG: Name of PID file is: %s" % pidfile # If a PID file already exists for this network interface, ABEND. if os.path.exists(pidfile): print "ERROR: A pidfile already exists for network interface %s." % pidfile print "ERROR: Is a daemon already running on this interface?" exit(5) # Write the PID file of this instance to the PID file. if debug: print "DEBUG: Creating pidfile for network interface %s." % str(interface) print "DEBUG: PID of process is %s." % str(os.getpid()) pid = PIDFile(cherrypy.engine, pidfile) pid.subscribe() # Configure a few things about the web server so we don't have to fuss # with an extra config file, namely, the port and IP address to listen on. cherrypy.config.update({'server.socket_host':'0.0.0.0', }) cherrypy.config.update({'server.socket_port':port, }) # Set up an SSL listener running in parallel. ssl_listener = cherrypy._cpserver.Server() ssl_listener.socket_host = '0.0.0.0' ssl_listener.socket_port = ssl_port ssl_listener.ssl_certificate = ssl_cert ssl_listener.ssl_private_key = ssl_private_key ssl_listener.subscribe()
# Start plugins if passed_args.daemon: if core.PLATFORM == '*nix': Daemonizer(cherrypy.engine).subscribe() elif core.PLATFORM == 'windows': from cherrypysytray import SysTrayPlugin # noqa menu_options = (('Open Browser', None, lambda *args: webbrowser.open(core.SERVER_URL)),) systrayplugin = SysTrayPlugin(cherrypy.engine, 'core/favicon.ico', 'Watcher', menu_options) systrayplugin.subscribe() systrayplugin.start() scheduler.create_plugin() if passed_args.pid: PIDFile(cherrypy.engine, passed_args.pid).subscribe() # SSL certs if core.CONFIG['Server']['ssl_cert'] and core.CONFIG['Server']['ssl_key']: logging.info('SSL Certs are enabled. Server will only be accessible via https.') print('SSL Certs are enabled. Server will only be accessible via https.') ssl_conf = {'server.ssl_certificate': core.CONFIG['Server']['ssl_cert'], 'server.ssl_private_key': core.CONFIG['Server']['ssl_key'], 'tools.https_redirect.on': True } try: from OpenSSL import SSL # noqa except ImportError as e: ssl_conf['server.ssl_module'] = 'builtin' m = ''' Using built-in SSL module. This may result in a large amount of
def symkey(self): jdata = json.dumps(cherrypy.request.json) eResponse = do_symkey(jdata) return eResponse @cherrypy.expose @cherrypy.tools.json_out() def payload(self): eResponse = do_payload() return eResponse def export_pk_pem(path, pubkey): with open(path, "w") as f: f.write(pubkey) if __name__ == '__main__': cherrypy.config.update((os.path.join(os.curdir, "server.conf"))) app = SGXServer() # Daemonizer(cherrypy.engine).subscribe() PIDFile(cherrypy.engine, 'sgx.pid').subscribe() cherrypy.tree.mount(app, '/', config=os.path.join( os.curdir, "apps", "sgx.conf")) cherrypy.engine.start() cherrypy.engine.block()
raise cherrypy.HTTPRedirect('/') @cherrypy.expose def sitemap(self, **params): self.first_step('sitemap') communities = self.get_all_communities() questions = self.get_all_questions() users = self.get_all_users() document = "<?xml version='1.0' encoding='UTF-8'?>\n" document += "<urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'>\n" for c in communities: document += "<url><loc>" + c.get_link(True) + "</loc><lastmod>" + str(c.created).split(' ')[0] + "</lastmod><changefreq>always</changefreq><priority>0.8</priority></url>\n" for q in questions: document += "<url><loc>" + q.get_link(True) + "</loc><lastmod>" + str(q.created).split(' ')[0] + "</lastmod><changefreq>always</changefreq><priority>0.9</priority></url>\n" for u in users: document += "<url><loc>" + u.get_link(True) + "</loc><lastmod>" + str(u.created).split(' ')[0] + "</lastmod><changefreq>always</changefreq><priority>0.8</priority></url>\n" document += "</urlset>\n" cherrypy.response.headers['Content-Type']='text/xml; charset=utf-8' return document if __name__ == "__main__": SAEnginePlugin(cherrypy.engine).subscribe() cherrypy.tools.db = SATool() if APP_RUN_AS_DAEMON: d = Daemonizer(cherrypy.engine) d.subscribe() p = PIDFile(cherrypy.engine, Ke_current_path+"/kelinux.pid") p.subscribe() cp_config['global']['log.screen'] = False cherrypy.quickstart(Main_web(), config=cp_config)
def start(): """ Main function for starting HTTP server """ logger = logging.getLogger('htpc.server') logger.debug("Setting up to start cherrypy") protocol = "" # Set server ip, port and root cherrypy.config.update({ 'server.socket_host': htpc.HOST, 'server.socket_port': htpc.PORT, 'log.screen': False, 'server.thread_pool': 15, 'server.socket_queue_size': 10 }) # Wrap htpc manager in secure headers. # http://cherrypy.readthedocs.org/en/latest/advanced.html#securing-your-server if htpc.settings.get('app_use_secure_headers', True): cherrypy.tools.secureheaders = cherrypy.Tool('before_finalize', secureheaders, priority=60) cherrypy.config.update({'tools.secureheaders.on': True}) # Enable auth if username and pass is set, add to db as admin if htpc.USERNAME and htpc.PASSWORD: """ Lets see if the that username and password is already in the db""" try: user = Manageusers.selectBy(username=htpc.USERNAME).getOne() # If the user exist if user: # Activate the new password user.password = htpc.PASSWORD except SQLObjectNotFound: logger.debug( "Added htpc.USERNAME and htpc.PASSWORD to Manageusers table") Manageusers(username=htpc.USERNAME, password=htpc.PASSWORD, role='admin') logger.debug('Updating cherrypy config, activating sessions and auth') cherrypy.config.update({ 'tools.sessions.on': True, 'tools.auth.on': True, 'tools.sessions.timeout': 43200, 'tools.sessions.httponly': True #'tools.sessions.secure': True # Auth does not work with this on #TODO }) # Set server environment to production unless when debugging if not htpc.DEV: cherrypy.config.update({'environment': 'production'}) if htpc.settings.get('app_use_ssl'): serverkey = os.path.join(htpc.DATADIR, 'server.key') cert = os.path.join(htpc.DATADIR, 'server.cert') # If either the HTTPS certificate or key do not exist, make some self-signed ones. if not (cert and os.path.exists(cert)) or not ( serverkey and os.path.exists(serverkey)): logger.debug( 'There isnt any certificate or key, trying to make them') if create_https_certificates(cert, serverkey): # Save the new crt and key to settings htpc.SSLKEY = htpc.settings.set('app_ssl_key', serverkey) htpc.SSLCERT = htpc.settings.set('app_ssl_cert', cert) htpc.ENABLESSL = True logger.debug("Created certificate and key successfully") logger.info("Restarting to activate SSL") do_restart() if (os.path.exists(htpc.settings.get('app_ssl_cert')) and os.path.exists(htpc.settings.get('app_ssl_key'))): htpc.ENABLESSL = True if htpc.ENABLESSL: protocol = "s" logger.debug("SSL is enabled") cherrypy.config.update({ 'server.ssl_certificate': htpc.settings.get('app_ssl_cert'), 'server.ssl_private_key': htpc.settings.get('app_ssl_key') }) if htpc.settings.get('app_use_proxy_headers'): cherrypy.config.update({'tools.proxy.on': True}) if htpc.settings.get('app_use_proxy_headers') and htpc.settings.get( 'app_use_proxy_headers_basepath'): cherrypy.config.update({ 'tools.proxy.base': str(htpc.settings.get('app_use_proxy_headers_basepath')) }) # Daemonize cherrypy if specified if htpc.DAEMON: if sys.platform == 'win32': logger.error( "You are using Windows - I cannot setup daemon mode. Please use the pythonw executable instead." ) logger.error( "More information at http://docs.python.org/2/using/windows.html." ) else: Daemonizer(cherrypy.engine).subscribe() # Create PID if specified if htpc.PID: PIDFile(cherrypy.engine, htpc.PID).subscribe() def stopp_ap(): htpc.SCHED.shutdown(wait=False) stopp_ap.priority = 10 cherrypy.engine.subscribe('stop', stopp_ap) cherrypy.engine.timeout_monitor.unsubscribe() # Set static directories webdir = os.path.join(htpc.RUNDIR, htpc.TEMPLATE) favicon = os.path.join(webdir, "img/favicon.ico") app_config = { '/': { 'tools.staticdir.root': webdir, 'tools.encode.on': True, 'tools.encode.encoding': 'utf-8', 'tools.gzip.on': True, 'tools.gzip.mime_types': [ 'text/html', 'text/plain', 'text/css', 'text/javascript', 'application/json', 'application/javascript' ] }, '/js': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.caching.delay': 0, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 24 * 30, 'tools.staticdir.on': True, 'tools.auth.on': False, 'tools.sessions.on': False, 'tools.staticdir.dir': 'js' }, '/css': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.caching.delay': 0, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 24 * 30, 'tools.staticdir.on': True, 'tools.auth.on': False, 'tools.sessions.on': False, 'tools.staticdir.dir': 'css' }, '/img': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.caching.delay': 0, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 24 * 30, 'tools.staticdir.on': True, 'tools.auth.on': False, 'tools.sessions.on': False, 'tools.staticdir.dir': 'img' }, '/favicon.ico': { 'tools.caching.on': True, 'tools.caching.force': True, 'tools.expires.on': True, 'tools.expires.secs': 60 * 60 * 24 * 30, 'tools.staticfile.on': True, 'tools.auth.on': False, 'tools.sessions.on': False, 'tools.staticfile.filename': favicon } } # Start the CherryPy server logger.info("Starting up webserver") print '*******************************************************************' print 'Starting HTPC Manager on port ' + str(htpc.PORT) + '.' print 'Start your browser and go to http%s://localhost:%s%s' % ( protocol, htpc.PORT, htpc.WEBDIR[:-1]) print '*******************************************************************' cherrypy.quickstart(htpc.ROOT, htpc.WEBDIR[:-1], config=app_config)
if Options().ssl_private_key != '': cherrypy.server.ssl_private_key = Options().ssl_private_key if Options().ssl_certificate_chain != '': cherrypy.server.ssl_certificate_chain = Options().ssl_certificate_chain if Options().daemon: # Daemon info is logged by CherryPy daemon = Daemonizer(cherrypy.engine) daemon.subscribe() else: logger.info('Not running as daemon.') # PID is logged by CherryPy pid = PIDFile(cherrypy.engine, os.path.join(Options().run_dir, 'cherryblog.pid')) pid.subscribe() if Options().privileges: # Privileges are logged by CherryPy privileges = DropPrivileges(cherrypy.engine, uid=Options().uid, gid=Options().gid) privileges.subscribe() else: logger.info('No user privileges specified.') cherrypy.quickstart(Application(), config=settings) ### # # Version: 2.2.1 # Date: 2020-04-25
def setup(): parse_arguments() try: if cfg.pidfile: from cherrypy.process.plugins import PIDFile PIDFile(cherrypy.engine, cfg.pidfile).subscribe() except AttributeError: pass os.chdir(cfg.file_root) cherrypy.config.update({'error_page.404': error_page_404}) cherrypy.config.update({'error_page.500': error_page_500}) cfg.log = Logger() load_modules() cfg.html_root = Root() cfg.users = plugin_mount.UserStoreModule.get_plugins()[0] cfg.page_plugins = plugin_mount.PagePlugin.get_plugins() cfg.log("Loaded %d page plugins" % len(cfg.page_plugins)) cfg.forms = plugin_mount.FormPlugin.get_plugins() # Add an extra server server = _cpserver.Server() server.socket_host = '127.0.0.1' server.socket_port = 52854 server.subscribe() # Configure default server cherrypy.config.update({ 'server.socket_host': '127.0.0.1', 'server.socket_port': cfg.port, 'server.thread_pool': 10, 'tools.staticdir.root': cfg.file_root, 'tools.sessions.on': True, 'tools.auth.on': True, 'tools.sessions.storage_type': "file", 'tools.sessions.timeout': 90, 'tools.sessions.storage_path': "%s/data/cherrypy_sessions" % cfg.file_root, }) config = { '/': { 'tools.staticdir.root': '%s/static' % cfg.file_root, 'tools.proxy.on': True, }, '/static': { 'tools.staticdir.on': True, 'tools.staticdir.dir': "." }, '/favicon.ico': { 'tools.staticfile.on': True, 'tools.staticfile.filename': "%s/static/theme/favicon.ico" % cfg.file_root } } cherrypy.tree.mount(cfg.html_root, '/', config=config) cherrypy.engine.signal_handler.subscribe()
format= '%(asctime)s : %(levelname)s : %(module)s:%(lineno)d : %(funcName)s(%(threadName)s) : %(message)s', level=logging.DEBUG) logger.info("running %s", ' '.join(sys.argv)) program = os.path.basename(sys.argv[0]) # check and process input arguments if len(sys.argv) < 2: print globals()['__doc__'] % locals() sys.exit(1) conf_file = sys.argv[1] config_srv = Config( **cherrypy.lib.reprconf.Config(conf_file).get('global')) config = Config( **cherrypy.lib.reprconf.Config(conf_file).get('w2v_server')) if config_srv.pid_file: PIDFile(cherrypy.engine, config_srv.pid_file).subscribe() if config_srv.run_user and config_srv.run_group: logging.info("dropping priviledges to %s:%s" % (config_srv.run_user, config_srv.run_group)) DropPrivileges(cherrypy.engine, gid=config_srv.run_group, uid=config_srv.run_user).subscribe() cherrypy.quickstart(Server(config.MODEL_FILE), config=conf_file) logger.info("finished running %s", program)
'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL } logger = logging.getLogger('mtt') logger.setLevel(log_levels[conf['internal']['log_level']]) handler = logging.FileHandler(conf['internal']['mtt_log_file']) handler.setFormatter( logging.Formatter('[%(asctime)s] %(levelname)s %(message)s')) logger.addHandler(handler) logger.info( 'Logging at %s to %s' % (conf['internal']['log_level'], conf['internal']['mtt_log_file'])) # Log the PID PIDFile(cherrypy.engine, conf['internal']['PIDfile']).subscribe() # # Setup the service # Daemonizer(cherrypy.engine).subscribe() cherrypy.tools.CORS = cherrypy._cptools.HandlerTool(_CORS) cherrypy.tree.mount(Root(cfg), '/', conf) cherrypy.tree.mount(Submit(cfg), '/submit', conf) cherrypy.tree.mount(Fields(cfg), '/fields', conf) cherrypy.tree.mount(Summary(cfg), '/summary', conf) cherrypy.tree.mount(Detail(cfg), '/detail', conf) logger.info('Starting cherrypy engine') cherrypy.engine.start()
def main(): global log if (sys.platform == 'win32' and sys.executable.split('\\')[-1] == 'pythonw.exe'): sys.stdout = open(os.devnull, "w") sys.stderr = open(os.devnull, "w") desc = "Gazee: Open Comic Book Reader" parser = argparse.ArgumentParser(description=desc) parser.add_argument('-d', '--daemon', action='store_true', help='Run as a daemon') parser.add_argument('-c', '--datadir', default="~/.gazee/", type=str, help='Set data directory') parser.add_argument('-v', dest="verbosity", action="count", default=0, help="Every time this flag appears on the cmdline, " "the verbosity increases.") parser.add_argument('--pidfile', type=str, default="/var/run/gazee.pid", help="Specify the PID file to use when daemonizing") args = parser.parse_args() rootdir = os.path.realpath(os.path.dirname(gazee.__file__)) pubdir = os.path.join(rootdir, 'public') gcfg = gazee.gcfg(args.datadir) log_path = os.path.join(gazee.config.LOG_DIR, "gazee.log") log = init_root_logger(log_path) elog = logging.getLogger() if (args.verbosity == 1): log.setLevel(logging.INFO) elog.setLevel(logging.INFO) elif (args.verbosity > 1): log.setLevel(logging.DEBUG) elog.setLevel(logging.DEBUG) gazee.UncompressThread(cherrypy.engine).subscribe() gazee.ScanDirs(cherrypy.engine, interval=300, comic_path=gazee.config.COMIC_PATH, temp_path=gazee.config.TEMP_DIR, thumb_width=gazee.config.THUMB_MAXWIDTH, thumb_height=gazee.config.THUMB_MAXHEIGHT).subscribe() if args.daemon: if sys.platform == 'win32': log.info("Daemonize not supported under Windows.") else: # If the pidfile already exists, Gazee may still # be running, so exit if os.path.exists(args.pidfile): log.error("PID %s already exists. Exiting.", args.pidfile) sys.exit(1) else: cherrypy.config.update({'log.screen': False}) Daemonizer(cherrypy.engine).subscribe() try: PIDFile(cherrypy.engine, args.pidfile).subscribe() except IOError as e: raise SystemExit("Unable to write PID file: %s [%d]" % (e.strerror, e.errno)) gazee.ARGS = sys.argv conf = { '/': { 'tools.gzip.on': True, 'tools.gzip.mime_types': ['text/*', 'application/*', 'image/*'], 'tools.staticdir.on': False, 'tools.sessions.on': True, 'tools.sessions.timeout': 1440, 'tools.sessions.storage_class': cherrypy.lib.sessions.FileSession, 'tools.sessions.storage_path': gazee.config.SESSIONS_DIR, 'tools.basic_auth.on': True, 'tools.basic_auth.realm': 'Gazee', 'tools.basic_auth.users': gazee.gazee_settings_db.get_password, 'tools.basic_auth.encrypt': gazee.gazee_settings_db.hash_pass, 'request.show_tracebacks': False }, '/static': { 'tools.staticdir.on': True, 'tools.staticdir.dir': pubdir }, '/favicon.ico': { 'tools.staticfile.on': True, 'tools.staticfile.filename': os.path.join(pubdir, "images", "favicon.ico") } } if (gazee.config.SSL_KEY == '') and (gazee.config.SSL_CERT == ''): options_dict = { 'server.socket_port': gazee.config.PORT, 'server.socket_host': gazee.config.BIND_ADDRESS, 'server.thread_pool': 16, 'log.screen': False, 'engine.autoreload.on': False, } else: options_dict = { 'server.socket_port': gazee.config.PORT, 'server.socket_host': gazee.config.BIND_ADDRESS, 'server.thread_pool': 30, 'server.ssl_module': 'builtin', 'server.ssl_certificate': gazee.config.SSL_CERT, 'server.ssl_private_key': gazee.config.SSL_KEY, 'log.screen': False, 'engine.autoreload.on': False, } cherrypy.config.update(options_dict) # cherrypy.engine.timeout_monitor.on = False cherrypy.tree.mount(gazee.Gazeesrv(), '/', config=conf) log.info("Gazee Started") cherrypy.engine.start() cherrypy.engine.block() log.info("Gazee exiting...") return