[pgAdmin][RM5017] Use cheroot as default production server

Aditya Toshniwal <[email protected]> Tue, 17 Dec 2019 15:15:05 +0530
Newsgroups gmane.comp.db.postgresql.pgadmin.devel
Message-ID <CAM9w-_kHiZMhHZK+ZznADSHYrEH+SFxR0oTkZ3oBdDYCcGS85w@mail.gmail.com>
Hi Hackers,

Attached is the patch to use https://pypi.org/project/cheroot/ instead of
current flask dev server. cheroot is a stable production ready server.
Plus, flask dev server is not recommended for production.
Code is changed to use cheroot only when DEBUG is False, otherwise you the
default flask server.

Kindly review.

-- 
Thanks and Regards,
Aditya Toshniwal
Sr. Software Engineer | EnterpriseDB India | Pune
"Don't Complain about Heat, Plant a TREE"
RM5017.patch (application/octet-stream, 2.1 KB)
diff --git a/requirements.txt b/requirements.txt
index dae5436d6..b2e00d610 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -15,6 +15,7 @@
 #       ignored when building a PIP Wheel.
 ##############################################################################
 blinker==1.4
+cheroot==8.2.1
 Flask==1.0.2
 Werkzeug>=0.15.0
 Flask-Gravatar==0.5.0
diff --git a/web/pgAdmin4.py b/web/pgAdmin4.py
index 71eaed5e1..5cfd61253 100644
--- a/web/pgAdmin4.py
+++ b/web/pgAdmin4.py
@@ -13,6 +13,7 @@ to start a web server."""
 
 import os
 import sys
+from cheroot.wsgi import Server as CherootServer
 
 if sys.version_info[0] >= 3:
     import builtins
@@ -190,15 +191,29 @@ if __name__ == '__main__':
     # Reference:
     # https://github.com/pallets/werkzeug/issues/220#issuecomment-11176538
     try:
-        app.run(
-            host=config.DEFAULT_SERVER,
-            port=server_port,
-            use_reloader=(
-                (not PGADMIN_RUNTIME) and app.debug and
-                os.environ.get("WERKZEUG_RUN_MAIN") is not None
-            ),
-            threaded=config.THREADED_MODE
-        )
-
+        if config.DEBUG:
+            app.run(
+                host=config.DEFAULT_SERVER,
+                port=server_port,
+                use_reloader=(
+                    (not PGADMIN_RUNTIME) and app.debug and
+                    os.environ.get("WERKZEUG_RUN_MAIN") is not None
+                ),
+                threaded=config.THREADED_MODE
+            )
+        else:
+            # Can use cheroot instead of flask dev server when not in debug
+            # 10 is default thread count in CherootServer
+            num_threads = 10 if config.THREADED_MODE else 1
+            prod_server = CherootServer(
+                (config.DEFAULT_SERVER, server_port),
+                wsgi_app=app,
+                numthreads=num_threads,
+                server_name=config.APP_NAME)
+            try:
+                print("Using production server...")
+                prod_server.start()
+            except KeyboardInterrupt:
+                prod_server.stop()
     except IOError:
         app.logger.error("Error starting the app server: %s", sys.exc_info())