def runDevelopment(): if "pdsf" in socket.gethostname(): from flup.server.fcgi import WSGIServer logger.info("Starting flup WSGI app") WSGIServer(app, bindAddress=("127.0.0.1",8851)).run() elif "sgn" in socket.gethostname(): from flup.server.fcgi import WSGIServer logger.info("Starting flup WSGI app on sciece gateway") WSGIServer(app, bindAddress=("127.0.0.1",8851)).run() else: logger.info("Starting flask app") # Careful with threaded, but it can be useful to test the status page, since the post request succeeds! app.run(host=serverParameters["ipAddress"], port=serverParameters["port"])#, threaded=True)
def main(): parsed_args = _parse_args() setup_logging(LOGFILENAME, parsed_args.foreground, parsed_args.debug) if parsed_args.debug: logger.info("Debug mode enabled.") flask_http_server.app.debug = True flask_http_server.register_blueprints_v1_1() if parsed_args.dev_mode: logger.info("Starting xivo-restapid in dev mode.") config.HOST = parsed_args.listen_addr config.PORT = parsed_args.listen_port logger.info("Running on %s:%s", config.HOST, config.PORT) flask_http_server.app.run(host=config.HOST, port=config.PORT) else: from flup.server.fcgi import WSGIServer if parsed_args.foreground: logger.info("Starting xivo-restapid in foreground mode.") else: logger.info("Starting xivo-restapid in standard mode.") _daemonize() WSGIServer(flask_http_server.app, bindAddress='/var/www/restws-fcgi.sock', multithreaded=False, multiprocess=True, debug=False).run()
def _runFlup(app, config, mode): """Run WsgiDAV using flup.server.fcgi, if Flup is installed.""" try: # http://trac.saddi.com/flup/wiki/FlupServers if mode == "flup-fcgi" or "runfcgi": from flup.server.fcgi import WSGIServer, __version__ as flupver elif mode == "flup-fcgi_fork": from flup.server.fcgi_fork import WSGIServer, __version__ as flupver else: raise ValueError if config["verbose"] >= 2: print "Running WsgiDAV/%s %s/%s..." % ( __version__, WSGIServer.__module__, flupver) server = WSGIServer( app, bindAddress=(config["host"], config["port"]), # bindAddress=("127.0.0.1", 8001), # debug=True, ) server.run() except ImportError, e: if config["verbose"] >= 1: print "Could not import flup.server.fcgi", e return False
def main(argv): log_dir = argv[1] # for exceptions pid = os.getpid() timestamp = time.strftime('%Y-%m-%d__%H-%M-%S') log_requests = os.getenv('WWZ_REQUEST_LOG') if log_requests: path1 = os.path.join(log_dir, '%s.%d.request.log' % (timestamp, pid)) request_log = TabularLogFile(REQUEST_LOG_SCHEMA, path1) else: request_log = NoLogFile() trace = os.getenv('WWZ_TRACE_LOG') if trace: path2 = os.path.join(log_dir, '%s.%d.trace.log' % (timestamp, pid)) trace_log = TabularLogFile(TRACE_SCHEMA, path2) else: trace_log = NoLogFile() # Global instance shared by all threads. app = App(request_log, trace_log, log_dir, pid) # NOTE: debug=True shows tracebacks. WSGIServer(app, debug=True).run()
def start(self): """Start the app""" # Start the logger so we can begin logging ----------------------------- logging_configurator = \ LoggingConfigurator(file_path=os.path.join(ROOT, "logs", "log.txt"), level="INFO") logging_configurator.start() # Init all Components -------------------------------------------------- self.platform = LinuxPlatform() self.resource_manager = ResourceManager() self.template_builder = TemplateBuilder(self.resource_manager) self.database = Database(self.resource_manager) self.login_manager = LoginManager(self.database, self.resource_manager, self.platform) self.router = Router(self.resource_manager, self.template_builder, self.login_manager, self.database, self.platform) # Start all Components ------------------------------------------------- self._start_component("Linux Platform", self.platform) self._start_component("Template Builder", self.template_builder) self._start_component("Login Manager", self.login_manager) self._start_component("Database", self.database) self._start_component("Router", self.router) WSGIServer(self.router.get_wsgi_app()).run()
def main(): # setup logging logging.basicConfig( datefmt='%Y-%m-%d %H:%M:%S', format='%(asctime)s [webapp.py] %(levelname)s: %(message)s', level=logging.INFO) # check if socket defined if 'TEST_PY3FCGI_SOCK' not in os.environ: logging.error('env TEST_PY3FCGI_SOCK not found') exit(1) socket = os.environ['TEST_PY3FCGI_SOCK'] logging.info("listening socket: " + socket) # run the server try: WSGIServer(app, bindAddress=socket, umask=0000).run() except (KeyboardInterrupt, SystemExit, SystemError): logging.info("Shutdown requested...exiting") except Exception: traceback.print_exc(file=sys.stdout) finally: if os.path.exists(socket): logging.info("removing socket: " + socket) os.remove(socket) else: logging.info("socket not exists: " + socket) # exit gracefully logging.info("bye bye") sys.exit(0)
def transmission_fcgi_start(args): if len(args) < 2: return False ip = args[0] port = long(args[1]) pid = os.fork() if pid < 0: return False if pid != 0: sys.exit(0) os.setsid() os.environ['DJANGO_SETTINGS_MODULE'] = 'transmissionUI.settings' import django.core.handlers.wsgi app = django.core.handlers.wsgi.WSGIHandler() res = False with open(transmission_fcgi_pidfile, "wb") as fp: fp.write(str(os.getpid())) fp.close() res = WSGIServer(app, bindAddress=(ip, port)).run() return res
def main(app): try: WSGIServer(app, bindAddress='./hello-world.sock', umask=0000).run() except (KeyboardInterrupt, SystemExit, SystemError): logging.info("Shutdown requested...exiting") except Exception: traceback.print_exc(file=sys.stdout)
def run(): """Run local server.""" if app.config['MODE'] == 'production': from flup.server.fcgi import WSGIServer WSGIServer(app).run() else: app.run(debug=True)
def main(args): load_plugins() config, path = get_config_and_path(args) app = make_app_for_config_and_path(config, path) if not config.get_option('user_port'): port = '8080' else: port = config.get_option('user_port') if not config.get_option('user_host'): host = '0.0.0.0' else: host = config.get_option('user_host') if not config.get_option('protocol'): protocol = 'http' else: protocol = config.get_option('protocol') if protocol == 'http': httpserver.serve(app, host=host, port=port) else: if protocol == 'fcgi': from flup.server.fcgi import WSGIServer elif protocol == 'scgi': from flup.server.scgi import WSGIServer elif protocol == 'ajp': from flup.server.ajp import WSGIServer else: print 'Unknown protocol: %s.' % (protocol) sys.exit(1) WSGIServer(app, bindAddress=(host, int(port))).run()
def runServer(self): """Starts up the server. It (will) support different config options via the config plugin.""" config = pm.getService("config") debug = config.get("flask.debug") cFCGI = config.get("flask.fcgi") host = config.get("flask.bind") app_port = config.get("flask.app_port") fcgi_port = config.get("flask.fcgi_port") must_have_client_cert = config.get("flask.force_client_cert") if cFCGI: logger.info("registering fcgi server at %s:%i", host, fcgi_port) from flup.server.fcgi import WSGIServer WSGIServer(self._app, bindAddress=(host, fcgi_port)).run() else: logger.info("registering app server at %s:%i", host, app_port) # do the following line manually, so we can intervene and adjust the ssl context # self._app.run(host=host, port=app_port, ssl_context='adhoc', debug=debug, request_handler=ClientCertHTTPRequestHandler) # the code from flask's `run...` # see https://github.com/mitsuhiko/flask/blob/master/flask/app.py options = {} try: # now the code from werkzeug's `run_simple(host, app_port, self._app, **options)` # see https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/serving.py from werkzeug.debug import DebuggedApplication import socket application = DebuggedApplication(self._app, True) # Set up an SSL context cert_path = expand_eisoil_path(config.get("delegatetools.trusted_cert_path")) cert_key_path = expand_eisoil_path(config.get("delegatetools.trusted_cert_keys_path")) context = SSL.Context(SSL.SSLv23_METHOD) context_crt = os.path.join(cert_path, "ch-cert.pem") context_key = os.path.join(cert_key_path, "ch-key.pem") try: context.use_certificate_file(context_crt) context.use_privatekey_file(context_key) except Exception as e: logger.critical("error starting flask server. Cert or key is missing under %s", cert_path) sys.exit(e) def inner(): # server = serving.make_server(host, app_port, self._app, False, 1, ClientCertHTTPRequestHandler, False, 'adhoc') server = serving.make_server(host, app_port, self._app, False, 1, ClientCertHTTPRequestHandler, False, ssl_context=context) # The following line is the reason why I copied all that code! if must_have_client_cert: server.ssl_context.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, lambda a,b,c,d,e: True) # That's it server.serve_forever() address_family = serving.select_ip_version(host, app_port) test_socket = socket.socket(address_family, socket.SOCK_STREAM) test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) test_socket.bind((host, app_port)) test_socket.close() serving.run_with_reloader(inner, None, 1) finally: self._app._got_first_request = False
def main(): app = cherrypy.tree.mount(Application(), '/zcommit') cherrypy.server.unsubscribe() cherrypy.engine.start() try: WSGIServer(app, environ={'SCRIPT_NAME': '/zcommit'}).run() finally: cherrypy.engine.stop()
def serve(pipe, port): global _PIPE _PIPE = pipe try: WSGIServer(handler, bindAddress=('127.0.0.1', port)).run() except Exception as e: print(f"Error: {e}") _PIPE.close()
def run(self, config, args): from werkzeug.debug import DebuggedApplication app = config_from_file(config) sock = app.config["FCGI_SOCKET"] if app.config.get("DEBUG"): app = DebuggedApplication(app, evalex=True) from flup.server.fcgi import WSGIServer return WSGIServer(app, bindAddress=sock).run()
def alternativeMain(self, main_) -> Any: """Process alternative main.""" from flup.server.fcgi import WSGIServer # type: ignore logger.info("=============================================") logger.info("FCGI:INFO: Listening socket %s", self._fcgiSocket) logger.info("FCGI:INFO: Sending queries to %s", self._fcgiCall) par_ = parser(main_, self._fcgiCall) WSGIServer(par_.call, bindAddress=self._fcgiSocket).run()
def runfcgi(): DEBUG = app.config.get('DEBUG', False) SERVER_NAME = app.config.get('SERVER_NAME', "0.0.0.0:80") server = SERVER_NAME.split(":") server_ip, server_port = server[0], int(server[1]) WSGIServer(app, bindAddress=(server_ip, server_port), multiprocess=app.config.get('fcgi_multiprocess', False), multithreaded=app.config.get('fcgi_multithread', False), multiplexed=app.config.get('fcgi_multiplexed', False), debug=DEBUG).run()
def start_fcgi(self, *args, **kwargs): ''' Start the Flup FastCGI/WSGIServer interface. Any options passed to this method are automatically passed to the Flup WSGIServer. ''' from flup.server.fcgi import WSGIServer self.server_type = 'fcgi' self._prep_start() logger.log_info("Starting FLUP WSGI Server...") WSGIServer(self, *args, **kwargs).run()
def _handle_fcgi(self, cao): from flup.server.fcgi import WSGIServer start = self.now exe = "%s fcgi" % sos.path.abspath(self.app_path) if cao.log_level: logging.info("[%s] Starting %s" % (start, exe)) try: return WSGIServer(self._handle_wsgi(cao)).run() finally: if cao.log_level: logging.info \ ("[%s <-- %s] Finished %s" % (self.now, start, exe))
def runServer(self): """Starts up the server. It (will) support different config options via the config plugin.""" config = pm.getService("config") debug = config.get("flask.debug") cFCGI = config.get("flask.fcgi") host = config.get("flask.bind") app_port = config.get("flask.app_port") fcgi_port = config.get("flask.fcgi_port") must_have_client_cert = config.get("flask.force_client_cert") if cFCGI: logger.info("registering fcgi server at %s:%i", host, fcgi_port) from flup.server.fcgi import WSGIServer WSGIServer(self._app, bindAddress=(host, fcgi_port)).run() else: logger.info("registering app server at %s:%i", host, app_port) # this workaround makes sure that the client cert can be acquired later (even when running the development server) # copied all this stuff from the actual flask implementation, so we can intervene and adjust the ssl context # self._app.run(host=host, port=app_port, ssl_context='adhoc', debug=debug, request_handler=ClientCertHTTPRequestHandler) # the code from flask's `run...` # see https://github.com/mitsuhiko/flask/blob/master/flask/app.py options = {} try: # now the code from werkzeug's `run_simple(host, app_port, self._app, **options)` # see https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/serving.py from werkzeug.debug import DebuggedApplication import socket application = DebuggedApplication(self._app, True) def inner(): server = serving.make_server(host, app_port, self._app, False, 1, ClientCertHTTPRequestHandler, False, 'adhoc') # The following line is the reason why I copied all that code! if must_have_client_cert: server.ssl_context.set_verify( SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, lambda a, b, c, d, e: True) # That's it server.serve_forever() address_family = serving.select_ip_version(host, app_port) test_socket = socket.socket(address_family, socket.SOCK_STREAM) test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) test_socket.bind((host, app_port)) test_socket.close() serving.run_with_reloader(inner, None, 1) finally: self._app._got_first_request = False
def main(args_in, app_name="rsauth"): p = optparse.OptionParser(description=__doc__, version=__version__) p.set_usage(__usage__) p.add_option("-v", action="store_true", dest="verbose", help="verbose logging") p.add_option("-n", type="int", dest="server_num", help="Server instance number") opt, args = p.parse_args(args_in) if not opt.server_num: print "ERROR: server number not specified" p.print_help() print "Running test cases." print auth( { 'REQUEST_URI': '//auth?client_id=test&redirect_uri=foo&response_type=code&state=elated', 'REQUEST_METHOD': 'GET' }, lambda x, y: None) print auth( { 'REQUEST_URI': '//auth?client_id=test&redirect_uri=foo&response_type=token&state=elated', 'REQUEST_METHOD': 'GET' }, lambda x, y: None) print auth( { 'REQUEST_URI': '//vrfy?token=test&access_type=token&state=elated', 'REQUEST_METHOD': 'GET' }, lambda x, y: None) return socketfile = get_socketpath(app_name, opt.server_num) app = get_application() try: WSGIServer( app, bindAddress=socketfile, umask=FCGI_SOCKET_UMASK, multiplexed=True, ).run() finally: # Clean up server socket file os.unlink(socketfile)
def serve(application, host='127.0.0.1', port=8080, socket=None, **options): """Basic FastCGI support via flup. This web server has many, many options. Please see the Flup project documentation for details. """ # Allow either on-disk socket (recommended) or TCP/IP socket use. if not socket: bindAddress = (host, int(port)) else: bindAddress = socket # Bind and start the blocking web server interface. WSGIServer(application, bindAddress=bindAddress, **options).run()
def runServer(self): """Starts up the server. It (will) support different config options via the config plugin.""" config = pm.getService("config") debug = config.get("flask.debug") cFCGI = config.get("flask.fcgi") host = config.get("flask.bind") app_port = config.get("flask.app_port") fcgi_port = config.get("flask.fcgi_port") if cFCGI: logger.info("registering fcgi server at %s:%i", host, fcgi_port) from flup.server.fcgi import WSGIServer WSGIServer(self._app, bindAddress=(host, fcgi_port)).run() else: logger.info("registering app server at %s:%i", host, app_port) self._app.run(host=host, port=app_port, ssl_context='adhoc', debug=debug)
def main(): """ main function """ # BOTTLE_APP.run(host='127.0.0.1', port=8080, debug=True, reloader=True) LOGGER.info("Starting the REST API Bottle App") initial_scan_thread = Thread(target=scan, daemon=True) initial_scan_thread.start() aggregate_thread = Thread(target=aggregate_loop, args=(UCI_PLUGIN.uci, ), daemon=True) aggregate_thread.start() signal(SIGUSR1, handle_usr1_signal) WSGIServer(BOTTLE_APP, bindAddress="/var/rest-api.fastcgi.py.socket", umask=0o000).run() aggregate_thread.join() LOGGER.info("Stopped the REST API Bottle App")
def start_windows(debug, open_browser): nginx_dir = os.path.join(os.path.dirname(__file__), "dependencies", "nginx") nginx_exe = os.path.join(nginx_dir, "nginx.exe") if not is_nginx_up(): subprocess.Popen(nginx_exe, cwd=nginx_dir) try: from flup.server.fcgi import WSGIServer except ImportError: # If flup isn't installed fall back to the copy in ./dependencies import sys sys.path.append(os.path.join(os.path.dirname(__file__), "dependencies")) from flup.server.fcgi import WSGIServer if open_browser: browser('localhost', _PORT, debug) WSGIServer(app, debug=debug, bindAddress=('localhost', _PORT + 1)).run()
def syncthing_fcgi_start(args): if len(args) < 2: return False ip = args[0] port = long(args[1]) os.environ['DJANGO_SETTINGS_MODULE'] = 'syncthingUI.settings' import django.core.handlers.wsgi app = django.core.handlers.wsgi.WSGIHandler() res = False with open(syncthing_fcgi_pidfile, "wb") as fp: fp.write(str(os.getpid())) fp.close() res = WSGIServer(app, bindAddress=(ip, port)).run() return res
def start(self): """Start the SCGI server.""" # We have to instantiate the server class here because its __init__ # starts a threadpool. If we do it too early, daemonize won't work. from flup.server.scgi import WSGIServer self.scgiserver = WSGIServer(*self.args, **self.kwargs) # TODO: report this bug upstream to flup. # If we don't set _oldSIGs on Windows, we get: # File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py", # line 108, in run # self._restoreSignalHandlers() # File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py", # line 156, in _restoreSignalHandlers # for signum,handler in self._oldSIGs: # AttributeError: 'WSGIServer' object has no attribute '_oldSIGs' self.scgiserver._installSignalHandlers = lambda: None self.scgiserver._oldSIGs = [] self.ready = True self.scgiserver.run()
def main(args_in, app_name="rs"): p = optparse.OptionParser(description=__doc__, version=__version__) p.set_usage(__usage__) p.add_option("-v", action="store_true", dest="verbose", help="verbose logging") p.add_option("-n", type="int", dest="server_num", help="Server instance number") opt, args = p.parse_args(args_in) if not opt.server_num: print "ERROR: server number not specified" p.print_help() print rs( { 'REQUEST_URI': '//public/documents', 'REQUEST_METHOD': 'GET', 'HTTP_ORIGIN': 'http://litewrite.net', 'HTTP_AUTHORIZATION': 'Bearer 6c517dbce2ae68497bd3fe4ce1cc65eb' }, lambda x, y: None) print verify_path("repo/locations/collections/") print verify_path( "repo/pictures/Camera/D7C5FF07-5711-46BF-AD83-9EF05C6D6780.jpg") return socketfile = get_socketpath(app_name, opt.server_num) app = get_application() try: WSGIServer( app, bindAddress=socketfile, umask=FCGI_SOCKET_UMASK, multiplexed=True, ).run() finally: # Clean up server socket file os.unlink(socketfile)
def main(app): global http_server if not tornado.options.options.fcgi: server_opts = le_config.tornado.server xheaders = False if 'xheaders' in server_opts: xheaders = server_opts.xheaders http_server = tornado.httpserver.HTTPServer(app, xheaders=xheaders) host = server_opts.host port = server_opts.port base = server_opts.base http_server.listen(port, address=host) tornado.log.gen_log.info('HTTP Server started on http://%s:%s/%s', host, port, base) signal.signal(signal.SIGTERM, sig_handler) signal.signal(signal.SIGINT, sig_handler) try: tornado.ioloop.IOLoop.instance().start() except KeyboardInterrupt: if hasattr(app, 'shutdown_hook'): app.shutdown_hook() raise else: from tornado.wsgi import WSGIAdapter wsgi_app = WSGIAdapter(app) def fcgiapp(env, start): # set the script name to "" so it does not appear in the tornado path match pattern env['SCRIPT_NAME'] = '' return wsgi_app(env, start) from flup.server.fcgi import WSGIServer WSGIServer(fcgiapp, bindAddress=tornado.options.options.fcgi).run()
def main(): # Parse arguments import argparse parser = argparse.ArgumentParser(epilog=__doc__) parser.add_argument( '--env', action='store', default='development', help= 'mode in which the app should run: development, ci, uat or production') parser.add_argument('--port', type=int, default=5000, help='port to run on when in local mode') args = parser.parse_args() print 'Running as {env}'.format(env=args.env) import os if args.env == 'development': os.environ.setdefault("UBIOME_ENVIRONMENT", "development") os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' # Run App from app import service if args.env != 'development': from flup.server.fcgi import WSGIServer WSGIServer(application=service, bindAddress=service.config.get('SOCKET_UNIX'), umask=0, debug=False).run() else: # sandbox mode print 'Service is running on {env} mode, go play with it =)'.format( env=args.env) print '\n' service.run(host='127.0.0.1', port=args.port, debug=True, threaded=True)
def main(): app = create_app() log_fmt = logging.Formatter("[%(asctime)s] %(module)s " "%(levelname)s %(message)s") suggestion_log_path = os.path.join(app.instance_path, 'database.log') suggestion_handler = logging.FileHandler(suggestion_log_path) suggestion_handler.setFormatter(log_fmt) database.log.addHandler(suggestion_handler) import sys if len(sys.argv) > 1: cmd = sys.argv[1] else: cmd = 'runserver' if cmd == 'runserver': app.run(debug=True) elif cmd == 'shell': from code import interact with app.test_request_context(): interact(local={'app': app}) elif cmd == 'fastcgi': from flup.server.fcgi import WSGIServer error_log_path = os.path.join(app.instance_path, 'error.log') error_handler = logging.FileHandler(error_log_path) error_handler.setFormatter(log_fmt) error_handler.setLevel(logging.ERROR) logging.getLogger().addHandler(error_handler) sock_path = os.path.join(app.instance_path, 'fcgi.sock') server = WSGIServer(app, bindAddress=sock_path, umask=0) server.run() elif cmd == 'update_identities': import sync with app.test_request_context(): sync.update_identities() elif cmd == 'new_people': with app.test_request_context(): database.add_people(line.strip() for line in sys.stdin) database.db.session.commit()