base.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. # -*- coding: utf-8 -
  2. #
  3. # This file is part of gunicorn released under the MIT license.
  4. # See the NOTICE for more information.
  5. import importlib.util
  6. import importlib.machinery
  7. import os
  8. import sys
  9. import traceback
  10. from gunicorn import util
  11. from gunicorn.arbiter import Arbiter
  12. from gunicorn.config import Config, get_default_config_file
  13. from gunicorn import debug
  14. class BaseApplication(object):
  15. """
  16. An application interface for configuring and loading
  17. the various necessities for any given web framework.
  18. """
  19. def __init__(self, usage=None, prog=None):
  20. self.usage = usage
  21. self.cfg = None
  22. self.callable = None
  23. self.prog = prog
  24. self.logger = None
  25. self.do_load_config()
  26. def do_load_config(self):
  27. """
  28. Loads the configuration
  29. """
  30. try:
  31. self.load_default_config()
  32. self.load_config()
  33. except Exception as e:
  34. print("\nError: %s" % str(e), file=sys.stderr)
  35. sys.stderr.flush()
  36. sys.exit(1)
  37. def load_default_config(self):
  38. # init configuration
  39. self.cfg = Config(self.usage, prog=self.prog)
  40. def init(self, parser, opts, args):
  41. raise NotImplementedError
  42. def load(self):
  43. raise NotImplementedError
  44. def load_config(self):
  45. """
  46. This method is used to load the configuration from one or several input(s).
  47. Custom Command line, configuration file.
  48. You have to override this method in your class.
  49. """
  50. raise NotImplementedError
  51. def reload(self):
  52. self.do_load_config()
  53. if self.cfg.spew:
  54. debug.spew()
  55. def wsgi(self):
  56. if self.callable is None:
  57. self.callable = self.load()
  58. return self.callable
  59. def run(self):
  60. try:
  61. Arbiter(self).run()
  62. except RuntimeError as e:
  63. print("\nError: %s\n" % e, file=sys.stderr)
  64. sys.stderr.flush()
  65. sys.exit(1)
  66. class Application(BaseApplication):
  67. # 'init' and 'load' methods are implemented by WSGIApplication.
  68. # pylint: disable=abstract-method
  69. def chdir(self):
  70. # chdir to the configured path before loading,
  71. # default is the current dir
  72. os.chdir(self.cfg.chdir)
  73. # add the path to sys.path
  74. if self.cfg.chdir not in sys.path:
  75. sys.path.insert(0, self.cfg.chdir)
  76. def get_config_from_filename(self, filename):
  77. if not os.path.exists(filename):
  78. raise RuntimeError("%r doesn't exist" % filename)
  79. ext = os.path.splitext(filename)[1]
  80. try:
  81. module_name = '__config__'
  82. if ext in [".py", ".pyc"]:
  83. spec = importlib.util.spec_from_file_location(module_name, filename)
  84. else:
  85. msg = "configuration file should have a valid Python extension.\n"
  86. util.warn(msg)
  87. loader_ = importlib.machinery.SourceFileLoader(module_name, filename)
  88. spec = importlib.util.spec_from_file_location(module_name, filename, loader=loader_)
  89. mod = importlib.util.module_from_spec(spec)
  90. sys.modules[module_name] = mod
  91. spec.loader.exec_module(mod)
  92. except Exception:
  93. print("Failed to read config file: %s" % filename, file=sys.stderr)
  94. traceback.print_exc()
  95. sys.stderr.flush()
  96. sys.exit(1)
  97. return vars(mod)
  98. def get_config_from_module_name(self, module_name):
  99. return vars(importlib.import_module(module_name))
  100. def load_config_from_module_name_or_filename(self, location):
  101. """
  102. Loads the configuration file: the file is a python file, otherwise raise an RuntimeError
  103. Exception or stop the process if the configuration file contains a syntax error.
  104. """
  105. if location.startswith("python:"):
  106. module_name = location[len("python:"):]
  107. cfg = self.get_config_from_module_name(module_name)
  108. else:
  109. if location.startswith("file:"):
  110. filename = location[len("file:"):]
  111. else:
  112. filename = location
  113. cfg = self.get_config_from_filename(filename)
  114. for k, v in cfg.items():
  115. # Ignore unknown names
  116. if k not in self.cfg.settings:
  117. continue
  118. try:
  119. self.cfg.set(k.lower(), v)
  120. except Exception:
  121. print("Invalid value for %s: %s\n" % (k, v), file=sys.stderr)
  122. sys.stderr.flush()
  123. raise
  124. return cfg
  125. def load_config_from_file(self, filename):
  126. return self.load_config_from_module_name_or_filename(location=filename)
  127. def load_config(self):
  128. # parse console args
  129. parser = self.cfg.parser()
  130. args = parser.parse_args()
  131. # optional settings from apps
  132. cfg = self.init(parser, args, args.args)
  133. # set up import paths and follow symlinks
  134. self.chdir()
  135. # Load up the any app specific configuration
  136. if cfg:
  137. for k, v in cfg.items():
  138. self.cfg.set(k.lower(), v)
  139. env_args = parser.parse_args(self.cfg.get_cmd_args_from_env())
  140. if args.config:
  141. self.load_config_from_file(args.config)
  142. elif env_args.config:
  143. self.load_config_from_file(env_args.config)
  144. else:
  145. default_config = get_default_config_file()
  146. if default_config is not None:
  147. self.load_config_from_file(default_config)
  148. # Load up environment configuration
  149. for k, v in vars(env_args).items():
  150. if v is None:
  151. continue
  152. if k == "args":
  153. continue
  154. self.cfg.set(k.lower(), v)
  155. # Lastly, update the configuration with any command line settings.
  156. for k, v in vars(args).items():
  157. if v is None:
  158. continue
  159. if k == "args":
  160. continue
  161. self.cfg.set(k.lower(), v)
  162. # current directory might be changed by the config now
  163. # set up import paths and follow symlinks
  164. self.chdir()
  165. def run(self):
  166. if self.cfg.print_config:
  167. print(self.cfg)
  168. if self.cfg.print_config or self.cfg.check_config:
  169. try:
  170. self.load()
  171. except Exception:
  172. msg = "\nError while loading the application:\n"
  173. print(msg, file=sys.stderr)
  174. traceback.print_exc()
  175. sys.stderr.flush()
  176. sys.exit(1)
  177. sys.exit(0)
  178. if self.cfg.spew:
  179. debug.spew()
  180. if self.cfg.daemon:
  181. util.daemonize(self.cfg.enable_stdio_inheritance)
  182. # set python paths
  183. if self.cfg.pythonpath:
  184. paths = self.cfg.pythonpath.split(",")
  185. for path in paths:
  186. pythonpath = os.path.abspath(path)
  187. if pythonpath not in sys.path:
  188. sys.path.insert(0, pythonpath)
  189. super().run()