Example #1
0
	def run(self):
		from cherrypy.process.plugins import Daemonizer
		d = Daemonizer(
			cherrypy.engine, stdout=config.get_log_file(),
			stderr=config.get_error_file())
		d.subscribe()
		with start_server(self.configs):
			cherrypy.engine.block()
Example #2
0
 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()
Example #3
0
  def run(self):
    from cherrypy._cpnative_server import CPHTTPServer
    cherrypy.server.httpserver = CPHTTPServer(cherrypy.server)

    engine = cherrypy.engine

    if hasattr(engine, "signal_handler"):
      engine.signal_handler.subscribe()

    if hasattr(engine, "console_control_handler"):
      engine.console_control_handler.subscribe()

    from cherrypy.process.plugins import Daemonizer
    d = Daemonizer(cherrypy.engine)
    d.subscribe()

    engine.start()

    engine.block()
Example #4
0
def mount_static_page(static_page_dir, **kargs ):
    conf={
        '/':{
            'tools.staticdir.on':True,
            'tools.staticdir.dir':static_page_dir,
            'tools.patch_set_cookie.on':True
        }
    }
    run_as_daemon = public.get_arg('daemon', kargs, False)
    if run_as_daemon:
        logfile = public.get_arg('logfile', kargs, None)
        if logfile:
            daemon_eng = Daemonizer(cherrypy.engine, stdout=logfile, stderr=logfile)
        else:
            daemon_eng = Daemonizer(cherrypy.engine)
        daemon_eng.subscribe()
    if cherrypy_ver_maj < 3:
        cherrypy.tree.mount(AppPage(), conf=conf)
    else:
        cherrypy.tree.mount(AppPage(), config=conf)
Example #5
0
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()
Example #6
0
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
      -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"))

    cpengine = cherrypy.engine

    cpenviron = kwargs.get("environment")
    if cpenviron:
        config = BlueberryPyConfiguration(config_dir=kwargs.get("config_dir"),
                                          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()
Example #7
0
    request = cherrypy.serving.request
    # Ignore all status requests as they do nothing but fill up the log
    if request.request_line != "GET /api/playr?fn=status HTTP/1.1":
      return LogManager.access(self)

class Html(object): pass

parser = argparse.ArgumentParser()
parser.add_argument("--daemon", help="Run as daemon process", 
                    action="store_true")
parser.add_argument("--port", type=int, help="Listen port (default 6969)")
args = parser.parse_args()

engine = cherrypy.engine
if args.daemon:
  Daemonizer(engine).subscribe()

cleanup()

cherrypy.log = IgnoreStatusLogger()

cherrypy.tree.mount(Api(), '/api')
cherrypy.tree.mount(Html(), '/', config = {
  '/': {
          'tools.staticdir.on': True,
          'tools.staticdir.dir': locations.HTML_PATH,
          'tools.staticdir.index': 'index.html',
    },
  })

def exit():
Example #8
0
def main():
    # http://bugs.python.org/issue7980 - Need to load strptime from main thread
    # so that it does not complain later in the process
    datetime.strptime('2010-01-01 00:00:00.000000', '%Y-%m-%d %H:%M:%S.%f')

    options, args, parser = command_line_handler()

    cherrypy.tree.mount(
        Unicorn(), '/', {
            '/static': {
                'tools.staticdir.on':
                True,
                'tools.staticdir.dir':
                static_dir,
                'tools.response_headers.on':
                True,
                'tools.response_headers.headers':
                [('Cache-Control', 'max-age=3600, must-revalidate'),
                 ('Proxy-Connection', 'close')]
            }
        })

    cherrypy.server.socket_host = options.ip_address
    cherrypy.server.socket_port = options.port

    db.set_up(options.db_user, options.db_password, options.db_name,
              options.db_host, options.db_port)
    if options.reset:
        print 'Resetting trailerpark database'
        db.tear_down(options.db_user, options.db_password, options.db_name,
                     options.db_host, options.db_port)
    db.create_tables(options.db_user, options.db_password, options.db_name,
                     options.db_host, options.db_port)
    if options.stop:
        try:
            with open(options.pid_file, 'r') as f:
                pid = int(f.read())
                print 'Stutting down service with PID %d' % pid
                os.kill(pid, signal.SIGTERM)
                os.remove(options.pid_file)
                sys.exit(1)
        except IOError:
            print 'No PID file found, aborting shutdown.'
            sys.exit(1)

    if options.daemon:
        from cherrypy.process.plugins import Daemonizer, PIDFile
        if os.path.exists(options.pid_file):
            print 'Cannot start process - PID file already exists: %s' % options.pid_file
            sys.exit(1)

        # Daemonise the process
        Daemonizer(cherrypy.engine).subscribe()
        # -- Manage the pid: this will create the pid file on start-up and delete on shutdown
        PIDFile(cherrypy.engine, options.pid_file).subscribe()

    if hasattr(cherrypy.engine, 'signal_handler'):
        cherrypy.engine.signal_handler.subscribe()
    if hasattr(cherrypy.engine, 'console_control_handler'):
        cherrypy.engine.console_control_handler.subscribe()
    try:
        cherrypy.engine.start()
    except IOError:
        print 'Unable to bind to address ({0}, {1}'.format(
            options.ip_address, cherrypy.port)
        sys.exit(1)
    cherrypy.engine.wait(cherrypy.process.wspbus.states.STARTED)
    cherrypy.engine.block()  # Wait until the app is started before proceeding
Example #9
0
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

    # Configure default server
    cherrypy.config.update({
        'server.socket_host': cfg.host,
        'server.socket_port': cfg.port,
        'server.thread_pool': 10,
        # Avoid stating files once per second in production
        'engine.autoreload.on': cfg.debug,
    })

    application = django.core.wsgi.get_wsgi_application()
    cherrypy.tree.graft(application, cfg.server_dir)

    static_dir = os.path.join(cfg.file_root, 'static')
    config = {
        '/': {
            'tools.staticdir.root': static_dir,
            'tools.staticdir.on': True,
            'tools.staticdir.dir': '.'
        }
    }
    cherrypy.tree.mount(None, django.conf.settings.STATIC_URL, config)
    logger.debug('Serving static directory %s on %s', static_dir,
                 django.conf.settings.STATIC_URL)

    js_dir = '/usr/share/javascript'
    js_url = '/javascript'
    config = {
        '/': {
            'tools.staticdir.root': js_dir,
            'tools.staticdir.on': True,
            'tools.staticdir.dir': '.'
        }
    }
    cherrypy.tree.mount(None, js_url, config)
    logger.debug('Serving javascript directory %s on %s', js_dir, js_url)

    manual_dir = os.path.join(cfg.doc_dir, 'images')
    manual_url = '/'.join([cfg.server_dir, 'help/manual/images']) \
        .replace('//', '/')
    config = {
        '/': {
            'tools.staticdir.root': manual_dir,
            'tools.staticdir.on': True,
            'tools.staticdir.dir': '.'
        }
    }
    cherrypy.tree.mount(None, manual_url, config)
    logger.debug('Serving manual images %s on %s', manual_dir, manual_url)

    for module_import_path in module_loader.loaded_modules:
        module = importlib.import_module(module_import_path)
        module_name = module_import_path.split('.')[-1]
        module_path = os.path.dirname(module.__file__)
        static_dir = os.path.join(module_path, 'static')
        if not os.path.isdir(static_dir):
            continue

        config = {
            '/': {
                'tools.staticdir.root': static_dir,
                'tools.staticdir.on': True,
                'tools.staticdir.dir': '.'
            }
        }
        urlprefix = "%s%s" % (django.conf.settings.STATIC_URL, module_name)
        cherrypy.tree.mount(None, urlprefix, config)
        logger.debug('Serving static directory %s on %s', static_dir,
                     urlprefix)

    if not cfg.no_daemon:
        Daemonizer(cherrypy.engine).subscribe()

    cherrypy.engine.signal_handler.subscribe()
Example #10
0
    def run(self) -> None:
        """ Starts the application """
        #### Command Line Argument Parsing
        parser = argparse.ArgumentParser(description='ARPOC')
        parser.add_argument('-c', '--config-file')
        parser.add_argument('--print-sample-config', action='store_true')
        parser.add_argument('--print-sample-ac', action='store_true')
        parser.add_argument('--add-provider')
        parser.add_argument('--client-id')
        parser.add_argument('--client-secret')
        parser.add_argument('-d', '--daemonize', action='store_true')
        parser.add_argument('--check-ac', action='store_true')

        args = parser.parse_args()

        config.cfg = config.OIDCProxyConfig(config_file=args.config_file)
        self.config = config.cfg

        assert self.config.proxy is not None

        #### Read Configuration
        if args.print_sample_config:
            config.cfg.print_sample_config()
            return

        if args.print_sample_ac:
            arpoc.ac.print_sample_ac()
            return
        self.setup_loggers()

        #### Create secrets dir and change ownership (perm)
        self.create_secrets_dir()

        self.oidc_handler = OidcHandler(self.config)

        if args.add_provider and args.client_id and args.client_secret:
            # read secrets
            secrets = self.read_secrets(self.config.proxy['secrets'])

            provider_cfg = self.config.openid_providers[args.add_provider]
            redirect_uris = provider_cfg.redirect_uris or self.config.proxy[
                'redirect_uris']

            # add secrets
            secret_dict = {
                "client_id": args.client_id,
                "client_secret": args.client_secret,
                "redirect_uris": args.redirect_uris
            }
            secrets[args.add_provider] = secret_dict
            self.oidc_handler._secrets = secrets
            self.oidc_handler.create_client_from_secrets(
                args.add_provider, provider_cfg)
            self.save_secrets()
            return

        #### Read AC Rules
        for acl_dir in self.config.access_control['json_dir']:
            ServiceProxy.ac.load_dir(acl_dir)

        if args.check_ac:
            ServiceProxy.ac.check()
            return

        if args.daemonize:
            daemonizer = Daemonizer(cherrypy.engine)
            daemonizer.subscribe()
            # check if pid file exists
            try:
                with open(self.config.misc.pid_file) as pidfile:
                    pid = int(pidfile.read().strip())
                    try:
                        os.kill(pid, 0)  # check if running
                    except OSError:
                        PIDFile(cherrypy.engine,
                                self.config.misc.pid_file).subscribe()
                        # not running
                    else:
                        # running
                        print("PID File %s exists" % self.config.misc.pid_file)
                        print("Another instance of arpoc seems to be running")
                        return
            except FileNotFoundError:
                PIDFile(cherrypy.engine, self.config.misc.pid_file).subscribe()

        #### Setup OIDC Provider
        cherrypy.engine.subscribe('start', self.setup_oidc_provider, 80)
        cherrypy.engine.subscribe('stop', self.cancel_scheduler, 80)
        cherrypy.engine.subscribe('stop', self.save_secrets, 80)
        #### Setup Cherrypy
        global_conf = {
            'log.screen': False,
            'log.access_file': '',
            'log.error_file': '',
            'server.socket_host': config.cfg.proxy['address'],
            'server.socket_port': config.cfg.proxy['tls_port'],
            'server.ssl_private_key': config.cfg.proxy['keyfile'],
            'server.ssl_certificate': config.cfg.proxy['certfile'],
            'engine.autoreload.on': False
        }
        cherrypy.config.update(global_conf)
        app_conf = {
            '/': {
                'tools.sessions.on': True,
                'request.dispatch': self.get_routes_dispatcher()
            }
        }
        DropPrivileges(cherrypy.engine, uid=self.uid, gid=self.gid).subscribe()

        #### Start Web Server
        cherrypy.tree.mount(None, '/', app_conf)
        if self.config.proxy['plain_port']:
            server2 = cherrypy._cpserver.Server()
            server2.socket_port = self.config.proxy['plain_port']
            server2._socket_host = self.config.proxy['address']
            server2.thread_pool = 30
            server2.subscribe()

        cherrypy.engine.start()
        cherrypy.engine.block()
Example #11
0
def start():
    """ Main function for starting HTTP server """
    logger = logging.getLogger('htpc.server')
    logger.debug("Setting up to start cherrypy")

    # Set server ip, port and root
    cherrypy.config.update({
        'server.socket_host': htpc.HOST,
        'server.socket_port': htpc.PORT,
        'log.screen': False
    })

    # 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()
        except SQLObjectNotFound:
            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':60
        })

    # Set server environment to production unless when debugging
    if not htpc.DEBUG:
        cherrypy.config.update({
            'environment': 'production'
        })

    # Enable SSL
    if htpc.SSLCERT and htpc.SSLKEY:
        cherrypy.config.update({
            'server.ssl_module': 'builtin',
            'server.ssl_certificate': htpc.SSLCERT,
            'server.ssl_private_key': htpc.SSLKEY
        })

    # 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()

    # 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 * 6,
            'tools.staticdir.on': True,
            '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 * 6,
            'tools.staticdir.on': True,
            '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 * 6,
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'img'
        },
        '/favicon.ico': {
            'tools.caching.on': True,
            'tools.caching.force': True,
            'tools.caching.delay': 0,
            'tools.expires.on': True,
            'tools.expires.secs': 60 * 60 * 6,
            'tools.staticfile.on': True,
            'tools.staticfile.filename': favicon
        },
    }

    # Start the CherryPy server (remove trailing slash from webdir)
    logger.info("Starting up webserver")
    print '******************************************************'
    print 'Starting HTPC Manager on port ' + str(htpc.PORT) + '.'
    print 'Start your browser and go to http://localhost:' + str(htpc.PORT) + htpc.WEBDIR[:-1]
    print '******************************************************'
    cherrypy.quickstart(htpc.ROOT, htpc.WEBDIR[:-1], config=app_config)
Example #12
0
def run_cmd(parsed_args):
    PIDFile(cherrypy.engine, parsed_args.pidfile).subscribe()
    if not parsed_args.foreground:
        Daemonizer(cherrypy.engine).subscribe()
Example #13
0
    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)

# Vim hints
# vim:ts=8:sw=8:et:fdm=marker
Example #14
0
                   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, "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
# ===============================================================
logger.info("Starting up SysAdminBoard web server...")
cherrypy.log.access_log.propagate = False  # Disable access logging
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
Example #15
0
    conf = {
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': os.path.abspath('./public')
        },
        '/slides': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': os.path.abspath('./slides')
        },
        '/': {
            'tools.sessions.on': True
        }
    }    

    if args.daemonize:
        d = Daemonizer(cherrypy.engine, stderr='/var/log/missionary_server.log')
        d.subscribe()
        PIDFile(cherrypy.engine, '/var/run/missionary_server.pid').subscribe()
        DropPrivileges(cherrypy.engine, uid=1000, gid=1000).subscribe()

    # cherrypy.config.update({'log.screen': False,
    #                         'log.access_file': '',
    #                         'log.error_file': ''})

    settings = Settings('settings.json')
    cherrypy.tree.mount(Root(settings), '/', conf)
    cherrypy.tree.mount(SlideShow('./slides'), '/slideshow', conf)
    cherrypy.tree.mount(Local(), '/local')
    cherrypy.tree.mount(Missionary(settings), '/missionary')
    cherrypy.tree.mount(PhotoUploader(os.path.abspath('./slides')), '/photos', conf)
    cherrypy.tree.mount(settings, '/settings', conf)
Example #16
0
    def stripejs(self, *args, **kwargs):
        print '\nArgs: {}'.format(args)
        print '\nKwrgs: {}'.format(kwargs)

        return s_template('stripe_js.mako')


##
# Server
if os.environ.get('DEV_STATE') == 'PRODUCTION':
    print '\n\n Im {}'.format(os.environ.get('DEV_STATE'))
    # Set PID
    from cherrypy.process.plugins import PIDFile
    p = PIDFile(cpy.engine, "/opt/python/pids/cherrypy-basic.pid")
    p.subscribe()

    # INIT
    from cherrypy.process.plugins import Daemonizer
    Daemonizer(cpy.engine).subscribe()

    cpy.config.update(current_dir + '/conf/cherry_conf')
    cpy.tree.mount(Root(), "/", config=current_dir + '/conf/cherry_conf')

    cpy.engine.start()
    cpy.engine.block()

else:
    print '\n\n Im {}'.format(os.environ.get('DEV_STATE'))
    cpy.config.update('conf/cherry_conf')
    cpy.tree.mount(Root(), '/')
round(((
    (
        SELECT EXTRACT(EPOCH FROM SUM(duration)::interval)
        FROM PeriodsSummary P2
        WHERE P2.status = 'A'
        AND P2.name = P.name
    )
    /
    (
        SELECT EXTRACT(EPOCH FROM (NOW() - MIN(start)))
        FROM PeriodsSummary P2
        WHERE P2.name = P.name
    )
) * 100)::numeric, 2) AS uptime
FROM PeriodsSummary P
GROUP BY name
ORDER BY mttf ASC;
""");
        return InterfaceTemplate.render(rows=db_cursor.fetchall())

    index.exposed = True


if __name__ == "__main__":
    cherrypy.server.socket_host = sys.argv[1]
    cherrypy.server.socket_port = int(sys.argv[2])

    daemon = Daemonizer(cherrypy.engine)
    daemon.subscribe()
    cherrypy.quickstart(Print2HereWeb())
Example #18
0
                if k == "id":
                    yield int(v)
                elif k == "children":
                    for child in self.setOrder_generator(v):
                        _id = int(i["id"])
                        yield {_id: child}


class APIController(object):
    exposed = True
    article = ArticleAPI()
    tag = TagAPI()
    ## Any other APIs can share this mount point


### Config ###

if __name__ == '__main__':
    daemon = Daemonizer(cherrypy.engine)
    daemon.subscribe()
    cherrypy.config.update('config/app.conf')
    SAEnginePlugin(cherrypy.engine).subscribe()
    cherrypy.tools.db = SATool()
    cherrypy.tree.mount(ClientController(), '/', config='config/app.conf')
    cherrypy.tree.mount(APIController(),
                        '/admin/api',
                        config='config/api.conf')
    cherrypy.tree.mount(AdminController(), '/admin')

cherrypy.engine.start()
cherrypy.engine.block()
Example #19
0
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)

    static_dir = os.path.join(cfg.file_root, 'static')
    config = {
        '/': {
            'tools.staticdir.root': static_dir,
            'tools.staticdir.on': True,
            'tools.staticdir.dir': '.'
        }
    }
    cherrypy.tree.mount(None, django.conf.settings.STATIC_URL, config)
    LOGGER.debug('Serving static directory %s on %s', static_dir,
                 django.conf.settings.STATIC_URL)

    js_dir = '/usr/share/javascript'
    js_url = '/javascript'
    config = {
        '/': {
            'tools.staticdir.root': js_dir,
            'tools.staticdir.on': True,
            'tools.staticdir.dir': '.'
        }
    }
    cherrypy.tree.mount(None, js_url, config)
    LOGGER.debug('Serving javascript directory %s on %s', js_dir, js_url)

    for module_import_path in module_loader.loaded_modules:
        module = importlib.import_module(module_import_path)
        module_name = module_import_path.split('.')[-1]
        module_path = os.path.dirname(module.__file__)
        static_dir = os.path.join(module_path, 'static')
        if not os.path.isdir(static_dir):
            continue

        config = {
            '/': {
                'tools.staticdir.root': static_dir,
                'tools.staticdir.on': True,
                'tools.staticdir.dir': '.'
            }
        }
        urlprefix = "%s%s" % (django.conf.settings.STATIC_URL, module_name)
        cherrypy.tree.mount(None, urlprefix, config)
        LOGGER.debug('Serving static directory %s on %s', static_dir,
                     urlprefix)

    if not cfg.no_daemon:
        Daemonizer(cherrypy.engine).subscribe()

    cherrypy.engine.signal_handler.subscribe()
Example #20
0
    def RunWebServer(self,isToDaemonize):
        LogEvent("Generating CherryPy configuration")
        cherrypy.config.update(config_path)
        css_path = os.path.join(app_path,'css')
        images_path = os.path.join(app_path,'images')
        navigation_images_path = os.path.join(css_path,'navigation_images')
        datatables_images_path = os.path.join(css_path,'datatables_images')
        js_path = os.path.join(app_path,'js')
        theme_path = os.path.join(css_path,'redmond')
        theme_images_path = os.path.join(theme_path,'images')
        config = ConfigParser.RawConfigParser()
        config.read('Gamez.ini')
        username = config.get('global','user_name').replace('"','')
        password = config.get('global','password').replace('"','')
        useAuth = False
        if(username <> "" or password <> ""):
            useAuth = True          	
        userPassDict = {username:password}  
        checkpassword = cherrypy.lib.auth_basic.checkpassword_dict(userPassDict)
        conf = {
        	'/':{'tools.auth_basic.on':useAuth,'tools.auth_basic.realm':'Gamez','tools.auth_basic.checkpassword':checkpassword},
                '/css': {'tools.staticdir.on':True,'tools.staticdir.dir':css_path},
                '/js':{'tools.staticdir.on':True,'tools.staticdir.dir':js_path},
                '/css/redmond':{'tools.staticdir.on':True,'tools.staticdir.dir':theme_path},
                '/css/redmond/images':{'tools.staticdir.on':True,'tools.staticdir.dir':theme_images_path},
                '/css/navigation_images':{'tools.staticdir.on':True,'tools.staticdir.dir':navigation_images_path},
                '/css/datatables_images':{'tools.staticdir.on':True,'tools.staticdir.dir':datatables_images_path},
            }
        
        if(isToDaemonize == 1):
            LogEvent("Preparing to run in daemon mode")  
            daemon = Daemonizer(cherrypy.engine)
            daemon.subscribe()        
        isSabEnabled = config.get('SystemGenerated','sabnzbd_enabled').replace('"','')
        if(isSabEnabled == "1"):
            LogEvent("Generating Post Process Script")
            GenerateSabPostProcessScript()
        RunGameTask()

        LogEvent("Getting download interval from config file and invoking scheduler")
        config = ConfigParser.RawConfigParser()
        config.read('Gamez.ini')
        interval = config.get('Scheduler','download_interval').replace('"','')
        updateGameListInterval = config.get('Scheduler','game_list_update_interval').replace('"','')
        fInterval = float(interval)
        fUpdateGameListInterval = float(updateGameListInterval)
        try:
            LogEvent("Setting up download scheduler")
            gameTasksScheduler = cherrypy.process.plugins.Monitor(cherrypy.engine,RunGameTask,fInterval)
            gameTasksScheduler.subscribe()
            LogEvent("Setting up game list update scheduler")
            gameListUpdaterScheduler = cherrypy.process.plugins.Monitor(cherrypy.engine,RunGameListUpdaterTask,fUpdateGameListInterval)
            gameListUpdaterScheduler.subscribe()
            LogEvent("Setting up folder processing scheduler")
            folderProcessingScheduler = cherrypy.process.plugins.Monitor(cherrypy.engine,RunFolderProcessingTask,float(900))
            folderProcessingScheduler.subscribe()
            LogEvent("Starting the Gamez web server")
            cherrypy.quickstart(WebRoot(app_path),'/',config=conf)
        except KeyboardInterrupt:
            LogEvent("Shutting down Gamez")
            if(isToDaemonize == 1):    
                daemon.unsubscribe()
            sys.exit()
Example #21
0
def main():
    parser = argparse.ArgumentParser(
        description='Gazee - Open Comic Book Reader')

    parser.add_argument('-d',
                        '--daemon',
                        action='store_true',
                        help='Run as a daemon')
    parser.add_argument('-c', '--datadir', help='Set data directory')
    parser.add_argument('-l', '--logdir', help='Set log directory')
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help='Set log level to debug')

    args = parser.parse_args()

    if args.datadir:
        gazee.DATA_DIR = args.datadir
        gazee.TEMP_DIR = os.path.join(args.datadir, 'tmp')

    if not os.path.exists(gazee.DATA_DIR):
        os.makedirs(os.path.abspath(gazee.DATA_DIR))

    if not os.path.exists(os.path.join(gazee.DATA_DIR, 'sessions')):
        os.makedirs(os.path.abspath(os.path.join(gazee.DATA_DIR, 'sessions')))

    if not os.path.exists(gazee.TEMP_DIR):
        os.makedirs(os.path.abspath(gazee.TEMP_DIR))

    from gazee import log
    if args.logdir:
        gazee.LOG_DIR = args.logdir
        gazee.ARGS += ["-l", gazee.LOG_DIR]
    else:
        gazee.LOG_DIR = gazee.DATA_DIR
    if args.verbose:
        log.start(gazee.LOG_DIR, True)
        gazee.ARGS += ["-v"]
    else:
        log.start(gazee.LOG_DIR, False)
    cherrypy.log.error_log.propagate = True
    cherrypy.log.access_log.propagate = False

    gazee.db.db_creation()
    gazee.config.config_read()

    if args.daemon:
        if sys.platform == 'win32':
            logging.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))
            if gazee.DATA_DIR is not 'data':
                gazee.ARGS += ["-c", gazee.DATA_DIR]
            gazee.ARGS += ["-d"]
            Daemonizer(cherrypy.engine).subscribe()

    # This verifies the color scheme stays between automated updates as what the user set.
    if os.path.exists('public/css/style.css'):
        with open('public/css/style.css') as f:
            style = f.read()

        with open('public/css/style.css', "w") as f:
            style = style.replace("757575", gazee.MAIN_COLOR)
            style = style.replace("BDBDBD", gazee.ACCENT_COLOR)
            style = style.replace("FFFFFF", gazee.WEB_TEXT_COLOR)
            f.write(style)

    if gazee.DATA_DIR is not 'data':
        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':
                os.path.join(gazee.DATA_DIR, "sessions"),
                'tools.auth_basic.on':
                True,
                'tools.auth_basic.realm':
                'Gazee',
                'tools.auth_basic.checkpassword':
                gazee.authmech.check_password,
                'request.show_tracebacks':
                False
            },
            '/static': {
                'tools.staticdir.on': True,
                'tools.staticdir.root': os.path.abspath(os.getcwd()),
                'tools.staticdir.dir': "public"
            },
            '/data': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': gazee.DATA_DIR
            },
            '/tmp': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': gazee.TEMP_DIR
            },
            '/favicon.ico': {
                'tools.staticfile.on':
                True,
                'tools.staticfile.filename':
                os.path.join(os.getcwd(), "public/images/favicon.ico")
            }
        }
    else:
        conf = {
            '/': {
                'tools.gzip.on':
                True,
                'tools.gzip.mime_types':
                ['text/*', 'application/*', 'image/*'],
                'tools.staticdir.root':
                os.path.abspath(os.getcwd()),
                'tools.sessions.on':
                True,
                'tools.sessions.timeout':
                1440,
                'tools.sessions.storage_class':
                cherrypy.lib.sessions.FileSession,
                'tools.sessions.storage_path':
                os.path.join(gazee.DATA_DIR, "sessions"),
                'tools.auth_basic.on':
                True,
                'tools.auth_basic.realm':
                'Gazee',
                'tools.auth_basic.checkpassword':
                gazee.authmech.check_password,
                'request.show_tracebacks':
                False
            },
            '/static': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': "public"
            },
            '/data': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': gazee.DATA_DIR
            },
            '/tmp': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': gazee.TEMP_DIR
            },
            '/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.signals.subscribe()
    cherrypy.engine.timeout_monitor.unsubscribe()
    cherrypy.tree.mount(Gazee(), '/', config=conf)

    logging.info("Gazee Started")

    cherrypy.engine.start()
    print("Gazee has started")
    scanner = ComicScanner()
    scanner.rescan_db()
    cherrypy.engine.block()
Example #22
0
    def run(self):
        
        engine = cherrypy.engine
        
        d = Daemonizer(engine)
		d.subscribe()
Example #23
0
                        )

    cherrypy.tree.mount(App.auth,
                        u'{}/auth'.format(core.URL_BASE),
                        'core/conf_auth.ini'
                        )

    # if everything goes well so far, open the browser
    if passed_args.browser or core.CONFIG['Server']['launchbrowser']:
        webbrowser.open(u"http://{}:{}{}".format(
            core.SERVER_ADDRESS, core.SERVER_PORT, core.URL_BASE))
        logging.info(u'Launching web browser.')

    # daemonize in *nix if desired
    if passed_args.daemon and os.name == 'posix':
        Daemonizer(cherrypy.engine).subscribe()

    # start engine
    cherrypy.config.update('core/conf_global.ini')
    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.ImdbRssSync.create()
    scheduler.PopularMoviesSync.create()
    scheduler_plugin.plugin.subscribe()
Example #24
0
    def RunWebServer(self, isToDaemonize):
        LogEvent("Generating CherryPy configuration")
        cherrypy.config.update(config_path)
        css_path = os.path.join(app_path, 'css')
        images_path = os.path.join(app_path, 'images')
        navigation_images_path = os.path.join(css_path, 'navigation_images')
        datatables_images_path = os.path.join(css_path, 'datatables_images')
        js_path = os.path.join(app_path, 'js')
        theme_path = os.path.join(css_path, 'redmond')
        theme_images_path = os.path.join(theme_path, 'images')
        config = ConfigParser.RawConfigParser()
        config.read('Gamez.ini')
        username = config.get('global', 'user_name').replace('"', '')
        password = config.get('global', 'password').replace('"', '')
        useAuth = False
        if (username <> "" or password <> ""):
            useAuth = True
        userPassDict = {username: password}
        checkpassword = cherrypy.lib.auth_basic.checkpassword_dict(
            userPassDict)
        conf = {
            '/': {
                'tools.auth_basic.on': useAuth,
                'tools.auth_basic.realm': 'Gamez',
                'tools.auth_basic.checkpassword': checkpassword
            },
            '/css': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': css_path
            },
            '/js': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': js_path
            },
            '/css/redmond': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': theme_path
            },
            '/css/redmond/images': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': theme_images_path
            },
            '/css/navigation_images': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': navigation_images_path
            },
            '/css/datatables_images': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': datatables_images_path
            },
        }

        if (isToDaemonize == 1):
            LogEvent("Preparing to run in daemon mode")
            daemon = Daemonizer(cherrypy.engine)
            daemon.subscribe()
        isSabEnabled = config.get('SystemGenerated',
                                  'sabnzbd_enabled').replace('"', '')
        if (isSabEnabled == "1"):
            LogEvent("Generating Post Process Script")
            GenerateSabPostProcessScript()
        RunGameTask()

        LogEvent(
            "Getting download interval from config file and invoking scheduler"
        )
        config = ConfigParser.RawConfigParser()
        config.read('Gamez.ini')
        interval = config.get('Scheduler',
                              'download_interval').replace('"', '')
        updateGameListInterval = config.get(
            'Scheduler', 'game_list_update_interval').replace('"', '')
        fInterval = float(interval)
        fUpdateGameListInterval = float(updateGameListInterval)
        try:
            LogEvent("Setting up download scheduler")
            gameTasksScheduler = cherrypy.process.plugins.Monitor(
                cherrypy.engine, RunGameTask, fInterval)
            gameTasksScheduler.subscribe()
            LogEvent("Setting up game list update scheduler")
            gameListUpdaterScheduler = cherrypy.process.plugins.Monitor(
                cherrypy.engine, RunGameListUpdaterTask,
                fUpdateGameListInterval)
            gameListUpdaterScheduler.subscribe()
            LogEvent("Setting up folder processing scheduler")
            folderProcessingScheduler = cherrypy.process.plugins.Monitor(
                cherrypy.engine, RunFolderProcessingTask, float(900))
            folderProcessingScheduler.subscribe()
            LogEvent("Starting the Gamez web server")
            cherrypy.quickstart(WebRoot(app_path), '/', config=conf)
        except KeyboardInterrupt:
            LogEvent("Shutting down Gamez")
            if (isToDaemonize == 1):
                daemon.unsubscribe()
            sys.exit()
Example #25
0
#
# You should have received a copy of the GNU General Public License
# along with this package.  If not, see <http://www.gnu.org/licenses/>.

import os
import cherrypy
import jinja2
import simplejson as json
from cherrypy.process.plugins import Daemonizer
from cherrypy.process.plugins import PIDFile
from serverutil import *

# Set up log and pid file. Run the server as a daemon.
pid = str(os.getcwd() + "/cherrypy.pid")
log = str(os.getcwd() + "/server.log")
Daemonizer(cherrypy.engine, stderr=log).subscribe()
PIDFile(cherrypy.engine, pid).subscribe()

# Set up jinja2 environment and filters that point to functions in serverutil.py.
templateLoader = jinja2.FileSystemLoader(searchpath=str(os.getcwd() +
                                                        '/html/'))
templateEnv = jinja2.Environment(loader=templateLoader)
templateEnv.filters['format_time'] = format_time
templateEnv.filters['format_hour'] = format_hour
templateEnv.filters['time_passed'] = time_passed
templateEnv.filters['normalize'] = normalize


class explorer:
    @cherrypy.expose
    def index(self, **args):
Example #26
0
def main():
    """Entry point for the cherrypy version of the app."""
    global g_app

    # Parse command line options.
    parser = argparse.ArgumentParser()
    parser.add_argument("--config",
                        type=str,
                        action="store",
                        default="",
                        help="The configuration file.",
                        required=False)

    try:
        args = parser.parse_args()
    except IOError as e:
        parser.error(e)
        sys.exit(1)

    config = Config.Config()
    if len(args.config) > 0:
        config.load(args.config)

    debug_enabled = config.is_debug_enabled()
    profiling_enabled = config.is_profiling_enabled()
    host = config.get_hostname()
    hostport = config.get_hostport()
    googlemaps_key = config.get_google_maps_key()

    if config.is_https_enabled():
        cert_file = config.get_certificate_file()
        privkey_file = config.get_private_key_file()
        print("Running HTTPS....")
        cherrypy.server.ssl_module = 'builtin'
        cherrypy.server.ssl_certificate = cert_file
        print("Certificate File: " + cert_file)
        cherrypy.server.ssl_private_key = privkey_file
        print("Private Key File: " + privkey_file)
        protocol = "https"
    else:
        protocol = "http"

    if len(host) == 0:
        if debug_enabled:
            host = "127.0.0.1"
        else:
            host = "openworkout.cloud"
        print("Hostname not provided, will use " + host)

    root_dir = os.path.dirname(os.path.abspath(__file__))
    root_url = protocol + "://" + host
    if hostport > 0:
        root_url = root_url + ":" + str(hostport)
    print("Root URL is " + root_url)

    if not debug_enabled:
        Daemonizer(cherrypy.engine).subscribe()

    # Register the signal handler.
    signal.signal(signal.SIGINT, signal_handler)

    # Configure the template engine.
    mako.collection_size = 100
    mako.directories = "templates"

    session_mgr = SessionMgr.CherryPySessionMgr()
    user_mgr = UserMgr.UserMgr(session_mgr)
    analysis_scheduler = AnalysisScheduler.AnalysisScheduler()
    import_scheduler = ImportScheduler.ImportScheduler()
    workout_plan_gen = WorkoutPlanGeneratorScheduler.WorkoutPlanGeneratorScheduler(
    )
    data_mgr = DataMgr.DataMgr(config, root_url, analysis_scheduler,
                               import_scheduler, workout_plan_gen)
    backend = App.App(user_mgr, data_mgr, root_dir, root_url, googlemaps_key,
                      profiling_enabled, debug_enabled)
    g_app = CherryPyFrontEnd(backend)

    # Configure the error logger.
    logging.basicConfig(filename=ERROR_LOG,
                        filemode='w',
                        level=logging.DEBUG,
                        format='%(asctime)s %(message)s',
                        datefmt='%m/%d/%Y %I:%M:%S %p')

    # The markdown library is kinda spammy.
    markdown_logger = logging.getLogger("MARKDOWN")
    markdown_logger.setLevel(logging.ERROR)

    # The direcory for session objects.
    if sys.version_info[0] < 3:
        session_dir = os.path.join(root_dir, 'sessions2')
    else:
        session_dir = os.path.join(root_dir, 'sessions3')
    if not os.path.exists(session_dir):
        os.makedirs(session_dir)

    cherrypy.tools.web_auth = cherrypy.Tool('before_handler', do_auth_check)

    conf = {
        '/': {
            'tools.staticdir.root': root_dir,
            'tools.web_auth.on': True,
            'tools.sessions.on': True,
            'tools.sessions.httponly': True,
            'tools.sessions.name': 'web_auth',
            'tools.sessions.storage_type': 'file',
            'tools.sessions.storage_path': session_dir,
            'tools.sessions.timeout': 129600,
            'tools.sessions.locking': 'early',
            'tools.secureheaders.on': True
        },
        '/api': {
            'tools.response_headers.on':
            True,
            'tools.response_headers.headers':
            [('Access-Control-Allow-Origin', '*')],
        },
        '/css': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'css'
        },
        '/data': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'data'
        },
        '/js': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'js'
        },
        '/jquery-timepicker': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'jquery-timepicker'
        },
        '/images': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'images',
        },
        '/media': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'media',
        },
        '/photos': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'photos',
        },
        '/.well-known': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': '.well-known',
        },
    }

    cherrypy.config.update({
        'server.socket_host': config.get_bindname(),
        'server.socket_port': config.get_bindport(),
        'requests.show_tracebacks': False,
        'error_page.404': g_app.error_404,
        'log.access_file': ACCESS_LOG
    })

    reload_feature = ReloadFeature(cherrypy.engine)
    reload_feature.subscribe()

    cherrypy.quickstart(g_app, config=conf)
Example #27
0
 def deamonize():
     """Run cherrypy instance in background."""
     d = Daemonizer(cherrypy.engine)
     d.subscribe()
     PIDFile(cherrypy.engine, 'daemon.pid').subscribe()
Example #28
0
 def _daemonize(self):
     DropPrivileges(cherrypy.engine,
                    uid=self.setup['daemon_uid'],
                    gid=self.setup['daemon_gid']).subscribe()
     Daemonizer(cherrypy.engine).subscribe()
     PIDFile(cherrypy.engine, self.setup['daemon']).subscribe()
Example #29
0
    # Try writing to directory.
    try:
        open('/var/run/pyredstone/test', 'w')
        os.remove('/var/run/pyredstone/test')
    except EnvironmentError as e:
        logger.error("Could not write to run directory /var/run/pyredstone. Try running 'sudo chown -R YOUR_USERNAME /var/run/pyredstone/'.")
        sys.exit(2)
    import argparse
    parser = argparse.ArgumentParser(description="Creates a remote HTTP/JSON API for the PyRedstone wrapper around a Minecraft Server.")
    parser.add_argument("--config", help="Path to PyRedstone config file.")
    args = parser.parse_args()
    if not os.path.exists(args.config):
        logger.error("Config file %s does not exist." % args.config)
        sys.exit(1)
    logger.info("Creating RedstoneServer with config file %s" % (args.config,))
    # Create global RedstoneServer
    rs = pyredstone.RedstoneServer(args.config)
    logger.info("Starting server on 0.0.0.0:7777")

    # Daemonize the server
    d = Daemonizer(cherrypy.engine)
    d.subscribe()
    PIDFile(cherrypy.engine, '/var/run/pyredstone/server.pid').subscribe()
    cherrypy.config.update({"server.socket_host": "0.0.0.0",
                            "server.socket_port": 7777,
                            "log.error_file": "cherrypy.log",
                            "log.access_file": "cherrypy.access",
                            "log.screen_file": "cherrypy.screen",
                            })
    cherrypy.quickstart(Root())
Example #30
0
def start():
    """ Main function for starting HTTP server """
    logger = logging.getLogger('htpc.server')
    logger.debug("Setting up to start cherrypy")

    # Set server ip, port and root
    cherrypy.config.update({
        'server.socket_host': htpc.HOST,
        'server.socket_port': htpc.PORT,
        'log.screen': False
    })

    # Set server environment to production unless when debugging
    if not htpc.DEBUG:
        cherrypy.config.update({
            'environment': 'production'
        })

    # Enable SSL
    if htpc.SSLCERT and htpc.SSLKEY:
        cherrypy.config.update({
            'server.ssl_module': 'builtin',
            'server.ssl_certificate': htpc.SSLCERT,
            'server.ssl_private_key': htpc.SSLKEY
        })

    # 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()

    # 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
        },
        '/js': {
            'tools.caching.on': True,
            'tools.caching.force': True,
            'tools.caching.delay': 0,
            'tools.expires.on': True,
            'tools.expires.secs': 60 * 60 * 6,
            'tools.staticdir.on': True,
            '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 * 6,
            'tools.staticdir.on': True,
            '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 * 6,
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'img'
        },
        '/favicon.ico': {
            'tools.caching.on': True,
            'tools.caching.force': True,
            'tools.caching.delay': 0,
            'tools.expires.on': True,
            'tools.expires.secs': 60 * 60 * 6,
            'tools.staticfile.on': True,
            'tools.staticfile.filename': favicon
        },
    }
    # Require username and password if they are set
    if htpc.USERNAME and htpc.PASSWORD:
        logger.info("Enabling username/password access")
        userpassdict = {htpc.USERNAME: htpc.PASSWORD}
        get_ha1 = get_ha1_dict_plain(userpassdict)
        app_config['/'].update({
            'tools.auth_digest.on': True,
            'tools.auth_digest.realm': "HTPC Manager",
            'tools.auth_digest.get_ha1': get_ha1,
            'tools.auth_digest.key': 'a565c27146791cfb'
        })

    # Start the CherryPy server (remove trailing slash from webdir)
    logger.info("Starting up webserver")
    print '******************************************************'
    print 'Starting HTPC Manager on port ' + str(htpc.PORT) + '.'
    print 'Start your browser and go to http://localhost:' + str(htpc.PORT)
    print '******************************************************'
    cherrypy.quickstart(htpc.ROOT, htpc.WEBDIR[:-1], config=app_config)