Beispiel #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()
Beispiel #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()
Beispiel #3
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()
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
Beispiel #5
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()
Beispiel #6
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)
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 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()
Beispiel #9
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()
Beispiel #10
0
        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.')

    cherrypy.quickstart(Application(), config=settings)
Beispiel #11
0
            'tools.CORS.on': True,
        },
        '/wol': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on': True,
            'tools.response_headers.headers': [('Content-Type', 'text/plain')],
            'tools.CORS.on': True,
        },   
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': 'public'
        },
        '/favicon.ico': {
            'tools.staticfile.on': True,
            'tools.staticfile.filename': '%s/favicon.ico' % cur_dir
        },
    }
    cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)
    webapp = WolMgr()
    webapp.wol = WolWebService()
    cherrypy.tree.mount(webapp, '/', conf)
    
    cherrypy.config.update(log_conf)
    d = Daemonizer(cherrypy.engine)
    d.subscribe()
    
    PIDFile(cherrypy.engine, run_file).subscribe()
    
    cherrypy.engine.start()
    cherrypy.engine.block()
Beispiel #12
0
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()
Beispiel #13
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()
Beispiel #14
0
 def deamonize():
     """Run cherrypy instance in background."""
     d = Daemonizer(cherrypy.engine)
     d.subscribe()
     PIDFile(cherrypy.engine, 'daemon.pid').subscribe()
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())
Beispiel #16
0
    def run(self):
        
        engine = cherrypy.engine
        
        d = Daemonizer(engine)
		d.subscribe()
Beispiel #17
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())
Beispiel #18
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()