sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def set_idle_params(self, timeout=None, exit=None): """Activate idle mode - put uWSGI in cheap mode after inactivity timeout. :param int timeout: Inactivity timeout in seconds. :param bool exit: Shutdown uWSGI when idle. """ self._set('idle', timeout) self._set('die-on-idle', exit, cast=bool) return self._section
Activate idle mode - put uWSGI in cheap mode after inactivity timeout. :param int timeout: Inactivity timeout in seconds. :param bool exit: Shutdown uWSGI when idle.
entailment
def set_reload_params(self, mercy=None, exit=None): """Set reload related params. :param int mercy: Set the maximum time (in seconds) we wait for workers and other processes to die during reload/shutdown. :param bool exit: Force exit even if a reload is requested. """ self._set('reload-mercy', mercy) self.set_exit_events(reload=exit) return self._section
Set reload related params. :param int mercy: Set the maximum time (in seconds) we wait for workers and other processes to die during reload/shutdown. :param bool exit: Force exit even if a reload is requested.
entailment
def add_cron_task( self, command, weekday=None, month=None, day=None, hour=None, minute=None, legion=None, unique=None, harakiri=None): """Adds a cron task running the given command on the given schedule. http://uwsgi.readthedocs.io/en/latest/Cron.html HINTS: * Use negative values to say `every`: hour=-3 stands for `every 3 hours` * Use - (minus) to make interval: minute='13-18' stands for `from minute 13 to 18` .. note:: We use cron2 option available since 1.9.11. :param str|unicode command: Command to execute on schedule (with or without path). :param int|str|unicode weekday: Day of a the week number. Defaults to `each`. 0 - Sunday 1 - Monday 2 - Tuesday 3 - Wednesday 4 - Thursday 5 - Friday 6 - Saturday :param int|str|unicode month: Month number 1-12. Defaults to `each`. :param int|str|unicode day: Day of the month number 1-31. Defaults to `each`. :param int|str|unicode hour: Hour 0-23. Defaults to `each`. :param int|str|unicode minute: Minute 0-59. Defaults to `each`. :param str|unicode legion: Set legion (cluster) name to use this cron command against. Such commands are only executed by legion lord node. :param bool unique: Marks command as unique. Default to not unique. Some commands can take a long time to finish or just hang doing their thing. Sometimes this is okay, but there are also cases when running multiple instances of the same command can be dangerous. :param int harakiri: Enforce a time limit (in seconds) on executed commands. If a command is taking longer it will be killed. """ rule = KeyValue( locals(), keys=['weekday', 'month', 'day', 'hour', 'minute', 'harakiri', 'legion', 'unique'], aliases={'weekday': 'week'}, bool_keys=['unique'], ) self._set('cron2', ('%s %s' % (rule, command)).strip(), multi=True) return self._section
Adds a cron task running the given command on the given schedule. http://uwsgi.readthedocs.io/en/latest/Cron.html HINTS: * Use negative values to say `every`: hour=-3 stands for `every 3 hours` * Use - (minus) to make interval: minute='13-18' stands for `from minute 13 to 18` .. note:: We use cron2 option available since 1.9.11. :param str|unicode command: Command to execute on schedule (with or without path). :param int|str|unicode weekday: Day of a the week number. Defaults to `each`. 0 - Sunday 1 - Monday 2 - Tuesday 3 - Wednesday 4 - Thursday 5 - Friday 6 - Saturday :param int|str|unicode month: Month number 1-12. Defaults to `each`. :param int|str|unicode day: Day of the month number 1-31. Defaults to `each`. :param int|str|unicode hour: Hour 0-23. Defaults to `each`. :param int|str|unicode minute: Minute 0-59. Defaults to `each`. :param str|unicode legion: Set legion (cluster) name to use this cron command against. Such commands are only executed by legion lord node. :param bool unique: Marks command as unique. Default to not unique. Some commands can take a long time to finish or just hang doing their thing. Sometimes this is okay, but there are also cases when running multiple instances of the same command can be dangerous. :param int harakiri: Enforce a time limit (in seconds) on executed commands. If a command is taking longer it will be killed.
entailment
def attach_process_classic(self, command_or_pid_path, background, control=False, for_legion=False): """Attaches a command/daemon to the master process optionally managed by a pidfile. This will allow the uWSGI master to control/monitor/respawn this process. .. note:: This uses old classic uWSGI means of process attaching To have more control use ``.attach_process()`` method (requires uWSGI 2.0+) http://uwsgi-docs.readthedocs.io/en/latest/AttachingDaemons.html :param str|unicode command_or_pid_path: :param bool background: Must indicate whether process is in background. :param bool control: Consider this process a control: when the daemon dies, the master exits. .. note:: pidfile managed processed not supported. :param bool for_legion: Legion daemons will be executed only on the legion lord node, so there will always be a single daemon instance running in each legion. Once the lord dies a daemon will be spawned on another node. .. note:: uWSGI 1.9.9+ required. """ prefix = 'legion-' if for_legion else '' if '.pid' in command_or_pid_path: if background: # Attach a command/daemon to the master process managed by a pidfile (the command must daemonize) self._set(prefix + 'smart-attach-daemon', command_or_pid_path, multi=True) else: # Attach a command/daemon to the master process managed by a pidfile (the command must NOT daemonize) self._set(prefix + 'smart-attach-daemon2', command_or_pid_path, multi=True) else: if background: raise ConfigurationError('Background flag is only supported for pid-governed commands') if control: # todo needs check self._set('attach-control-daemon', command_or_pid_path, multi=True) else: # Attach a command/daemon to the master process (the command has to remain in foreground) self._set(prefix + 'attach-daemon', command_or_pid_path, multi=True) return self._section
Attaches a command/daemon to the master process optionally managed by a pidfile. This will allow the uWSGI master to control/monitor/respawn this process. .. note:: This uses old classic uWSGI means of process attaching To have more control use ``.attach_process()`` method (requires uWSGI 2.0+) http://uwsgi-docs.readthedocs.io/en/latest/AttachingDaemons.html :param str|unicode command_or_pid_path: :param bool background: Must indicate whether process is in background. :param bool control: Consider this process a control: when the daemon dies, the master exits. .. note:: pidfile managed processed not supported. :param bool for_legion: Legion daemons will be executed only on the legion lord node, so there will always be a single daemon instance running in each legion. Once the lord dies a daemon will be spawned on another node. .. note:: uWSGI 1.9.9+ required.
entailment
def attach_process( self, command, for_legion=False, broken_counter=None, pidfile=None, control=None, daemonize=None, touch_reload=None, signal_stop=None, signal_reload=None, honour_stdin=None, uid=None, gid=None, new_pid_ns=None, change_dir=None): """Attaches a command/daemon to the master process. This will allow the uWSGI master to control/monitor/respawn this process. http://uwsgi-docs.readthedocs.io/en/latest/AttachingDaemons.html :param str|unicode command: The command line to execute. :param bool for_legion: Legion daemons will be executed only on the legion lord node, so there will always be a single daemon instance running in each legion. Once the lord dies a daemon will be spawned on another node. :param int broken_counter: Maximum attempts before considering a daemon "broken". :param str|unicode pidfile: The pidfile path to check (enable smart mode). :param bool control: If True, the daemon becomes a `control` one: if it dies the whole uWSGI instance dies. :param bool daemonize: Daemonize the process (enable smart2 mode). :param list|str|unicode touch_reload: List of files to check: whenever they are 'touched', the daemon is restarted :param int signal_stop: The signal number to send to the daemon when uWSGI is stopped. :param int signal_reload: The signal number to send to the daemon when uWSGI is reloaded. :param bool honour_stdin: The signal number to send to the daemon when uWSGI is reloaded. :param str|unicode|int uid: Drop privileges to the specified uid. .. note:: Requires master running as root. :param str|unicode|int gid: Drop privileges to the specified gid. .. note:: Requires master running as root. :param bool new_pid_ns: Spawn the process in a new pid namespace. .. note:: Requires master running as root. .. note:: Linux only. :param str|unicode change_dir: Use chdir() to the specified directory before running the command. """ rule = KeyValue( locals(), keys=[ 'command', 'broken_counter', 'pidfile', 'control', 'daemonize', 'touch_reload', 'signal_stop', 'signal_reload', 'honour_stdin', 'uid', 'gid', 'new_pid_ns', 'change_dir', ], aliases={ 'command': 'cmd', 'broken_counter': 'freq', 'touch_reload': 'touch', 'signal_stop': 'stopsignal', 'signal_reload': 'reloadsignal', 'honour_stdin': 'stdin', 'new_pid_ns': 'ns_pid', 'change_dir': 'chdir', }, bool_keys=['control', 'daemonize', 'honour_stdin'], list_keys=['touch_reload'], ) prefix = 'legion-' if for_legion else '' self._set(prefix + 'attach-daemon2', rule, multi=True) return self._section
Attaches a command/daemon to the master process. This will allow the uWSGI master to control/monitor/respawn this process. http://uwsgi-docs.readthedocs.io/en/latest/AttachingDaemons.html :param str|unicode command: The command line to execute. :param bool for_legion: Legion daemons will be executed only on the legion lord node, so there will always be a single daemon instance running in each legion. Once the lord dies a daemon will be spawned on another node. :param int broken_counter: Maximum attempts before considering a daemon "broken". :param str|unicode pidfile: The pidfile path to check (enable smart mode). :param bool control: If True, the daemon becomes a `control` one: if it dies the whole uWSGI instance dies. :param bool daemonize: Daemonize the process (enable smart2 mode). :param list|str|unicode touch_reload: List of files to check: whenever they are 'touched', the daemon is restarted :param int signal_stop: The signal number to send to the daemon when uWSGI is stopped. :param int signal_reload: The signal number to send to the daemon when uWSGI is reloaded. :param bool honour_stdin: The signal number to send to the daemon when uWSGI is reloaded. :param str|unicode|int uid: Drop privileges to the specified uid. .. note:: Requires master running as root. :param str|unicode|int gid: Drop privileges to the specified gid. .. note:: Requires master running as root. :param bool new_pid_ns: Spawn the process in a new pid namespace. .. note:: Requires master running as root. .. note:: Linux only. :param str|unicode change_dir: Use chdir() to the specified directory before running the command.
entailment
def set_basic_params( self, check_interval_busy=None, busy_max=None, busy_min=None, idle_cycles_max=None, idle_cycles_penalty=None, verbose=None): """ :param int check_interval_busy: Interval (sec) to check worker busyness. :param int busy_max: Maximum busyness (percents). Every time the calculated busyness is higher than this value, uWSGI will spawn new workers. Default: 50. :param int busy_min: Minimum busyness (percents). If busyness is below this value, the app is considered in an "idle cycle" and uWSGI will start counting them. Once we reach needed number of idle cycles uWSGI will kill one worker. Default: 25. :param int idle_cycles_max: This option tells uWSGI how many idle cycles are allowed before stopping a worker. :param int idle_cycles_penalty: Number of idle cycles to add to ``idle_cycles_max`` in case worker spawned too early. Default is 1. :param bool verbose: Enables debug logs for this algo. """ self._set('cheaper-overload', check_interval_busy) self._set('cheaper-busyness-max', busy_max) self._set('cheaper-busyness-min', busy_min) self._set('cheaper-busyness-multiplier', idle_cycles_max) self._set('cheaper-busyness-penalty', idle_cycles_penalty) self._set('cheaper-busyness-verbose', verbose, cast=bool) return self._section
:param int check_interval_busy: Interval (sec) to check worker busyness. :param int busy_max: Maximum busyness (percents). Every time the calculated busyness is higher than this value, uWSGI will spawn new workers. Default: 50. :param int busy_min: Minimum busyness (percents). If busyness is below this value, the app is considered in an "idle cycle" and uWSGI will start counting them. Once we reach needed number of idle cycles uWSGI will kill one worker. Default: 25. :param int idle_cycles_max: This option tells uWSGI how many idle cycles are allowed before stopping a worker. :param int idle_cycles_penalty: Number of idle cycles to add to ``idle_cycles_max`` in case worker spawned too early. Default is 1. :param bool verbose: Enables debug logs for this algo.
entailment
def set_emergency_params( self, workers_step=None, idle_cycles_max=None, queue_size=None, queue_nonzero_delay=None): """Sets busyness algorithm emergency workers related params. Emergency workers could be spawned depending upon uWSGI backlog state. .. note:: These options are Linux only. :param int workers_step: Number of emergency workers to spawn. Default: 1. :param int idle_cycles_max: Idle cycles to reach before stopping an emergency worker. Default: 3. :param int queue_size: Listen queue (backlog) max size to spawn an emergency worker. Default: 33. :param int queue_nonzero_delay: If the request listen queue is > 0 for more than given amount of seconds new emergency workers will be spawned. Default: 60. """ self._set('cheaper-busyness-backlog-step', workers_step) self._set('cheaper-busyness-backlog-multiplier', idle_cycles_max) self._set('cheaper-busyness-backlog-alert', queue_size) self._set('cheaper-busyness-backlog-nonzero', queue_nonzero_delay) return self
Sets busyness algorithm emergency workers related params. Emergency workers could be spawned depending upon uWSGI backlog state. .. note:: These options are Linux only. :param int workers_step: Number of emergency workers to spawn. Default: 1. :param int idle_cycles_max: Idle cycles to reach before stopping an emergency worker. Default: 3. :param int queue_size: Listen queue (backlog) max size to spawn an emergency worker. Default: 33. :param int queue_nonzero_delay: If the request listen queue is > 0 for more than given amount of seconds new emergency workers will be spawned. Default: 60.
entailment
def set_basic_params( self, spawn_on_request=None, cheaper_algo=None, workers_min=None, workers_startup=None, workers_step=None): """ :param bool spawn_on_request: Spawn workers only after the first request. :param Algo cheaper_algo: The algorithm object to be used used for adaptive process spawning. Default: ``spare``. See ``.algorithms``. :param int workers_min: Minimal workers count. Enables cheaper mode (adaptive process spawning). .. note:: Must be lower than max workers count. :param int workers_startup: The number of workers to be started when starting the application. After the app is started the algorithm can stop or start workers if needed. :param int workers_step: Number of additional processes to spawn at a time if they are needed, """ self._set('cheap', spawn_on_request, cast=bool) if cheaper_algo: self._set('cheaper-algo', cheaper_algo.name) if cheaper_algo.plugin: self._section.set_plugins_params(plugins=cheaper_algo.plugin) cheaper_algo._contribute_to_opts(self) self._set('cheaper', workers_min) self._set('cheaper-initial', workers_startup) self._set('cheaper-step', workers_step) return self._section
:param bool spawn_on_request: Spawn workers only after the first request. :param Algo cheaper_algo: The algorithm object to be used used for adaptive process spawning. Default: ``spare``. See ``.algorithms``. :param int workers_min: Minimal workers count. Enables cheaper mode (adaptive process spawning). .. note:: Must be lower than max workers count. :param int workers_startup: The number of workers to be started when starting the application. After the app is started the algorithm can stop or start workers if needed. :param int workers_step: Number of additional processes to spawn at a time if they are needed,
entailment
def set_memory_limits(self, rss_soft=None, rss_hard=None): """Sets worker memory limits for cheapening. :param int rss_soft: Don't spawn new workers if total resident memory usage of all workers is higher than this limit in bytes. .. warning:: This option expects memory reporting enabled: ``.logging.set_basic_params(memory_report=1)`` :param int rss_hard: Try to stop workers if total workers resident memory usage is higher that thi limit in bytes. """ self._set('cheaper-rss-limit-soft', rss_soft) self._set('cheaper-rss-limit-hard', rss_hard) return self._section
Sets worker memory limits for cheapening. :param int rss_soft: Don't spawn new workers if total resident memory usage of all workers is higher than this limit in bytes. .. warning:: This option expects memory reporting enabled: ``.logging.set_basic_params(memory_report=1)`` :param int rss_hard: Try to stop workers if total workers resident memory usage is higher that thi limit in bytes.
entailment
def get_version(self, as_tuple=False): """Returns uWSGI version string or tuple. :param bool as_tuple: :rtype: str|tuple """ if as_tuple: return uwsgi.version_info return decode(uwsgi.version)
Returns uWSGI version string or tuple. :param bool as_tuple: :rtype: str|tuple
entailment
def register_route(self, route_rules, label=None): """Registers a routing rule. :param RouteRule|list[RouteRule] route_rules: :param str|unicode label: Label to mark the given set of rules. This can be used in conjunction with ``do_goto`` rule action. * http://uwsgi.readthedocs.io/en/latest/InternalRouting.html#goto """ route_rules = listify(route_rules) if route_rules and label: self._set(route_rules[0].command_label, label, multi=True) for route_rules in route_rules: self._set(route_rules.command, route_rules.value, multi=True) return self._section
Registers a routing rule. :param RouteRule|list[RouteRule] route_rules: :param str|unicode label: Label to mark the given set of rules. This can be used in conjunction with ``do_goto`` rule action. * http://uwsgi.readthedocs.io/en/latest/InternalRouting.html#goto
entailment
def set_error_page(self, status, html_fpath): """Add an error page (html) for managed 403, 404, 500 response. :param int status: HTTP status code. :param str|unicode html_fpath: HTML page file path. """ statuses = [403, 404, 500] status = int(status) if status not in statuses: raise ConfigurationError( 'Code `%s` for `routing.set_error_page()` is unsupported. Supported: %s' % (status, ', '.join(map(str, statuses)))) self._set('error-page-%s' % status, html_fpath, multi=True) return self._section
Add an error page (html) for managed 403, 404, 500 response. :param int status: HTTP status code. :param str|unicode html_fpath: HTML page file path.
entailment
def set_error_pages(self, codes_map=None, common_prefix=None): """Add an error pages for managed 403, 404, 500 responses. Shortcut for ``.set_error_page()``. :param dict codes_map: Status code mapped into an html filepath or just a filename if common_prefix is used. If not set, filename containing status code is presumed: 400.html, 500.html, etc. :param str|unicode common_prefix: Common path (prefix) for all files. """ statuses = [403, 404, 500] if common_prefix: if not codes_map: codes_map = {code: '%s.html' % code for code in statuses} for code, filename in codes_map.items(): codes_map[code] = os.path.join(common_prefix, filename) for code, filepath in codes_map.items(): self.set_error_page(code, filepath) return self._section
Add an error pages for managed 403, 404, 500 responses. Shortcut for ``.set_error_page()``. :param dict codes_map: Status code mapped into an html filepath or just a filename if common_prefix is used. If not set, filename containing status code is presumed: 400.html, 500.html, etc. :param str|unicode common_prefix: Common path (prefix) for all files.
entailment
def set_geoip_params(self, db_country=None, db_city=None): """Sets GeoIP parameters. * http://uwsgi.readthedocs.io/en/latest/GeoIP.html :param str|unicode db_country: Country database file path. :param str|unicode db_city: City database file path. Example: ``GeoLiteCity.dat``. """ self._set('geoip-country', db_country, plugin='geoip') self._set('geoip-city', db_city, plugin='geoip') return self._section
Sets GeoIP parameters. * http://uwsgi.readthedocs.io/en/latest/GeoIP.html :param str|unicode db_country: Country database file path. :param str|unicode db_city: City database file path. Example: ``GeoLiteCity.dat``.
entailment
def header_add(self, name, value): """Automatically add HTTP headers to response. :param str|unicode name: :param str|unicode value: """ self._set('add-header', '%s: %s' % (name, value), multi=True) return self._section
Automatically add HTTP headers to response. :param str|unicode name: :param str|unicode value:
entailment
def header_remove(self, value): """Automatically remove specified HTTP header from the response. :param str|unicode value: """ self._set('del-header', value, multi=True) return self._section
Automatically remove specified HTTP header from the response. :param str|unicode value:
entailment
def header_collect(self, name, target_var, pull=False): """Store the specified response header in a request var (optionally removing it from the response). :param str|unicode name: :param str|unicode target_var: :param bool pull: Whether to remove header from response. """ self._set( 'pull-header' if pull else 'collect-header', '%s %s' % (name, target_var), multi=True) return self._section
Store the specified response header in a request var (optionally removing it from the response). :param str|unicode name: :param str|unicode target_var: :param bool pull: Whether to remove header from response.
entailment
def register_static_map(self, mountpoint, target, retain_resource_path=False, safe_target=False): """Allows mapping mountpoint to a static directory (or file). * http://uwsgi.readthedocs.io/en/latest/StaticFiles.html#mode-3-using-static-file-mount-points :param str|unicode mountpoint: :param str|unicode target: :param bool retain_resource_path: Append the requested resource to the docroot. Example: if ``/images`` maps to ``/var/www/img`` requested ``/images/logo.png`` will be served from: * ``True``: ``/var/www/img/images/logo.png`` * ``False``: ``/var/www/img/logo.png`` :param bool safe_target: Skip security checks if the file is under the specified path. Whether to consider resolved (real) target a safe one to serve from. * http://uwsgi.readthedocs.io/en/latest/StaticFiles.html#security """ command = 'static-map' if retain_resource_path: command += '2' self._set(command, '%s=%s' % (mountpoint, target), multi=True) if safe_target: self._set('static-safe', target, multi=True) return self._section
Allows mapping mountpoint to a static directory (or file). * http://uwsgi.readthedocs.io/en/latest/StaticFiles.html#mode-3-using-static-file-mount-points :param str|unicode mountpoint: :param str|unicode target: :param bool retain_resource_path: Append the requested resource to the docroot. Example: if ``/images`` maps to ``/var/www/img`` requested ``/images/logo.png`` will be served from: * ``True``: ``/var/www/img/images/logo.png`` * ``False``: ``/var/www/img/logo.png`` :param bool safe_target: Skip security checks if the file is under the specified path. Whether to consider resolved (real) target a safe one to serve from. * http://uwsgi.readthedocs.io/en/latest/StaticFiles.html#security
entailment
def add_expiration_rule(self, criterion, value, timeout, use_mod_time=False): """Adds statics expiration rule based on a criterion. :param str|unicode criterion: Criterion (subject) to base expiration on. See ``.expiration_criteria``. :param str|unicode|list[str|unicode] value: Value to test criteria upon. .. note:: Usually a regular expression. :param int timeout: Number of seconds to expire after. :param bool use_mod_time: Base on file modification time instead of the current time. """ command = 'static-expires' separator = ' ' if criterion != self.expiration_criteria.FILENAME: command += '-%s' % criterion if criterion == self.expiration_criteria.MIME_TYPE: separator = '=' if use_mod_time: command += '-mtime' for value in listify(value): self._set(command, '%s%s%s' % (value, separator, timeout), multi=True) return self._section
Adds statics expiration rule based on a criterion. :param str|unicode criterion: Criterion (subject) to base expiration on. See ``.expiration_criteria``. :param str|unicode|list[str|unicode] value: Value to test criteria upon. .. note:: Usually a regular expression. :param int timeout: Number of seconds to expire after. :param bool use_mod_time: Base on file modification time instead of the current time.
entailment
def set_paths_caching_params(self, timeout=None, cache_name=None): """Use the uWSGI caching subsystem to store mappings from URI to filesystem paths. * http://uwsgi.readthedocs.io/en/latest/StaticFiles.html#caching-paths-mappings-resolutions :param int timeout: Amount of seconds to put resolved paths in the uWSGI cache. :param str|unicode cache_name: Cache name to use for static paths. """ self._set('static-cache-paths', timeout) self._set('static-cache-paths-name', cache_name) return self._section
Use the uWSGI caching subsystem to store mappings from URI to filesystem paths. * http://uwsgi.readthedocs.io/en/latest/StaticFiles.html#caching-paths-mappings-resolutions :param int timeout: Amount of seconds to put resolved paths in the uWSGI cache. :param str|unicode cache_name: Cache name to use for static paths.
entailment
def set_socket_params( self, send_timeout=None, keep_alive=None, no_defer_accept=None, buffer_send=None, buffer_receive=None): """Sets common socket params. :param int send_timeout: Send (write) timeout in seconds. :param bool keep_alive: Enable TCP KEEPALIVEs. :param bool no_defer_accept: Disable deferred ``accept()`` on sockets by default (where available) uWSGI will defer the accept() of requests until some data is sent by the client (this is a security/performance measure). If you want to disable this feature for some reason, specify this option. :param int buffer_send: Set SO_SNDBUF (bytes). :param int buffer_receive: Set SO_RCVBUF (bytes). """ self._set('so-send-timeout', send_timeout) self._set('so-keepalive', keep_alive, cast=bool) self._set('no-defer-accept', no_defer_accept, cast=bool) self._set('socket-sndbuf', buffer_send) self._set('socket-rcvbuf', buffer_receive) return self._section
Sets common socket params. :param int send_timeout: Send (write) timeout in seconds. :param bool keep_alive: Enable TCP KEEPALIVEs. :param bool no_defer_accept: Disable deferred ``accept()`` on sockets by default (where available) uWSGI will defer the accept() of requests until some data is sent by the client (this is a security/performance measure). If you want to disable this feature for some reason, specify this option. :param int buffer_send: Set SO_SNDBUF (bytes). :param int buffer_receive: Set SO_RCVBUF (bytes).
entailment
def set_unix_socket_params(self, abstract=None, permissions=None, owner=None, umask=None): """Sets Unix-socket related params. :param bool abstract: Force UNIX socket into abstract mode (Linux only). :param str permissions: UNIX sockets are filesystem objects that obey UNIX permissions like any other filesystem object. You can set the UNIX sockets' permissions with this option if your webserver would otherwise have no access to the uWSGI socket. When used without a parameter, the permissions will be set to 666. Otherwise the specified chmod value will be used. :param str|unicode owner: Chown UNIX sockets. :param str|unicode umask: Set UNIX socket umask. """ self._set('abstract-socket', abstract, cast=bool) self._set('chmod-socket', permissions) self._set('chown-socket', owner) self._set('umask', umask) return self._section
Sets Unix-socket related params. :param bool abstract: Force UNIX socket into abstract mode (Linux only). :param str permissions: UNIX sockets are filesystem objects that obey UNIX permissions like any other filesystem object. You can set the UNIX sockets' permissions with this option if your webserver would otherwise have no access to the uWSGI socket. When used without a parameter, the permissions will be set to 666. Otherwise the specified chmod value will be used. :param str|unicode owner: Chown UNIX sockets. :param str|unicode umask: Set UNIX socket umask.
entailment
def set_bsd_socket_params(self, port_reuse=None): """Sets BSD-sockets related params. :param bool port_reuse: Enable REUSE_PORT flag on socket to allow multiple instances binding on the same address (BSD only). """ self._set('reuse-port', port_reuse, cast=bool) return self._section
Sets BSD-sockets related params. :param bool port_reuse: Enable REUSE_PORT flag on socket to allow multiple instances binding on the same address (BSD only).
entailment
def register_socket(self, socket): """Registers the given socket(s) for further use. :param Socket|list[Socket] socket: Socket type object. See ``.sockets``. """ sockets = self._sockets for socket in listify(socket): uses_shared = isinstance(socket.address, SocketShared) if uses_shared: # Handling shared sockets involves socket index resolution. shared_socket = socket.address # type: SocketShared if shared_socket not in sockets: self.register_socket(shared_socket) socket.address = self._get_shared_socket_idx(shared_socket) socket.address = self._section.replace_placeholders(socket.address) self._set(socket.name, socket, multi=True) socket._contribute_to_opts(self) bound_workers = socket.bound_workers if bound_workers: self._set( 'map-socket', '%s:%s' % (len(sockets), ','.join(map(str, bound_workers))), multi=True) if not uses_shared: sockets.append(socket) return self._section
Registers the given socket(s) for further use. :param Socket|list[Socket] socket: Socket type object. See ``.sockets``.
entailment
def set_sni_params(self, name, cert, key, ciphers=None, client_ca=None, wildcard=False): """Allows setting Server Name Identification (virtual hosting for SSL nodes) params. * http://uwsgi.readthedocs.io/en/latest/SNI.html :param str|unicode name: Node/server/host name. :param str|unicode cert: Certificate file. :param str|unicode key: Private key file. :param str|unicode ciphers: Ciphers [alias] string. Example: * DEFAULT * HIGH * DHE, EDH * https://www.openssl.org/docs/man1.1.0/apps/ciphers.html :param str|unicode client_ca: Client CA file for client-based auth. .. note: You can prepend ! (exclamation mark) to make client certificate authentication mandatory. :param bool wildcard: Allow regular expressions in ``name`` (used for wildcard certificates). """ command = 'sni' if wildcard: command += '-regexp' args = [item for item in (cert, key, ciphers, client_ca) if item is not None] self._set(command, '%s %s' % (name, ','.join(args))) return self._section
Allows setting Server Name Identification (virtual hosting for SSL nodes) params. * http://uwsgi.readthedocs.io/en/latest/SNI.html :param str|unicode name: Node/server/host name. :param str|unicode cert: Certificate file. :param str|unicode key: Private key file. :param str|unicode ciphers: Ciphers [alias] string. Example: * DEFAULT * HIGH * DHE, EDH * https://www.openssl.org/docs/man1.1.0/apps/ciphers.html :param str|unicode client_ca: Client CA file for client-based auth. .. note: You can prepend ! (exclamation mark) to make client certificate authentication mandatory. :param bool wildcard: Allow regular expressions in ``name`` (used for wildcard certificates).
entailment
def set_sni_dir_params(self, dir, ciphers=None): """Enable checking for cert/key/client_ca file in the specified directory and create a sni/ssl context on demand. Expected filenames: * <sni-name>.crt * <sni-name>.key * <sni-name>.ca - this file is optional * http://uwsgi.readthedocs.io/en/latest/SNI.html#massive-sni-hosting :param str|unicode dir: :param str|unicode ciphers: Ciphers [alias] string. Example: * DEFAULT * HIGH * DHE, EDH * https://www.openssl.org/docs/man1.1.0/apps/ciphers.html """ self._set('sni-dir', dir) self._set('sni-dir-ciphers', ciphers) return self._section
Enable checking for cert/key/client_ca file in the specified directory and create a sni/ssl context on demand. Expected filenames: * <sni-name>.crt * <sni-name>.key * <sni-name>.ca - this file is optional * http://uwsgi.readthedocs.io/en/latest/SNI.html#massive-sni-hosting :param str|unicode dir: :param str|unicode ciphers: Ciphers [alias] string. Example: * DEFAULT * HIGH * DHE, EDH * https://www.openssl.org/docs/man1.1.0/apps/ciphers.html
entailment
def enable(self, size, block_size=None, store=None, store_sync_interval=None): """Enables shared queue of the given size. :param int size: Queue size. :param int block_size: Block size in bytes. Default: 8 KiB. :param str|unicode store: Persist the queue into file. :param int store_sync_interval: Store sync interval in master cycles (usually seconds). """ self._set('queue', size) self._set('queue-blocksize', block_size) self._set('queue-store', store) self._set('queue-store-sync', store_sync_interval) return self._section
Enables shared queue of the given size. :param int size: Queue size. :param int block_size: Block size in bytes. Default: 8 KiB. :param str|unicode store: Persist the queue into file. :param int store_sync_interval: Store sync interval in master cycles (usually seconds).
entailment
def set_basic_params(self, count=None, thunder_lock=None, lock_engine=None): """ :param int count: Create the specified number of shared locks. :param bool thunder_lock: Serialize accept() usage (if possible) Could improve performance on Linux with robust pthread mutexes. http://uwsgi.readthedocs.io/en/latest/articles/SerializingAccept.html :param str|unicode lock_engine: Set the lock engine. Example: - ipcsem """ self._set('thunder-lock', thunder_lock, cast=bool) self._set('lock-engine', lock_engine) self._set('locks', count) return self._section
:param int count: Create the specified number of shared locks. :param bool thunder_lock: Serialize accept() usage (if possible) Could improve performance on Linux with robust pthread mutexes. http://uwsgi.readthedocs.io/en/latest/articles/SerializingAccept.html :param str|unicode lock_engine: Set the lock engine. Example: - ipcsem
entailment
def set_ipcsem_params(self, ftok=None, persistent=None): """Sets ipcsem lock engine params. :param str|unicode ftok: Set the ipcsem key via ftok() for avoiding duplicates. :param bool persistent: Do not remove ipcsem's on shutdown. """ self._set('ftok', ftok) self._set('persistent-ipcsem', persistent, cast=bool) return self._section
Sets ipcsem lock engine params. :param str|unicode ftok: Set the ipcsem key via ftok() for avoiding duplicates. :param bool persistent: Do not remove ipcsem's on shutdown.
entailment
def lock_file(self, fpath, after_setup=False, wait=False): """Locks the specified file. :param str|unicode fpath: File path. :param bool after_setup: True - after logging/daemon setup False - before starting :param bool wait: True - wait if locked False - exit if locked """ command = 'flock-wait' if wait else 'flock' if after_setup: command = '%s2' % command self._set(command, fpath) return self._section
Locks the specified file. :param str|unicode fpath: File path. :param bool after_setup: True - after logging/daemon setup False - before starting :param bool wait: True - wait if locked False - exit if locked
entailment
def register_rpc(name=None): """Decorator. Allows registering a function for RPC. * http://uwsgi.readthedocs.io/en/latest/RPC.html Example: .. code-block:: python @register_rpc() def expose_me(): do() :param str|unicode name: RPC function name to associate with decorated function. :rtype: callable """ def wrapper(func): func_name = func.__name__ rpc_name = name or func_name uwsgi.register_rpc(rpc_name, func) _LOG.debug("Registering '%s' for RPC under '%s' alias ...", func_name, rpc_name) return func return wrapper
Decorator. Allows registering a function for RPC. * http://uwsgi.readthedocs.io/en/latest/RPC.html Example: .. code-block:: python @register_rpc() def expose_me(): do() :param str|unicode name: RPC function name to associate with decorated function. :rtype: callable
entailment
def make_rpc_call(func_name, args=None, remote=None): """Performs an RPC function call (local or remote) with the given arguments. :param str|unicode func_name: RPC function name to call. :param Iterable args: Function arguments. :param str|unicode remote: :rtype: bytes|str :raises ValueError: If unable to call RPC function. """ args = args or [] args = [encode(str(arg)) for arg in args] if remote: result = uwsgi.rpc(remote, func_name, *args) else: result = uwsgi.call(func_name, *args) return decode(result)
Performs an RPC function call (local or remote) with the given arguments. :param str|unicode func_name: RPC function name to call. :param Iterable args: Function arguments. :param str|unicode remote: :rtype: bytes|str :raises ValueError: If unable to call RPC function.
entailment
def set_emperor_command_params( self, command_socket=None, wait_for_command=None, wait_for_command_exclude=None): """Emperor commands related parameters. * http://uwsgi-docs.readthedocs.io/en/latest/tutorials/EmperorSubscriptions.html :param str|unicode command_socket: Enable the Emperor command socket. It is a channel allowing external process to govern vassals. :param bool wait_for_command: Always wait for a 'spawn' Emperor command before starting a vassal. :param str|unicode|list[str|unicode] wait_for_command_exclude: Vassals that will ignore ``wait_for_command``. """ self._set('emperor-command-socket', command_socket) self._set('emperor-wait-for-command', wait_for_command, cast=bool) self._set('emperor-wait-for-command-ignore', wait_for_command_exclude, multi=True) return self._section
Emperor commands related parameters. * http://uwsgi-docs.readthedocs.io/en/latest/tutorials/EmperorSubscriptions.html :param str|unicode command_socket: Enable the Emperor command socket. It is a channel allowing external process to govern vassals. :param bool wait_for_command: Always wait for a 'spawn' Emperor command before starting a vassal. :param str|unicode|list[str|unicode] wait_for_command_exclude: Vassals that will ignore ``wait_for_command``.
entailment
def set_vassals_wrapper_params(self, wrapper=None, overrides=None, fallbacks=None): """Binary wrapper for vassals parameters. :param str|unicode wrapper: Set a binary wrapper for vassals. :param str|unicode|list[str|unicode] overrides: Set a binary wrapper for vassals to try before the default one :param str|unicode|list[str|unicode] fallbacks: Set a binary wrapper for vassals to try as a last resort. Allows you to specify an alternative binary to execute when running a vassal and the default binary_path is not found (or returns an error). """ self._set('emperor-wrapper', wrapper) self._set('emperor-wrapper-override', overrides, multi=True) self._set('emperor-wrapper-fallback', fallbacks, multi=True) return self._section
Binary wrapper for vassals parameters. :param str|unicode wrapper: Set a binary wrapper for vassals. :param str|unicode|list[str|unicode] overrides: Set a binary wrapper for vassals to try before the default one :param str|unicode|list[str|unicode] fallbacks: Set a binary wrapper for vassals to try as a last resort. Allows you to specify an alternative binary to execute when running a vassal and the default binary_path is not found (or returns an error).
entailment
def set_throttle_params(self, level=None, level_max=None): """Throttling options. * http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#throttling * http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#loyalty :param int level: Set throttling level (in milliseconds) for bad behaving vassals. Default: 1000. :param int level_max: Set maximum throttling level (in milliseconds) for bad behaving vassals. Default: 3 minutes. """ self._set('emperor-throttle', level) self._set('emperor-max-throttle', level_max) return self._section
Throttling options. * http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#throttling * http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#loyalty :param int level: Set throttling level (in milliseconds) for bad behaving vassals. Default: 1000. :param int level_max: Set maximum throttling level (in milliseconds) for bad behaving vassals. Default: 3 minutes.
entailment
def set_tolerance_params(self, for_heartbeat=None, for_cursed_vassals=None): """Various tolerance options. :param int for_heartbeat: Set the Emperor tolerance about heartbeats. * http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#heartbeat-system :param int for_cursed_vassals: Set the Emperor tolerance about cursed vassals. * http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#blacklist-system """ self._set('emperor-required-heartbeat', for_heartbeat) self._set('emperor-curse-tolerance', for_cursed_vassals) return self._section
Various tolerance options. :param int for_heartbeat: Set the Emperor tolerance about heartbeats. * http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#heartbeat-system :param int for_cursed_vassals: Set the Emperor tolerance about cursed vassals. * http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#blacklist-system
entailment
def set_mode_tyrant_params(self, enable=None, links_no_follow=None, use_initgroups=None): """Tyrant mode (secure multi-user hosting). In Tyrant mode the Emperor will run the vassal using the UID/GID of the vassal configuration file. * http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#tyrant-mode-secure-multi-user-hosting :param enable: Puts the Emperor in Tyrant mode. :param bool links_no_follow: Do not follow symlinks when checking for uid/gid in Tyrant mode. :param bool use_initgroups: Add additional groups set via initgroups() in Tyrant mode. """ self._set('emperor-tyrant', enable, cast=bool) self._set('emperor-tyrant-nofollow', links_no_follow, cast=bool) self._set('emperor-tyrant-initgroups', use_initgroups, cast=bool) return self._section
Tyrant mode (secure multi-user hosting). In Tyrant mode the Emperor will run the vassal using the UID/GID of the vassal configuration file. * http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#tyrant-mode-secure-multi-user-hosting :param enable: Puts the Emperor in Tyrant mode. :param bool links_no_follow: Do not follow symlinks when checking for uid/gid in Tyrant mode. :param bool use_initgroups: Add additional groups set via initgroups() in Tyrant mode.
entailment
def set_mode_broodlord_params( self, zerg_count=None, vassal_overload_sos_interval=None, vassal_queue_items_sos=None): """This mode is a way for a vassal to ask for reinforcements to the Emperor. Reinforcements are new vassals spawned on demand generally bound on the same socket. .. warning:: If you are looking for a way to dynamically adapt the number of workers of an instance, check the Cheaper subsystem - adaptive process spawning mode. *Broodlord mode is for spawning totally new instances.* :param int zerg_count: Maximum number of zergs to spawn. :param int vassal_overload_sos_interval: Ask emperor for reinforcement when overloaded. Accepts the number of seconds to wait between asking for a new reinforcements. :param int vassal_queue_items_sos: Ask emperor for sos if listen queue (backlog) has more items than the value specified """ self._set('emperor-broodlord', zerg_count) self._set('vassal-sos', vassal_overload_sos_interval) self._set('vassal-sos-backlog', vassal_queue_items_sos) return self._section
This mode is a way for a vassal to ask for reinforcements to the Emperor. Reinforcements are new vassals spawned on demand generally bound on the same socket. .. warning:: If you are looking for a way to dynamically adapt the number of workers of an instance, check the Cheaper subsystem - adaptive process spawning mode. *Broodlord mode is for spawning totally new instances.* :param int zerg_count: Maximum number of zergs to spawn. :param int vassal_overload_sos_interval: Ask emperor for reinforcement when overloaded. Accepts the number of seconds to wait between asking for a new reinforcements. :param int vassal_queue_items_sos: Ask emperor for sos if listen queue (backlog) has more items than the value specified
entailment
def run_command_as_worker(self, command, after_post_fork_hook=False): """Run the specified command as worker. :param str|unicode command: :param bool after_post_fork_hook: Whether to run it after `post_fork` hook. """ self._set('worker-exec2' if after_post_fork_hook else 'worker-exec', command, multi=True) return self._section
Run the specified command as worker. :param str|unicode command: :param bool after_post_fork_hook: Whether to run it after `post_fork` hook.
entailment
def set_count_auto(self, count=None): """Sets workers count. By default sets it to detected number of available cores :param int count: """ count = count or self._section.vars.CPU_CORES self._set('workers', count) return self._section
Sets workers count. By default sets it to detected number of available cores :param int count:
entailment
def set_thread_params( self, enable=None, count=None, count_offload=None, stack_size=None, no_wait=None): """Sets threads related params. :param bool enable: Enable threads in the embedded languages. This will allow to spawn threads in your app. .. warning:: Threads will simply *not work* if this option is not enabled. There will likely be no error, just no execution of your thread code. :param int count: Run each worker in prethreaded mode with the specified number of threads per worker. .. warning:: Do not use with ``gevent``. .. note:: Enables threads automatically. :param int count_offload: Set the number of threads (per-worker) to spawn for offloading. Default: 0. These threads run such tasks in a non-blocking/evented way allowing for a huge amount of concurrency. Various components of the uWSGI stack are offload-friendly. .. note:: Try to set it to the number of CPU cores to take advantage of SMP. * http://uwsgi-docs.readthedocs.io/en/latest/OffloadSubsystem.html :param int stack_size: Set threads stacksize. :param bool no_wait: Do not wait for threads cancellation on quit/reload. """ self._set('enable-threads', enable, cast=bool) self._set('no-threads-wait', no_wait, cast=bool) self._set('threads', count) self._set('offload-threads', count_offload) if count: self._section.print_out('Threads per worker: %s' % count) self._set('threads-stacksize', stack_size) return self._section
Sets threads related params. :param bool enable: Enable threads in the embedded languages. This will allow to spawn threads in your app. .. warning:: Threads will simply *not work* if this option is not enabled. There will likely be no error, just no execution of your thread code. :param int count: Run each worker in prethreaded mode with the specified number of threads per worker. .. warning:: Do not use with ``gevent``. .. note:: Enables threads automatically. :param int count_offload: Set the number of threads (per-worker) to spawn for offloading. Default: 0. These threads run such tasks in a non-blocking/evented way allowing for a huge amount of concurrency. Various components of the uWSGI stack are offload-friendly. .. note:: Try to set it to the number of CPU cores to take advantage of SMP. * http://uwsgi-docs.readthedocs.io/en/latest/OffloadSubsystem.html :param int stack_size: Set threads stacksize. :param bool no_wait: Do not wait for threads cancellation on quit/reload.
entailment
def set_mules_params( self, mules=None, touch_reload=None, harakiri_timeout=None, farms=None, reload_mercy=None, msg_buffer=None, msg_buffer_recv=None): """Sets mules related params. http://uwsgi.readthedocs.io/en/latest/Mules.html Mules are worker processes living in the uWSGI stack but not reachable via socket connections, that can be used as a generic subsystem to offload tasks. :param int|list mules: Add the specified mules or number of mules. :param str|list touch_reload: Reload mules if the specified file is modified/touched. :param int harakiri_timeout: Set harakiri timeout for mule tasks. :param list[MuleFarm] farms: Mule farms list. Examples: * cls_mule_farm('first', 2) * cls_mule_farm('first', [4, 5]) :param int reload_mercy: Set the maximum time (in seconds) a mule can take to reload/shutdown. Default: 60. :param int msg_buffer: Set mule message buffer size (bytes) given for mule message queue. :param int msg_buffer: Set mule message recv buffer size (bytes). """ farms = farms or [] next_mule_number = 1 farm_mules_count = 0 for farm in farms: if isinstance(farm.mule_numbers, int): farm.mule_numbers = list(range(next_mule_number, next_mule_number + farm.mule_numbers)) next_mule_number = farm.mule_numbers[-1] + 1 farm_mules_count += len(farm.mule_numbers) self._set('farm', farm, multi=True) if mules is None and farm_mules_count: mules = farm_mules_count if isinstance(mules, int): self._set('mules', mules) elif isinstance(mules, list): for mule in mules: self._set('mule', mule, multi=True) self._set('touch-mules-reload', touch_reload, multi=True) self._set('mule-harakiri', harakiri_timeout) self._set('mule-reload-mercy', reload_mercy) self._set('mule-msg-size', msg_buffer) self._set('mule-msg-recv-size', msg_buffer_recv) return self._section
Sets mules related params. http://uwsgi.readthedocs.io/en/latest/Mules.html Mules are worker processes living in the uWSGI stack but not reachable via socket connections, that can be used as a generic subsystem to offload tasks. :param int|list mules: Add the specified mules or number of mules. :param str|list touch_reload: Reload mules if the specified file is modified/touched. :param int harakiri_timeout: Set harakiri timeout for mule tasks. :param list[MuleFarm] farms: Mule farms list. Examples: * cls_mule_farm('first', 2) * cls_mule_farm('first', [4, 5]) :param int reload_mercy: Set the maximum time (in seconds) a mule can take to reload/shutdown. Default: 60. :param int msg_buffer: Set mule message buffer size (bytes) given for mule message queue. :param int msg_buffer: Set mule message recv buffer size (bytes).
entailment
def set_reload_params( self, min_lifetime=None, max_lifetime=None, max_requests=None, max_requests_delta=None, max_addr_space=None, max_rss=None, max_uss=None, max_pss=None, max_addr_space_forced=None, max_rss_forced=None, watch_interval_forced=None, mercy=None): """Sets workers reload parameters. :param int min_lifetime: A worker cannot be destroyed/reloaded unless it has been alive for N seconds (default 60). This is an anti-fork-bomb measure. Since 1.9 :param int max_lifetime: Reload workers after this many seconds. Disabled by default. Since 1.9 :param int max_requests: Reload workers after the specified amount of managed requests (avoid memory leaks). When a worker reaches this number of requests it will get recycled (killed and restarted). You can use this option to "dumb fight" memory leaks. Also take a look at the ``reload-on-as`` and ``reload-on-rss`` options as they are more useful for memory leaks. .. warning:: The default min-worker-lifetime 60 seconds takes priority over `max-requests`. Do not use with benchmarking as you'll get stalls such as `worker respawning too fast !!! i have to sleep a bit (2 seconds)...` :param int max_requests_delta: Add (worker_id * delta) to the max_requests value of each worker. :param int max_addr_space: Reload a worker if its address space usage is higher than the specified value in megabytes. :param int max_rss: Reload a worker if its physical unshared memory (resident set size) is higher than the specified value (in megabytes). :param int max_uss: Reload a worker if Unique Set Size is higher than the specified value in megabytes. .. note:: Linux only. :param int max_pss: Reload a worker if Proportional Set Size is higher than the specified value in megabytes. .. note:: Linux only. :param int max_addr_space_forced: Force the master to reload a worker if its address space is higher than specified megabytes (in megabytes). :param int max_rss_forced: Force the master to reload a worker if its resident set size memory is higher than specified in megabytes. :param int watch_interval_forced: The memory collector [per-worker] thread memeory watch interval (seconds) used for forced reloads. Default: 3. :param int mercy: Set the maximum time (in seconds) a worker can take before reload/shutdown. Default: 60. """ self._set('max-requests', max_requests) self._set('max-requests-delta', max_requests_delta) self._set('min-worker-lifetime', min_lifetime) self._set('max-worker-lifetime', max_lifetime) self._set('reload-on-as', max_addr_space) self._set('reload-on-rss', max_rss) self._set('reload-on-uss', max_uss) self._set('reload-on-pss', max_pss) self._set('evil-reload-on-as', max_addr_space_forced) self._set('evil-reload-on-rss', max_rss_forced) self._set('mem-collector-freq', watch_interval_forced) self._set('worker-reload-mercy', mercy) return self._section
Sets workers reload parameters. :param int min_lifetime: A worker cannot be destroyed/reloaded unless it has been alive for N seconds (default 60). This is an anti-fork-bomb measure. Since 1.9 :param int max_lifetime: Reload workers after this many seconds. Disabled by default. Since 1.9 :param int max_requests: Reload workers after the specified amount of managed requests (avoid memory leaks). When a worker reaches this number of requests it will get recycled (killed and restarted). You can use this option to "dumb fight" memory leaks. Also take a look at the ``reload-on-as`` and ``reload-on-rss`` options as they are more useful for memory leaks. .. warning:: The default min-worker-lifetime 60 seconds takes priority over `max-requests`. Do not use with benchmarking as you'll get stalls such as `worker respawning too fast !!! i have to sleep a bit (2 seconds)...` :param int max_requests_delta: Add (worker_id * delta) to the max_requests value of each worker. :param int max_addr_space: Reload a worker if its address space usage is higher than the specified value in megabytes. :param int max_rss: Reload a worker if its physical unshared memory (resident set size) is higher than the specified value (in megabytes). :param int max_uss: Reload a worker if Unique Set Size is higher than the specified value in megabytes. .. note:: Linux only. :param int max_pss: Reload a worker if Proportional Set Size is higher than the specified value in megabytes. .. note:: Linux only. :param int max_addr_space_forced: Force the master to reload a worker if its address space is higher than specified megabytes (in megabytes). :param int max_rss_forced: Force the master to reload a worker if its resident set size memory is higher than specified in megabytes. :param int watch_interval_forced: The memory collector [per-worker] thread memeory watch interval (seconds) used for forced reloads. Default: 3. :param int mercy: Set the maximum time (in seconds) a worker can take before reload/shutdown. Default: 60.
entailment
def set_reload_on_exception_params(self, do_reload=None, etype=None, evalue=None, erepr=None): """Sets workers reload on exceptions parameters. :param bool do_reload: Reload a worker when an exception is raised. :param str etype: Reload a worker when a specific exception type is raised. :param str evalue: Reload a worker when a specific exception value is raised. :param str erepr: Reload a worker when a specific exception type+value (language-specific) is raised. """ self._set('reload-on-exception', do_reload, cast=bool) self._set('reload-on-exception-type', etype) self._set('reload-on-exception-value', evalue) self._set('reload-on-exception-repr', erepr) return self._section
Sets workers reload on exceptions parameters. :param bool do_reload: Reload a worker when an exception is raised. :param str etype: Reload a worker when a specific exception type is raised. :param str evalue: Reload a worker when a specific exception value is raised. :param str erepr: Reload a worker when a specific exception type+value (language-specific) is raised.
entailment
def set_harakiri_params(self, timeout=None, verbose=None, disable_for_arh=None): """Sets workers harakiri parameters. :param int timeout: Harakiri timeout in seconds. Every request that will take longer than the seconds specified in the harakiri timeout will be dropped and the corresponding worker is thereafter recycled. :param bool verbose: Harakiri verbose mode. When a request is killed by Harakiri you will get a message in the uWSGI log. Enabling this option will print additional info (for example, the current syscall will be reported on Linux platforms). :param bool disable_for_arh: Disallow Harakiri killings during after-request hook methods. """ self._set('harakiri', timeout) self._set('harakiri-verbose', verbose, cast=bool) self._set('harakiri-no-arh', disable_for_arh, cast=bool) return self._section
Sets workers harakiri parameters. :param int timeout: Harakiri timeout in seconds. Every request that will take longer than the seconds specified in the harakiri timeout will be dropped and the corresponding worker is thereafter recycled. :param bool verbose: Harakiri verbose mode. When a request is killed by Harakiri you will get a message in the uWSGI log. Enabling this option will print additional info (for example, the current syscall will be reported on Linux platforms). :param bool disable_for_arh: Disallow Harakiri killings during after-request hook methods.
entailment
def set_zerg_server_params(self, socket, clients_socket_pool=None): """Zerg mode. Zerg server params. When your site load is variable, it would be nice to be able to add workers dynamically. Enabling Zerg mode you can allow zerg clients to attach to your already running server and help it in the work. * http://uwsgi-docs.readthedocs.io/en/latest/Zerg.html :param str|unicode socket: Unix socket to bind server to. Examples: * unix socket - ``/var/run/mutalisk`` * Linux abstract namespace - ``@nydus`` :param str|unicode|list[str|unicode] clients_socket_pool: This enables Zerg Pools. .. note:: Expects master process. Accepts sockets that will be mapped to Zerg socket. * http://uwsgi-docs.readthedocs.io/en/latest/Zerg.html#zerg-pools """ if clients_socket_pool: self._set('zergpool', '%s:%s' % (socket, ','.join(listify(clients_socket_pool))), multi=True) else: self._set('zerg-server', socket) return self._section
Zerg mode. Zerg server params. When your site load is variable, it would be nice to be able to add workers dynamically. Enabling Zerg mode you can allow zerg clients to attach to your already running server and help it in the work. * http://uwsgi-docs.readthedocs.io/en/latest/Zerg.html :param str|unicode socket: Unix socket to bind server to. Examples: * unix socket - ``/var/run/mutalisk`` * Linux abstract namespace - ``@nydus`` :param str|unicode|list[str|unicode] clients_socket_pool: This enables Zerg Pools. .. note:: Expects master process. Accepts sockets that will be mapped to Zerg socket. * http://uwsgi-docs.readthedocs.io/en/latest/Zerg.html#zerg-pools
entailment
def set_zerg_client_params(self, server_sockets, use_fallback_socket=None): """Zerg mode. Zergs params. :param str|unicode|list[str|unicode] server_sockets: Attaches zerg to a zerg server. :param bool use_fallback_socket: Fallback to normal sockets if the zerg server is not available """ self._set('zerg', server_sockets, multi=True) if use_fallback_socket is not None: self._set('zerg-fallback', use_fallback_socket, cast=bool) for socket in listify(server_sockets): self._section.networking.register_socket(self._section.networking.sockets.default(socket)) return self._section
Zerg mode. Zergs params. :param str|unicode|list[str|unicode] server_sockets: Attaches zerg to a zerg server. :param bool use_fallback_socket: Fallback to normal sockets if the zerg server is not available
entailment
def format_print_text(text, color_fg=None, color_bg=None): """Format given text using ANSI formatting escape sequences. Could be useful gfor print command. :param str|unicode text: :param str|unicode color_fg: text (foreground) color :param str|unicode color_bg: text (background) color :rtype: str|unicode """ from .config import Section color_fg = { 'black': '30', 'red': '31', 'reder': '91', 'green': '32', 'greener': '92', 'yellow': '33', 'yellower': '93', 'blue': '34', 'bluer': '94', 'magenta': '35', 'magenter': '95', 'cyan': '36', 'cyaner': '96', 'gray': '37', 'grayer': '90', 'white': '97', }.get(color_fg, '39') color_bg = { 'black': '40', 'red': '41', 'reder': '101', 'green': '42', 'greener': '102', 'yellow': '43', 'yellower': '103', 'blue': '44', 'bluer': '104', 'magenta': '45', 'magenter': '105', 'cyan': '46', 'cyaner': '106', 'gray': '47', 'grayer': '100', 'white': '107', }.get(color_bg, '49') mod = ';'.join([color_fg, color_bg]) text = '%(esc)s[%(mod)sm%(value)s%(end)s' % { 'esc': Section.vars.FORMAT_ESCAPE, 'end': Section.vars.FORMAT_END, 'mod': mod, 'value': text, } return text
Format given text using ANSI formatting escape sequences. Could be useful gfor print command. :param str|unicode text: :param str|unicode color_fg: text (foreground) color :param str|unicode color_bg: text (background) color :rtype: str|unicode
entailment
def iter_options(self): """Iterates configuration sections groups options.""" for section in self.sections: name = str(section) for key, value in section._get_options(): yield name, key, value
Iterates configuration sections groups options.
entailment
def set_memory_params(self, ksm_interval=None, no_swap=None): """Set memory related parameters. :param int ksm_interval: Kernel Samepage Merging frequency option, that can reduce memory usage. Accepts a number of requests (or master process cycles) to run page scanner after. .. note:: Linux only. * http://uwsgi.readthedocs.io/en/latest/KSM.html :param bool no_swap: Lock all memory pages avoiding swapping. """ self._set('ksm', ksm_interval) self._set('never_swap', no_swap, cast=bool) return self._section
Set memory related parameters. :param int ksm_interval: Kernel Samepage Merging frequency option, that can reduce memory usage. Accepts a number of requests (or master process cycles) to run page scanner after. .. note:: Linux only. * http://uwsgi.readthedocs.io/en/latest/KSM.html :param bool no_swap: Lock all memory pages avoiding swapping.
entailment
def daemonize(self, log_into, after_app_loading=False): """Daemonize uWSGI. :param str|unicode log_into: Logging destination: * File: /tmp/mylog.log * UPD: 192.168.1.2:1717 .. note:: This will require an UDP server to manage log messages. Use ``networking.register_socket('192.168.1.2:1717, type=networking.SOCK_UDP)`` to start uWSGI UDP server. :param str|unicode bool after_app_loading: Whether to daemonize after or before applications loading. """ self._set('daemonize2' if after_app_loading else 'daemonize', log_into) return self._section
Daemonize uWSGI. :param str|unicode log_into: Logging destination: * File: /tmp/mylog.log * UPD: 192.168.1.2:1717 .. note:: This will require an UDP server to manage log messages. Use ``networking.register_socket('192.168.1.2:1717, type=networking.SOCK_UDP)`` to start uWSGI UDP server. :param str|unicode bool after_app_loading: Whether to daemonize after or before applications loading.
entailment
def change_dir(self, to, after_app_loading=False): """Chdir to specified directory before or after apps loading. :param str|unicode to: Target directory. :param bool after_app_loading: *True* - after load *False* - before load """ self._set('chdir2' if after_app_loading else 'chdir', to) return self._section
Chdir to specified directory before or after apps loading. :param str|unicode to: Target directory. :param bool after_app_loading: *True* - after load *False* - before load
entailment
def set_owner_params(self, uid=None, gid=None, add_gids=None, set_asap=False): """Set process owner params - user, group. :param str|unicode|int uid: Set uid to the specified username or uid. :param str|unicode|int gid: Set gid to the specified groupname or gid. :param list|str|unicode|int add_gids: Add the specified group id to the process credentials. This options allows you to add additional group ids to the current process. You can specify it multiple times. :param bool set_asap: Set as soon as possible. Setting them on top of your vassal file will force the instance to setuid()/setgid() as soon as possible and without the (theoretical) possibility to override them. """ prefix = 'immediate-' if set_asap else '' self._set(prefix + 'uid', uid) self._set(prefix + 'gid', gid) self._set('add-gid', add_gids, multi=True) # This may be wrong for subsequent method calls. self.owner = [uid, gid] return self._section
Set process owner params - user, group. :param str|unicode|int uid: Set uid to the specified username or uid. :param str|unicode|int gid: Set gid to the specified groupname or gid. :param list|str|unicode|int add_gids: Add the specified group id to the process credentials. This options allows you to add additional group ids to the current process. You can specify it multiple times. :param bool set_asap: Set as soon as possible. Setting them on top of your vassal file will force the instance to setuid()/setgid() as soon as possible and without the (theoretical) possibility to override them.
entailment
def get_owner(self, default=True): """Return (User ID, Group ID) tuple :param bool default: Whether to return default if not set. :rtype: tuple[int, int] """ uid, gid = self.owner if not uid and default: uid = os.getuid() if not gid and default: gid = os.getgid() return uid, gid
Return (User ID, Group ID) tuple :param bool default: Whether to return default if not set. :rtype: tuple[int, int]
entailment
def set_hook(self, phase, action): """Allows setting hooks (attaching actions) for various uWSGI phases. :param str|unicode phase: See constants in ``.phases``. :param str|unicode|list|HookAction|list[HookAction] action: """ self._set('hook-%s' % phase, action, multi=True) return self._section
Allows setting hooks (attaching actions) for various uWSGI phases. :param str|unicode phase: See constants in ``.phases``. :param str|unicode|list|HookAction|list[HookAction] action:
entailment
def set_hook_touch(self, fpath, action): """Allows running certain action when the specified file is touched. :param str|unicode fpath: File path. :param str|unicode|list|HookAction|list[HookAction] action: """ self._set('hook-touch', '%s %s' % (fpath, action), multi=True) return self._section
Allows running certain action when the specified file is touched. :param str|unicode fpath: File path. :param str|unicode|list|HookAction|list[HookAction] action:
entailment
def set_hook_after_request(self, func): """Run the specified function/symbol (C level) after each request. :param str|unicode func: """ self._set('after-request-hook', func, multi=True) return self._section
Run the specified function/symbol (C level) after each request. :param str|unicode func:
entailment
def set_on_exit_params(self, skip_hooks=None, skip_teardown=None): """Set params related to process exit procedure. :param bool skip_hooks: Skip ``EXIT`` phase hook. .. note:: Ignored by the master. :param bool skip_teardown: Allows skipping teardown (finalization) processes for some plugins. .. note:: Ignored by the master. Supported by: * Perl * Python """ self._set('skip-atexit', skip_hooks, cast=bool) self._set('skip-atexit-teardown', skip_teardown, cast=bool) return self._section
Set params related to process exit procedure. :param bool skip_hooks: Skip ``EXIT`` phase hook. .. note:: Ignored by the master. :param bool skip_teardown: Allows skipping teardown (finalization) processes for some plugins. .. note:: Ignored by the master. Supported by: * Perl * Python
entailment
def run_command_on_event(self, command, phase=phases.ASAP): """Run the given command on a given phase. :param str|unicode command: :param str|unicode phase: See constants in ``Phases`` class. """ self._set('exec-%s' % phase, command, multi=True) return self._section
Run the given command on a given phase. :param str|unicode command: :param str|unicode phase: See constants in ``Phases`` class.
entailment
def run_command_on_touch(self, command, target): """Run command when the specified file is modified/touched. :param str|unicode command: :param str|unicode target: File path. """ self._set('touch-exec', '%s %s' % (target, command), multi=True) return self._section
Run command when the specified file is modified/touched. :param str|unicode command: :param str|unicode target: File path.
entailment
def set_pid_file(self, fpath, before_priv_drop=True, safe=False): """Creates pidfile before or after privileges drop. :param str|unicode fpath: File path. :param bool before_priv_drop: Whether to create pidfile before privileges are dropped. .. note:: Vacuum is made after privileges drop, so it may not be able to delete PID file if it was created before dropping. :param bool safe: The safe-pidfile works similar to pidfile but performs the write a little later in the loading process. This avoids overwriting the value when app loading fails, with the consequent loss of a valid PID number. """ command = 'pidfile' if not before_priv_drop: command += '2' if safe: command = 'safe-' + command self._set(command, fpath) return self._section
Creates pidfile before or after privileges drop. :param str|unicode fpath: File path. :param bool before_priv_drop: Whether to create pidfile before privileges are dropped. .. note:: Vacuum is made after privileges drop, so it may not be able to delete PID file if it was created before dropping. :param bool safe: The safe-pidfile works similar to pidfile but performs the write a little later in the loading process. This avoids overwriting the value when app loading fails, with the consequent loss of a valid PID number.
entailment
def set_naming_params(self, autonaming=None, prefix=None, suffix=None, name=None): """Setups processes naming parameters. :param bool autonaming: Automatically set process name to something meaningful. Generated process names may be 'uWSGI Master', 'uWSGI Worker #', etc. :param str|unicode prefix: Add prefix to process names. :param str|unicode suffix: Append string to process names. :param str|unicode name: Set process names to given static value. """ self._set('auto-procname', autonaming, cast=bool) self._set('procname-prefix%s' % ('-spaced' if prefix and prefix.endswith(' ') else ''), prefix) self._set('procname-append', suffix) self._set('procname', name) return self._section
Setups processes naming parameters. :param bool autonaming: Automatically set process name to something meaningful. Generated process names may be 'uWSGI Master', 'uWSGI Worker #', etc. :param str|unicode prefix: Add prefix to process names. :param str|unicode suffix: Append string to process names. :param str|unicode name: Set process names to given static value.
entailment
def errorprint(): """Print out descriptions from ConfigurationError.""" try: yield except ConfigurationError as e: click.secho('%s' % e, err=True, fg='red') sys.exit(1)
Print out descriptions from ConfigurationError.
entailment
def run(conf, only): """Runs uWSGI passing to it using the default or another `uwsgiconf` configuration module. """ with errorprint(): config = ConfModule(conf) spawned = config.spawn_uwsgi(only) for alias, pid in spawned: click.secho("Spawned uWSGI for configuration aliased '%s'. PID %s" % (alias, pid), fg='green')
Runs uWSGI passing to it using the default or another `uwsgiconf` configuration module.
entailment
def compile(conf): """Compiles classic uWSGI configuration file using the default or given `uwsgiconf` configuration module. """ with errorprint(): config = ConfModule(conf) for conf in config.configurations: conf.format(do_print=True)
Compiles classic uWSGI configuration file using the default or given `uwsgiconf` configuration module.
entailment
def sysinit(systype, conf, project): """Outputs configuration for system initialization subsystem.""" click.secho(get_config( systype, conf=ConfModule(conf).configurations[0], conf_path=conf, project_name=project, ))
Outputs configuration for system initialization subsystem.
entailment
def probe_plugins(): """Runs uWSGI to determine what plugins are available and prints them out. Generic plugins come first then after blank line follow request plugins. """ plugins = UwsgiRunner().get_plugins() for plugin in sorted(plugins.generic): click.secho(plugin) click.secho('') for plugin in sorted(plugins.request): click.secho(plugin)
Runs uWSGI to determine what plugins are available and prints them out. Generic plugins come first then after blank line follow request plugins.
entailment
def register_handler(self, target=None): """Decorator for a function to be used as a signal handler. :param str|unicode target: Where this signal will be delivered to. Default: ``worker``. * ``workers`` - run the signal handler on all the workers * ``workerN`` - run the signal handler only on worker N * ``worker``/``worker0`` - run the signal handler on the first available worker * ``active-workers`` - run the signal handlers on all the active [non-cheaped] workers * ``mules`` - run the signal handler on all of the mules * ``muleN`` - run the signal handler on mule N * ``mule``/``mule0`` - run the signal handler on the first available mule * ``spooler`` - run the signal on the first available spooler * ``farmN/farm_XXX`` - run the signal handler in the mule farm N or named XXX * http://uwsgi.readthedocs.io/en/latest/Signals.html#signals-targets """ target = target or 'worker' sign_num = self.num def wrapper(func): _LOG.debug("Registering '%s' as signal '%s' handler ...", func.__name__, sign_num) uwsgi.register_signal(sign_num, target, func) return func return wrapper
Decorator for a function to be used as a signal handler. :param str|unicode target: Where this signal will be delivered to. Default: ``worker``. * ``workers`` - run the signal handler on all the workers * ``workerN`` - run the signal handler only on worker N * ``worker``/``worker0`` - run the signal handler on the first available worker * ``active-workers`` - run the signal handlers on all the active [non-cheaped] workers * ``mules`` - run the signal handler on all of the mules * ``muleN`` - run the signal handler on mule N * ``mule``/``mule0`` - run the signal handler on the first available mule * ``spooler`` - run the signal on the first available spooler * ``farmN/farm_XXX`` - run the signal handler in the mule farm N or named XXX * http://uwsgi.readthedocs.io/en/latest/Signals.html#signals-targets
entailment
def add(self, work_dir, external=False): """Run a spooler on the specified directory. :param str|unicode work_dir: .. note:: Placeholders can be used to build paths, e.g.: {project_runtime_dir}/spool/ See ``Section.project_name`` and ``Section.runtime_dir``. :param bool external: map spoolers requests to a spooler directory managed by an external instance """ command = 'spooler' if external: command += '-external' self._set(command, self._section.replace_placeholders(work_dir), multi=True) return self._section
Run a spooler on the specified directory. :param str|unicode work_dir: .. note:: Placeholders can be used to build paths, e.g.: {project_runtime_dir}/spool/ See ``Section.project_name`` and ``Section.runtime_dir``. :param bool external: map spoolers requests to a spooler directory managed by an external instance
entailment
def configure(self): """Configures broodlord mode and returns emperor and zerg sections. :rtype: tuple """ section_emperor = self.section_emperor section_zerg = self.section_zerg socket = self.socket section_emperor.workers.set_zerg_server_params(socket=socket) section_emperor.empire.set_emperor_params(vassals_home=self.vassals_home) section_emperor.empire.set_mode_broodlord_params(**self.broodlord_params) section_zerg.name = 'zerg' section_zerg.workers.set_zerg_client_params(server_sockets=socket) if self.die_on_idle: section_zerg.master_process.set_idle_params(timeout=30, exit=True) return section_emperor, section_zerg
Configures broodlord mode and returns emperor and zerg sections. :rtype: tuple
entailment
def get_log_format_default(self): """Returns default log message format. .. note:: Some params may be missing. """ vars = self.logging.vars format_default = ( '[pid: %s|app: %s|req: %s/%s] %s (%s) {%s vars in %s bytes} [%s] %s %s => ' 'generated %s bytes in %s %s%s(%s %s) %s headers in %s bytes (%s switches on core %s)' % ( vars.WORKER_PID, '-', # app id '-', # app req count '-', # worker req count vars.REQ_REMOTE_ADDR, vars.REQ_REMOTE_USER, vars.REQ_COUNT_VARS_CGI, vars.SIZE_PACKET_UWSGI, vars.REQ_START_CTIME, vars.REQ_METHOD, vars.REQ_URI, vars.RESP_SIZE_BODY, vars.RESP_TIME_MS, # or RESP_TIME_US, '-', # tsize '-', # via sendfile/route/offload vars.REQ_SERVER_PROTOCOL, vars.RESP_STATUS, vars.RESP_COUNT_HEADERS, vars.RESP_SIZE_HEADERS, vars.ASYNC_SWITCHES, vars.CORE, )) return format_default
Returns default log message format. .. note:: Some params may be missing.
entailment
def configure_owner(self, owner='www-data'): """Shortcut to set process owner data. :param str|unicode owner: Sets user and group. Default: ``www-data``. """ if owner is not None: self.main_process.set_owner_params(uid=owner, gid=owner) return self
Shortcut to set process owner data. :param str|unicode owner: Sets user and group. Default: ``www-data``.
entailment
def set_basic_params(self, msg_size=None, cheap=None, anti_loop_timeout=None): """ :param int msg_size: Set the max size of an alarm message in bytes. Default: 8192. :param bool cheap: Use main alarm thread rather than create dedicated threads for curl-based alarms :param int anti_loop_timeout: Tune the anti-loop alarm system. Default: 3 seconds. """ self._set('alarm-msg-size', msg_size) self._set('alarm-cheap', cheap, cast=bool) self._set('alarm-freq', anti_loop_timeout) return self._section
:param int msg_size: Set the max size of an alarm message in bytes. Default: 8192. :param bool cheap: Use main alarm thread rather than create dedicated threads for curl-based alarms :param int anti_loop_timeout: Tune the anti-loop alarm system. Default: 3 seconds.
entailment
def register_alarm(self, alarm): """Register (create) an alarm. :param AlarmType|list[AlarmType] alarm: Alarm. """ for alarm in listify(alarm): if alarm not in self._alarms: self._set('alarm', alarm, multi=True) self._alarms.append(alarm) return self._section
Register (create) an alarm. :param AlarmType|list[AlarmType] alarm: Alarm.
entailment
def alarm_on_log(self, alarm, matcher, skip=False): """Raise (or skip) the specified alarm when a log line matches the specified regexp. :param AlarmType|list[AlarmType] alarm: Alarm. :param str|unicode matcher: Regular expression to match log line. :param bool skip: """ self.register_alarm(alarm) value = '%s %s' % ( ','.join(map(attrgetter('alias'), listify(alarm))), matcher) self._set('not-alarm-log' if skip else 'alarm-log', value) return self._section
Raise (or skip) the specified alarm when a log line matches the specified regexp. :param AlarmType|list[AlarmType] alarm: Alarm. :param str|unicode matcher: Regular expression to match log line. :param bool skip:
entailment
def alarm_on_fd_ready(self, alarm, fd, message, byte_count=None): """Triggers the alarm when the specified file descriptor is ready for read. This is really useful for integration with the Linux eventfd() facility. Pretty low-level and the basis of most of the alarm plugins. * http://uwsgi-docs.readthedocs.io/en/latest/Changelog-1.9.7.html#alarm-fd :param AlarmType|list[AlarmType] alarm: Alarm. :param str|unicode fd: File descriptor. :param str|unicode message: Message to send. :param int byte_count: Files to read. Default: 1 byte. .. note:: For ``eventfd`` set 8. """ self.register_alarm(alarm) value = fd if byte_count: value += ':%s' % byte_count value += ' %s' % message for alarm in listify(alarm): self._set('alarm-fd', '%s %s' % (alarm.alias, value), multi=True) return self._section
Triggers the alarm when the specified file descriptor is ready for read. This is really useful for integration with the Linux eventfd() facility. Pretty low-level and the basis of most of the alarm plugins. * http://uwsgi-docs.readthedocs.io/en/latest/Changelog-1.9.7.html#alarm-fd :param AlarmType|list[AlarmType] alarm: Alarm. :param str|unicode fd: File descriptor. :param str|unicode message: Message to send. :param int byte_count: Files to read. Default: 1 byte. .. note:: For ``eventfd`` set 8.
entailment
def alarm_on_segfault(self, alarm): """Raise the specified alarm when the segmentation fault handler is executed. Sends a backtrace. :param AlarmType|list[AlarmType] alarm: Alarm. """ self.register_alarm(alarm) for alarm in listify(alarm): self._set('alarm-segfault', alarm.alias, multi=True) return self._section
Raise the specified alarm when the segmentation fault handler is executed. Sends a backtrace. :param AlarmType|list[AlarmType] alarm: Alarm.
entailment
def get_config(systype, conf, conf_path, runner=None, project_name=None): """Returns init system configuration file contents. :param str|unicode systype: System type alias, e.g. systemd, upstart :param Section|Configuration conf: Configuration/Section object. :param str|unicode conf_path: File path to a configuration file or a command producing such a configuration. :param str|unicode runner: Runner command to execute conf_path. Defaults to ``uwsgiconf`` runner. :param str|unicode project_name: Project name to override. :rtype: str|unicode """ runner = runner or ('%s run' % Finder.uwsgiconf()) conf_path = abspath(conf_path) if isinstance(conf, Configuration): conf = conf.sections[0] # todo Maybe something more intelligent. tpl = dedent(TEMPLATES.get(systype)(conf=conf)) formatted = tpl.strip().format( project=project_name or conf.project_name or basename(dirname(conf_path)), command='%s %s' % (runner, conf_path), ) return formatted
Returns init system configuration file contents. :param str|unicode systype: System type alias, e.g. systemd, upstart :param Section|Configuration conf: Configuration/Section object. :param str|unicode conf_path: File path to a configuration file or a command producing such a configuration. :param str|unicode runner: Runner command to execute conf_path. Defaults to ``uwsgiconf`` runner. :param str|unicode project_name: Project name to override. :rtype: str|unicode
entailment
def app_1(env, start_response): """This is simple WSGI application that will be served by uWSGI.""" from uwsgiconf.runtime.environ import uwsgi_env start_response('200 OK', [('Content-Type','text/html')]) data = [ '<h1>uwsgiconf demo: one file</h1>', '<div>uWSGI version: %s</div>' % uwsgi_env.get_version(), '<div>uWSGI request ID: %s</div>' % uwsgi_env.request.id, ] return encode(data)
This is simple WSGI application that will be served by uWSGI.
entailment
def app_2(env, start_response): """This is another simple WSGI application that will be served by uWSGI.""" import random start_response('200 OK', [('Content-Type','text/html')]) data = [ '<h1>uwsgiconf demo: one file second app</h1>', '<div>Some random number for you: %s</div>' % random.randint(1, 99999), ] return encode(data)
This is another simple WSGI application that will be served by uWSGI.
entailment
def configure(): """Configure uWSGI. This returns several configuration objects, which will be used to spawn several uWSGI processes. Applications are on 127.0.0.1 on ports starting from 8000. """ import os from uwsgiconf.presets.nice import PythonSection FILE = os.path.abspath(__file__) port = 8000 configurations = [] for idx in range(2): alias = 'app_%s' % (idx + 1) section = PythonSection( # Automatically reload uWSGI if this file is changed. touch_reload=FILE, # To differentiate easily. process_prefix=alias, # Serve WSGI application (see above) from this very file. wsgi_module=FILE, # Custom WSGI callable for second app. wsgi_callable=alias, # One is just enough, no use in worker on every core # for this demo. workers=1, ).networking.register_socket( PythonSection.networking.sockets.http('127.0.0.1:%s' % port) ) port += 1 configurations.append( # We give alias for configuration to prevent clashes. section.as_configuration(alias=alias)) return configurations
Configure uWSGI. This returns several configuration objects, which will be used to spawn several uWSGI processes. Applications are on 127.0.0.1 on ports starting from 8000.
entailment
def headers_raw_to_dict(headers_raw): r""" Convert raw headers (single multi-line bytestring) to a dictionary. For example: >>> from copyheaders import headers_raw_to_dict >>> headers_raw_to_dict(b"Content-type: text/html\n\rAccept: gzip\n\n") # doctest: +SKIP {'Content-type': ['text/html'], 'Accept': ['gzip']} Incorrect input: >>> headers_raw_to_dict(b"Content-typt gzip\n\n") {} >>> Argument is ``None`` (return ``None``): >>> headers_raw_to_dict(None) >>> """ if headers_raw is None: return None headers = headers_raw.splitlines() headers_tuples = [header.split(b':', 1) for header in headers] result_dict = {} for header_item in headers_tuples: if not len(header_item) == 2: continue item_key = header_item[0].strip() item_value = header_item[1].strip() result_dict[item_key] = item_value return result_dict
r""" Convert raw headers (single multi-line bytestring) to a dictionary. For example: >>> from copyheaders import headers_raw_to_dict >>> headers_raw_to_dict(b"Content-type: text/html\n\rAccept: gzip\n\n") # doctest: +SKIP {'Content-type': ['text/html'], 'Accept': ['gzip']} Incorrect input: >>> headers_raw_to_dict(b"Content-typt gzip\n\n") {} >>> Argument is ``None`` (return ``None``): >>> headers_raw_to_dict(None) >>>
entailment
def log_into(self, target, before_priv_drop=True): """Simple file or UDP logging. .. note:: This doesn't require any Logger plugin and can be used if no log routing is required. :param str|unicode target: Filepath or UDP address. :param bool before_priv_drop: Whether to log data before or after privileges drop. """ command = 'logto' if not before_priv_drop: command += '2' self._set(command, target) return self._section
Simple file or UDP logging. .. note:: This doesn't require any Logger plugin and can be used if no log routing is required. :param str|unicode target: Filepath or UDP address. :param bool before_priv_drop: Whether to log data before or after privileges drop.
entailment
def set_file_params( self, reopen_on_reload=None, trucate_on_statup=None, max_size=None, rotation_fname=None, touch_reopen=None, touch_rotate=None, owner=None, mode=None): """Set various parameters related to file logging. :param bool reopen_on_reload: Reopen log after reload. :param bool trucate_on_statup: Truncate log on startup. :param int max_size: Set maximum logfile size in bytes after which log should be rotated. :param str|unicode rotation_fname: Set log file name after rotation. :param str|unicode|list touch_reopen: Trigger log reopen if the specified file is modified/touched. .. note:: This can be set to a file touched by ``postrotate`` script of ``logrotate`` to implement rotation. :param str|unicode|list touch_rotate: Trigger log rotation if the specified file is modified/touched. :param str|unicode owner: Set owner chown() for logs. :param str|unicode mode: Set mode chmod() for logs. """ self._set('log-reopen', reopen_on_reload, cast=bool) self._set('log-truncate', trucate_on_statup, cast=bool) self._set('log-maxsize', max_size) self._set('log-backupname', rotation_fname) self._set('touch-logreopen', touch_reopen, multi=True) self._set('touch-logrotate', touch_rotate, multi=True) self._set('logfile-chown', owner) self._set('logfile-chmod', mode) return self._section
Set various parameters related to file logging. :param bool reopen_on_reload: Reopen log after reload. :param bool trucate_on_statup: Truncate log on startup. :param int max_size: Set maximum logfile size in bytes after which log should be rotated. :param str|unicode rotation_fname: Set log file name after rotation. :param str|unicode|list touch_reopen: Trigger log reopen if the specified file is modified/touched. .. note:: This can be set to a file touched by ``postrotate`` script of ``logrotate`` to implement rotation. :param str|unicode|list touch_rotate: Trigger log rotation if the specified file is modified/touched. :param str|unicode owner: Set owner chown() for logs. :param str|unicode mode: Set mode chmod() for logs.
entailment
def set_filters(self, include=None, exclude=None, write_errors=None, write_errors_tolerance=None, sigpipe=None): """Set various log data filters. :param str|unicode|list include: Show only log lines matching the specified regexp. .. note:: Requires enabled PCRE support. :param str|unicode|list exclude: Do not show log lines matching the specified regexp. .. note:: Requires enabled PCRE support. :param bool write_errors: Log (annoying) write()/writev() errors. Default: ``True``. .. note:: If both this and ``sigpipe`` set to ``False``, it's the same as setting ``write-errors-exception-only`` uWSGI option. :param int write_errors_tolerance: Set the maximum number of allowed write errors before exception is raised. Default: no tolerance. .. note:: Available for Python, Perl, PHP. :param bool sigpipe: Log (annoying) SIGPIPE. Default: ``True``. .. note:: If both this and ``write_errors`` set to ``False``, it's the same as setting ``write-errors-exception-only`` uWSGI option. """ if write_errors is not None: self._set('ignore-write-errors', not write_errors, cast=bool) if sigpipe is not None: self._set('ignore-sigpipe', not sigpipe, cast=bool) self._set('write-errors-tolerance', write_errors_tolerance) for line in listify(include): self._set('log-filter', line, multi=True) for line in listify(exclude): self._set('log-drain', line, multi=True) return self._section
Set various log data filters. :param str|unicode|list include: Show only log lines matching the specified regexp. .. note:: Requires enabled PCRE support. :param str|unicode|list exclude: Do not show log lines matching the specified regexp. .. note:: Requires enabled PCRE support. :param bool write_errors: Log (annoying) write()/writev() errors. Default: ``True``. .. note:: If both this and ``sigpipe`` set to ``False``, it's the same as setting ``write-errors-exception-only`` uWSGI option. :param int write_errors_tolerance: Set the maximum number of allowed write errors before exception is raised. Default: no tolerance. .. note:: Available for Python, Perl, PHP. :param bool sigpipe: Log (annoying) SIGPIPE. Default: ``True``. .. note:: If both this and ``write_errors`` set to ``False``, it's the same as setting ``write-errors-exception-only`` uWSGI option.
entailment
def set_requests_filters( self, slower=None, bigger=None, status_4xx=None, status_5xx=None, no_body=None, sendfile=None, io_errors=None): """Set various log data filters. :param int slower: Log requests slower than the specified number of milliseconds. :param int bigger: Log requests bigger than the specified size in bytes. :param status_4xx: Log requests with a 4xx response. :param status_5xx: Log requests with a 5xx response. :param bool no_body: Log responses without body. :param bool sendfile: Log sendfile requests. :param bool io_errors: Log requests with io errors. """ self._set('log-slow', slower) self._set('log-big', bigger) self._set('log-4xx', status_4xx, cast=bool) self._set('log-5xx', status_5xx, cast=bool) self._set('log-zero', no_body, cast=bool) self._set('log-sendfile', sendfile, cast=bool) self._set('log-ioerror', io_errors, cast=bool) return self._section
Set various log data filters. :param int slower: Log requests slower than the specified number of milliseconds. :param int bigger: Log requests bigger than the specified size in bytes. :param status_4xx: Log requests with a 4xx response. :param status_5xx: Log requests with a 5xx response. :param bool no_body: Log responses without body. :param bool sendfile: Log sendfile requests. :param bool io_errors: Log requests with io errors.
entailment
def set_master_logging_params( self, enable=None, dedicate_thread=None, buffer=None, sock_stream=None, sock_stream_requests_only=None): """Sets logging params for delegating logging to master process. :param bool enable: Delegate logging to master process. Delegate the write of the logs to the master process (this will put all of the logging I/O to a single process). Useful for system with advanced I/O schedulers/elevators. :param bool dedicate_thread: Delegate log writing to a thread. As error situations could cause the master to block while writing a log line to a remote server, it may be a good idea to use this option and delegate writes to a secondary thread. :param int buffer: Set the buffer size for the master logger in bytes. Bigger log messages will be truncated. :param bool|tuple sock_stream: Create the master logpipe as SOCK_STREAM. :param bool|tuple sock_stream_requests_only: Create the master requests logpipe as SOCK_STREAM. """ self._set('log-master', enable, cast=bool) self._set('threaded-logger', dedicate_thread, cast=bool) self._set('log-master-bufsize', buffer) self._set('log-master-stream', sock_stream, cast=bool) if sock_stream_requests_only: self._set('log-master-req-stream', sock_stream_requests_only, cast=bool) return self._section
Sets logging params for delegating logging to master process. :param bool enable: Delegate logging to master process. Delegate the write of the logs to the master process (this will put all of the logging I/O to a single process). Useful for system with advanced I/O schedulers/elevators. :param bool dedicate_thread: Delegate log writing to a thread. As error situations could cause the master to block while writing a log line to a remote server, it may be a good idea to use this option and delegate writes to a secondary thread. :param int buffer: Set the buffer size for the master logger in bytes. Bigger log messages will be truncated. :param bool|tuple sock_stream: Create the master logpipe as SOCK_STREAM. :param bool|tuple sock_stream_requests_only: Create the master requests logpipe as SOCK_STREAM.
entailment
def add_logger(self, logger, requests_only=False, for_single_worker=False): """Set/add a common logger or a request requests only. :param str|unicode|list|Logger|list[Logger] logger: :param bool requests_only: Logger used only for requests information messages. :param bool for_single_worker: Logger to be used in single-worker setup. """ if for_single_worker: command = 'worker-logger-req' if requests_only else 'worker-logger' else: command = 'req-logger' if requests_only else 'logger' for logger in listify(logger): self._set(command, logger, multi=True) return self._section
Set/add a common logger or a request requests only. :param str|unicode|list|Logger|list[Logger] logger: :param bool requests_only: Logger used only for requests information messages. :param bool for_single_worker: Logger to be used in single-worker setup.
entailment
def add_logger_route(self, logger, matcher, requests_only=False): """Log to the specified named logger if regexp applied on log item matches. :param str|unicode|list|Logger|list[Logger] logger: Logger to associate route with. :param str|unicode matcher: Regular expression to apply to log item. :param bool requests_only: Matching should be used only for requests information messages. """ command = 'log-req-route' if requests_only else 'log-route' for logger in listify(logger): self._set(command, '%s %s' % (logger, matcher), multi=True) return self._section
Log to the specified named logger if regexp applied on log item matches. :param str|unicode|list|Logger|list[Logger] logger: Logger to associate route with. :param str|unicode matcher: Regular expression to apply to log item. :param bool requests_only: Matching should be used only for requests information messages.
entailment
def add_logger_encoder(self, encoder, logger=None, requests_only=False, for_single_worker=False): """Add an item in the log encoder or request encoder chain. * http://uwsgi-docs.readthedocs.io/en/latest/LogEncoders.html .. note:: Encoders automatically enable master log handling (see ``.set_master_logging_params()``). .. note:: For best performance consider allocating a thread for log sending with ``dedicate_thread``. :param str|unicode|list|Encoder encoder: Encoder (or a list) to add into processing. :param str|unicode|Logger logger: Logger apply associate encoders to. :param bool requests_only: Encoder to be used only for requests information messages. :param bool for_single_worker: Encoder to be used in single-worker setup. """ if for_single_worker: command = 'worker-log-req-encoder' if requests_only else 'worker-log-encoder' else: command = 'log-req-encoder' if requests_only else 'log-encoder' for encoder in listify(encoder): value = '%s' % encoder if logger: if isinstance(logger, Logger): logger = logger.alias value += ':%s' % logger self._set(command, value, multi=True) return self._section
Add an item in the log encoder or request encoder chain. * http://uwsgi-docs.readthedocs.io/en/latest/LogEncoders.html .. note:: Encoders automatically enable master log handling (see ``.set_master_logging_params()``). .. note:: For best performance consider allocating a thread for log sending with ``dedicate_thread``. :param str|unicode|list|Encoder encoder: Encoder (or a list) to add into processing. :param str|unicode|Logger logger: Logger apply associate encoders to. :param bool requests_only: Encoder to be used only for requests information messages. :param bool for_single_worker: Encoder to be used in single-worker setup.
entailment
def _compiler_type(): """ Gets the compiler type from distutils. On Windows with MSVC it will be "msvc". On macOS and linux it is "unix". Borrowed from https://github.com/pyca/cryptography/blob\ /05b34433fccdc2fec0bb014c3668068169d769fd/src/_cffi_src/utils.py#L78 """ dist = distutils.dist.Distribution() dist.parse_config_files() cmd = dist.get_command_obj('build') cmd.ensure_finalized() compiler = distutils.ccompiler.new_compiler(compiler=cmd.compiler) return compiler.compiler_type
Gets the compiler type from distutils. On Windows with MSVC it will be "msvc". On macOS and linux it is "unix". Borrowed from https://github.com/pyca/cryptography/blob\ /05b34433fccdc2fec0bb014c3668068169d769fd/src/_cffi_src/utils.py#L78
entailment
def set_metrics_params(self, enable=None, store_dir=None, restore=None, no_cores=None): """Sets basic Metrics subsystem params. uWSGI metrics subsystem allows you to manage "numbers" from your apps. When enabled, the subsystem configures a vast amount of metrics (like requests per-core, memory usage, etc) but, in addition to this, you can configure your own metrics, such as the number of active users or, say, hits of a particular URL, as well as the memory consumption of your app or the whole server. * http://uwsgi.readthedocs.io/en/latest/Metrics.html * SNMP Integration - http://uwsgi.readthedocs.io/en/latest/Metrics.html#snmp-integration :param bool enable: Enables the subsystem. :param str|unicode store_dir: Directory to store metrics. The metrics subsystem can expose all of its metrics in the form of text files in a directory. The content of each file is the value of the metric (updated in real time). .. note:: Placeholders can be used to build paths, e.g.: {project_runtime_dir}/metrics/ See ``Section.project_name`` and ``Section.runtime_dir``. :param bool restore: Restore previous metrics from ``store_dir``. When you restart a uWSGI instance, all of its metrics are reset. Use the option to force the metric subsystem to read-back the values from the metric directory before starting to collect values. :param bool no_cores: Disable generation of cores-related metrics. """ self._set('enable-metrics', enable, cast=bool) self._set('metrics-dir', self._section.replace_placeholders(store_dir)) self._set('metrics-dir-restore', restore, cast=bool) self._set('metrics-no-cores', no_cores, cast=bool) return self._section
Sets basic Metrics subsystem params. uWSGI metrics subsystem allows you to manage "numbers" from your apps. When enabled, the subsystem configures a vast amount of metrics (like requests per-core, memory usage, etc) but, in addition to this, you can configure your own metrics, such as the number of active users or, say, hits of a particular URL, as well as the memory consumption of your app or the whole server. * http://uwsgi.readthedocs.io/en/latest/Metrics.html * SNMP Integration - http://uwsgi.readthedocs.io/en/latest/Metrics.html#snmp-integration :param bool enable: Enables the subsystem. :param str|unicode store_dir: Directory to store metrics. The metrics subsystem can expose all of its metrics in the form of text files in a directory. The content of each file is the value of the metric (updated in real time). .. note:: Placeholders can be used to build paths, e.g.: {project_runtime_dir}/metrics/ See ``Section.project_name`` and ``Section.runtime_dir``. :param bool restore: Restore previous metrics from ``store_dir``. When you restart a uWSGI instance, all of its metrics are reset. Use the option to force the metric subsystem to read-back the values from the metric directory before starting to collect values. :param bool no_cores: Disable generation of cores-related metrics.
entailment
def set_metrics_threshold(self, name, value, check_interval=None, reset_to=None, alarm=None, alarm_message=None): """Sets metric threshold parameters. :param str|unicode name: Metric name. :param int value: Threshold value. :param int reset_to: Reset value to when threshold is reached. :param int check_interval: Threshold check interval in seconds. :param str|unicode|AlarmType alarm: Alarm to trigger when threshold is reached. :param str|unicode alarm_message: Message to pass to alarm. If not set metrics name is passed. """ if alarm is not None and isinstance(alarm, AlarmType): self._section.alarms.register_alarm(alarm) alarm = alarm.alias value = KeyValue( locals(), aliases={ 'name': 'key', 'reset_to': 'reset', 'check_interval': 'rate', 'alarm_message': 'msg', }, ) self._set('metric-threshold', value, multi=True) return self._section
Sets metric threshold parameters. :param str|unicode name: Metric name. :param int value: Threshold value. :param int reset_to: Reset value to when threshold is reached. :param int check_interval: Threshold check interval in seconds. :param str|unicode|AlarmType alarm: Alarm to trigger when threshold is reached. :param str|unicode alarm_message: Message to pass to alarm. If not set metrics name is passed.
entailment
def set_stats_params( self, address=None, enable_http=None, minify=None, no_cores=None, no_metrics=None, push_interval=None): """Enables stats server on the specified address. * http://uwsgi.readthedocs.io/en/latest/StatsServer.html :param str|unicode address: Address/socket to make stats available on. Examples: * 127.0.0.1:1717 * /tmp/statsock * :5050 :param bool enable_http: Server stats over HTTP. Prefixes stats server json output with http headers. :param bool minify: Minify statistics json output. :param bool no_cores: Disable generation of cores-related stats. :param bool no_metrics: Do not include metrics in stats output. :param int push_interval: Set the default frequency of stats pushers in seconds/ """ self._set('stats-server', address) self._set('stats-http', enable_http, cast=bool) self._set('stats-minified', minify, cast=bool) self._set('stats-no-cores', no_cores, cast=bool) self._set('stats-no-metrics', no_metrics, cast=bool) self._set('stats-pusher-default-freq', push_interval) return self._section
Enables stats server on the specified address. * http://uwsgi.readthedocs.io/en/latest/StatsServer.html :param str|unicode address: Address/socket to make stats available on. Examples: * 127.0.0.1:1717 * /tmp/statsock * :5050 :param bool enable_http: Server stats over HTTP. Prefixes stats server json output with http headers. :param bool minify: Minify statistics json output. :param bool no_cores: Disable generation of cores-related stats. :param bool no_metrics: Do not include metrics in stats output. :param int push_interval: Set the default frequency of stats pushers in seconds/
entailment
def register_stats_pusher(self, pusher): """Registers a pusher to be used for pushing statistics to various remotes/locals. :param Pusher|list[Pusher] pusher: """ for pusher in listify(pusher): self._set('stats-push', pusher, multi=True) return self._section
Registers a pusher to be used for pushing statistics to various remotes/locals. :param Pusher|list[Pusher] pusher:
entailment
def enable_snmp(self, address, community_string): """Enables SNMP. uWSGI server embeds a tiny SNMP server that you can use to integrate your web apps with your monitoring infrastructure. * http://uwsgi.readthedocs.io/en/latest/SNMP.html .. note:: SNMP server is started in the master process after dropping the privileges. If you want it to listen on a privileged port, you can either use Capabilities on Linux, or use the ``as-root`` option to run the master process as root. :param str|unicode address: UDP address to bind to. Examples: * 192.168.1.1:2222 :param str|unicode community_string: SNMP instance identifier to address it. """ self._set('snmp', address) self._set('snmp-community', community_string) return self._section
Enables SNMP. uWSGI server embeds a tiny SNMP server that you can use to integrate your web apps with your monitoring infrastructure. * http://uwsgi.readthedocs.io/en/latest/SNMP.html .. note:: SNMP server is started in the master process after dropping the privileges. If you want it to listen on a privileged port, you can either use Capabilities on Linux, or use the ``as-root`` option to run the master process as root. :param str|unicode address: UDP address to bind to. Examples: * 192.168.1.1:2222 :param str|unicode community_string: SNMP instance identifier to address it.
entailment
def mount(self, mountpoint, app, into_worker=False): """Load application under mountpoint. Example: * .mount('', 'app0.py') -- Root URL part * .mount('/app1', 'app1.py') -- URL part * .mount('/pinax/here', '/var/www/pinax/deploy/pinax.wsgi') * .mount('the_app3', 'app3.py') -- Variable value: application alias (can be set by ``UWSGI_APPID``) * .mount('example.com', 'app2.py') -- Variable value: Hostname (variable set in nginx) * http://uwsgi-docs.readthedocs.io/en/latest/Nginx.html#hosting-multiple-apps-in-the-same-process-aka-managing-script-name-and-path-info :param str|unicode mountpoint: URL part, or variable value. .. note:: In case of URL part you may also want to set ``manage_script_name`` basic param to ``True``. .. warning:: In case of URL part a trailing slash may case problems in some cases (e.g. with Django based projects). :param str|unicode app: App module/file. :param bool into_worker: Load application under mountpoint in the specified worker or after workers spawn. """ # todo check worker mount -- uwsgi_init_worker_mount_app() expects worker:// self._set('worker-mount' if into_worker else 'mount', '%s=%s' % (mountpoint, app), multi=True) return self._section
Load application under mountpoint. Example: * .mount('', 'app0.py') -- Root URL part * .mount('/app1', 'app1.py') -- URL part * .mount('/pinax/here', '/var/www/pinax/deploy/pinax.wsgi') * .mount('the_app3', 'app3.py') -- Variable value: application alias (can be set by ``UWSGI_APPID``) * .mount('example.com', 'app2.py') -- Variable value: Hostname (variable set in nginx) * http://uwsgi-docs.readthedocs.io/en/latest/Nginx.html#hosting-multiple-apps-in-the-same-process-aka-managing-script-name-and-path-info :param str|unicode mountpoint: URL part, or variable value. .. note:: In case of URL part you may also want to set ``manage_script_name`` basic param to ``True``. .. warning:: In case of URL part a trailing slash may case problems in some cases (e.g. with Django based projects). :param str|unicode app: App module/file. :param bool into_worker: Load application under mountpoint in the specified worker or after workers spawn.
entailment
def switch_into_lazy_mode(self, affect_master=None): """Load apps in workers instead of master. This option may have memory usage implications as Copy-on-Write semantics can not be used. .. note:: Consider using ``touch_chain_reload`` option in ``workers`` basic params for lazy apps reloading. :param bool affect_master: If **True** only workers will be reloaded by uWSGI's reload signals; the master will remain alive. .. warning:: uWSGI configuration changes are not picked up on reload by the master. """ self._set('lazy' if affect_master else 'lazy-apps', True, cast=bool) return self._section
Load apps in workers instead of master. This option may have memory usage implications as Copy-on-Write semantics can not be used. .. note:: Consider using ``touch_chain_reload`` option in ``workers`` basic params for lazy apps reloading. :param bool affect_master: If **True** only workers will be reloaded by uWSGI's reload signals; the master will remain alive. .. warning:: uWSGI configuration changes are not picked up on reload by the master.
entailment
def set_basic_params( self, workers=None, zerg_server=None, fallback_node=None, concurrent_events=None, cheap_mode=None, stats_server=None, quiet=None, buffer_size=None, keepalive=None, resubscribe_addresses=None): """ :param int workers: Number of worker processes to spawn. :param str|unicode zerg_server: Attach the router to a zerg server. :param str|unicode fallback_node: Fallback to the specified node in case of error. :param int concurrent_events: Set the maximum number of concurrent events router can manage. Default: system dependent. :param bool cheap_mode: Enables cheap mode. When the router is in cheap mode, it will not respond to requests until a node is available. This means that when there are no nodes subscribed, only your local app (if any) will respond. When all of the nodes go down, the router will return in cheap mode. :param str|unicode stats_server: Router stats server address to run at. :param bool quiet: Do not report failed connections to instances. :param int buffer_size: Set internal buffer size in bytes. Default: page size. :param int keepalive: Allows holding the connection open even if the request has a body. * http://uwsgi.readthedocs.io/en/latest/HTTP.html#http-keep-alive .. note:: See http11 socket type for an alternative. :param str|unicode|list[str|unicode] resubscribe_addresses: Forward subscriptions to the specified subscription server. """ super(RouterHttp, self).set_basic_params(**filter_locals(locals(), drop=[ 'keepalive', 'resubscribe_addresses', ])) self._set_aliased('keepalive', keepalive) self._set_aliased('resubscribe', resubscribe_addresses, multi=True) return self
:param int workers: Number of worker processes to spawn. :param str|unicode zerg_server: Attach the router to a zerg server. :param str|unicode fallback_node: Fallback to the specified node in case of error. :param int concurrent_events: Set the maximum number of concurrent events router can manage. Default: system dependent. :param bool cheap_mode: Enables cheap mode. When the router is in cheap mode, it will not respond to requests until a node is available. This means that when there are no nodes subscribed, only your local app (if any) will respond. When all of the nodes go down, the router will return in cheap mode. :param str|unicode stats_server: Router stats server address to run at. :param bool quiet: Do not report failed connections to instances. :param int buffer_size: Set internal buffer size in bytes. Default: page size. :param int keepalive: Allows holding the connection open even if the request has a body. * http://uwsgi.readthedocs.io/en/latest/HTTP.html#http-keep-alive .. note:: See http11 socket type for an alternative. :param str|unicode|list[str|unicode] resubscribe_addresses: Forward subscriptions to the specified subscription server.
entailment
def set_connections_params( self, harakiri=None, timeout_socket=None, retry_delay=None, timeout_headers=None, timeout_backend=None): """Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Used to set the SPDY timeout. This is the maximum amount of inactivity after the SPDY connection is closed. Default: 60. :param int retry_delay: Retry connections to dead static nodes after the specified amount of seconds. Default: 30. :param int timeout_headers: Defines the timeout (seconds) while waiting for http headers. Default: `socket_timeout`. :param int timeout_backend: Defines the timeout (seconds) when connecting to backend instances. Default: `socket_timeout`. """ super(RouterHttp, self).set_connections_params( **filter_locals(locals(), ['timeout_headers', 'timeout_backend'])) self._set_aliased('headers-timeout', timeout_headers) self._set_aliased('connect-timeout', timeout_backend) return self
Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Used to set the SPDY timeout. This is the maximum amount of inactivity after the SPDY connection is closed. Default: 60. :param int retry_delay: Retry connections to dead static nodes after the specified amount of seconds. Default: 30. :param int timeout_headers: Defines the timeout (seconds) while waiting for http headers. Default: `socket_timeout`. :param int timeout_backend: Defines the timeout (seconds) when connecting to backend instances. Default: `socket_timeout`.
entailment