def run_server(app): http_config = app.config['rest_api']['http'] https_config = app.config['rest_api']['https'] signal.signal(signal.SIGTERM, signal_handler) if app.config['profile']: app.wsgi_app = ProfilerMiddleware(app.wsgi_app, profile_dir=app.config['profile']) wsgi_app = wsgiserver.WSGIPathInfoDispatcher({'/': app}) cherrypy.server.unsubscribe() cherrypy.config.update({'environment': 'production'}) if not (http_config['enabled'] or https_config['enabled']): logger.critical('No HTTP/HTTPS server enabled') exit() if https_config['enabled']: try: bind_addr_https = (https_config['listen'], https_config['port']) server_https = CherryPyWSGIServer(bind_addr=bind_addr_https, wsgi_app=wsgi_app) server_https.ssl_adapter = http_helpers.ssl_adapter(https_config['certificate'], https_config['private_key'], https_config['ciphers']) ServerAdapter(cherrypy.engine, server_https).subscribe() logger.debug('HTTPS server starting on %s:%s', *bind_addr_https) except IOError as e: logger.warning("HTTPS server won't start: %s", e) else: logger.debug('HTTPS server is disabled') if http_config['enabled']: bind_addr_http = (http_config['listen'], http_config['port']) server_http = CherryPyWSGIServer(bind_addr=bind_addr_http, wsgi_app=wsgi_app) ServerAdapter(cherrypy.engine, server_http).subscribe() logger.debug('HTTP server starting on %s:%s', *bind_addr_http) else: logger.debug('HTTP server is disabled') try: cherrypy.engine.start() cherrypy.engine.block() except KeyboardInterrupt: cherrypy.engine.stop()
def run(self): try: self.server = CherryPyWSGIServer((address, port), StaticFilesHandler(WSGIHandler())) self.server.start() except Exception as e: log("Server error: %s" % e)
def run(self, handler): self.options['bind_addr'] = (self.host, self.port) self.options['wsgi_app'] = handler certfile = self.options.get('certfile') if certfile or 'certfile' in self.options: del self.options['certfile'] keyfile = self.options.get('keyfile') if keyfile or 'keyfile' in self.options: del self.options['keyfile'] server = CherryPyWSGIServer(**self.options) if keyfile and certfile: LOGGER.info("Start using HTTPS") server.ssl_adapter = pyOpenSSLAdapter(certfile, keyfile, None) context = ssl.Context(ssl.SSLv23_METHOD) context.set_cipher_list('HIGH') context.use_privatekey_file(keyfile) context.use_certificate_file(certfile) server.ssl_adapter.context = context else: LOGGER.info("Start using HTTP") try: server.start() finally: server.stop()
def run(self, handler): server = CherryPyWSGIServer((self.host, self.port), handler) server.ssl_adapter = pyOpenSSLAdapter(CONSTANTS['certificate'], CONSTANTS['key']) try: server.start() finally: server.stop()
def main(): rootpath = gettempdir() provider = FilesystemProvider(rootpath) config = DEFAULT_CONFIG.copy() config.update({ "provider_mapping": { "/": provider }, "user_mapping": {}, "verbose": 1, "enable_loggers": [], "propsmanager": True, # True: use property_manager.PropertyManager "locksmanager": True, # True: use lock_manager.LockManager "domaincontroller": None, # None: domain_controller.WsgiDAVDomainController(user_mapping) }) app = WsgiDAVApp(config) # For an example, use CherryPy from cherrypy.wsgiserver import CherryPyWSGIServer server = CherryPyWSGIServer( bind_addr=(config["host"], config["port"]), wsgi_app=app, server_name="WsgiDAV/%s %s" % (__version__, CherryPyWSGIServer.version), ) try: server.start() except KeyboardInterrupt: print("Caught Ctrl-C, shutting down...") finally: server.stop()
def main(): root_path = gettempdir() provider = FilesystemProvider(root_path) config = { "provider_mapping": {"/": provider}, "http_authenticator": { "domain_controller": None # None: dc.simple_dc.SimpleDomainController(user_mapping) }, "simple_dc": {"user_mapping": {"*": True}}, # anonymous access "verbose": 1, "enable_loggers": [], "property_manager": True, # True: use property_manager.PropertyManager "lock_manager": True, # True: use lock_manager.LockManager } app = WsgiDAVApp(config) # For an example, use CherryPy from cherrypy.wsgiserver import CherryPyWSGIServer server = CherryPyWSGIServer( bind_addr=(config["host"], config["port"]), wsgi_app=app, server_name="WsgiDAV/{} {}".format(__version__, CherryPyWSGIServer.version), ) try: server.start() except KeyboardInterrupt: print("Caught Ctrl-C, shutting down...") finally: server.stop()
def inner_run(): if ssl_private_key and ssl_certificate: print "MSS server is running at https://%s:%s/" % (addr, port) else: print "MSS server is running at http://%s:%s/" % (addr, port) if settings.DEBUG: print "Devel mode is ON" print "Quit the server with %s." % quit_command app = WSGIHandler() path = {} if show_log: logged_app = TransLogger(app) path['/'] = logged_app else: path['/'] = app path[settings.MEDIA_URL] = MediaHandler(settings.MEDIA_ROOT) dispatcher = WSGIPathInfoDispatcher(path) server = CherryPyWSGIServer((addr, int(port)), dispatcher, threads) if ssl_private_key and ssl_certificate: from cherrypy.wsgiserver.ssl_pyopenssl import pyOpenSSLAdapter server.ssl_adapter = pyOpenSSLAdapter(ssl_certificate, ssl_private_key, None) try: server.start() except KeyboardInterrupt: server.stop() sys.exit(0)
def setup_kws_server(self): """ sets up the KWS server to run on a separate port """ # based on http://docs.cherrypy.org/stable/refman/process/servers.html if not self.config['keyword_search']['kws_service_on']: return # load KWSWebService here since it will be loaded after self.configure # which brings secmodv2 into cherrypy.tools from DAS.web.kws_web_srv import KWSWebService kws_service = KWSWebService(self.config) kws_wsgi_app = _cptree.Tree() kws_wsgi_app.mount(kws_service, '/das') config = self.config['web_server'] port = int(config.get("kws_port", 8214)) host = config.get("kws_host", '0.0.0.0') if CherryPyWSGIServer: kws_server = CherryPyWSGIServer( bind_addr=(host, port), wsgi_app=kws_wsgi_app, numthreads=int(config.get("thread_pool_kws", 10)), request_queue_size=cpconfig["server.socket_queue_size"], # below are cherrypy default settings... # max=-1, # timeout=10, # shutdown_timeout=5 ) srv_adapter = ServerAdapter(engine, kws_server) srv_adapter.subscribe()
def _cherrypy(): from cherrypy.wsgiserver import CherryPyWSGIServer server = CherryPyWSGIServer( (hostname, port), app, server_name=ctx.cfg['base_domain_name'], request_queue_size=500) server.start()
def handle(self, **options): # Determine the port number if 'port' in options: port = int(options['port'] or settings.PORT) else: port = settings.PORT # Determine the number of threads if 'threads' in options: threads = int(options['threads'] or 25) if threads < 1: raise Exception("Invalid number of threads: %s" % threads) else: threads = 25 # Determine the IP-address to listen on: # - either as command line argument # - either 0.0.0.0 by default, which means all active IPv4 interfaces address = 'address' in options and options['address'] or '0.0.0.0' # Validate the address and port number try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((address, port)) s.close() except socket.error as e: raise Exception("Invalid address '%s' and/or port '%s': %s" % (address, port, e)) # Print a header message hostname = socket.getfqdn() print('Starting frePPLe %s web server\n' % VERSION) print( 'To access the server, point your browser to either of the following URLS:' ) if address == '0.0.0.0': print(' http://%s:%s/' % (hostname, port)) for ip in socket.gethostbyname_ex(socket.gethostname())[2]: print(' http://%s:%s/' % (ip, port)) else: print(' http://%s:%s/' % (address, port)) print('Quit the server with CTRL-C.\n') # Start a separate thread that will check for updates # We don't wait for it to finish CheckUpdates().start() # Run the WSGI server server = CherryPyWSGIServer((address, port), StaticFilesHandler(WSGIHandler()), numthreads=threads) # Want SSL support? Just set these attributes apparently, but I haven't tested or verified this # server.ssl_certificate = <filename> # server.ssl_private_key = <filename> try: server.start() except KeyboardInterrupt: server.stop()
def __init__(self, host, port, http_interface, use_ssl, ca_cert, ssl_key, ssl_cert, server_dh, daemon_thread_pool_size): # pylint: disable=too-many-arguments """ Initialize HTTP daemon :param host: host address :param port: listening port :param http_interface: :param use_ssl: :param ca_cert: :param ssl_key: :param ssl_cert: :param daemon_thread_pool_size: """ # Port = 0 means "I don't want HTTP server" if port == 0: return sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((host, port)) if result == 0: msg = "Error: Sorry, the port %s/%d is not free" % (host, port) raise PortNotFree(msg) self.port = port self.host = host self.use_ssl = use_ssl protocol = 'http' if use_ssl: protocol = 'https' self.uri = '%s://%s:%s' % (protocol, self.host, self.port) logger.info("Opening HTTP socket at %s", self.uri) # This config overrides default processors so we put them back in case we need them config = { '/': { 'request.body.processors': {'application/x-www-form-urlencoded': process_urlencoded, 'multipart/form-data': process_multipart_form_data, 'multipart': process_multipart, 'application/zlib': zlib_processor}, 'tools.gzip.on': True, 'tools.gzip.mime_types': ['text/*', 'application/json'], } } # disable console logging of cherrypy when not in DEBUG if getattr(logger, 'level') != logging.DEBUG: cherrypy.log.screen = False if use_ssl: CherryPyWSGIServer.ssl_adapter = Pyopenssl(ssl_cert, ssl_key, ca_cert, server_dh) self.srv = CherryPyWSGIServer((host, port), cherrypy.Application(http_interface, "/", config), numthreads=daemon_thread_pool_size, shutdown_timeout=1, request_queue_size=30)
def __init__(self, host, port, http_interface, use_ssl, ca_cert, ssl_key, ssl_cert, daemon_thread_pool_size): self.port = port self.host = host self.srv = None # Port = 0 means "I don't want HTTP server" if self.port == 0: return self.use_ssl = use_ssl self.srv = None protocol = 'http' if use_ssl: protocol = 'https' self.uri = '%s://%s:%s' % (protocol, self.host, self.port) logger.info("Opening HTTP socket at %s", self.uri) # This config override default processors so we put them back in case we need them config = { '/': { 'request.body.processors': {'application/x-www-form-urlencoded': process_urlencoded, 'multipart/form-data': process_multipart_form_data, 'multipart': process_multipart, 'application/zlib': zlib_processor}, 'tools.gzip.on': True, 'tools.gzip.mime_types': ['text/*', 'application/json'] } } # disable console logging of cherrypy when not in DEBUG if getattr(logger, 'level') != logging.DEBUG: cherrypy.log.screen = False self.srv = CherryPyWSGIServer((host, port), cherrypy.Application(http_interface, "/", config), numthreads=daemon_thread_pool_size, shutdown_timeout=1) if SSL and pyOpenSSLAdapter and use_ssl: adapter = pyOpenSSLAdapter(ssl_cert, ssl_key, ca_cert) context = adapter.get_context() # SSLV2 is deprecated since 2011 by RFC 6176 # SSLV3, TLSV1 and TLSV1.1 have POODLE weakness (harder to exploit on TLS) # So for now (until a new TLS version) we only have TLSv1.2 left # WE also remove compression because of BREACH weakness context.set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3 | SSL.OP_NO_TLSv1 | SSL.OP_NO_TLSv1_1 | SSL.OP_NO_COMPRESSION) # All excluded algorithm beyond are known to be weak. context.set_cipher_list('DEFAULT:!DSS:!PSK:!SRP:!3DES:!RC4:!DES:!IDEA:!RC2:!NULL') adapter.context = context self.srv.ssl_adapter = adapter if use_ssl: self.srv.ssl_certificate = ssl_cert self.srv.ssl_private_key = ssl_key
def main(): parser = argparse.ArgumentParser( description='zmq based session and user manager for web applications.') parser.add_argument("-i", "--ip", default="0.0.0.0", help="listen on this ip (default: 0.0.0.0)") parser.add_argument("-p", "--port", default=8088, type=int, help="listen on this port (default: 8088)") parser.add_argument( "-s", "--settings", default="zums.zumsd_users.settings", help="settings module to use (default: zums.zumsd_users.settings)") parser.add_argument( "-t", "--templates", default="./ROOT/templates", help="location of templates (default: ./ROOT/templates)") parser.add_argument("-d", "--debug", default=False, action="store_true", help="run in debug mode, default is in settings file") parser.add_argument("--init", default=False, action="store_true", help="create user database") args = parser.parse_args() os.environ["DJANGO_SETTINGS_MODULE"] = args.settings from django.core.management import call_command from django.core.handlers.wsgi import WSGIHandler from django.conf import settings if args.init: call_command('syncdb', interactive=True) return if args.templates: settings.TEMPLATE_DIRS = (args.templates, ) if args.debug: settings.DEBUG = True server = CherryPyWSGIServer((args.ip, args.port), WSGIHandler()) print "Started http server on %s:%s." % (args.ip, args.port) print "Hit ^C to exit." try: server.start() except KeyboardInterrupt: print "Shutting down gracefully." server.stop()
def run(self, handler): server = CherryPyWSGIServer((self.host, self.port), handler) server.ssl_adapter = \ pyOpenSSLAdapter(RestConfig.get('ssl', 'certificate'), RestConfig.get('ssl', 'key')) try: server.start() finally: server.stop()
def launch_server_cherrypy(host, port, app): """use cherrypy's wsgiserver, a multithreaded scallable server""" from cherrypy.wsgiserver import CherryPyWSGIServer server = CherryPyWSGIServer((host, port), app) logging.info("Starting CherryPy server, listening on port %s", port) try: server.start() except KeyboardInterrupt: server.stop()
def WSGIServer(port, application): from weberror.evalexception import EvalException application = EvalException(application, ) application = timeit_middleware(application) logging.info('\nGAME BEGIN\n\n') server = CherryPyWSGIServer(('0.0.0.0', port), application, numthreads=10) try: server.start() except KeyboardInterrupt: server.stop()
def run(self, handler): server = CherryPyWSGIServer((self.host, self.port), handler, server_name='localhost') try: server.start() except Exception as e: error = parse_exception(e) log_exception(error_log_path, error) print(error) finally: server.stop()
def main(): cherrypy.config.update({'error_page.404': err_pages.err_404}) # = Daemonizer(cherrypy.engine) #d.subscribe() AppDispatcher = WSGIPathInfoDispatcher({ '/': cherrypy.tree.mount(Main(), '/', config=config), #'/login': LoginApp, '/file': FileApp }) server = CherryPyWSGIServer((settings['ip'], settings['port']), AppDispatcher, server_name=render('__server_info__'), numthreads=100, request_queue_size=70) serverSSL = None if settings.has_key('ssl_certificate') and settings.has_key( 'ssl_private_key'): if os.path.exists(settings['ssl_certificate']) and os.path.exists( settings['ssl_private_key']): serverSSL = CherryPyWSGIServer( (settings['ip'], settings['sslport']), AppDispatcher, server_name=render('__server_info__'), numthreads=100, request_queue_size=70) serverSSL.ssl_certificate = settings['ssl_certificate'] serverSSL.ssl_private_key = settings['ssl_private_key'] s2 = ServerAdapter(cherrypy.engine, serverSSL) s2.subscribe() s1 = ServerAdapter(cherrypy.engine, server) s1.subscribe() check_create_db(settings['db_name'], settings['db_name']) cherrypy.engine.timeout_monitor.unsubscribe() cherrypy.engine.start() cherrypy.engine.block()
def _start_httpd(self, host_port): host_port = to_ip(host_port) if not self.running_tests: if host_port not in self.servs: host, _, port = host_port.partition(':') serv = CherryPyWSGIServer((host, int(port)), self.dispatcher, request_queue_size=128, numthreads=4) start_new_thread(start_serv, (serv, )) #while not serv.ready: # time.sleep(.1) self.servs[host_port] = serv while not self.servs[host_port].ready: time.sleep(.001)
def start_server(self, address='0.0.0.0', port=8000): _application = AdminMediaHandler(WSGIHandler()) def application(environ, start_response): environ['PATH_INFO'] = environ['SCRIPT_NAME'] + environ['PATH_INFO'] return _application(environ, start_response) from cherrypy.wsgiserver import CherryPyWSGIServer from threading import Thread self.httpd = CherryPyWSGIServer((address, port), application, server_name='django-test-http') self.httpd_thread = Thread(target=self.httpd.start) self.httpd_thread.start() #FIXME: This could be avoided by passing self to thread class starting django # and waiting for Event lock time.sleep(.5)
def serve(application, host='127.0.0.1', port=8080): """CherryPy-based WSGI-HTTP server.""" # Instantiate the server with our configuration and application. server = CherryPyWSGIServer((host, int(port)), application, server_name=host) # Try to be handy as many terminals allow clicking links. print("serving on http://{0}:{1}".format(host, port)) # Bind and launch the server; this is a blocking operation. try: server.start() except KeyboardInterrupt: server.stop() # CherryPy has some of its own shutdown work to do.
def _start_server(): from cherrypy.wsgiserver import CherryPyWSGIServer from wsgiref.simple_server import demo_app from threading import Thread import time global _httpd _httpd = CherryPyWSGIServer(('127.0.0.1', 57909), demo_app, server_name='osmpoint-test-http') Thread(target=_httpd.start).start() for t in xrange(100): if _httpd.ready: break time.sleep(.01) else: raise ValueError("CherryPy server has not started")
def main(): params = sys.argv[1:] if params: host, port = params if host == "0": host = "0.0.0.0" port = int(port) else: host, port = "127.0.0.1", 8000 httpd = CherryPyWSGIServer((host, port), WSGIHandler(), server_name="localhost") daemonize() write_pid() try: httpd.start() except KeyboardInterrupt: httpd.stop()
def handle(self, *args, **options): self.server = CherryPyWSGIServer((options["host"], options["port"]), WSGIHandler()) self.pidfile = os.path.join(settings.PROJECT_ROOT, "logs/wsgi.pid") try: action = args[0] except IndexError: print "You must provide an action. Possible actions are start, stop and restart." raise SystemExit if options["daemonize"]: daemonize() if action == "start": self.start() elif action == "stop": pid = open(self.pidfile, "r").read() self.stop(pid) elif action == "restart": pid = open(self.pidfile, "r").read() self.restart(pid)
def _runCherryPy(self, app, config): version = "WsgiDAV/%s %s Python/%s" % ( __version__, wsgiserver.CherryPyWSGIServer.version, PYTHON_VERSION) wsgiserver.CherryPyWSGIServer.version = version protocol = "http" if config["verbose"] >= 1: print("Running %s" % version) print("Listening on %s://%s:%s ..." % (protocol, config["host"], config["port"])) self._server = CherryPyWSGIServer( (config["host"], config["port"]), app, server_name=version, ) self._server.start()
def run(self, handler): server = CherryPyWSGIServer((self.host, self.port), handler, server_name='localhost') """ openssl genrsa -out privkey.pem 1024 openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095 """ crt = '/etc/coinbend/cacert.pem' key = '/etc/coinbend/privkey.pem' #ca = '/etc/ssl/intermediate.crt' server.ssl_module = "pyopenssl" server.ssl_adapter = PatchBuiltinSSLAdapter(crt, key) # f*****g p.o.s. cherry does NOT support prebuilt ssl contexts #server.ssl_adapter.context = sc try: server.start() finally: server.stop()
def start_server(options): """ Start Django server and serve static files """ if options['daemonize'] and options['server_user'] and options[ 'server_group']: #ensure the that the daemon runs as specified user change_uid_gid(options['server_user'], options['server_group']) from cherrypy.wsgiserver import CherryPyWSGIServer, WSGIPathInfoDispatcher #from cherrypy.wsgiserver import CherryPyWSGIServer, WSGIPathInfoDispatcher from django.core.handlers.wsgi import WSGIHandler from django.conf import settings app = WSGIHandler() if options['adminserve']: # serve the admin media too # AdminMediaHandler is middleware for local use import django.core.servers.basehttp app = django.core.servers.basehttp.AdminMediaHandler(app) # route the requests appropriately path = { '/': app, settings.MEDIA_URL: mediahandler.MediaHandler(settings.MEDIA_ROOT), # settings.MEDIA_URL: mediahandler.MediaHandler(settings.MEDIA_ROOT), # settings.STATIC_URL + "admin/": mediahandler.MediaHandler( # os.path.join(django.contrib.admin.__path__[0], 'static/admin') # ) } dispatcher = WSGIPathInfoDispatcher(path) server = CherryPyWSGIServer( (options['host'], int(options['port'])), dispatcher, int(options['threads']), options['server_name']) try: server.start() except KeyboardInterrupt: server.stop()
def server_maker(config, **extra_config): """ Return a server-making callable to create a CherryPy WSGI server. The server-making callable should be passed a WSGI application, and it will return an instance of `cherrypy.wsgiserver.CherryPyWSGIServer`. You can optionally override any of the hardwired configuration parameters by passing in keyword arguments which will be passed along to the `CherryPyWSGIServer` constructor. """ from cherrypy.wsgiserver import CherryPyWSGIServer bind_addr = (config['server.bind'], config['server.port']) kwargs = dict(numthreads=config['server.num-threads'], server_name=config['server.name'], request_queue_size=config['server.request-queue-size'], timeout=config['server.timeout']) kwargs.update(extra_config) return lambda wsgi_app: CherryPyWSGIServer(bind_addr, wsgi_app, **kwargs)
def run_rack_manager_default(app, ssl_enabled, host='0.0.0.0', port=8080, number_threads=30, config=None, **kwargs): if config is not None: cpy.config.update(config) server = CherryPyWSGIServer((host, port), app, numthreads=number_threads, **kwargs) if (ssl_enabled): server.ssl_adapter = pyOpenSSLAdapter( certificate="/usr/lib/sslcerts/certs.pem", private_key="/usr/lib/sslcerts/privkey.pem") try: server.start() except KeyboardInterrupt: server.stop()
def Run(self): # Import modules import cherrypy from cherrypy.wsgiserver import CherryPyWSGIServer from subprocess import call, DEVNULL from win32process import DETACHED_PROCESS, CREATE_NO_WINDOW # Initialize django os.environ.setdefault('DJANGO_SETTINGS_MODULE', "freppledb.settings") os.environ.setdefault('FREPPLE_APP', os.path.join(sys.path[0], 'custom')) import django django.setup() from django.conf import settings from django.core.handlers.wsgi import WSGIHandler from django.contrib.staticfiles.handlers import StaticFilesHandler # Override the debugging settings settings.DEBUG = False settings.TEMPLATE_DEBUG = False # Sys.path contains the zip file with all packages. We need to put the # application directory into the path as well. sys.path += [os.environ['FREPPLE_APP']] # Append all output to a unbuffered log stream with open(os.path.join(settings.FREPPLE_LOGDIR, 'service.log'), 'a') as logfile: sys.stderr = sys.stdout = logfile try: # Using the included postgres database # Check if the database is running. If not, start it. if os.path.exists( os.path.join(settings.FREPPLE_HOME, '..', 'pgsql', 'bin', 'pg_ctl.exe')): status = call([ os.path.join(settings.FREPPLE_HOME, '..', 'pgsql', 'bin', 'pg_ctl.exe'), "--pgdata", os.path.join(settings.FREPPLE_LOGDIR, 'database'), "--silent", "status" ], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, creationflags=CREATE_NO_WINDOW) if status: print("%s\tStarting the PostgreSQL database" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"), flush=True) call([ os.path.join(settings.FREPPLE_HOME, '..', 'pgsql', 'bin', 'pg_ctl.exe'), "--pgdata", os.path.join(settings.FREPPLE_LOGDIR, 'database'), "--log", os.path.join(settings.FREPPLE_LOGDIR, 'database', 'server.log'), "start" ], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, creationflags=DETACHED_PROCESS) # Prepare web server cherrypy.config.update({ 'global': { 'log.screen': False, 'tools.log_tracebacks.on': True, 'engine.autoreload.on': False, 'engine.SIGHUP': None, 'engine.SIGTERM': None } }) self.server = CherryPyWSGIServer( (settings.ADDRESS, settings.PORT), StaticFilesHandler(WSGIHandler())) # Synchronize the scenario table with the settings from freppledb.common.models import Scenario Scenario.syncWithSettings() # Infinite loop serving requests # The loop gets interrupted when the service gets ordered to shut down. print("%s\tfrePPLe web server listening on http://%s:%d" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), settings.ADDRESS, settings.PORT), flush=True) self.server.start() print("%s\tStopping service" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"), flush=True) # Using the included postgres database? if os.path.exists( os.path.join(settings.FREPPLE_HOME, '..', 'pgsql', 'bin', 'pg_ctl.exe')): # Check if the database is running. If so, stop it. os.environ['PATH'] = os.path.join( settings.FREPPLE_HOME, '..', 'pgsql', 'bin') + os.pathsep + os.environ['PATH'] status = call([ os.path.join(settings.FREPPLE_HOME, '..', 'pgsql', 'bin', 'pg_ctl.exe'), "--pgdata", os.path.join(settings.FREPPLE_LOGDIR, 'database'), "--silent", "status" ], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, creationflags=CREATE_NO_WINDOW) if not status: print("%s\tShutting down the database" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"), flush=True) call( [ os.path.join(settings.FREPPLE_HOME, '..', 'pgsql', 'bin', 'pg_ctl.exe'), "--pgdata", os.path.join(settings.FREPPLE_LOGDIR, 'database'), "--log", os.path.join(settings.FREPPLE_LOGDIR, 'database', 'server.log'), "-w", # Wait till it's down "stop" ], stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, creationflags=CREATE_NO_WINDOW) # Notify the manager self.stopEvent.set() except Exception as e: print("%s\tfrePPLe web server failure: %s" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), e), flush=True)