config.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860
  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. # Please remember to run "make -C docs html" after update "desc" attributes.
  6. import copy
  7. import grp
  8. import inspect
  9. try:
  10. import argparse
  11. except ImportError: # python 2.6
  12. from . import argparse_compat as argparse
  13. import os
  14. import pwd
  15. import re
  16. import ssl
  17. import sys
  18. import textwrap
  19. import shlex
  20. from gunicorn import __version__
  21. from gunicorn import _compat
  22. from gunicorn.errors import ConfigError
  23. from gunicorn.reloader import reloader_engines
  24. from gunicorn import six
  25. from gunicorn import util
  26. KNOWN_SETTINGS = []
  27. PLATFORM = sys.platform
  28. def wrap_method(func):
  29. def _wrapped(instance, *args, **kwargs):
  30. return func(*args, **kwargs)
  31. return _wrapped
  32. def make_settings(ignore=None):
  33. settings = {}
  34. ignore = ignore or ()
  35. for s in KNOWN_SETTINGS:
  36. setting = s()
  37. if setting.name in ignore:
  38. continue
  39. settings[setting.name] = setting.copy()
  40. return settings
  41. def auto_int(_, x):
  42. if x.startswith('0') and not x.lower().startswith('0x'):
  43. # for compatible with octal numbers in python3
  44. x = x.replace('0', '0o', 1)
  45. return int(x, 0)
  46. class Config(object):
  47. def __init__(self, usage=None, prog=None):
  48. self.settings = make_settings()
  49. self.usage = usage
  50. self.prog = prog or os.path.basename(sys.argv[0])
  51. self.env_orig = os.environ.copy()
  52. def __getattr__(self, name):
  53. if name not in self.settings:
  54. raise AttributeError("No configuration setting for: %s" % name)
  55. return self.settings[name].get()
  56. def __setattr__(self, name, value):
  57. if name != "settings" and name in self.settings:
  58. raise AttributeError("Invalid access!")
  59. super(Config, self).__setattr__(name, value)
  60. def set(self, name, value):
  61. if name not in self.settings:
  62. raise AttributeError("No configuration setting for: %s" % name)
  63. self.settings[name].set(value)
  64. def get_cmd_args_from_env(self):
  65. if 'GUNICORN_CMD_ARGS' in self.env_orig:
  66. return shlex.split(self.env_orig['GUNICORN_CMD_ARGS'])
  67. return []
  68. def parser(self):
  69. kwargs = {
  70. "usage": self.usage,
  71. "prog": self.prog
  72. }
  73. parser = argparse.ArgumentParser(**kwargs)
  74. parser.add_argument("-v", "--version",
  75. action="version", default=argparse.SUPPRESS,
  76. version="%(prog)s (version " + __version__ + ")\n",
  77. help="show program's version number and exit")
  78. parser.add_argument("args", nargs="*", help=argparse.SUPPRESS)
  79. keys = sorted(self.settings, key=self.settings.__getitem__)
  80. for k in keys:
  81. self.settings[k].add_option(parser)
  82. return parser
  83. @property
  84. def worker_class_str(self):
  85. uri = self.settings['worker_class'].get()
  86. ## are we using a threaded worker?
  87. is_sync = uri.endswith('SyncWorker') or uri == 'sync'
  88. if is_sync and self.threads > 1:
  89. return "threads"
  90. return uri
  91. @property
  92. def worker_class(self):
  93. uri = self.settings['worker_class'].get()
  94. ## are we using a threaded worker?
  95. is_sync = uri.endswith('SyncWorker') or uri == 'sync'
  96. if is_sync and self.threads > 1:
  97. uri = "gunicorn.workers.gthread.ThreadWorker"
  98. worker_class = util.load_class(uri)
  99. if hasattr(worker_class, "setup"):
  100. worker_class.setup()
  101. return worker_class
  102. @property
  103. def threads(self):
  104. return self.settings['threads'].get()
  105. @property
  106. def workers(self):
  107. return self.settings['workers'].get()
  108. @property
  109. def address(self):
  110. s = self.settings['bind'].get()
  111. return [util.parse_address(_compat.bytes_to_str(bind)) for bind in s]
  112. @property
  113. def uid(self):
  114. return self.settings['user'].get()
  115. @property
  116. def gid(self):
  117. return self.settings['group'].get()
  118. @property
  119. def proc_name(self):
  120. pn = self.settings['proc_name'].get()
  121. if pn is not None:
  122. return pn
  123. else:
  124. return self.settings['default_proc_name'].get()
  125. @property
  126. def logger_class(self):
  127. uri = self.settings['logger_class'].get()
  128. if uri == "simple":
  129. # support the default
  130. uri = LoggerClass.default
  131. # if default logger is in use, and statsd is on, automagically switch
  132. # to the statsd logger
  133. if uri == LoggerClass.default:
  134. if 'statsd_host' in self.settings and self.settings['statsd_host'].value is not None:
  135. uri = "gunicorn.instrument.statsd.Statsd"
  136. logger_class = util.load_class(
  137. uri,
  138. default="gunicorn.glogging.Logger",
  139. section="gunicorn.loggers")
  140. if hasattr(logger_class, "install"):
  141. logger_class.install()
  142. return logger_class
  143. @property
  144. def is_ssl(self):
  145. return self.certfile or self.keyfile
  146. @property
  147. def ssl_options(self):
  148. opts = {}
  149. for name, value in self.settings.items():
  150. if value.section == 'SSL':
  151. opts[name] = value.get()
  152. return opts
  153. @property
  154. def env(self):
  155. raw_env = self.settings['raw_env'].get()
  156. env = {}
  157. if not raw_env:
  158. return env
  159. for e in raw_env:
  160. s = _compat.bytes_to_str(e)
  161. try:
  162. k, v = s.split('=', 1)
  163. except ValueError:
  164. raise RuntimeError("environment setting %r invalid" % s)
  165. env[k] = v
  166. return env
  167. @property
  168. def sendfile(self):
  169. if self.settings['sendfile'].get() is not None:
  170. return False
  171. if 'SENDFILE' in os.environ:
  172. sendfile = os.environ['SENDFILE'].lower()
  173. return sendfile in ['y', '1', 'yes', 'true']
  174. return True
  175. @property
  176. def paste_global_conf(self):
  177. raw_global_conf = self.settings['raw_paste_global_conf'].get()
  178. if raw_global_conf is None:
  179. return None
  180. global_conf = {}
  181. for e in raw_global_conf:
  182. s = _compat.bytes_to_str(e)
  183. try:
  184. k, v = re.split(r'(?<!\\)=', s, 1)
  185. except ValueError:
  186. raise RuntimeError("environment setting %r invalid" % s)
  187. k = k.replace('\\=', '=')
  188. v = v.replace('\\=', '=')
  189. global_conf[k] = v
  190. return global_conf
  191. class SettingMeta(type):
  192. def __new__(cls, name, bases, attrs):
  193. super_new = super(SettingMeta, cls).__new__
  194. parents = [b for b in bases if isinstance(b, SettingMeta)]
  195. if not parents:
  196. return super_new(cls, name, bases, attrs)
  197. attrs["order"] = len(KNOWN_SETTINGS)
  198. attrs["validator"] = wrap_method(attrs["validator"])
  199. new_class = super_new(cls, name, bases, attrs)
  200. new_class.fmt_desc(attrs.get("desc", ""))
  201. KNOWN_SETTINGS.append(new_class)
  202. return new_class
  203. def fmt_desc(cls, desc):
  204. desc = textwrap.dedent(desc).strip()
  205. setattr(cls, "desc", desc)
  206. setattr(cls, "short", desc.splitlines()[0])
  207. class Setting(object):
  208. name = None
  209. value = None
  210. section = None
  211. cli = None
  212. validator = None
  213. type = None
  214. meta = None
  215. action = None
  216. default = None
  217. short = None
  218. desc = None
  219. nargs = None
  220. const = None
  221. def __init__(self):
  222. if self.default is not None:
  223. self.set(self.default)
  224. def add_option(self, parser):
  225. if not self.cli:
  226. return
  227. args = tuple(self.cli)
  228. help_txt = "%s [%s]" % (self.short, self.default)
  229. help_txt = help_txt.replace("%", "%%")
  230. kwargs = {
  231. "dest": self.name,
  232. "action": self.action or "store",
  233. "type": self.type or str,
  234. "default": None,
  235. "help": help_txt
  236. }
  237. if self.meta is not None:
  238. kwargs['metavar'] = self.meta
  239. if kwargs["action"] != "store":
  240. kwargs.pop("type")
  241. if self.nargs is not None:
  242. kwargs["nargs"] = self.nargs
  243. if self.const is not None:
  244. kwargs["const"] = self.const
  245. parser.add_argument(*args, **kwargs)
  246. def copy(self):
  247. return copy.copy(self)
  248. def get(self):
  249. return self.value
  250. def set(self, val):
  251. if not six.callable(self.validator):
  252. raise TypeError('Invalid validator: %s' % self.name)
  253. self.value = self.validator(val)
  254. def __lt__(self, other):
  255. return (self.section == other.section and
  256. self.order < other.order)
  257. __cmp__ = __lt__
  258. Setting = SettingMeta('Setting', (Setting,), {})
  259. def validate_bool(val):
  260. if val is None:
  261. return
  262. if isinstance(val, bool):
  263. return val
  264. if not isinstance(val, six.string_types):
  265. raise TypeError("Invalid type for casting: %s" % val)
  266. if val.lower().strip() == "true":
  267. return True
  268. elif val.lower().strip() == "false":
  269. return False
  270. else:
  271. raise ValueError("Invalid boolean: %s" % val)
  272. def validate_dict(val):
  273. if not isinstance(val, dict):
  274. raise TypeError("Value is not a dictionary: %s " % val)
  275. return val
  276. def validate_pos_int(val):
  277. if not isinstance(val, six.integer_types):
  278. val = int(val, 0)
  279. else:
  280. # Booleans are ints!
  281. val = int(val)
  282. if val < 0:
  283. raise ValueError("Value must be positive: %s" % val)
  284. return val
  285. def validate_string(val):
  286. if val is None:
  287. return None
  288. if not isinstance(val, six.string_types):
  289. raise TypeError("Not a string: %s" % val)
  290. return val.strip()
  291. def validate_list_string(val):
  292. if not val:
  293. return []
  294. # legacy syntax
  295. if isinstance(val, six.string_types):
  296. val = [val]
  297. return [validate_string(v) for v in val]
  298. def validate_string_to_list(val):
  299. val = validate_string(val)
  300. if not val:
  301. return []
  302. return [v.strip() for v in val.split(",") if v]
  303. def validate_class(val):
  304. if inspect.isfunction(val) or inspect.ismethod(val):
  305. val = val()
  306. if inspect.isclass(val):
  307. return val
  308. return validate_string(val)
  309. def validate_callable(arity):
  310. def _validate_callable(val):
  311. if isinstance(val, six.string_types):
  312. try:
  313. mod_name, obj_name = val.rsplit(".", 1)
  314. except ValueError:
  315. raise TypeError("Value '%s' is not import string. "
  316. "Format: module[.submodules...].object" % val)
  317. try:
  318. mod = __import__(mod_name, fromlist=[obj_name])
  319. val = getattr(mod, obj_name)
  320. except ImportError as e:
  321. raise TypeError(str(e))
  322. except AttributeError:
  323. raise TypeError("Can not load '%s' from '%s'"
  324. "" % (obj_name, mod_name))
  325. if not six.callable(val):
  326. raise TypeError("Value is not six.callable: %s" % val)
  327. if arity != -1 and arity != len(inspect.getargspec(val)[0]):
  328. raise TypeError("Value must have an arity of: %s" % arity)
  329. return val
  330. return _validate_callable
  331. def validate_user(val):
  332. if val is None:
  333. return os.geteuid()
  334. if isinstance(val, int):
  335. return val
  336. elif val.isdigit():
  337. return int(val)
  338. else:
  339. try:
  340. return pwd.getpwnam(val).pw_uid
  341. except KeyError:
  342. raise ConfigError("No such user: '%s'" % val)
  343. def validate_group(val):
  344. if val is None:
  345. return os.getegid()
  346. if isinstance(val, int):
  347. return val
  348. elif val.isdigit():
  349. return int(val)
  350. else:
  351. try:
  352. return grp.getgrnam(val).gr_gid
  353. except KeyError:
  354. raise ConfigError("No such group: '%s'" % val)
  355. def validate_post_request(val):
  356. val = validate_callable(-1)(val)
  357. largs = len(inspect.getargspec(val)[0])
  358. if largs == 4:
  359. return val
  360. elif largs == 3:
  361. return lambda worker, req, env, _r: val(worker, req, env)
  362. elif largs == 2:
  363. return lambda worker, req, _e, _r: val(worker, req)
  364. else:
  365. raise TypeError("Value must have an arity of: 4")
  366. def validate_chdir(val):
  367. # valid if the value is a string
  368. val = validate_string(val)
  369. # transform relative paths
  370. path = os.path.abspath(os.path.normpath(os.path.join(util.getcwd(), val)))
  371. # test if the path exists
  372. if not os.path.exists(path):
  373. raise ConfigError("can't chdir to %r" % val)
  374. return path
  375. def validate_hostport(val):
  376. val = validate_string(val)
  377. if val is None:
  378. return None
  379. elements = val.split(":")
  380. if len(elements) == 2:
  381. return (elements[0], int(elements[1]))
  382. else:
  383. raise TypeError("Value must consist of: hostname:port")
  384. def validate_reload_engine(val):
  385. if val not in reloader_engines:
  386. raise ConfigError("Invalid reload_engine: %r" % val)
  387. return val
  388. def get_default_config_file():
  389. config_path = os.path.join(os.path.abspath(os.getcwd()),
  390. 'gunicorn.conf.py')
  391. if os.path.exists(config_path):
  392. return config_path
  393. return None
  394. class ConfigFile(Setting):
  395. name = "config"
  396. section = "Config File"
  397. cli = ["-c", "--config"]
  398. meta = "CONFIG"
  399. validator = validate_string
  400. default = None
  401. desc = """\
  402. The Gunicorn config file.
  403. A string of the form ``PATH``, ``file:PATH``, or ``python:MODULE_NAME``.
  404. Only has an effect when specified on the command line or as part of an
  405. application specific configuration.
  406. .. versionchanged:: 19.4
  407. Loading the config from a Python module requires the ``python:``
  408. prefix.
  409. """
  410. class Bind(Setting):
  411. name = "bind"
  412. action = "append"
  413. section = "Server Socket"
  414. cli = ["-b", "--bind"]
  415. meta = "ADDRESS"
  416. validator = validate_list_string
  417. if 'PORT' in os.environ:
  418. default = ['0.0.0.0:{0}'.format(os.environ.get('PORT'))]
  419. else:
  420. default = ['127.0.0.1:8000']
  421. desc = """\
  422. The socket to bind.
  423. A string of the form: ``HOST``, ``HOST:PORT``, ``unix:PATH``. An IP is
  424. a valid ``HOST``.
  425. Multiple addresses can be bound. ex.::
  426. $ gunicorn -b 127.0.0.1:8000 -b [::1]:8000 test:app
  427. will bind the `test:app` application on localhost both on ipv6
  428. and ipv4 interfaces.
  429. """
  430. class Backlog(Setting):
  431. name = "backlog"
  432. section = "Server Socket"
  433. cli = ["--backlog"]
  434. meta = "INT"
  435. validator = validate_pos_int
  436. type = int
  437. default = 2048
  438. desc = """\
  439. The maximum number of pending connections.
  440. This refers to the number of clients that can be waiting to be served.
  441. Exceeding this number results in the client getting an error when
  442. attempting to connect. It should only affect servers under significant
  443. load.
  444. Must be a positive integer. Generally set in the 64-2048 range.
  445. """
  446. class Workers(Setting):
  447. name = "workers"
  448. section = "Worker Processes"
  449. cli = ["-w", "--workers"]
  450. meta = "INT"
  451. validator = validate_pos_int
  452. type = int
  453. default = int(os.environ.get("WEB_CONCURRENCY", 1))
  454. desc = """\
  455. The number of worker processes for handling requests.
  456. A positive integer generally in the ``2-4 x $(NUM_CORES)`` range.
  457. You'll want to vary this a bit to find the best for your particular
  458. application's work load.
  459. By default, the value of the ``WEB_CONCURRENCY`` environment variable.
  460. If it is not defined, the default is ``1``.
  461. """
  462. class WorkerClass(Setting):
  463. name = "worker_class"
  464. section = "Worker Processes"
  465. cli = ["-k", "--worker-class"]
  466. meta = "STRING"
  467. validator = validate_class
  468. default = "sync"
  469. desc = """\
  470. The type of workers to use.
  471. The default class (``sync``) should handle most "normal" types of
  472. workloads. You'll want to read :doc:`design` for information on when
  473. you might want to choose one of the other worker classes.
  474. A string referring to one of the following bundled classes:
  475. * ``sync``
  476. * ``eventlet`` - Requires eventlet >= 0.9.7
  477. * ``gevent`` - Requires gevent >= 0.13
  478. * ``tornado`` - Requires tornado >= 0.2
  479. * ``gthread`` - Python 2 requires the futures package to be installed
  480. * ``gaiohttp`` - Requires Python 3.4 and aiohttp >= 0.21.5
  481. Optionally, you can provide your own worker by giving Gunicorn a
  482. Python path to a subclass of ``gunicorn.workers.base.Worker``.
  483. This alternative syntax will load the gevent class:
  484. ``gunicorn.workers.ggevent.GeventWorker``.
  485. """
  486. class WorkerThreads(Setting):
  487. name = "threads"
  488. section = "Worker Processes"
  489. cli = ["--threads"]
  490. meta = "INT"
  491. validator = validate_pos_int
  492. type = int
  493. default = 1
  494. desc = """\
  495. The number of worker threads for handling requests.
  496. Run each worker with the specified number of threads.
  497. A positive integer generally in the ``2-4 x $(NUM_CORES)`` range.
  498. You'll want to vary this a bit to find the best for your particular
  499. application's work load.
  500. If it is not defined, the default is ``1``.
  501. This setting only affects the Gthread worker type.
  502. """
  503. class WorkerConnections(Setting):
  504. name = "worker_connections"
  505. section = "Worker Processes"
  506. cli = ["--worker-connections"]
  507. meta = "INT"
  508. validator = validate_pos_int
  509. type = int
  510. default = 1000
  511. desc = """\
  512. The maximum number of simultaneous clients.
  513. This setting only affects the Eventlet and Gevent worker types.
  514. """
  515. class MaxRequests(Setting):
  516. name = "max_requests"
  517. section = "Worker Processes"
  518. cli = ["--max-requests"]
  519. meta = "INT"
  520. validator = validate_pos_int
  521. type = int
  522. default = 0
  523. desc = """\
  524. The maximum number of requests a worker will process before restarting.
  525. Any value greater than zero will limit the number of requests a work
  526. will process before automatically restarting. This is a simple method
  527. to help limit the damage of memory leaks.
  528. If this is set to zero (the default) then the automatic worker
  529. restarts are disabled.
  530. """
  531. class MaxRequestsJitter(Setting):
  532. name = "max_requests_jitter"
  533. section = "Worker Processes"
  534. cli = ["--max-requests-jitter"]
  535. meta = "INT"
  536. validator = validate_pos_int
  537. type = int
  538. default = 0
  539. desc = """\
  540. The maximum jitter to add to the *max_requests* setting.
  541. The jitter causes the restart per worker to be randomized by
  542. ``randint(0, max_requests_jitter)``. This is intended to stagger worker
  543. restarts to avoid all workers restarting at the same time.
  544. .. versionadded:: 19.2
  545. """
  546. class Timeout(Setting):
  547. name = "timeout"
  548. section = "Worker Processes"
  549. cli = ["-t", "--timeout"]
  550. meta = "INT"
  551. validator = validate_pos_int
  552. type = int
  553. default = 30
  554. desc = """\
  555. Workers silent for more than this many seconds are killed and restarted.
  556. Generally set to thirty seconds. Only set this noticeably higher if
  557. you're sure of the repercussions for sync workers. For the non sync
  558. workers it just means that the worker process is still communicating and
  559. is not tied to the length of time required to handle a single request.
  560. """
  561. class GracefulTimeout(Setting):
  562. name = "graceful_timeout"
  563. section = "Worker Processes"
  564. cli = ["--graceful-timeout"]
  565. meta = "INT"
  566. validator = validate_pos_int
  567. type = int
  568. default = 30
  569. desc = """\
  570. Timeout for graceful workers restart.
  571. After receiving a restart signal, workers have this much time to finish
  572. serving requests. Workers still alive after the timeout (starting from
  573. the receipt of the restart signal) are force killed.
  574. """
  575. class Keepalive(Setting):
  576. name = "keepalive"
  577. section = "Worker Processes"
  578. cli = ["--keep-alive"]
  579. meta = "INT"
  580. validator = validate_pos_int
  581. type = int
  582. default = 2
  583. desc = """\
  584. The number of seconds to wait for requests on a Keep-Alive connection.
  585. Generally set in the 1-5 seconds range.
  586. """
  587. class LimitRequestLine(Setting):
  588. name = "limit_request_line"
  589. section = "Security"
  590. cli = ["--limit-request-line"]
  591. meta = "INT"
  592. validator = validate_pos_int
  593. type = int
  594. default = 4094
  595. desc = """\
  596. The maximum size of HTTP request line in bytes.
  597. This parameter is used to limit the allowed size of a client's
  598. HTTP request-line. Since the request-line consists of the HTTP
  599. method, URI, and protocol version, this directive places a
  600. restriction on the length of a request-URI allowed for a request
  601. on the server. A server needs this value to be large enough to
  602. hold any of its resource names, including any information that
  603. might be passed in the query part of a GET request. Value is a number
  604. from 0 (unlimited) to 8190.
  605. This parameter can be used to prevent any DDOS attack.
  606. """
  607. class LimitRequestFields(Setting):
  608. name = "limit_request_fields"
  609. section = "Security"
  610. cli = ["--limit-request-fields"]
  611. meta = "INT"
  612. validator = validate_pos_int
  613. type = int
  614. default = 100
  615. desc = """\
  616. Limit the number of HTTP headers fields in a request.
  617. This parameter is used to limit the number of headers in a request to
  618. prevent DDOS attack. Used with the *limit_request_field_size* it allows
  619. more safety. By default this value is 100 and can't be larger than
  620. 32768.
  621. """
  622. class LimitRequestFieldSize(Setting):
  623. name = "limit_request_field_size"
  624. section = "Security"
  625. cli = ["--limit-request-field_size"]
  626. meta = "INT"
  627. validator = validate_pos_int
  628. type = int
  629. default = 8190
  630. desc = """\
  631. Limit the allowed size of an HTTP request header field.
  632. Value is a positive number or 0. Setting it to 0 will allow unlimited
  633. header field sizes.
  634. .. warning::
  635. Setting this parameter to a very high or unlimited value can open
  636. up for DDOS attacks.
  637. """
  638. class Reload(Setting):
  639. name = "reload"
  640. section = 'Debugging'
  641. cli = ['--reload']
  642. validator = validate_bool
  643. action = 'store_true'
  644. default = False
  645. desc = '''\
  646. Restart workers when code changes.
  647. This setting is intended for development. It will cause workers to be
  648. restarted whenever application code changes.
  649. The reloader is incompatible with application preloading. When using a
  650. paste configuration be sure that the server block does not import any
  651. application code or the reload will not work as designed.
  652. The default behavior is to attempt inotify with a fallback to file
  653. system polling. Generally, inotify should be preferred if available
  654. because it consumes less system resources.
  655. .. note::
  656. In order to use the inotify reloader, you must have the ``inotify``
  657. package installed.
  658. '''
  659. class ReloadEngine(Setting):
  660. name = "reload_engine"
  661. section = "Debugging"
  662. cli = ["--reload-engine"]
  663. meta = "STRING"
  664. validator = validate_reload_engine
  665. default = "auto"
  666. desc = """\
  667. The implementation that should be used to power :ref:`reload`.
  668. Valid engines are:
  669. * 'auto'
  670. * 'poll'
  671. * 'inotify' (requires inotify)
  672. .. versionadded:: 19.7
  673. """
  674. class Spew(Setting):
  675. name = "spew"
  676. section = "Debugging"
  677. cli = ["--spew"]
  678. validator = validate_bool
  679. action = "store_true"
  680. default = False
  681. desc = """\
  682. Install a trace function that spews every line executed by the server.
  683. This is the nuclear option.
  684. """
  685. class ConfigCheck(Setting):
  686. name = "check_config"
  687. section = "Debugging"
  688. cli = ["--check-config"]
  689. validator = validate_bool
  690. action = "store_true"
  691. default = False
  692. desc = """\
  693. Check the configuration.
  694. """
  695. class PreloadApp(Setting):
  696. name = "preload_app"
  697. section = "Server Mechanics"
  698. cli = ["--preload"]
  699. validator = validate_bool
  700. action = "store_true"
  701. default = False
  702. desc = """\
  703. Load application code before the worker processes are forked.
  704. By preloading an application you can save some RAM resources as well as
  705. speed up server boot times. Although, if you defer application loading
  706. to each worker process, you can reload your application code easily by
  707. restarting workers.
  708. """
  709. class Sendfile(Setting):
  710. name = "sendfile"
  711. section = "Server Mechanics"
  712. cli = ["--no-sendfile"]
  713. validator = validate_bool
  714. action = "store_const"
  715. const = False
  716. desc = """\
  717. Disables the use of ``sendfile()``.
  718. If not set, the value of the ``SENDFILE`` environment variable is used
  719. to enable or disable its usage.
  720. .. versionadded:: 19.2
  721. .. versionchanged:: 19.4
  722. Swapped ``--sendfile`` with ``--no-sendfile`` to actually allow
  723. disabling.
  724. .. versionchanged:: 19.6
  725. added support for the ``SENDFILE`` environment variable
  726. """
  727. class Chdir(Setting):
  728. name = "chdir"
  729. section = "Server Mechanics"
  730. cli = ["--chdir"]
  731. validator = validate_chdir
  732. default = util.getcwd()
  733. desc = """\
  734. Chdir to specified directory before apps loading.
  735. """
  736. class Daemon(Setting):
  737. name = "daemon"
  738. section = "Server Mechanics"
  739. cli = ["-D", "--daemon"]
  740. validator = validate_bool
  741. action = "store_true"
  742. default = False
  743. desc = """\
  744. Daemonize the Gunicorn process.
  745. Detaches the server from the controlling terminal and enters the
  746. background.
  747. """
  748. class Env(Setting):
  749. name = "raw_env"
  750. action = "append"
  751. section = "Server Mechanics"
  752. cli = ["-e", "--env"]
  753. meta = "ENV"
  754. validator = validate_list_string
  755. default = []
  756. desc = """\
  757. Set environment variable (key=value).
  758. Pass variables to the execution environment. Ex.::
  759. $ gunicorn -b 127.0.0.1:8000 --env FOO=1 test:app
  760. and test for the foo variable environment in your application.
  761. """
  762. class Pidfile(Setting):
  763. name = "pidfile"
  764. section = "Server Mechanics"
  765. cli = ["-p", "--pid"]
  766. meta = "FILE"
  767. validator = validate_string
  768. default = None
  769. desc = """\
  770. A filename to use for the PID file.
  771. If not set, no PID file will be written.
  772. """
  773. class WorkerTmpDir(Setting):
  774. name = "worker_tmp_dir"
  775. section = "Server Mechanics"
  776. cli = ["--worker-tmp-dir"]
  777. meta = "DIR"
  778. validator = validate_string
  779. default = None
  780. desc = """\
  781. A directory to use for the worker heartbeat temporary file.
  782. If not set, the default temporary directory will be used.
  783. .. note::
  784. The current heartbeat system involves calling ``os.fchmod`` on
  785. temporary file handlers and may block a worker for arbitrary time
  786. if the directory is on a disk-backed filesystem.
  787. See :ref:`blocking-os-fchmod` for more detailed information
  788. and a solution for avoiding this problem.
  789. """
  790. class User(Setting):
  791. name = "user"
  792. section = "Server Mechanics"
  793. cli = ["-u", "--user"]
  794. meta = "USER"
  795. validator = validate_user
  796. default = os.geteuid()
  797. desc = """\
  798. Switch worker processes to run as this user.
  799. A valid user id (as an integer) or the name of a user that can be
  800. retrieved with a call to ``pwd.getpwnam(value)`` or ``None`` to not
  801. change the worker process user.
  802. """
  803. class Group(Setting):
  804. name = "group"
  805. section = "Server Mechanics"
  806. cli = ["-g", "--group"]
  807. meta = "GROUP"
  808. validator = validate_group
  809. default = os.getegid()
  810. desc = """\
  811. Switch worker process to run as this group.
  812. A valid group id (as an integer) or the name of a user that can be
  813. retrieved with a call to ``pwd.getgrnam(value)`` or ``None`` to not
  814. change the worker processes group.
  815. """
  816. class Umask(Setting):
  817. name = "umask"
  818. section = "Server Mechanics"
  819. cli = ["-m", "--umask"]
  820. meta = "INT"
  821. validator = validate_pos_int
  822. type = auto_int
  823. default = 0
  824. desc = """\
  825. A bit mask for the file mode on files written by Gunicorn.
  826. Note that this affects unix socket permissions.
  827. A valid value for the ``os.umask(mode)`` call or a string compatible
  828. with ``int(value, 0)`` (``0`` means Python guesses the base, so values
  829. like ``0``, ``0xFF``, ``0022`` are valid for decimal, hex, and octal
  830. representations)
  831. """
  832. class Initgroups(Setting):
  833. name = "initgroups"
  834. section = "Server Mechanics"
  835. cli = ["--initgroups"]
  836. validator = validate_bool
  837. action = 'store_true'
  838. default = False
  839. desc = """\
  840. If true, set the worker process's group access list with all of the
  841. groups of which the specified username is a member, plus the specified
  842. group id.
  843. .. versionadded:: 19.7
  844. """
  845. class TmpUploadDir(Setting):
  846. name = "tmp_upload_dir"
  847. section = "Server Mechanics"
  848. meta = "DIR"
  849. validator = validate_string
  850. default = None
  851. desc = """\
  852. Directory to store temporary request data as they are read.
  853. This may disappear in the near future.
  854. This path should be writable by the process permissions set for Gunicorn
  855. workers. If not specified, Gunicorn will choose a system generated
  856. temporary directory.
  857. """
  858. class SecureSchemeHeader(Setting):
  859. name = "secure_scheme_headers"
  860. section = "Server Mechanics"
  861. validator = validate_dict
  862. default = {
  863. "X-FORWARDED-PROTOCOL": "ssl",
  864. "X-FORWARDED-PROTO": "https",
  865. "X-FORWARDED-SSL": "on"
  866. }
  867. desc = """\
  868. A dictionary containing headers and values that the front-end proxy
  869. uses to indicate HTTPS requests. These tell Gunicorn to set
  870. ``wsgi.url_scheme`` to ``https``, so your application can tell that the
  871. request is secure.
  872. The dictionary should map upper-case header names to exact string
  873. values. The value comparisons are case-sensitive, unlike the header
  874. names, so make sure they're exactly what your front-end proxy sends
  875. when handling HTTPS requests.
  876. It is important that your front-end proxy configuration ensures that
  877. the headers defined here can not be passed directly from the client.
  878. """
  879. class ForwardedAllowIPS(Setting):
  880. name = "forwarded_allow_ips"
  881. section = "Server Mechanics"
  882. cli = ["--forwarded-allow-ips"]
  883. meta = "STRING"
  884. validator = validate_string_to_list
  885. default = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1")
  886. desc = """\
  887. Front-end's IPs from which allowed to handle set secure headers.
  888. (comma separate).
  889. Set to ``*`` to disable checking of Front-end IPs (useful for setups
  890. where you don't know in advance the IP address of Front-end, but
  891. you still trust the environment).
  892. By default, the value of the ``FORWARDED_ALLOW_IPS`` environment
  893. variable. If it is not defined, the default is ``"127.0.0.1"``.
  894. """
  895. class AccessLog(Setting):
  896. name = "accesslog"
  897. section = "Logging"
  898. cli = ["--access-logfile"]
  899. meta = "FILE"
  900. validator = validate_string
  901. default = None
  902. desc = """\
  903. The Access log file to write to.
  904. ``'-'`` means log to stdout.
  905. """
  906. class AccessLogFormat(Setting):
  907. name = "access_log_format"
  908. section = "Logging"
  909. cli = ["--access-logformat"]
  910. meta = "STRING"
  911. validator = validate_string
  912. default = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'
  913. desc = """\
  914. The access log format.
  915. =========== ===========
  916. Identifier Description
  917. =========== ===========
  918. h remote address
  919. l ``'-'``
  920. u user name
  921. t date of the request
  922. r status line (e.g. ``GET / HTTP/1.1``)
  923. m request method
  924. U URL path without query string
  925. q query string
  926. H protocol
  927. s status
  928. B response length
  929. b response length or ``'-'`` (CLF format)
  930. f referer
  931. a user agent
  932. T request time in seconds
  933. D request time in microseconds
  934. L request time in decimal seconds
  935. p process ID
  936. {Header}i request header
  937. {Header}o response header
  938. {Variable}e environment variable
  939. =========== ===========
  940. """
  941. class ErrorLog(Setting):
  942. name = "errorlog"
  943. section = "Logging"
  944. cli = ["--error-logfile", "--log-file"]
  945. meta = "FILE"
  946. validator = validate_string
  947. default = '-'
  948. desc = """\
  949. The Error log file to write to.
  950. Using ``'-'`` for FILE makes gunicorn log to stderr.
  951. .. versionchanged:: 19.2
  952. Log to stderr by default.
  953. """
  954. class Loglevel(Setting):
  955. name = "loglevel"
  956. section = "Logging"
  957. cli = ["--log-level"]
  958. meta = "LEVEL"
  959. validator = validate_string
  960. default = "info"
  961. desc = """\
  962. The granularity of Error log outputs.
  963. Valid level names are:
  964. * debug
  965. * info
  966. * warning
  967. * error
  968. * critical
  969. """
  970. class CaptureOutput(Setting):
  971. name = "capture_output"
  972. section = "Logging"
  973. cli = ["--capture-output"]
  974. validator = validate_bool
  975. action = 'store_true'
  976. default = False
  977. desc = """\
  978. Redirect stdout/stderr to Error log.
  979. .. versionadded:: 19.6
  980. """
  981. class LoggerClass(Setting):
  982. name = "logger_class"
  983. section = "Logging"
  984. cli = ["--logger-class"]
  985. meta = "STRING"
  986. validator = validate_class
  987. default = "gunicorn.glogging.Logger"
  988. desc = """\
  989. The logger you want to use to log events in Gunicorn.
  990. The default class (``gunicorn.glogging.Logger``) handle most of
  991. normal usages in logging. It provides error and access logging.
  992. You can provide your own logger by giving Gunicorn a
  993. Python path to a subclass like ``gunicorn.glogging.Logger``.
  994. """
  995. class LogConfig(Setting):
  996. name = "logconfig"
  997. section = "Logging"
  998. cli = ["--log-config"]
  999. meta = "FILE"
  1000. validator = validate_string
  1001. default = None
  1002. desc = """\
  1003. The log config file to use.
  1004. Gunicorn uses the standard Python logging module's Configuration
  1005. file format.
  1006. """
  1007. class SyslogTo(Setting):
  1008. name = "syslog_addr"
  1009. section = "Logging"
  1010. cli = ["--log-syslog-to"]
  1011. meta = "SYSLOG_ADDR"
  1012. validator = validate_string
  1013. if PLATFORM == "darwin":
  1014. default = "unix:///var/run/syslog"
  1015. elif PLATFORM in ('freebsd', 'dragonfly', ):
  1016. default = "unix:///var/run/log"
  1017. elif PLATFORM == "openbsd":
  1018. default = "unix:///dev/log"
  1019. else:
  1020. default = "udp://localhost:514"
  1021. desc = """\
  1022. Address to send syslog messages.
  1023. Address is a string of the form:
  1024. * ``unix://PATH#TYPE`` : for unix domain socket. ``TYPE`` can be ``stream``
  1025. for the stream driver or ``dgram`` for the dgram driver.
  1026. ``stream`` is the default.
  1027. * ``udp://HOST:PORT`` : for UDP sockets
  1028. * ``tcp://HOST:PORT`` : for TCP sockets
  1029. """
  1030. class Syslog(Setting):
  1031. name = "syslog"
  1032. section = "Logging"
  1033. cli = ["--log-syslog"]
  1034. validator = validate_bool
  1035. action = 'store_true'
  1036. default = False
  1037. desc = """\
  1038. Send *Gunicorn* logs to syslog.
  1039. """
  1040. class SyslogPrefix(Setting):
  1041. name = "syslog_prefix"
  1042. section = "Logging"
  1043. cli = ["--log-syslog-prefix"]
  1044. meta = "SYSLOG_PREFIX"
  1045. validator = validate_string
  1046. default = None
  1047. desc = """\
  1048. Makes Gunicorn use the parameter as program-name in the syslog entries.
  1049. All entries will be prefixed by ``gunicorn.<prefix>``. By default the
  1050. program name is the name of the process.
  1051. """
  1052. class SyslogFacility(Setting):
  1053. name = "syslog_facility"
  1054. section = "Logging"
  1055. cli = ["--log-syslog-facility"]
  1056. meta = "SYSLOG_FACILITY"
  1057. validator = validate_string
  1058. default = "user"
  1059. desc = """\
  1060. Syslog facility name
  1061. """
  1062. class EnableStdioInheritance(Setting):
  1063. name = "enable_stdio_inheritance"
  1064. section = "Logging"
  1065. cli = ["-R", "--enable-stdio-inheritance"]
  1066. validator = validate_bool
  1067. default = False
  1068. action = "store_true"
  1069. desc = """\
  1070. Enable stdio inheritance.
  1071. Enable inheritance for stdio file descriptors in daemon mode.
  1072. Note: To disable the Python stdout buffering, you can to set the user
  1073. environment variable ``PYTHONUNBUFFERED`` .
  1074. """
  1075. # statsD monitoring
  1076. class StatsdHost(Setting):
  1077. name = "statsd_host"
  1078. section = "Logging"
  1079. cli = ["--statsd-host"]
  1080. meta = "STATSD_ADDR"
  1081. default = None
  1082. validator = validate_hostport
  1083. desc = """\
  1084. ``host:port`` of the statsd server to log to.
  1085. .. versionadded:: 19.1
  1086. """
  1087. class StatsdPrefix(Setting):
  1088. name = "statsd_prefix"
  1089. section = "Logging"
  1090. cli = ["--statsd-prefix"]
  1091. meta = "STATSD_PREFIX"
  1092. default = ""
  1093. validator = validate_string
  1094. desc = """\
  1095. Prefix to use when emitting statsd metrics (a trailing ``.`` is added,
  1096. if not provided).
  1097. .. versionadded:: 19.2
  1098. """
  1099. class Procname(Setting):
  1100. name = "proc_name"
  1101. section = "Process Naming"
  1102. cli = ["-n", "--name"]
  1103. meta = "STRING"
  1104. validator = validate_string
  1105. default = None
  1106. desc = """\
  1107. A base to use with setproctitle for process naming.
  1108. This affects things like ``ps`` and ``top``. If you're going to be
  1109. running more than one instance of Gunicorn you'll probably want to set a
  1110. name to tell them apart. This requires that you install the setproctitle
  1111. module.
  1112. If not set, the *default_proc_name* setting will be used.
  1113. """
  1114. class DefaultProcName(Setting):
  1115. name = "default_proc_name"
  1116. section = "Process Naming"
  1117. validator = validate_string
  1118. default = "gunicorn"
  1119. desc = """\
  1120. Internal setting that is adjusted for each type of application.
  1121. """
  1122. class PythonPath(Setting):
  1123. name = "pythonpath"
  1124. section = "Server Mechanics"
  1125. cli = ["--pythonpath"]
  1126. meta = "STRING"
  1127. validator = validate_string
  1128. default = None
  1129. desc = """\
  1130. A comma-separated list of directories to add to the Python path.
  1131. e.g.
  1132. ``'/home/djangoprojects/myproject,/home/python/mylibrary'``.
  1133. """
  1134. class Paste(Setting):
  1135. name = "paste"
  1136. section = "Server Mechanics"
  1137. cli = ["--paste", "--paster"]
  1138. meta = "STRING"
  1139. validator = validate_string
  1140. default = None
  1141. desc = """\
  1142. Load a PasteDeploy config file. The argument may contain a ``#``
  1143. symbol followed by the name of an app section from the config file,
  1144. e.g. ``production.ini#admin``.
  1145. At this time, using alternate server blocks is not supported. Use the
  1146. command line arguments to control server configuration instead.
  1147. """
  1148. class OnStarting(Setting):
  1149. name = "on_starting"
  1150. section = "Server Hooks"
  1151. validator = validate_callable(1)
  1152. type = six.callable
  1153. def on_starting(server):
  1154. pass
  1155. default = staticmethod(on_starting)
  1156. desc = """\
  1157. Called just before the master process is initialized.
  1158. The callable needs to accept a single instance variable for the Arbiter.
  1159. """
  1160. class OnReload(Setting):
  1161. name = "on_reload"
  1162. section = "Server Hooks"
  1163. validator = validate_callable(1)
  1164. type = six.callable
  1165. def on_reload(server):
  1166. pass
  1167. default = staticmethod(on_reload)
  1168. desc = """\
  1169. Called to recycle workers during a reload via SIGHUP.
  1170. The callable needs to accept a single instance variable for the Arbiter.
  1171. """
  1172. class WhenReady(Setting):
  1173. name = "when_ready"
  1174. section = "Server Hooks"
  1175. validator = validate_callable(1)
  1176. type = six.callable
  1177. def when_ready(server):
  1178. pass
  1179. default = staticmethod(when_ready)
  1180. desc = """\
  1181. Called just after the server is started.
  1182. The callable needs to accept a single instance variable for the Arbiter.
  1183. """
  1184. class Prefork(Setting):
  1185. name = "pre_fork"
  1186. section = "Server Hooks"
  1187. validator = validate_callable(2)
  1188. type = six.callable
  1189. def pre_fork(server, worker):
  1190. pass
  1191. default = staticmethod(pre_fork)
  1192. desc = """\
  1193. Called just before a worker is forked.
  1194. The callable needs to accept two instance variables for the Arbiter and
  1195. new Worker.
  1196. """
  1197. class Postfork(Setting):
  1198. name = "post_fork"
  1199. section = "Server Hooks"
  1200. validator = validate_callable(2)
  1201. type = six.callable
  1202. def post_fork(server, worker):
  1203. pass
  1204. default = staticmethod(post_fork)
  1205. desc = """\
  1206. Called just after a worker has been forked.
  1207. The callable needs to accept two instance variables for the Arbiter and
  1208. new Worker.
  1209. """
  1210. class PostWorkerInit(Setting):
  1211. name = "post_worker_init"
  1212. section = "Server Hooks"
  1213. validator = validate_callable(1)
  1214. type = six.callable
  1215. def post_worker_init(worker):
  1216. pass
  1217. default = staticmethod(post_worker_init)
  1218. desc = """\
  1219. Called just after a worker has initialized the application.
  1220. The callable needs to accept one instance variable for the initialized
  1221. Worker.
  1222. """
  1223. class WorkerInt(Setting):
  1224. name = "worker_int"
  1225. section = "Server Hooks"
  1226. validator = validate_callable(1)
  1227. type = six.callable
  1228. def worker_int(worker):
  1229. pass
  1230. default = staticmethod(worker_int)
  1231. desc = """\
  1232. Called just after a worker exited on SIGINT or SIGQUIT.
  1233. The callable needs to accept one instance variable for the initialized
  1234. Worker.
  1235. """
  1236. class WorkerAbort(Setting):
  1237. name = "worker_abort"
  1238. section = "Server Hooks"
  1239. validator = validate_callable(1)
  1240. type = six.callable
  1241. def worker_abort(worker):
  1242. pass
  1243. default = staticmethod(worker_abort)
  1244. desc = """\
  1245. Called when a worker received the SIGABRT signal.
  1246. This call generally happens on timeout.
  1247. The callable needs to accept one instance variable for the initialized
  1248. Worker.
  1249. """
  1250. class PreExec(Setting):
  1251. name = "pre_exec"
  1252. section = "Server Hooks"
  1253. validator = validate_callable(1)
  1254. type = six.callable
  1255. def pre_exec(server):
  1256. pass
  1257. default = staticmethod(pre_exec)
  1258. desc = """\
  1259. Called just before a new master process is forked.
  1260. The callable needs to accept a single instance variable for the Arbiter.
  1261. """
  1262. class PreRequest(Setting):
  1263. name = "pre_request"
  1264. section = "Server Hooks"
  1265. validator = validate_callable(2)
  1266. type = six.callable
  1267. def pre_request(worker, req):
  1268. worker.log.debug("%s %s" % (req.method, req.path))
  1269. default = staticmethod(pre_request)
  1270. desc = """\
  1271. Called just before a worker processes the request.
  1272. The callable needs to accept two instance variables for the Worker and
  1273. the Request.
  1274. """
  1275. class PostRequest(Setting):
  1276. name = "post_request"
  1277. section = "Server Hooks"
  1278. validator = validate_post_request
  1279. type = six.callable
  1280. def post_request(worker, req, environ, resp):
  1281. pass
  1282. default = staticmethod(post_request)
  1283. desc = """\
  1284. Called after a worker processes the request.
  1285. The callable needs to accept two instance variables for the Worker and
  1286. the Request.
  1287. """
  1288. class ChildExit(Setting):
  1289. name = "child_exit"
  1290. section = "Server Hooks"
  1291. validator = validate_callable(2)
  1292. type = six.callable
  1293. def child_exit(server, worker):
  1294. pass
  1295. default = staticmethod(child_exit)
  1296. desc = """\
  1297. Called just after a worker has been exited, in the master process.
  1298. The callable needs to accept two instance variables for the Arbiter and
  1299. the just-exited Worker.
  1300. .. versionadded:: 19.7
  1301. """
  1302. class WorkerExit(Setting):
  1303. name = "worker_exit"
  1304. section = "Server Hooks"
  1305. validator = validate_callable(2)
  1306. type = six.callable
  1307. def worker_exit(server, worker):
  1308. pass
  1309. default = staticmethod(worker_exit)
  1310. desc = """\
  1311. Called just after a worker has been exited, in the worker process.
  1312. The callable needs to accept two instance variables for the Arbiter and
  1313. the just-exited Worker.
  1314. """
  1315. class NumWorkersChanged(Setting):
  1316. name = "nworkers_changed"
  1317. section = "Server Hooks"
  1318. validator = validate_callable(3)
  1319. type = six.callable
  1320. def nworkers_changed(server, new_value, old_value):
  1321. pass
  1322. default = staticmethod(nworkers_changed)
  1323. desc = """\
  1324. Called just after *num_workers* has been changed.
  1325. The callable needs to accept an instance variable of the Arbiter and
  1326. two integers of number of workers after and before change.
  1327. If the number of workers is set for the first time, *old_value* would
  1328. be ``None``.
  1329. """
  1330. class OnExit(Setting):
  1331. name = "on_exit"
  1332. section = "Server Hooks"
  1333. validator = validate_callable(1)
  1334. def on_exit(server):
  1335. pass
  1336. default = staticmethod(on_exit)
  1337. desc = """\
  1338. Called just before exiting Gunicorn.
  1339. The callable needs to accept a single instance variable for the Arbiter.
  1340. """
  1341. class ProxyProtocol(Setting):
  1342. name = "proxy_protocol"
  1343. section = "Server Mechanics"
  1344. cli = ["--proxy-protocol"]
  1345. validator = validate_bool
  1346. default = False
  1347. action = "store_true"
  1348. desc = """\
  1349. Enable detect PROXY protocol (PROXY mode).
  1350. Allow using HTTP and Proxy together. It may be useful for work with
  1351. stunnel as HTTPS frontend and Gunicorn as HTTP server.
  1352. PROXY protocol: http://haproxy.1wt.eu/download/1.5/doc/proxy-protocol.txt
  1353. Example for stunnel config::
  1354. [https]
  1355. protocol = proxy
  1356. accept = 443
  1357. connect = 80
  1358. cert = /etc/ssl/certs/stunnel.pem
  1359. key = /etc/ssl/certs/stunnel.key
  1360. """
  1361. class ProxyAllowFrom(Setting):
  1362. name = "proxy_allow_ips"
  1363. section = "Server Mechanics"
  1364. cli = ["--proxy-allow-from"]
  1365. validator = validate_string_to_list
  1366. default = "127.0.0.1"
  1367. desc = """\
  1368. Front-end's IPs from which allowed accept proxy requests (comma separate).
  1369. Set to ``*`` to disable checking of Front-end IPs (useful for setups
  1370. where you don't know in advance the IP address of Front-end, but
  1371. you still trust the environment)
  1372. """
  1373. class KeyFile(Setting):
  1374. name = "keyfile"
  1375. section = "SSL"
  1376. cli = ["--keyfile"]
  1377. meta = "FILE"
  1378. validator = validate_string
  1379. default = None
  1380. desc = """\
  1381. SSL key file
  1382. """
  1383. class CertFile(Setting):
  1384. name = "certfile"
  1385. section = "SSL"
  1386. cli = ["--certfile"]
  1387. meta = "FILE"
  1388. validator = validate_string
  1389. default = None
  1390. desc = """\
  1391. SSL certificate file
  1392. """
  1393. class SSLVersion(Setting):
  1394. name = "ssl_version"
  1395. section = "SSL"
  1396. cli = ["--ssl-version"]
  1397. validator = validate_pos_int
  1398. default = ssl.PROTOCOL_SSLv23
  1399. desc = """\
  1400. SSL version to use (see stdlib ssl module's)
  1401. .. versionchanged:: 19.7
  1402. The default value has been changed from ``ssl.PROTOCOL_TLSv1`` to
  1403. ``ssl.PROTOCOL_SSLv23``.
  1404. """
  1405. class CertReqs(Setting):
  1406. name = "cert_reqs"
  1407. section = "SSL"
  1408. cli = ["--cert-reqs"]
  1409. validator = validate_pos_int
  1410. default = ssl.CERT_NONE
  1411. desc = """\
  1412. Whether client certificate is required (see stdlib ssl module's)
  1413. """
  1414. class CACerts(Setting):
  1415. name = "ca_certs"
  1416. section = "SSL"
  1417. cli = ["--ca-certs"]
  1418. meta = "FILE"
  1419. validator = validate_string
  1420. default = None
  1421. desc = """\
  1422. CA certificates file
  1423. """
  1424. class SuppressRaggedEOFs(Setting):
  1425. name = "suppress_ragged_eofs"
  1426. section = "SSL"
  1427. cli = ["--suppress-ragged-eofs"]
  1428. action = "store_true"
  1429. default = True
  1430. validator = validate_bool
  1431. desc = """\
  1432. Suppress ragged EOFs (see stdlib ssl module's)
  1433. """
  1434. class DoHandshakeOnConnect(Setting):
  1435. name = "do_handshake_on_connect"
  1436. section = "SSL"
  1437. cli = ["--do-handshake-on-connect"]
  1438. validator = validate_bool
  1439. action = "store_true"
  1440. default = False
  1441. desc = """\
  1442. Whether to perform SSL handshake on socket connect (see stdlib ssl module's)
  1443. """
  1444. if sys.version_info >= (2, 7):
  1445. class Ciphers(Setting):
  1446. name = "ciphers"
  1447. section = "SSL"
  1448. cli = ["--ciphers"]
  1449. validator = validate_string
  1450. default = 'TLSv1'
  1451. desc = """\
  1452. Ciphers to use (see stdlib ssl module's)
  1453. """
  1454. class PasteGlobalConf(Setting):
  1455. name = "raw_paste_global_conf"
  1456. action = "append"
  1457. section = "Server Mechanics"
  1458. cli = ["--paste-global"]
  1459. meta = "CONF"
  1460. validator = validate_list_string
  1461. default = []
  1462. desc = """\
  1463. Set a PasteDeploy global config variable in ``key=value`` form.
  1464. The option can be specified multiple times.
  1465. The variables are passed to the the PasteDeploy entrypoint. Example::
  1466. $ gunicorn -b 127.0.0.1:8000 --paste development.ini --paste-global FOO=1 --paste-global BAR=2
  1467. .. versionadded:: 19.7
  1468. """