config.py 60 KB

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