text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 :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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def errorprint():
"""Print out descriptions from ConfigurationError.""" |
try:
yield
except ConfigurationError as e:
click.secho('%s' % e, err=True, fg='red')
sys.exit(1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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,
)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_manage_params( self, chunked_input=None, chunked_output=None, gzip=None, websockets=None, source_method=None, rtsp=None, proxy_protocol=None):
"""Allows enabling various automatic management mechanics. * http://uwsgi.readthedocs.io/en/latest/Changelog-1.9.html#http-router-keepalive-auto-chunking-auto-gzip-and-transparent-websockets :param bool chunked_input: Automatically detect chunked input requests and put the session in raw mode. :param bool chunked_output: Automatically transform output to chunked encoding during HTTP 1.1 keepalive (if needed). :param bool gzip: Automatically gzip content if uWSGI-Encoding header is set to gzip, but content size (Content-Length/Transfer-Encoding) and Content-Encoding are not specified. :param bool websockets: Automatically detect websockets connections and put the session in raw mode. :param bool source_method: Automatically put the session in raw mode for `SOURCE` HTTP method. * http://uwsgi.readthedocs.io/en/latest/Changelog-2.0.5.html#icecast2-protocol-helpers :param bool rtsp: Allow the HTTP router to detect RTSP and chunked requests automatically. :param bool proxy_protocol: Allows the HTTP router to manage PROXY1 protocol requests, such as those made by Haproxy or Amazon Elastic Load Balancer (ELB). """ |
self._set_aliased('chunked-input', chunked_input, cast=bool)
self._set_aliased('auto-chunked', chunked_output, cast=bool)
self._set_aliased('auto-gzip', gzip, cast=bool)
self._set_aliased('websockets', websockets, cast=bool)
self._set_aliased('manage-source', source_method, cast=bool)
self._set_aliased('manage-rtsp', rtsp, cast=bool)
self._set_aliased('enable-proxy-protocol', proxy_protocol, cast=bool)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_owner_params(self, uid=None, gid=None):
"""Drop http router privileges to specified user and 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. """ |
self._set_aliased('uid', uid)
self._set_aliased('gid', gid)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_postbuffering_params(self, size=None, store_dir=None):
"""Sets buffering params. Web-proxies like nginx are "buffered", so they wait til the whole request (and its body) has been read, and then it sends it to the backends. :param int size: The size (in bytes) of the request body after which the body will be stored to disk (as a temporary file) instead of memory. :param str|unicode store_dir: Put buffered files to the specified directory. Default: TMPDIR, /tmp/ """ |
self._set_aliased('post-buffering', size)
self._set_aliased('post-buffering-dir', store_dir)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_window_params(self, cols=None, rows=None):
"""Sets pty window params. :param int cols: :param int rows: """ |
self._set_aliased('cols', cols)
self._set_aliased('rows', rows)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_route(self, src, dst, gateway):
"""Adds a routing rule to the tuntap router. :param str|unicode src: Source/mask. :param str|unicode dst: Destination/mask. :param str|unicode gateway: Gateway address. """ |
self._set_aliased('router-route', ' '.join((src, dst, gateway)), multi=True)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def device_add_rule(self, direction, action, src, dst, target=None):
"""Adds a tuntap device rule. To be used in a vassal. :param str|unicode direction: Direction: * in * out. :param str|unicode action: Action: * allow * deny * route * gateway. :param str|unicode src: Source/mask. :param str|unicode dst: Destination/mask. :param str|unicode target: Depends on action. * Route / Gateway: Accept addr:port """ |
value = [direction, src, dst, action]
if target:
value.append(target)
self._set_aliased('device-rule', ' '.join(value), multi=True)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_firewall_rule(self, direction, action, src=None, dst=None):
"""Adds a firewall rule to the router. The TunTap router includes a very simple firewall for governing vassal's traffic. The first matching rule stops the chain, if no rule applies, the policy is "allow". :param str|unicode direction: Direction: * in * out :param str|unicode action: Action: * allow * deny :param str|unicode src: Source/mask. :param str|unicode dst: Destination/mask """ |
value = [action]
if src:
value.extend((src, dst))
self._set_aliased('router-firewall-%s' % direction.lower(), ' '.join(value), multi=True)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_uwsgi(configurator_func):
"""Allows configuring uWSGI using Configuration objects returned by the given configuration function. .. code-block: python # In configuration module, e.g `uwsgicfg.py` from uwsgiconf.config import configure_uwsgi configure_uwsgi(get_configurations) :param callable configurator_func: Function which return a list on configurations. :rtype: list|None :returns: A list with detected configurations or ``None`` if called from within uWSGI (e.g. when trying to load WSGI application). :raises ConfigurationError: """ |
from .settings import ENV_CONF_READY, ENV_CONF_ALIAS, CONFIGS_MODULE_ATTR
if os.environ.get(ENV_CONF_READY):
# This call is from uWSGI trying to load an application.
# We prevent unnecessary configuration
# for setups where application is located in the same
# file as configuration.
del os.environ[ENV_CONF_READY] # Drop it support consecutive reconfiguration.
return None
configurations = configurator_func()
registry = OrderedDict()
if not isinstance(configurations, (list, tuple)):
configurations = [configurations]
for conf_candidate in configurations:
if not isinstance(conf_candidate, (Section, Configuration)):
continue
if isinstance(conf_candidate, Section):
conf_candidate = conf_candidate.as_configuration()
alias = conf_candidate.alias
if alias in registry:
raise ConfigurationError(
"Configuration alias '%s' clashes with another configuration. "
"Please change the alias." % alias)
registry[alias] = conf_candidate
if not registry:
raise ConfigurationError(
"Callable passed into 'configure_uwsgi' must return 'Section' or 'Configuration' objects.")
# Try to get configuration alias from env with fall back
# to --conf argument (as passed by UwsgiRunner.spawn()).
target_alias = os.environ.get(ENV_CONF_ALIAS)
if not target_alias:
last = sys.argv[-2:]
if len(last) == 2 and last[0] == '--conf':
target_alias = last[1]
conf_list = list(registry.values())
if target_alias:
# This call is [presumably] from uWSGI configuration read procedure.
config = registry.get(target_alias)
if config:
section = config.sections[0] # type: Section
# Set ready marker which is checked above.
os.environ[ENV_CONF_READY] = '1'
# Placeholder for runtime introspection.
section.set_placeholder('config-alias', target_alias)
# Print out
config.print_ini()
else:
# This call is from module containing uWSGI configurations.
import inspect
# Set module attribute automatically.
config_module = inspect.currentframe().f_back
config_module.f_locals[CONFIGS_MODULE_ATTR] = conf_list
return conf_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_stamp(self):
"""Prints out a stamp containing useful information, such as what and when has generated this configuration. """ |
from . import VERSION
print_out = partial(self.print_out, format_options='red')
print_out('This configuration was automatically generated using')
print_out('uwsgiconf v%s on %s' % ('.'.join(map(str, VERSION)), datetime.now().isoformat(' ')))
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_out(self, value, indent=None, format_options=None, asap=False):
"""Prints out the given value. :param value: :param str|unicode indent: :param dict|str|unicode format_options: text color :param bool asap: Print as soon as possible. """ |
if indent is None:
indent = '> '
text = indent + str(value)
if format_options is None:
format_options = 'gray'
if self._style_prints and format_options:
if not isinstance(format_options, dict):
format_options = {'color_fg': format_options}
text = format_print_text(text, **format_options)
command = 'iprint' if asap else 'print'
self._set(command, text, multi=True)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_variables(self):
"""Prints out magic variables available in config files alongside with their values and descriptions. May be useful for debugging. http://uwsgi-docs.readthedocs.io/en/latest/Configuration.html#magic-variables """ |
print_out = partial(self.print_out, format_options='green')
print_out('===== variables =====')
for var, hint in self.vars.get_descriptions().items():
print_out(' %' + var + ' = ' + var + ' = ' + hint.replace('%', '%%'))
print_out('=====================')
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_plugins_params(self, plugins=None, search_dirs=None, autoload=None, required=False):
"""Sets plugin-related parameters. :param list|str|unicode|OptionsGroup|list[OptionsGroup] plugins: uWSGI plugins to load :param list|str|unicode search_dirs: Directories to search for uWSGI plugins. :param bool autoload: Try to automatically load plugins when unknown options are found. :param bool required: Load uWSGI plugins and exit on error. """ |
plugins = plugins or []
command = 'need-plugin' if required else 'plugin'
for plugin in listify(plugins):
if plugin not in self._plugins:
self._set(command, plugin, multi=True)
self._plugins.append(plugin)
self._set('plugins-dir', search_dirs, multi=True, priority=0)
self._set('autoload', autoload, cast=bool)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_fallback(self, target):
"""Sets a fallback configuration for section. Re-exec uWSGI with the specified config when exit code is 1. :param str|unicode|Section target: File path or Section to include. """ |
if isinstance(target, Section):
target = ':' + target.name
self._set('fallback-config', target)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_placeholder(self, key, value):
"""Placeholders are custom magic variables defined during configuration time. .. note:: These are accessible, like any uWSGI option, in your application code via ``.runtime.environ.uwsgi_env.config``. :param str|unicode key: :param str|unicode value: """ |
self._set('set-placeholder', '%s=%s' % (key, value), multi=True)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def include(self, target):
"""Includes target contents into config. :param str|unicode|Section|list target: File path or Section to include. """ |
for target_ in listify(target):
if isinstance(target_, Section):
target_ = ':' + target_.name
self._set('ini', target_, multi=True)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def derive_from(cls, section, name=None):
"""Creates a new section based on the given. :param Section section: Section to derive from, :param str|unicode name: New section name. :rtype: Section """ |
new_section = deepcopy(section)
if name:
new_section.name = name
return new_section |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_sections(cls, sections):
"""Validates sections types and uniqueness.""" |
names = []
for section in sections:
if not hasattr(section, 'name'):
raise ConfigurationError('`sections` attribute requires a list of Section')
name = section.name
if name in names:
raise ConfigurationError('`%s` section name must be unique' % name)
names.append(name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format(self, do_print=False, stamp=True):
"""Applies formatting to configuration. *Currently formats to .ini* :param bool do_print: Whether to print out formatted config. :param bool stamp: Whether to add stamp data to the first configuration section. :rtype: str|unicode """ |
if stamp and self.sections:
self.sections[0].print_stamp()
formatted = IniFormatter(self.sections).format()
if do_print:
print(formatted)
return formatted |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tofile(self, filepath=None):
"""Saves configuration into a file and returns its path. Convenience method. :param str|unicode filepath: Filepath to save configuration into. If not provided a temporary file will be automatically generated. :rtype: str|unicode """ |
if filepath is None:
with NamedTemporaryFile(prefix='%s_' % self.alias, suffix='.ini', delete=False) as f:
filepath = f.name
else:
filepath = os.path.abspath(filepath)
if os.path.isdir(filepath):
filepath = os.path.join(filepath, '%s.ini' % self.alias)
with open(filepath, 'w') as target_file:
target_file.write(self.format())
target_file.flush()
return filepath |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_name(self, version=AUTO):
"""Returns plugin name.""" |
name = 'python'
if version:
if version is AUTO:
version = sys.version_info[0]
if version == 2:
version = ''
name = '%s%s' % (name, version)
self.name = name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_app_args(self, *args):
"""Sets ``sys.argv`` for python apps. Examples: * pyargv="one two three" will set ``sys.argv`` to ``('one', 'two', 'three')``. :param args: """ |
if args:
self._set('pyargv', ' '.join(args))
return self._section |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_wsgi_params(self, module=None, callable_name=None, env_strategy=None):
"""Set wsgi related parameters. :param str|unicode module: * load .wsgi file as the Python application * load a WSGI module as the application. .. note:: The module (sans ``.py``) must be importable, ie. be in ``PYTHONPATH``. Examples: * mypackage.my_wsgi_module -- read from `application` attr of mypackage/my_wsgi_module.py * mypackage.my_wsgi_module:my_app -- read from `my_app` attr of mypackage/my_wsgi_module.py :param str|unicode callable_name: Set WSGI callable name. Default: application. :param str|unicode env_strategy: Strategy for allocating/deallocating the WSGI env, can be: * ``cheat`` - preallocates the env dictionary on uWSGI startup and clears it after each request. Default behaviour for uWSGI <= 2.0.x * ``holy`` - creates and destroys the environ dictionary at each request. Default behaviour for uWSGI >= 2.1 """ |
module = module or ''
if '/' in module:
self._set('wsgi-file', module, condition=module)
else:
self._set('wsgi', module, condition=module)
self._set('callable', callable_name)
self._set('wsgi-env-behaviour', env_strategy)
return self._section |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_autoreload_params(self, scan_interval=None, ignore_modules=None):
"""Sets autoreload related parameters. :param int scan_interval: Seconds. Monitor Python modules' modification times to trigger reload. .. warning:: Use only in development. :param list|st|unicode ignore_modules: Ignore the specified module during auto-reload scan. """ |
self._set('py-auto-reload', scan_interval)
self._set('py-auto-reload-ignore', ignore_modules, multi=True)
return self._section |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_module_alias(self, alias, module_path, after_init=False):
"""Adds an alias for a module. http://uwsgi-docs.readthedocs.io/en/latest/PythonModuleAlias.html :param str|unicode alias: :param str|unicode module_path: :param bool after_init: add a python module alias after uwsgi module initialization """ |
command = 'post-pymodule-alias' if after_init else 'pymodule-alias'
self._set(command, '%s=%s' % (alias, module_path), multi=True)
return self._section |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_module(self, modules, shared=False, into_spooler=False):
"""Imports a python module. :param list|str|unicode modules: :param bool shared: Import a python module in all of the processes. This is done after fork but before request processing. :param bool into_spooler: Import a python module in the spooler. http://uwsgi-docs.readthedocs.io/en/latest/Spooler.html """ |
if all((shared, into_spooler)):
raise ConfigurationError('Unable to set both `shared` and `into_spooler` flags')
if into_spooler:
command = 'spooler-python-import'
else:
command = 'shared-python-import' if shared else 'python-import'
self._set(command, modules, multi=True)
return self._section |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_server_params( self, client_notify_address=None, mountpoints_depth=None, require_vassal=None, tolerance=None, tolerance_inactive=None, key_dot_split=None):
"""Sets subscription server related params. :param str|unicode client_notify_address: Set the notification socket for subscriptions. When you subscribe to a server, you can ask it to "acknowledge" the acceptance of your request. pointing address (Unix socket or UDP), on which your instance will bind and the subscription server will send acknowledgements to. :param int mountpoints_depth: Enable support of mountpoints of certain depth for subscription system. * http://uwsgi-docs.readthedocs.io/en/latest/SubscriptionServer.html#mountpoints-uwsgi-2-1 :param bool require_vassal: Require a vassal field (see ``subscribe``) from each subscription. :param int tolerance: Subscription reclaim tolerance (seconds). :param int tolerance_inactive: Subscription inactivity tolerance (seconds). :param bool key_dot_split: Try to fallback to the next part in (dot based) subscription key. Used, for example, in SNI. """ |
# todo notify-socket (fallback) relation
self._set('subscription-notify-socket', client_notify_address)
self._set('subscription-mountpoint', mountpoints_depth)
self._set('subscription-vassal-required', require_vassal, cast=bool)
self._set('subscription-tolerance', tolerance)
self._set('subscription-tolerance-inactive', tolerance_inactive)
self._set('subscription-dotsplit', key_dot_split, cast=bool)
return self._section |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_server_verification_params( self, digest_algo=None, dir_cert=None, tolerance=None, no_check_uid=None, dir_credentials=None, pass_unix_credentials=None):
"""Sets peer verification params for subscription server. These are for secured subscriptions. :param str|unicode digest_algo: Digest algorithm. Example: SHA1 .. note:: Also requires ``dir_cert`` to be set. :param str|unicode dir_cert: Certificate directory. .. note:: Also requires ``digest_algo`` to be set. :param int tolerance: Maximum tolerance (in seconds) of clock skew for secured subscription system. Default: 24h. :param str|unicode|int|list[str|unicode|int] no_check_uid: Skip signature check for the specified uids when using unix sockets credentials. :param str|unicode|list[str|unicode] dir_credentials: Directories to search for subscriptions key credentials. :param bool pass_unix_credentials: Enable management of SCM_CREDENTIALS in subscriptions UNIX sockets. """ |
if digest_algo and dir_cert:
self._set('subscriptions-sign-check', '%s:%s' % (digest_algo, dir_cert))
self._set('subscriptions-sign-check-tolerance', tolerance)
self._set('subscriptions-sign-skip-uid', no_check_uid, multi=True)
self._set('subscriptions-credentials-check', dir_credentials, multi=True)
self._set('subscriptions-use-credentials', pass_unix_credentials, cast=bool)
return self._section |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_client_params( self, start_unsubscribed=None, clear_on_exit=None, unsubscribe_on_reload=None, announce_interval=None):
"""Sets subscribers related params. :param bool start_unsubscribed: Configure subscriptions but do not send them. .. note:: Useful with master FIFO. :param bool clear_on_exit: Force clear instead of unsubscribe during shutdown. :param bool unsubscribe_on_reload: Force unsubscribe request even during graceful reload. :param int announce_interval: Send subscription announce at the specified interval. Default: 10 master cycles. """ |
self._set('start-unsubscribed', start_unsubscribed, cast=bool)
self._set('subscription-clear-on-shutdown', clear_on_exit, cast=bool)
self._set('unsubscribe-on-graceful-reload', unsubscribe_on_reload, cast=bool)
self._set('subscribe-freq', announce_interval)
return self._section |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subscribe( self, server=None, key=None, address=None, address_vassal=None, balancing_weight=None, balancing_algo=None, modifier=None, signing=None, check_file=None, protocol=None, sni_cert=None, sni_key=None, sni_client_ca=None):
"""Registers a subscription intent. :param str|unicode server: Subscription server address (UDP or UNIX socket). Examples: * 127.0.0.1:7171 :param str|unicode key: Key to subscribe. Generally the domain name (+ optional '/< mountpoint>'). Examples: * mydomain.it/foo * mydomain.it/foo/bar (requires ``mountpoints_depth=2``) * mydomain.it * ubuntu64.local:9090 :param str|unicode|int address: Address to subscribe (the value for the key) or zero-based internal socket number (integer). :param str|unicode address: Vassal node address. :param int balancing_weight: Load balancing value. Default: 1. :param balancing_algo: Load balancing algorithm to use. See ``balancing_algorithms`` .. note:: Since 2.1 :param Modifier modifier: Routing modifier object. See ``.routing.modifiers`` :param list|tuple signing: Signing basics, expects two elements list/tuple: (signing_algorithm, key). Examples: * SHA1:idlessh001 :param str|unicode check_file: If this file exists the subscription packet is sent, otherwise it is skipped. :param str|unicode protocol: the protocol to use, by default it is ``uwsgi``. See ``.networking.socket_types``. .. note:: Since 2.1 :param str|unicode sni_cert: Certificate file to use for SNI proxy management. * http://uwsgi.readthedocs.io/en/latest/SNI.html#subscription-system-and-sni :param str|unicode sni_key: sni_key Key file to use for SNI proxy management. * http://uwsgi.readthedocs.io/en/latest/SNI.html#subscription-system-and-sni :param str|unicode sni_client_ca: Ca file to use for SNI proxy management. * http://uwsgi.readthedocs.io/en/latest/SNI.html#subscription-system-and-sni """ |
# todo params: inactive (inactive slot activation)
if not any((server, key)):
raise ConfigurationError('Subscription requires `server` or `key` to be set.')
address_key = 'addr'
if isinstance(address, int):
address_key = 'socket'
if balancing_algo:
backup = getattr(balancing_algo, 'backup_level', None)
if signing:
signing = ':'.join(signing)
if modifier:
modifier1 = modifier
if modifier.submod:
modifier2 = modifier.submod
rule = KeyValue(
filter_locals(locals(), drop=['address_key', 'modifier']),
aliases={
'address': address_key,
'address_vassal': 'vassal',
'signing': 'sign',
'check_file': 'check',
'balancing_weight': 'weight',
'balancing_algo': 'algo',
'protocol': 'proto',
'sni_cert': 'sni_crt',
'sni_client_ca': 'sni_ca',
},
)
self._set('subscribe2', rule)
return self._section |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_project_dir():
"""Runs up the stack to find the location of manage.py which will be considered a project base path. :rtype: str|unicode """ |
frame = inspect.currentframe()
while True:
frame = frame.f_back
fname = frame.f_globals['__file__']
if os.path.basename(fname) == 'manage.py':
break
return os.path.dirname(fname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_uwsgi(config_section, compile_only=False):
"""Runs uWSGI using the given section configuration. :param Section config_section: :param bool compile_only: Do not run, only compile and output configuration file for run. """ |
config = config_section.as_configuration()
if compile_only:
config.print_ini()
return
config_path = config.tofile()
os.execvp('uwsgi', ['uwsgi', '--ini=%s' % config_path]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spawn(cls, options=None, dir_base=None):
"""Alternative constructor. Creates a mutator and returns section object. :param dict options: :param str|unicode dir_base: :rtype: SectionMutator """ |
from uwsgiconf.utils import ConfModule
options = options or {
'compile': True,
}
dir_base = os.path.abspath(dir_base or find_project_dir())
name_module = ConfModule.default_name
name_project = get_project_name(dir_base)
path_conf = os.path.join(dir_base, name_module)
if os.path.exists(path_conf):
# Read an existing config for further modification of first section.
section = cls._get_section_existing(name_module, name_project)
else:
# Create section on-fly.
section = cls._get_section_new(dir_base)
mutator = cls(
section=section,
dir_base=dir_base,
project_name=name_project,
options=options)
mutator.mutate()
return mutator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_section_new(cls, dir_base):
"""Creates a new section with default settings. :param str|unicode dir_base: :rtype: Section """ |
from uwsgiconf.presets.nice import PythonSection
from django.conf import settings
wsgi_app = settings.WSGI_APPLICATION
path_wsgi, filename, _, = wsgi_app.split('.')
path_wsgi = os.path.join(dir_base, path_wsgi, '%s.py' %filename)
section = PythonSection(
wsgi_module=path_wsgi,
).networking.register_socket(
PythonSection.networking.sockets.http('127.0.0.1:8000')
).main_process.change_dir(dir_base)
return section |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contribute_static(self):
"""Contributes static and media file serving settings to an existing section.""" |
options = self.options
if options['compile'] or not options['use_static_handler']:
return
from django.core.management import call_command
settings = self.settings
statics = self.section.statics
statics.register_static_map(settings.STATIC_URL, settings.STATIC_ROOT)
statics.register_static_map(settings.MEDIA_URL, settings.MEDIA_ROOT)
call_command('collectstatic', clear=True, interactive=False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contribute_error_pages(self):
"""Contributes generic static error massage pages to an existing section.""" |
static_dir = self.settings.STATIC_ROOT
if not static_dir:
# Source static directory is not configured. Use temporary.
import tempfile
static_dir = os.path.join(tempfile.gettempdir(), self.project_name)
self.settings.STATIC_ROOT = static_dir
self.section.routing.set_error_pages(
common_prefix=os.path.join(static_dir, 'uwsgify')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mutate(self):
"""Mutates current section.""" |
section = self.section
project_name = self.project_name
section.project_name = project_name
self.contribute_runtime_dir()
main = section.main_process
main.set_naming_params(prefix='[%s] ' % project_name)
main.set_pid_file(
self.get_pid_filepath(),
before_priv_drop=False, # For vacuum to cleanup properly.
safe=True,
)
section.master_process.set_basic_params(
fifo_file=self.get_fifo_filepath(),
)
# todo maybe autoreload in debug
apps = section.applications
apps.set_basic_params(
manage_script_name=True,
)
self.contribute_error_pages()
self.contribute_static() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, value, mode=None):
"""Sets metric value. :param int|long value: New value. :param str|unicode mode: Update mode. * None - Unconditional update. * max - Sets metric value if it is greater that the current one. * min - Sets metric value if it is less that the current one. :rtype: bool """ |
if mode == 'max':
func = uwsgi.metric_set_max
elif mode == 'min':
func = uwsgi.metric_set_min
else:
func = uwsgi.metric_set
return func(self.name, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_message(cls, signals=True, farms=False, buffer_size=65536, timeout=-1):
"""Block until a mule message is received and return it. This can be called from multiple threads in the same programmed mule. :param bool signals: Whether to manage signals. :param bool farms: Whether to manage farms. :param int buffer_size: :param int timeout: Seconds. :rtype: str|unicode :raises ValueError: If not in a mule. """ |
return decode(uwsgi.mule_get_msg(signals, farms, buffer_size, timeout)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_command_plugins_output(out):
"""Parses ``plugin-list`` command output from uWSGI and returns object containing lists of embedded plugin names. :param str|unicode out: :rtype EmbeddedPlugins: """ |
out = out.split('--- end of plugins list ---')[0]
out = out.partition('plugins ***')[2]
out = out.splitlines()
current_slot = 0
plugins = EmbeddedPlugins([], [])
for line in out:
line = line.strip()
if not line:
continue
if line.startswith('***'):
current_slot += 1
continue
if current_slot is not None:
plugins[current_slot].append(line)
plugins = plugins._replace(request=[plugin.partition(' ')[2] for plugin in plugins.request])
return plugins |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_uwsgi_stub_attrs_diff():
"""Returns attributes difference two elements tuple between real uwsgi module and its stub. Might be of use while describing in stub new uwsgi functions. :return: (uwsgi_only_attrs, stub_only_attrs) :rtype: tuple """ |
try:
import uwsgi
except ImportError:
from uwsgiconf.exceptions import UwsgiconfException
raise UwsgiconfException(
'`uwsgi` module is unavailable. Calling `get_attrs_diff` in such environment makes no sense.')
from . import uwsgi_stub
def get_attrs(src):
return set(attr for attr in dir(src) if not attr.startswith('_'))
attrs_uwsgi = get_attrs(uwsgi)
attrs_stub = get_attrs(uwsgi_stub)
from_uwsgi = sorted(attrs_uwsgi.difference(attrs_stub))
from_stub = sorted(attrs_stub.difference(attrs_uwsgi))
return from_uwsgi, from_stub |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configurations(self):
"""Configurations from uwsgiconf module.""" |
if self._confs is not None:
return self._confs
with output_capturing():
module = self.load(self.fpath)
confs = getattr(module, CONFIGS_MODULE_ATTR)
confs = listify(confs)
self._confs = confs
return confs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(cls, fpath):
"""Loads a module and returns its object. :param str|unicode fpath: :rtype: module """ |
module_name = os.path.splitext(os.path.basename(fpath))[0]
sys.path.insert(0, os.path.dirname(fpath))
try:
module = import_module(module_name)
finally:
sys.path = sys.path[1:]
return module |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_log(self, reopen=False, rotate=False):
"""Allows managing of uWSGI log related stuff :param bool reopen: Reopen log file. Could be required after third party rotation. :param bool rotate: Trigger built-in log rotation. """ |
cmd = b''
if reopen:
cmd += b'l'
if rotate:
cmd += b'L'
return self.send_command(cmd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_reload(self, force=False, workers_only=False, workers_chain=False):
"""Reloads uWSGI master process, workers. :param bool force: Use forced (brutal) reload instead of a graceful one. :param bool workers_only: Reload only workers. :param bool workers_chain: Run chained workers reload (one after another, instead of destroying all of them in bulk). """ |
if workers_chain:
return self.send_command(b'c')
if workers_only:
return self.send_command(b'R' if force else b'r')
return self.send_command(b'R' if force else b'r') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_command(self, cmd):
"""Sends a generic command into FIFO. :param bytes cmd: Command chars to send into FIFO. """ |
if not cmd:
return
with open(self.fifo, 'wb') as f:
f.write(cmd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_env(cls):
"""Prepares current environment and returns Python binary name. This adds some virtualenv friendliness so that we try use uwsgi from it. :rtype: str|unicode """ |
os.environ['PATH'] = cls.get_env_path()
return os.path.basename(Finder.python()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spawn(self, filepath, configuration_alias, replace=False):
"""Spawns uWSGI using the given configuration module. :param str|unicode filepath: :param str|unicode configuration_alias: :param bool replace: Whether a new process should replace current one. """ |
# Pass --conf as an argument to have a chance to use
# touch reloading form .py configuration file change.
args = ['uwsgi', '--ini', 'exec://%s %s --conf %s' % (self.binary_python, filepath, configuration_alias)]
if replace:
return os.execvp('uwsgi', args)
return os.spawnvp(os.P_NOWAIT, 'uwsgi', args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, key, default=None, as_int=False, setter=None):
"""Gets a value from the cache. :param str|unicode key: The cache key to get value for. :param default: Value to return if none found in cache. :param bool as_int: Return 64bit number instead of str. :param callable setter: Setter callable to automatically set cache value if not already cached. Required to accept a key and return a value that will be cached. :rtype: str|unicode|int """ |
if as_int:
val = uwsgi.cache_num(key, self.name)
else:
val = decode(uwsgi.cache_get(key, self.name))
if val is None:
if setter is None:
return default
val = setter(key)
if val is None:
return default
self.set(key, val)
return val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, key, value):
"""Sets the specified key value. :param str|unicode key: :param int|str|unicode value: :rtype: bool """ |
return uwsgi.cache_set(key, value, self.timeout, self.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decr(self, key, delta=1):
"""Decrements the specified key value by the specified value. :param str|unicode key: :param int delta: :rtype: bool """ |
return uwsgi.cache_dec(key, delta, self.timeout, self.name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mul(self, key, value=2):
"""Multiplies the specified key value by the specified value. :param str|unicode key: :param int value: :rtype: bool """ |
return uwsgi.cache_mul(key, value, self.timeout, self.name) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.