def quickstart(server_class, config=None, daemon=False): # daemonize the server if asked to if daemon: from cherrypy.process.plugins import Daemonizer Daemonizer(cherrypy.engine).subscribe() # define the socket host and port jflowconf = JFlowConfigReader() socket_opts = jflowconf.get_socket_options() # add the result directory if config is None or not '/' in config: config['/'] = {'tools.staticdir.root': jflowconf.get_work_directory()} else: link = os.path.join(config['/']['tools.staticdir.root'], "data") if not os.path.islink(link): os.symlink(jflowconf.get_work_directory(), link) config[os.path.join('/', JFlowServer.JFLOW_WDATA)] = {'tools.staticdir.on' : True, 'tools.staticdir.dir' : jflowconf.get_work_directory()} # remove any limit on the request body size; cherrypy's default is 100MB # (maybe we should just increase it ?) cherrypy.server.max_request_body_size = 0 # increase server socket timeout to 60s; we are more tolerant of bad # quality client-server connections (cherrypy's default is 10s) cherrypy.server.socket_timeout = 60 cherrypy.config.update({'server.socket_host': socket_opts[0], 'server.socket_port': socket_opts[1]}) # start the server cherrypy.quickstart(server_class(), config=config)
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 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 _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
def server(port): 'Server initialization' Daemonizer(cherrypy.engine).subscribe() cherrypy.server.socket_host = '0.0.0.0' cherrypy.config.update({'server.socket_port': int(port)}) cherrypy.response.headers["Access-Control-Allow-Origin"] = "*" cherrypy.response.headers[ "Access-Control-Allow-Headers"] = "X-Requested-With" cherrypy.quickstart(MeshGramServer(), '/', 'config.txt')
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 _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 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 __init__(self, database, stateIndex): self.database = database self.stateIndex = stateIndex self.fileIds = {} logging.debug("FileIds Id: %s" % id(self.fileIds)) logging.info("Starting Webserver!") root = Root(self.fileIds, self.stateIndex, self.database) root.download = Download(self.fileIds) config = {"server.socket_host": "0.0.0.0", "server.socket_port": 8010} cherrypy.config.update(config) d = Daemonizer(cherrypy.engine) d.subscribe() cherrypy.tree.mount(root) cherrypy.engine.start()
def run_server(flask_app): #enable WSGI logging via paste api_logged=TransLogger(flask_app) #Mount the WSgi callable object (app) on root dir cherrypy.tree.graft(api_logged,'/') #set the configuration of the webserver cherrypy.config.update({'engine.autoreload.on':True,'log.screen':True, 'server.socket_port':8199, 'server.socket_host':"localhost"}) Daemonizer(cherrypy.engine).subscribe() #start the cherrypy WSGI web server cherrypy.engine.start() cherrypy.engine.block()
def start_server(): try: config_file = Utils.get_config_file() Config(api_url=config_file['quickStart']['url'], api_key=config_file['quickStart']['key'], products=config_file['quickStart']['products']) logger.setLevel(config_file['quickStart']['log_level']) logger.addHandler(FileHandler(config_file['logFilename'])) daemonizer = Daemonizer(cherrypy.engine) daemonizer.subscribe() # Configure and launch cherrypy.config.update( {'server.socket_port': config_file['executionPort']}) cherrypy.quickstart(FulfilmentExecution(config_file)) except Exception as err: raise err
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") }) Daemonizer(cherrypy.engine).subscribe() PIDFile(cherrypy.engine, 'astre.pid').subscribe() cherrypy.quickstart(Root())
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 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 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()
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 __call__(app, dataset=None, daemonize=False): apps = assure_list(app) if not apps: raise ValueError('no app specification given') if not isinstance(apps[0], (list, tuple)): apps = [apps] apps = { a[0] if isinstance(a, (list, tuple)) else a: a[1] if isinstance(a, (list, tuple)) and len(a) > 1 else None for a in apps } import cherrypy # global config cherrypy.config.update({ # prevent visible tracebacks, etc: # http://docs.cherrypy.org/en/latest/config.html#id14 #'environment': 'production', #'log.error_file': 'site.log', }) # set the priority according to your needs if you are hooking something # else on the 'before_finalize' hook point. @cherrypy.tools.register('before_finalize', priority=60) def secureheaders(): headers = cherrypy.response.headers headers['X-Frame-Options'] = 'DENY' headers['X-XSS-Protection'] = '1; mode=block' headers['Content-Security-Policy'] = "default-src='self'" # only add Strict-Transport headers if we're actually using SSL; see the ietf spec # "An HSTS Host MUST NOT include the STS header field in HTTP responses # conveyed over non-secure transport" # http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-14#section-7.2 if (cherrypy.server.ssl_certificate != None and cherrypy.server.ssl_private_key != None): headers[ 'Strict-Transport-Security'] = 'max-age=31536000' # one year if daemonize: from cherrypy.process.plugins import Daemonizer Daemonizer(cherrypy.engine).subscribe() #PIDFile(cherrypy.engine, '/var/run/myapp.pid').subscribe() # when running on a priviledged port #DropPrivileges(cherrypy.engine, uid=1000, gid=1000).subscribe() enabled_apps = [] for ep in iter_entry_points('datalad.webapps'): if ep.name not in apps: continue mount = apps[ep.name] if apps[ep.name] else '/' # get the webapp class cls = ep.load() # fire up the webapp instance inst = cls(**dict(dataset=dataset)) # mount under global URL tree (default or given suburl) app = cherrypy.tree.mount( root=inst, script_name=mount, # app config file, it is ok for that file to not exist config=cls._webapp_config) # forcefully impose more secure mode # TODO might need one (or more) switch(es) to turn things off for # particular scenarios enabled_apps.append(ep.name) app.merge({ '/': { # turns all security headers on 'tools.secureheaders.on': True, 'tools.sessions.secure': True, 'tools.sessions.httponly': True } }) static_dir = opj(cls._webapp_dir, cls._webapp_staticdir) if isdir(static_dir): app.merge({ # the key has to be / even when an app is mount somewhere # below '/': { 'tools.staticdir.on': True, 'tools.staticdir.root': cls._webapp_dir, 'tools.staticdir.dir': cls._webapp_staticdir } }) failed_apps = set(apps).difference(enabled_apps) if failed_apps: lgr.warning('Failed to load webapps: %s', failed_apps) if not enabled_apps: return cherrypy.engine.start() cherrypy.engine.block() yield {}
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
# You must use the builtin SSL option. If you use pyOpenSLL you get the error below (see history) cherrypy.server.ssl_module = 'builtin' if Options().ssl_certificate != '': cherrypy.server.ssl_certificate = Options().ssl_certificate 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.')
def run(app_directory, listener_address=None, no_logs=False, running_describe=False): """ When an application is run, the following is performed: - Identify application root - Check for qwstart.py on - Startup script directory - Current working directory - Setup port number, if $PORT is not set, use a random port """ start_t = time() # Use for startup time calculation print("** Starting application %s using QuickWeb %s " % (info(app_directory), info(quickweb.version.version))) startup_cwd = os.getcwd() # Check if beeing run from gunicorn is_gunicorn = "gunicorn" in os.environ.get("SERVER_SOFTWARE", "") if is_gunicorn: sys.stderr.write( "Quickweb provides it's own HTTP server module.\n" "Running from another HTTP server is not supported at this time\n") sys.exit(1) # Identify the application root directory app_root_directory = app_directory or os.getcwd() startup.setup_app("app_name", app_root_directory, no_logs) if running_describe: return colored_elapsed_time = info("%0.2fms" % ((time() - start_t) * 1000.0)) print("=" * 10 + " Startup completed in " + colored_elapsed_time) # Determine the HTTP listener port listener_port = int(os.getenv("PORT", 8080)) if os.name == "posix": socket_host = "0.0.0.0" else: socket_host = "127.0.0.1" if listener_address is not None: socket_host = listener_address cherrypy.config.update({"server.socket_host": socket_host}) cherrypy.config.update({"server.socket_port": listener_port}) ssl_certificate = os.environ.get("SSL_CERTIFICATE") if ssl_certificate: ssl_adapter = BuiltinSSLAdapter( certificate=ssl_certificate, private_key=os.environ["SSL_PRIVATE_KEY"], certificate_chain=os.environ.get("SSL_CERTIFICATE_CHAIN"), ) verify_mode = ssl.CERT_NONE if os.getenv("SSL_VERIFY_CLIENT_CERT") == "required": verify_mode = ssl.CERT_REQUIRED if os.getenv("SSL_VERIFY_CLIENT_CERT") == "optional": verify_mode = ssl.CERT_OPTIONAL ssl_adapter.context.verify_mode = verify_mode HTTPServer.ssl_adapter = ssl_adapter # In some platforms signals are not available: if hasattr(cherrypy.engine, "signals"): cherrypy.engine.signals.subscribe() cherrypy.engine.subscribe("stop", lambda: os.chdir(startup_cwd)) if os.environ.get("DAEMON_MODE"): daemon = Daemonizer(cherrypy.engine, stdout='stdout.log', stderr='stderr.log') daemon.subscribe() PIDFile(cherrypy.engine, 'quickweb.pid').subscribe() cherrypy.engine.start() cherrypy.engine.block()
# existing configuration. for entry in proxy_conf: conf["/"][entry] = proxy_conf[entry] if ll_mirror: ds.DNSSD_Plugin(cherrypy.engine, gconf).subscribe() if reindex: # Tell depot to update search indexes when possible; # this is done as a background task so that packages # can be served immediately while search indexes are # still being updated. depot._queue_refresh_index() # If stdin is not a tty and the pkgdepot controller isn't being used, # then assume process should be daemonized. if not os.environ.get("PKGDEPOT_CONTROLLER") and \ not os.isatty(sys.stdin.fileno()): # Translate the values in log_cfg into paths. Daemonizer(cherrypy.engine, stderr=log_cfg["errors"], stdout=log_cfg["access"]).subscribe() try: root = cherrypy.Application(depot) cherrypy.quickstart(root, config=conf) except Exception as _e: emsg("pkg.depotd: unknown error starting depot server, " \ "illegal option value specified?") emsg(_e) sys.exit(1)
) auth = AuthController() cherrypy.tree.mount(auth, '{}/auth'.format(core.URL_BASE), auth.conf ) # if everything goes well so far, open the browser if passed_args.browser or core.CONFIG['Server']['launchbrowser'] == 'true': webbrowser.open("http://{}:{}{}".format( core.SERVER_ADDRESS, core.SERVER_PORT, core.URL_BASE)) logging.info('Launching web browser.') # daemonize in *nix if desired if passed_args.daemon and os.name == 'posix': Daemonizer(cherrypy.engine).subscribe() # start engine cherrypy.engine.signals.subscribe() cherrypy.engine.start() # Create plugin instances and subscribe scheduler_plugin = scheduler.Scheduler() scheduler.AutoSearch.create() scheduler.AutoUpdateCheck.create() scheduler.AutoUpdateInstall.create() scheduler_plugin.plugin.subscribe() # If windows os and daemon selected, start systray if passed_args.daemon and os.name == 'nt': systrayplugin = systray.SysTrayPlugin(cherrypy.engine)
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)
def serve(**kwargs): """ Spawn a new running Cherrypy process usage: blubeberry serve [options] options: -h, --help show this help message and exit -b BINDING, --bind BINDING the address and port to bind to. [default: 127.0.0.1:8080] -e ENVIRONMENT, --environment ENVIRONMENT apply the given config environment -C ENV_VAR_NAME, --env-var ENV_VAR_NAME add the given config from environment variable name [default: BLUEBERRYPY_CONFIG] -f start a fastcgi server instead of the default HTTP server -s start a scgi server instead of the default HTTP server -d, --daemonize run the server as a daemon. [default: False] -p, --drop-privilege drop privilege to separately specified umask, uid and gid. [default: False] -P PIDFILE, --pidfile PIDFILE store the process id in the given file -u UID, --uid UID setuid to uid [default: www] -g GID, --gid GID setgid to gid [default: www] -m UMASK, --umask UMASK set umask [default: 022] """ config = BlueberryPyConfiguration(config_dir=kwargs.get('config_dir'), env_var_name=kwargs.get('env_var')) cpengine = cherrypy.engine cpenviron = kwargs.get("environment") if cpenviron: config = BlueberryPyConfiguration(config_dir=kwargs.get('config_dir'), env_var_name=kwargs.get('env_var'), environment=cpenviron) cherrypy.config.update({"environment": cpenviron}) if config.use_email and config.email_config: from blueberrypy import email email.configure(config.email_config) if config.use_logging and config.logging_config: from blueberrypy.plugins import LoggingPlugin cpengine.logging = LoggingPlugin(cpengine, config=config.logging_config) if config.use_redis: from blueberrypy.session import RedisSession cherrypy.lib.sessions.RedisSession = RedisSession if config.use_sqlalchemy: from blueberrypy.plugins import SQLAlchemyPlugin cpengine.sqlalchemy = SQLAlchemyPlugin(cpengine, config=config.sqlalchemy_config) from blueberrypy.tools import SQLAlchemySessionTool cherrypy.tools.orm_session = SQLAlchemySessionTool() if config.use_jinja2: if config.webassets_env: configure_jinja2(assets_env=config.webassets_env, **config.jinja2_config) else: configure_jinja2(**config.jinja2_config) # update global config first, so subsequent command line options can # override the settings in the config files cherrypy.config.update(config.app_config) if kwargs.get("bind"): address, port = kwargs.get("bind").strip().split(":") cherrypy.server.socket_host = address cherrypy.server.socket_port = int(port) if kwargs.get("daemonize"): cherrypy.config.update({'log.screen': False}) Daemonizer(cpengine).subscribe() if kwargs.get("drop_privilege"): cherrypy.config.update({'engine.autoreload_on': False}) DropPrivileges(cpengine, umask=int(kwargs.get("umask")), uid=kwargs.get("uid") or "www", gid=kwargs.get("gid") or "www").subscribe() if kwargs.get("pidfile"): PIDFile(cpengine, kwargs.get("pidfile")).subscribe() fastcgi, scgi = kwargs.get("fastcgi"), kwargs.get("scgi") if fastcgi and scgi: cherrypy.log.error("You may only specify one of the fastcgi and " "scgi options.", 'ENGINE') sys.exit(1) elif fastcgi or scgi: # Turn off autoreload when using *cgi. cherrypy.config.update({'engine.autoreload_on': False}) # Turn off the default HTTP server (which is subscribed by default). cherrypy.server.unsubscribe() addr = cherrypy.server.bind_addr if fastcgi: f = servers.FlupFCGIServer(application=cherrypy.tree, bindAddress=addr) elif scgi: f = servers.FlupSCGIServer(application=cherrypy.tree, bindAddress=addr) s = servers.ServerPlugin(cpengine, httpserver=f, bind_addr=addr) s.subscribe() if hasattr(cpengine, 'signal_handler'): cpengine.signal_handler.subscribe() # for win32 only if hasattr(cpengine, "console_control_handler"): cpengine.console_control_handler.subscribe() # mount the controllers for script_name, section in config.controllers_config.viewitems(): section = section.copy() controller = section.pop("controller") if isinstance(controller, cherrypy.dispatch.RoutesDispatcher): routes_config = {'/': {"request.dispatch": controller}} for path in section.viewkeys(): if path.strip() == '/': routes_config['/'].update(section['/']) else: routes_config[path] = section[path].copy() app_config = config.app_config.copy() app_config.pop("controllers") routes_config.update(app_config) cherrypy.tree.mount(None, script_name=script_name, config=routes_config) else: app_config = config.app_config.copy() app_config.pop("controllers") controller_config = section.copy() controller_config.update(app_config) cherrypy.tree.mount(controller(), script_name=script_name, config=controller_config) # Add the blueberrypy config files into CP's autoreload monitor # Jinja2 templates are monitored by Jinja2 itself and will autoreload if # needed if config.config_file_paths: for path in config.config_file_paths: cpengine.autoreload.files.add(path) try: cpengine.start() except: sys.exit(1) else: cpengine.block()
"/" + sysadminboard_module.module_name, controller=sysadminboard_module, action='index') mapper.connect(sysadminboard_module.module_name + '/ajax', "/" + sysadminboard_module.module_name + '/ajax', controller=sysadminboard_module, action='ajax') # Here we define a location for non-python files CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_DIR = os.path.join(CURRENT_DIR, u"static") CONFIG = { '/': { 'request.dispatch': mapper, # use a dispatcher to assign URLs }, '/static': { 'tools.staticdir.on': True, 'tools.staticdir.dir': STATIC_DIR }, } #=================Disable this line when debugging============== Daemonizer( cherrypy.engine).subscribe() # When we start, do it as a daemon process #=============================================================== cherrypy.config.update({'server.socket_host': '0.0.0.0'}) # Listen on all local IPs (on port 8080) cherrypy.tree.mount(root, '/', config=CONFIG) # Mount the app on the root cherrypy.engine.start() # Start the web server
def main(): logging.basicConfig(level=logging.DEBUG, filename='data/gazee.log') logger = logging.getLogger(__name__) parser = argparse.ArgumentParser( description='Gazee - Open Comic Book Reader') parser.add_argument('-d', '--daemon', action='store_true', help='Run as a daemon') args = parser.parse_args() if args.daemon: if sys.platform == 'win32': logger.info( "Daemonize not supported under Windows, starting normally") else: # If the pidfile already exists, Gazee may still be running, so exit if os.path.exists(gazee.PIDFILE): sys.exit("PID file '" + gazee.PIDFILE + "' already exists. Exiting.") # The pidfile is only useful in daemon mode, make sure we can write the file properly try: PIDFile(cherrypy.engine, gazee.PIDFILE).subscribe() except IOError as e: raise SystemExit("Unable to write PID file: %s [%d]" % (e.strerror, e.errno)) Daemonizer(cherrypy.engine).subscribe() conf = { '/': { 'tools.gzip.on': True, 'tools.gzip.mime_types': ['text/*', 'application/*', 'image/*'], 'tools.sessions.on': True, 'tools.sessions.timeout': 1440, 'tools.sessions.storage_class': cherrypy.lib.sessions.FileSession, 'tools.sessions.storage_path': "data/sessions", 'tools.staticdir.root': os.path.abspath(os.getcwd()), 'tools.basic_auth.on': True, 'tools.basic_auth.realm': 'Gazee', 'tools.basic_auth.users': gazee.authmech.getPassword, 'tools.basic_auth.encrypt': gazee.authmech.hashPass, 'request.show_tracebacks': False }, '/static': { 'tools.staticdir.on': True, 'tools.staticdir.dir': "public" }, '/data': { 'tools.staticdir.on': True, 'tools.staticdir.dir': "data" }, '/tmp': { 'tools.staticdir.on': True, 'tools.staticdir.dir': "tmp" }, '/favicon.ico': { 'tools.staticfile.on': True, 'tools.staticfile.filename': os.path.join(os.getcwd(), "public/images/favicon.ico") } } if (gazee.SSL_KEY == '') and (gazee.SSL_CERT == ''): options_dict = { 'server.socket_port': gazee.PORT, 'server.socket_host': '0.0.0.0', 'server.thread_pool': 30, 'log.screen': False, 'engine.autoreload.on': False, } else: options_dict = { 'server.socket_port': gazee.PORT, 'server.socket_host': '0.0.0.0', 'server.thread_pool': 30, 'server.ssl_module': 'builtin', 'server.ssl_certificate': gazee.SSL_CERT, 'server.ssl_private_key': gazee.SSL_KEY, 'log.screen': False, 'engine.autoreload.on': False, } cherrypy.config.update(options_dict) cherrypy.engine.timeout_monitor.on: False cherrypy.tree.mount(Gazee(), '/', config=conf) logging.info("Gazee Started") cherrypy.engine.start() scanner = ComicScanner() scanner.rescanDB() cherrypy.engine.block() if (os.path.exists(os.path.join(gazee.DATA_DIR, 'db.lock'))): os.remove(gazee.DATA_DIR, 'db.lock') return