Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.py 46KB

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