repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
saltstack/salt
salt/modules/bsd_shadow.py
set_change
def set_change(name, change): ''' Sets the time at which the password expires (in seconds since the UNIX epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on FreeBSD. A value of ``0`` sets the password to never expire. CLI Example: .. code-block:: bash salt '*' shadow.set_change username 1419980400 ''' pre_info = info(name) if change == pre_info['change']: return True if __grains__['kernel'] == 'FreeBSD': cmd = ['pw', 'user', 'mod', name, '-f', change] else: cmd = ['usermod', '-f', change, name] __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['change'] != pre_info['change']: return post_info['change'] == change
python
def set_change(name, change): ''' Sets the time at which the password expires (in seconds since the UNIX epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on FreeBSD. A value of ``0`` sets the password to never expire. CLI Example: .. code-block:: bash salt '*' shadow.set_change username 1419980400 ''' pre_info = info(name) if change == pre_info['change']: return True if __grains__['kernel'] == 'FreeBSD': cmd = ['pw', 'user', 'mod', name, '-f', change] else: cmd = ['usermod', '-f', change, name] __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['change'] != pre_info['change']: return post_info['change'] == change
[ "def", "set_change", "(", "name", ",", "change", ")", ":", "pre_info", "=", "info", "(", "name", ")", "if", "change", "==", "pre_info", "[", "'change'", "]", ":", "return", "True", "if", "__grains__", "[", "'kernel'", "]", "==", "'FreeBSD'", ":", "cmd"...
Sets the time at which the password expires (in seconds since the UNIX epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on FreeBSD. A value of ``0`` sets the password to never expire. CLI Example: .. code-block:: bash salt '*' shadow.set_change username 1419980400
[ "Sets", "the", "time", "at", "which", "the", "password", "expires", "(", "in", "seconds", "since", "the", "UNIX", "epoch", ")", ".", "See", "man", "8", "usermod", "on", "NetBSD", "and", "OpenBSD", "or", "man", "8", "pw", "on", "FreeBSD", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bsd_shadow.py#L106-L130
train
saltstack/salt
salt/modules/bsd_shadow.py
set_expire
def set_expire(name, expire): ''' Sets the time at which the account expires (in seconds since the UNIX epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on FreeBSD. A value of ``0`` sets the account to never expire. CLI Example: .. code-block:: bash salt '*' shadow.set_expire username 1419980400 ''' pre_info = info(name) if expire == pre_info['expire']: return True if __grains__['kernel'] == 'FreeBSD': cmd = ['pw', 'user', 'mod', name, '-e', expire] else: cmd = ['usermod', '-e', expire, name] __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['expire'] != pre_info['expire']: return post_info['expire'] == expire
python
def set_expire(name, expire): ''' Sets the time at which the account expires (in seconds since the UNIX epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on FreeBSD. A value of ``0`` sets the account to never expire. CLI Example: .. code-block:: bash salt '*' shadow.set_expire username 1419980400 ''' pre_info = info(name) if expire == pre_info['expire']: return True if __grains__['kernel'] == 'FreeBSD': cmd = ['pw', 'user', 'mod', name, '-e', expire] else: cmd = ['usermod', '-e', expire, name] __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['expire'] != pre_info['expire']: return post_info['expire'] == expire
[ "def", "set_expire", "(", "name", ",", "expire", ")", ":", "pre_info", "=", "info", "(", "name", ")", "if", "expire", "==", "pre_info", "[", "'expire'", "]", ":", "return", "True", "if", "__grains__", "[", "'kernel'", "]", "==", "'FreeBSD'", ":", "cmd"...
Sets the time at which the account expires (in seconds since the UNIX epoch). See ``man 8 usermod`` on NetBSD and OpenBSD or ``man 8 pw`` on FreeBSD. A value of ``0`` sets the account to never expire. CLI Example: .. code-block:: bash salt '*' shadow.set_expire username 1419980400
[ "Sets", "the", "time", "at", "which", "the", "account", "expires", "(", "in", "seconds", "since", "the", "UNIX", "epoch", ")", ".", "See", "man", "8", "usermod", "on", "NetBSD", "and", "OpenBSD", "or", "man", "8", "pw", "on", "FreeBSD", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bsd_shadow.py#L133-L157
train
saltstack/salt
salt/modules/bsd_shadow.py
set_password
def set_password(name, password): ''' Set the password for a named user. The password must be a properly defined hash. The password hash can be generated with this command: ``python -c "import crypt; print crypt.crypt('password', ciphersalt)"`` .. note:: When constructing the ``ciphersalt`` string, you must escape any dollar signs, to avoid them being interpolated by the shell. ``'password'`` is, of course, the password for which you want to generate a hash. ``ciphersalt`` is a combination of a cipher identifier, an optional number of rounds, and the cryptographic salt. The arrangement and format of these fields depends on the cipher and which flavor of BSD you are using. For more information on this, see the manpage for ``crpyt(3)``. On NetBSD, additional information is available in ``passwd.conf(5)``. It is important to make sure that a supported cipher is used. CLI Example: .. code-block:: bash salt '*' shadow.set_password someuser '$1$UYCIxa628.9qXjpQCjM4a..' ''' if __grains__.get('os', '') == 'FreeBSD': cmd = ['pw', 'user', 'mod', name, '-H', '0'] stdin = password else: cmd = ['usermod', '-p', password, name] stdin = None __salt__['cmd.run'](cmd, stdin=stdin, output_loglevel='quiet', python_shell=False) return info(name)['passwd'] == password
python
def set_password(name, password): ''' Set the password for a named user. The password must be a properly defined hash. The password hash can be generated with this command: ``python -c "import crypt; print crypt.crypt('password', ciphersalt)"`` .. note:: When constructing the ``ciphersalt`` string, you must escape any dollar signs, to avoid them being interpolated by the shell. ``'password'`` is, of course, the password for which you want to generate a hash. ``ciphersalt`` is a combination of a cipher identifier, an optional number of rounds, and the cryptographic salt. The arrangement and format of these fields depends on the cipher and which flavor of BSD you are using. For more information on this, see the manpage for ``crpyt(3)``. On NetBSD, additional information is available in ``passwd.conf(5)``. It is important to make sure that a supported cipher is used. CLI Example: .. code-block:: bash salt '*' shadow.set_password someuser '$1$UYCIxa628.9qXjpQCjM4a..' ''' if __grains__.get('os', '') == 'FreeBSD': cmd = ['pw', 'user', 'mod', name, '-H', '0'] stdin = password else: cmd = ['usermod', '-p', password, name] stdin = None __salt__['cmd.run'](cmd, stdin=stdin, output_loglevel='quiet', python_shell=False) return info(name)['passwd'] == password
[ "def", "set_password", "(", "name", ",", "password", ")", ":", "if", "__grains__", ".", "get", "(", "'os'", ",", "''", ")", "==", "'FreeBSD'", ":", "cmd", "=", "[", "'pw'", ",", "'user'", ",", "'mod'", ",", "name", ",", "'-H'", ",", "'0'", "]", "...
Set the password for a named user. The password must be a properly defined hash. The password hash can be generated with this command: ``python -c "import crypt; print crypt.crypt('password', ciphersalt)"`` .. note:: When constructing the ``ciphersalt`` string, you must escape any dollar signs, to avoid them being interpolated by the shell. ``'password'`` is, of course, the password for which you want to generate a hash. ``ciphersalt`` is a combination of a cipher identifier, an optional number of rounds, and the cryptographic salt. The arrangement and format of these fields depends on the cipher and which flavor of BSD you are using. For more information on this, see the manpage for ``crpyt(3)``. On NetBSD, additional information is available in ``passwd.conf(5)``. It is important to make sure that a supported cipher is used. CLI Example: .. code-block:: bash salt '*' shadow.set_password someuser '$1$UYCIxa628.9qXjpQCjM4a..'
[ "Set", "the", "password", "for", "a", "named", "user", ".", "The", "password", "must", "be", "a", "properly", "defined", "hash", ".", "The", "password", "hash", "can", "be", "generated", "with", "this", "command", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bsd_shadow.py#L178-L216
train
saltstack/salt
salt/netapi/rest_tornado/saltnado_websockets.py
AllEventsHandler.get
def get(self, token): ''' Check the token, returns a 401 if the token is invalid. Else open the websocket connection ''' log.debug('In the websocket get method') self.token = token # close the connection, if not authenticated if not self.application.auth.get_tok(token): log.debug('Refusing websocket connection, bad token!') self.send_error(401) return super(AllEventsHandler, self).get(token)
python
def get(self, token): ''' Check the token, returns a 401 if the token is invalid. Else open the websocket connection ''' log.debug('In the websocket get method') self.token = token # close the connection, if not authenticated if not self.application.auth.get_tok(token): log.debug('Refusing websocket connection, bad token!') self.send_error(401) return super(AllEventsHandler, self).get(token)
[ "def", "get", "(", "self", ",", "token", ")", ":", "log", ".", "debug", "(", "'In the websocket get method'", ")", "self", ".", "token", "=", "token", "# close the connection, if not authenticated", "if", "not", "self", ".", "application", ".", "auth", ".", "g...
Check the token, returns a 401 if the token is invalid. Else open the websocket connection
[ "Check", "the", "token", "returns", "a", "401", "if", "the", "token", "is", "invalid", ".", "Else", "open", "the", "websocket", "connection" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado_websockets.py#L315-L328
train
saltstack/salt
salt/netapi/rest_tornado/saltnado_websockets.py
AllEventsHandler.on_message
def on_message(self, message): """Listens for a "websocket client ready" message. Once that message is received an asynchronous job is stated that yields messages to the client. These messages make up salt's "real time" event stream. """ log.debug('Got websocket message %s', message) if message == 'websocket client ready': if self.connected: # TBD: Add ability to run commands in this branch log.debug('Websocket already connected, returning') return self.connected = True while True: try: event = yield self.application.event_listener.get_event(self) self.write_message( salt.utils.json.dumps(event, _json_module=_json)) except Exception as err: log.info('Error! Ending server side websocket connection. Reason = %s', err) break self.close() else: # TBD: Add logic to run salt commands here pass
python
def on_message(self, message): """Listens for a "websocket client ready" message. Once that message is received an asynchronous job is stated that yields messages to the client. These messages make up salt's "real time" event stream. """ log.debug('Got websocket message %s', message) if message == 'websocket client ready': if self.connected: # TBD: Add ability to run commands in this branch log.debug('Websocket already connected, returning') return self.connected = True while True: try: event = yield self.application.event_listener.get_event(self) self.write_message( salt.utils.json.dumps(event, _json_module=_json)) except Exception as err: log.info('Error! Ending server side websocket connection. Reason = %s', err) break self.close() else: # TBD: Add logic to run salt commands here pass
[ "def", "on_message", "(", "self", ",", "message", ")", ":", "log", ".", "debug", "(", "'Got websocket message %s'", ",", "message", ")", "if", "message", "==", "'websocket client ready'", ":", "if", "self", ".", "connected", ":", "# TBD: Add ability to run command...
Listens for a "websocket client ready" message. Once that message is received an asynchronous job is stated that yields messages to the client. These messages make up salt's "real time" event stream.
[ "Listens", "for", "a", "websocket", "client", "ready", "message", ".", "Once", "that", "message", "is", "received", "an", "asynchronous", "job", "is", "stated", "that", "yields", "messages", "to", "the", "client", ".", "These", "messages", "make", "up", "sal...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado_websockets.py#L338-L366
train
saltstack/salt
salt/netapi/rest_tornado/saltnado_websockets.py
AllEventsHandler.check_origin
def check_origin(self, origin): """ If cors is enabled, check that the origin is allowed """ mod_opts = self.application.mod_opts if mod_opts.get('cors_origin'): return bool(_check_cors_origin(origin, mod_opts['cors_origin'])) else: return super(AllEventsHandler, self).check_origin(origin)
python
def check_origin(self, origin): """ If cors is enabled, check that the origin is allowed """ mod_opts = self.application.mod_opts if mod_opts.get('cors_origin'): return bool(_check_cors_origin(origin, mod_opts['cors_origin'])) else: return super(AllEventsHandler, self).check_origin(origin)
[ "def", "check_origin", "(", "self", ",", "origin", ")", ":", "mod_opts", "=", "self", ".", "application", ".", "mod_opts", "if", "mod_opts", ".", "get", "(", "'cors_origin'", ")", ":", "return", "bool", "(", "_check_cors_origin", "(", "origin", ",", "mod_o...
If cors is enabled, check that the origin is allowed
[ "If", "cors", "is", "enabled", "check", "that", "the", "origin", "is", "allowed" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado_websockets.py#L375-L385
train
saltstack/salt
salt/netapi/rest_tornado/saltnado_websockets.py
FormattedEventsHandler.on_message
def on_message(self, message): """Listens for a "websocket client ready" message. Once that message is received an asynchronous job is stated that yields messages to the client. These messages make up salt's "real time" event stream. """ log.debug('Got websocket message %s', message) if message == 'websocket client ready': if self.connected: # TBD: Add ability to run commands in this branch log.debug('Websocket already connected, returning') return self.connected = True evt_processor = event_processor.SaltInfo(self) client = salt.netapi.NetapiClient(self.application.opts) client.run({ 'fun': 'grains.items', 'tgt': '*', 'token': self.token, 'mode': 'client', 'asynchronous': 'local_async', 'client': 'local' }) while True: try: event = yield self.application.event_listener.get_event(self) evt_processor.process(event, self.token, self.application.opts) # self.write_message('data: {0}\n\n'.format(salt.utils.json.dumps(event, _json_module=_json))) except Exception as err: log.debug('Error! Ending server side websocket connection. Reason = %s', err) break self.close() else: # TBD: Add logic to run salt commands here pass
python
def on_message(self, message): """Listens for a "websocket client ready" message. Once that message is received an asynchronous job is stated that yields messages to the client. These messages make up salt's "real time" event stream. """ log.debug('Got websocket message %s', message) if message == 'websocket client ready': if self.connected: # TBD: Add ability to run commands in this branch log.debug('Websocket already connected, returning') return self.connected = True evt_processor = event_processor.SaltInfo(self) client = salt.netapi.NetapiClient(self.application.opts) client.run({ 'fun': 'grains.items', 'tgt': '*', 'token': self.token, 'mode': 'client', 'asynchronous': 'local_async', 'client': 'local' }) while True: try: event = yield self.application.event_listener.get_event(self) evt_processor.process(event, self.token, self.application.opts) # self.write_message('data: {0}\n\n'.format(salt.utils.json.dumps(event, _json_module=_json))) except Exception as err: log.debug('Error! Ending server side websocket connection. Reason = %s', err) break self.close() else: # TBD: Add logic to run salt commands here pass
[ "def", "on_message", "(", "self", ",", "message", ")", ":", "log", ".", "debug", "(", "'Got websocket message %s'", ",", "message", ")", "if", "message", "==", "'websocket client ready'", ":", "if", "self", ".", "connected", ":", "# TBD: Add ability to run command...
Listens for a "websocket client ready" message. Once that message is received an asynchronous job is stated that yields messages to the client. These messages make up salt's "real time" event stream.
[ "Listens", "for", "a", "websocket", "client", "ready", "message", ".", "Once", "that", "message", "is", "received", "an", "asynchronous", "job", "is", "stated", "that", "yields", "messages", "to", "the", "client", ".", "These", "messages", "make", "up", "sal...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_tornado/saltnado_websockets.py#L391-L429
train
saltstack/salt
salt/modules/supervisord.py
_get_supervisorctl_bin
def _get_supervisorctl_bin(bin_env): ''' Return supervisorctl command to call, either from a virtualenv, an argument passed in, or from the global modules options ''' cmd = 'supervisorctl' if not bin_env: which_result = __salt__['cmd.which_bin']([cmd]) if which_result is None: raise CommandNotFoundError( 'Could not find a `{0}` binary'.format(cmd) ) return which_result # try to get binary from env if os.path.isdir(bin_env): cmd_bin = os.path.join(bin_env, 'bin', cmd) if os.path.isfile(cmd_bin): return cmd_bin raise CommandNotFoundError('Could not find a `{0}` binary'.format(cmd)) return bin_env
python
def _get_supervisorctl_bin(bin_env): ''' Return supervisorctl command to call, either from a virtualenv, an argument passed in, or from the global modules options ''' cmd = 'supervisorctl' if not bin_env: which_result = __salt__['cmd.which_bin']([cmd]) if which_result is None: raise CommandNotFoundError( 'Could not find a `{0}` binary'.format(cmd) ) return which_result # try to get binary from env if os.path.isdir(bin_env): cmd_bin = os.path.join(bin_env, 'bin', cmd) if os.path.isfile(cmd_bin): return cmd_bin raise CommandNotFoundError('Could not find a `{0}` binary'.format(cmd)) return bin_env
[ "def", "_get_supervisorctl_bin", "(", "bin_env", ")", ":", "cmd", "=", "'supervisorctl'", "if", "not", "bin_env", ":", "which_result", "=", "__salt__", "[", "'cmd.which_bin'", "]", "(", "[", "cmd", "]", ")", "if", "which_result", "is", "None", ":", "raise", ...
Return supervisorctl command to call, either from a virtualenv, an argument passed in, or from the global modules options
[ "Return", "supervisorctl", "command", "to", "call", "either", "from", "a", "virtualenv", "an", "argument", "passed", "in", "or", "from", "the", "global", "modules", "options" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/supervisord.py#L28-L49
train
saltstack/salt
salt/modules/supervisord.py
_ctl_cmd
def _ctl_cmd(cmd, name, conf_file, bin_env): ''' Return the command list to use ''' ret = [_get_supervisorctl_bin(bin_env)] if conf_file is not None: ret += ['-c', conf_file] ret.append(cmd) if name: ret.append(name) return ret
python
def _ctl_cmd(cmd, name, conf_file, bin_env): ''' Return the command list to use ''' ret = [_get_supervisorctl_bin(bin_env)] if conf_file is not None: ret += ['-c', conf_file] ret.append(cmd) if name: ret.append(name) return ret
[ "def", "_ctl_cmd", "(", "cmd", ",", "name", ",", "conf_file", ",", "bin_env", ")", ":", "ret", "=", "[", "_get_supervisorctl_bin", "(", "bin_env", ")", "]", "if", "conf_file", "is", "not", "None", ":", "ret", "+=", "[", "'-c'", ",", "conf_file", "]", ...
Return the command list to use
[ "Return", "the", "command", "list", "to", "use" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/supervisord.py#L52-L62
train
saltstack/salt
salt/modules/supervisord.py
start
def start(name='all', user=None, conf_file=None, bin_env=None): ''' Start the named service. Process group names should not include a trailing asterisk. user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.start <service> salt '*' supervisord.start <group>: ''' if name.endswith(':*'): name = name[:-1] ret = __salt__['cmd.run_all']( _ctl_cmd('start', name, conf_file, bin_env), runas=user, python_shell=False, ) return _get_return(ret)
python
def start(name='all', user=None, conf_file=None, bin_env=None): ''' Start the named service. Process group names should not include a trailing asterisk. user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.start <service> salt '*' supervisord.start <group>: ''' if name.endswith(':*'): name = name[:-1] ret = __salt__['cmd.run_all']( _ctl_cmd('start', name, conf_file, bin_env), runas=user, python_shell=False, ) return _get_return(ret)
[ "def", "start", "(", "name", "=", "'all'", ",", "user", "=", "None", ",", "conf_file", "=", "None", ",", "bin_env", "=", "None", ")", ":", "if", "name", ".", "endswith", "(", "':*'", ")", ":", "name", "=", "name", "[", ":", "-", "1", "]", "ret"...
Start the named service. Process group names should not include a trailing asterisk. user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.start <service> salt '*' supervisord.start <group>:
[ "Start", "the", "named", "service", ".", "Process", "group", "names", "should", "not", "include", "a", "trailing", "asterisk", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/supervisord.py#L72-L99
train
saltstack/salt
salt/modules/supervisord.py
reread
def reread(user=None, conf_file=None, bin_env=None): ''' Reload the daemon's configuration files user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.reread ''' ret = __salt__['cmd.run_all']( _ctl_cmd('reread', None, conf_file, bin_env), runas=user, python_shell=False, ) return _get_return(ret)
python
def reread(user=None, conf_file=None, bin_env=None): ''' Reload the daemon's configuration files user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.reread ''' ret = __salt__['cmd.run_all']( _ctl_cmd('reread', None, conf_file, bin_env), runas=user, python_shell=False, ) return _get_return(ret)
[ "def", "reread", "(", "user", "=", "None", ",", "conf_file", "=", "None", ",", "bin_env", "=", "None", ")", ":", "ret", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "_ctl_cmd", "(", "'reread'", ",", "None", ",", "conf_file", ",", "bin_env", ")", ...
Reload the daemon's configuration files user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.reread
[ "Reload", "the", "daemon", "s", "configuration", "files" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/supervisord.py#L222-L245
train
saltstack/salt
salt/modules/supervisord.py
update
def update(user=None, conf_file=None, bin_env=None, name=None): ''' Reload config and add/remove/update as necessary user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed name name of the process group to update. if none then update any process group that has changes CLI Example: .. code-block:: bash salt '*' supervisord.update ''' if isinstance(name, string_types): if name.endswith(':'): name = name[:-1] elif name.endswith(':*'): name = name[:-2] ret = __salt__['cmd.run_all']( _ctl_cmd('update', name, conf_file, bin_env), runas=user, python_shell=False, ) return _get_return(ret)
python
def update(user=None, conf_file=None, bin_env=None, name=None): ''' Reload config and add/remove/update as necessary user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed name name of the process group to update. if none then update any process group that has changes CLI Example: .. code-block:: bash salt '*' supervisord.update ''' if isinstance(name, string_types): if name.endswith(':'): name = name[:-1] elif name.endswith(':*'): name = name[:-2] ret = __salt__['cmd.run_all']( _ctl_cmd('update', name, conf_file, bin_env), runas=user, python_shell=False, ) return _get_return(ret)
[ "def", "update", "(", "user", "=", "None", ",", "conf_file", "=", "None", ",", "bin_env", "=", "None", ",", "name", "=", "None", ")", ":", "if", "isinstance", "(", "name", ",", "string_types", ")", ":", "if", "name", ".", "endswith", "(", "':'", ")...
Reload config and add/remove/update as necessary user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed name name of the process group to update. if none then update any process group that has changes CLI Example: .. code-block:: bash salt '*' supervisord.update
[ "Reload", "config", "and", "add", "/", "remove", "/", "update", "as", "necessary" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/supervisord.py#L248-L281
train
saltstack/salt
salt/modules/supervisord.py
status
def status(name=None, user=None, conf_file=None, bin_env=None): ''' List programs and its state user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.status ''' all_process = {} for line in status_raw(name, user, conf_file, bin_env).splitlines(): if len(line.split()) > 2: process, state, reason = line.split(None, 2) else: process, state, reason = line.split() + [''] all_process[process] = {'state': state, 'reason': reason} return all_process
python
def status(name=None, user=None, conf_file=None, bin_env=None): ''' List programs and its state user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.status ''' all_process = {} for line in status_raw(name, user, conf_file, bin_env).splitlines(): if len(line.split()) > 2: process, state, reason = line.split(None, 2) else: process, state, reason = line.split() + [''] all_process[process] = {'state': state, 'reason': reason} return all_process
[ "def", "status", "(", "name", "=", "None", ",", "user", "=", "None", ",", "conf_file", "=", "None", ",", "bin_env", "=", "None", ")", ":", "all_process", "=", "{", "}", "for", "line", "in", "status_raw", "(", "name", ",", "user", ",", "conf_file", ...
List programs and its state user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.status
[ "List", "programs", "and", "its", "state" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/supervisord.py#L284-L309
train
saltstack/salt
salt/modules/supervisord.py
status_raw
def status_raw(name=None, user=None, conf_file=None, bin_env=None): ''' Display the raw output of status user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.status_raw ''' ret = __salt__['cmd.run_all']( _ctl_cmd('status', name, conf_file, bin_env), runas=user, python_shell=False, ) return _get_return(ret)
python
def status_raw(name=None, user=None, conf_file=None, bin_env=None): ''' Display the raw output of status user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.status_raw ''' ret = __salt__['cmd.run_all']( _ctl_cmd('status', name, conf_file, bin_env), runas=user, python_shell=False, ) return _get_return(ret)
[ "def", "status_raw", "(", "name", "=", "None", ",", "user", "=", "None", ",", "conf_file", "=", "None", ",", "bin_env", "=", "None", ")", ":", "ret", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "_ctl_cmd", "(", "'status'", ",", "name", ",", "con...
Display the raw output of status user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.status_raw
[ "Display", "the", "raw", "output", "of", "status" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/supervisord.py#L312-L335
train
saltstack/salt
salt/modules/supervisord.py
custom
def custom(command, user=None, conf_file=None, bin_env=None): ''' Run any custom supervisord command user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.custom "mstop '*gunicorn*'" ''' ret = __salt__['cmd.run_all']( _ctl_cmd(command, None, conf_file, bin_env), runas=user, python_shell=False, ) return _get_return(ret)
python
def custom(command, user=None, conf_file=None, bin_env=None): ''' Run any custom supervisord command user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.custom "mstop '*gunicorn*'" ''' ret = __salt__['cmd.run_all']( _ctl_cmd(command, None, conf_file, bin_env), runas=user, python_shell=False, ) return _get_return(ret)
[ "def", "custom", "(", "command", ",", "user", "=", "None", ",", "conf_file", "=", "None", ",", "bin_env", "=", "None", ")", ":", "ret", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "_ctl_cmd", "(", "command", ",", "None", ",", "conf_file", ",", "...
Run any custom supervisord command user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.custom "mstop '*gunicorn*'"
[ "Run", "any", "custom", "supervisord", "command" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/supervisord.py#L338-L361
train
saltstack/salt
salt/modules/supervisord.py
_read_config
def _read_config(conf_file=None): ''' Reads the config file using configparser ''' if conf_file is None: paths = ('/etc/supervisor/supervisord.conf', '/etc/supervisord.conf') for path in paths: if os.path.exists(path): conf_file = path break if conf_file is None: raise CommandExecutionError('No suitable config file found') config = configparser.ConfigParser() try: config.read(conf_file) except (IOError, OSError) as exc: raise CommandExecutionError( 'Unable to read from {0}: {1}'.format(conf_file, exc) ) return config
python
def _read_config(conf_file=None): ''' Reads the config file using configparser ''' if conf_file is None: paths = ('/etc/supervisor/supervisord.conf', '/etc/supervisord.conf') for path in paths: if os.path.exists(path): conf_file = path break if conf_file is None: raise CommandExecutionError('No suitable config file found') config = configparser.ConfigParser() try: config.read(conf_file) except (IOError, OSError) as exc: raise CommandExecutionError( 'Unable to read from {0}: {1}'.format(conf_file, exc) ) return config
[ "def", "_read_config", "(", "conf_file", "=", "None", ")", ":", "if", "conf_file", "is", "None", ":", "paths", "=", "(", "'/etc/supervisor/supervisord.conf'", ",", "'/etc/supervisord.conf'", ")", "for", "path", "in", "paths", ":", "if", "os", ".", "path", "....
Reads the config file using configparser
[ "Reads", "the", "config", "file", "using", "configparser" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/supervisord.py#L366-L385
train
saltstack/salt
salt/modules/supervisord.py
options
def options(name, conf_file=None): ''' .. versionadded:: 2014.1.0 Read the config file and return the config options for a given process name Name of the configured process conf_file path to supervisord config file CLI Example: .. code-block:: bash salt '*' supervisord.options foo ''' config = _read_config(conf_file) section_name = 'program:{0}'.format(name) if section_name not in config.sections(): raise CommandExecutionError('Process \'{0}\' not found'.format(name)) ret = {} for key, val in config.items(section_name): val = salt.utils.stringutils.to_num(val.split(';')[0].strip()) # pylint: disable=maybe-no-member if isinstance(val, string_types): if val.lower() == 'true': val = True elif val.lower() == 'false': val = False # pylint: enable=maybe-no-member ret[key] = val return ret
python
def options(name, conf_file=None): ''' .. versionadded:: 2014.1.0 Read the config file and return the config options for a given process name Name of the configured process conf_file path to supervisord config file CLI Example: .. code-block:: bash salt '*' supervisord.options foo ''' config = _read_config(conf_file) section_name = 'program:{0}'.format(name) if section_name not in config.sections(): raise CommandExecutionError('Process \'{0}\' not found'.format(name)) ret = {} for key, val in config.items(section_name): val = salt.utils.stringutils.to_num(val.split(';')[0].strip()) # pylint: disable=maybe-no-member if isinstance(val, string_types): if val.lower() == 'true': val = True elif val.lower() == 'false': val = False # pylint: enable=maybe-no-member ret[key] = val return ret
[ "def", "options", "(", "name", ",", "conf_file", "=", "None", ")", ":", "config", "=", "_read_config", "(", "conf_file", ")", "section_name", "=", "'program:{0}'", ".", "format", "(", "name", ")", "if", "section_name", "not", "in", "config", ".", "sections...
.. versionadded:: 2014.1.0 Read the config file and return the config options for a given process name Name of the configured process conf_file path to supervisord config file CLI Example: .. code-block:: bash salt '*' supervisord.options foo
[ "..", "versionadded", "::", "2014", ".", "1", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/supervisord.py#L388-L420
train
saltstack/salt
salt/states/logadm.py
rotate
def rotate(name, **kwargs): ''' Add a log to the logadm configuration name : string alias for entryname kwargs : boolean|string|int optional additional flags and parameters ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} # cleanup kwargs kwargs = salt.utils.args.clean_kwargs(**kwargs) # inject name as entryname if 'entryname' not in kwargs: kwargs['entryname'] = name # figure out log_file and entryname if 'log_file' not in kwargs or not kwargs['log_file']: if 'entryname' in kwargs and kwargs['entryname']: if kwargs['entryname'].startswith('/'): kwargs['log_file'] = kwargs['entryname'] # check for log_file if 'log_file' not in kwargs or not kwargs['log_file']: ret['result'] = False ret['comment'] = 'Missing log_file attribute!' else: # lookup old configuration old_config = __salt__['logadm.list_conf']() # remove existing entry if kwargs['log_file'] in old_config: res = __salt__['logadm.remove'](kwargs['entryname'] if 'entryname' in kwargs else kwargs['log_file']) ret['result'] = 'Error' not in res if not ret['result']: ret['comment'] = res['Error'] ret['changes'] = {} # add new entry res = __salt__['logadm.rotate'](name, **kwargs) ret['result'] = 'Error' not in res if ret['result']: new_config = __salt__['logadm.list_conf']() ret['comment'] = 'Log configuration {}'.format('updated' if kwargs['log_file'] in old_config else 'added') if kwargs['log_file'] in old_config: for key, val in salt.utils.data.compare_dicts(old_config[kwargs['log_file']], new_config[kwargs['log_file']]).items(): ret['changes'][key] = val['new'] else: ret['changes'] = new_config[kwargs['log_file']] log.debug(ret['changes']) else: ret['comment'] = res['Error'] # NOTE: we need to remove the log file first # potentially the log configuraiton can get lost :s if kwargs['log_file'] in old_config: ret['changes'] = {kwargs['log_file']: None} else: ret['changes'] = {} return ret
python
def rotate(name, **kwargs): ''' Add a log to the logadm configuration name : string alias for entryname kwargs : boolean|string|int optional additional flags and parameters ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} # cleanup kwargs kwargs = salt.utils.args.clean_kwargs(**kwargs) # inject name as entryname if 'entryname' not in kwargs: kwargs['entryname'] = name # figure out log_file and entryname if 'log_file' not in kwargs or not kwargs['log_file']: if 'entryname' in kwargs and kwargs['entryname']: if kwargs['entryname'].startswith('/'): kwargs['log_file'] = kwargs['entryname'] # check for log_file if 'log_file' not in kwargs or not kwargs['log_file']: ret['result'] = False ret['comment'] = 'Missing log_file attribute!' else: # lookup old configuration old_config = __salt__['logadm.list_conf']() # remove existing entry if kwargs['log_file'] in old_config: res = __salt__['logadm.remove'](kwargs['entryname'] if 'entryname' in kwargs else kwargs['log_file']) ret['result'] = 'Error' not in res if not ret['result']: ret['comment'] = res['Error'] ret['changes'] = {} # add new entry res = __salt__['logadm.rotate'](name, **kwargs) ret['result'] = 'Error' not in res if ret['result']: new_config = __salt__['logadm.list_conf']() ret['comment'] = 'Log configuration {}'.format('updated' if kwargs['log_file'] in old_config else 'added') if kwargs['log_file'] in old_config: for key, val in salt.utils.data.compare_dicts(old_config[kwargs['log_file']], new_config[kwargs['log_file']]).items(): ret['changes'][key] = val['new'] else: ret['changes'] = new_config[kwargs['log_file']] log.debug(ret['changes']) else: ret['comment'] = res['Error'] # NOTE: we need to remove the log file first # potentially the log configuraiton can get lost :s if kwargs['log_file'] in old_config: ret['changes'] = {kwargs['log_file']: None} else: ret['changes'] = {} return ret
[ "def", "rotate", "(", "name", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "# cleanup kwargs", "kwargs", "=", "salt", "."...
Add a log to the logadm configuration name : string alias for entryname kwargs : boolean|string|int optional additional flags and parameters
[ "Add", "a", "log", "to", "the", "logadm", "configuration" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/logadm.py#L48-L114
train
saltstack/salt
salt/states/logadm.py
remove
def remove(name, log_file=None): ''' Remove a log from the logadm configuration name : string entryname log_file : string (optional) log file path .. note:: If log_file is specified it will be used instead of the entry name. ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} # retrieve all log configuration config = __salt__['logadm.list_conf']() # figure out log_file and name if not log_file: if name.startswith('/'): log_file = name name = None else: for log in config: if 'entryname' in config[log] and config[log]['entryname'] == name: log_file = config[log]['log_file'] break if not name: for log in config: if 'log_file' in config[log] and config[log]['log_file'] == log_file: if 'entryname' in config[log]: name = config[log]['entryname'] break # remove log if needed if log_file in config: res = __salt__['logadm.remove'](name if name else log_file) ret['result'] = 'Error' not in res if ret['result']: ret['comment'] = 'Configuration for {} removed.'.format(log_file) ret['changes'][log_file] = None else: ret['comment'] = res['Error'] else: ret['result'] = True ret['comment'] = 'No configuration for {} present.'.format(log_file) return ret
python
def remove(name, log_file=None): ''' Remove a log from the logadm configuration name : string entryname log_file : string (optional) log file path .. note:: If log_file is specified it will be used instead of the entry name. ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} # retrieve all log configuration config = __salt__['logadm.list_conf']() # figure out log_file and name if not log_file: if name.startswith('/'): log_file = name name = None else: for log in config: if 'entryname' in config[log] and config[log]['entryname'] == name: log_file = config[log]['log_file'] break if not name: for log in config: if 'log_file' in config[log] and config[log]['log_file'] == log_file: if 'entryname' in config[log]: name = config[log]['entryname'] break # remove log if needed if log_file in config: res = __salt__['logadm.remove'](name if name else log_file) ret['result'] = 'Error' not in res if ret['result']: ret['comment'] = 'Configuration for {} removed.'.format(log_file) ret['changes'][log_file] = None else: ret['comment'] = res['Error'] else: ret['result'] = True ret['comment'] = 'No configuration for {} present.'.format(log_file) return ret
[ "def", "remove", "(", "name", ",", "log_file", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "# retrieve all log configuration", "config", ...
Remove a log from the logadm configuration name : string entryname log_file : string (optional) log file path .. note:: If log_file is specified it will be used instead of the entry name.
[ "Remove", "a", "log", "from", "the", "logadm", "configuration" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/logadm.py#L117-L168
train
saltstack/salt
salt/states/win_firewall.py
add_rule
def add_rule(name, localport, protocol='tcp', action='allow', dir='in', remoteip='any'): ''' Add a new inbound or outbound rule to the firewall policy Args: name (str): The name of the rule. Must be unique and cannot be "all". Required. localport (int): The port the rule applies to. Must be a number between 0 and 65535. Can be a range. Can specify multiple ports separated by commas. Required. protocol (Optional[str]): The protocol. Can be any of the following: - A number between 0 and 255 - icmpv4 - icmpv6 - tcp - udp - any action (Optional[str]): The action the rule performs. Can be any of the following: - allow - block - bypass dir (Optional[str]): The direction. Can be ``in`` or ``out``. remoteip (Optional [str]): The remote IP. Can be any of the following: - any - localsubnet - dns - dhcp - wins - defaultgateway - Any valid IPv4 address (192.168.0.12) - Any valid IPv6 address (2002:9b3b:1a31:4:208:74ff:fe39:6c43) - Any valid subnet (192.168.1.0/24) - Any valid range of IP addresses (192.168.0.1-192.168.0.12) - A list of valid IP addresses Can be combinations of the above separated by commas. .. versionadded:: 2016.11.6 Example: .. code-block:: yaml open_smb_port: win_firewall.add_rule: - name: SMB (445) - localport: 445 - protocol: tcp - action: allow ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} # Check if rule exists if not __salt__['firewall.rule_exists'](name): ret['changes'] = {'new rule': name} else: ret['comment'] = 'A rule with that name already exists' return ret if __opts__['test']: ret['result'] = not ret['changes'] or None ret['comment'] = ret['changes'] ret['changes'] = {} return ret # Add rule try: __salt__['firewall.add_rule']( name, localport, protocol, action, dir, remoteip) except CommandExecutionError: ret['comment'] = 'Could not add rule' return ret
python
def add_rule(name, localport, protocol='tcp', action='allow', dir='in', remoteip='any'): ''' Add a new inbound or outbound rule to the firewall policy Args: name (str): The name of the rule. Must be unique and cannot be "all". Required. localport (int): The port the rule applies to. Must be a number between 0 and 65535. Can be a range. Can specify multiple ports separated by commas. Required. protocol (Optional[str]): The protocol. Can be any of the following: - A number between 0 and 255 - icmpv4 - icmpv6 - tcp - udp - any action (Optional[str]): The action the rule performs. Can be any of the following: - allow - block - bypass dir (Optional[str]): The direction. Can be ``in`` or ``out``. remoteip (Optional [str]): The remote IP. Can be any of the following: - any - localsubnet - dns - dhcp - wins - defaultgateway - Any valid IPv4 address (192.168.0.12) - Any valid IPv6 address (2002:9b3b:1a31:4:208:74ff:fe39:6c43) - Any valid subnet (192.168.1.0/24) - Any valid range of IP addresses (192.168.0.1-192.168.0.12) - A list of valid IP addresses Can be combinations of the above separated by commas. .. versionadded:: 2016.11.6 Example: .. code-block:: yaml open_smb_port: win_firewall.add_rule: - name: SMB (445) - localport: 445 - protocol: tcp - action: allow ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} # Check if rule exists if not __salt__['firewall.rule_exists'](name): ret['changes'] = {'new rule': name} else: ret['comment'] = 'A rule with that name already exists' return ret if __opts__['test']: ret['result'] = not ret['changes'] or None ret['comment'] = ret['changes'] ret['changes'] = {} return ret # Add rule try: __salt__['firewall.add_rule']( name, localport, protocol, action, dir, remoteip) except CommandExecutionError: ret['comment'] = 'Could not add rule' return ret
[ "def", "add_rule", "(", "name", ",", "localport", ",", "protocol", "=", "'tcp'", ",", "action", "=", "'allow'", ",", "dir", "=", "'in'", ",", "remoteip", "=", "'any'", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ...
Add a new inbound or outbound rule to the firewall policy Args: name (str): The name of the rule. Must be unique and cannot be "all". Required. localport (int): The port the rule applies to. Must be a number between 0 and 65535. Can be a range. Can specify multiple ports separated by commas. Required. protocol (Optional[str]): The protocol. Can be any of the following: - A number between 0 and 255 - icmpv4 - icmpv6 - tcp - udp - any action (Optional[str]): The action the rule performs. Can be any of the following: - allow - block - bypass dir (Optional[str]): The direction. Can be ``in`` or ``out``. remoteip (Optional [str]): The remote IP. Can be any of the following: - any - localsubnet - dns - dhcp - wins - defaultgateway - Any valid IPv4 address (192.168.0.12) - Any valid IPv6 address (2002:9b3b:1a31:4:208:74ff:fe39:6c43) - Any valid subnet (192.168.1.0/24) - Any valid range of IP addresses (192.168.0.1-192.168.0.12) - A list of valid IP addresses Can be combinations of the above separated by commas. .. versionadded:: 2016.11.6 Example: .. code-block:: yaml open_smb_port: win_firewall.add_rule: - name: SMB (445) - localport: 445 - protocol: tcp - action: allow
[ "Add", "a", "new", "inbound", "or", "outbound", "rule", "to", "the", "firewall", "policy" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_firewall.py#L94-L184
train
saltstack/salt
salt/states/win_firewall.py
delete_rule
def delete_rule(name, localport=None, protocol=None, dir=None, remoteip=None): ''' Delete an existing firewall rule identified by name and optionally by ports, protocols, direction, and remote IP. .. versionadded:: Neon Args: name (str): The name of the rule to delete. If the name ``all`` is used you must specify additional parameters. localport (Optional[str]): The port of the rule. If protocol is not specified, protocol will be set to ``tcp`` protocol (Optional[str]): The protocol of the rule. Default is ``tcp`` when ``localport`` is specified dir (Optional[str]): The direction of the rule. remoteip (Optional[str]): The remote IP of the rule. Example: .. code-block:: yaml delete_smb_port_rule: win_firewall.delete_rule: - name: SMB (445) ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} # Check if rule exists if __salt__['firewall.rule_exists'](name): ret['changes'] = {'delete rule': name} else: ret['comment'] = 'A rule with that name does not exist' return ret if __opts__['test']: ret['result'] = not ret['changes'] or None ret['comment'] = ret['changes'] ret['changes'] = {} return ret # Delete rule try: __salt__['firewall.delete_rule']( name, localport, protocol, dir, remoteip) except CommandExecutionError: ret['comment'] = 'Could not delete rule' return ret
python
def delete_rule(name, localport=None, protocol=None, dir=None, remoteip=None): ''' Delete an existing firewall rule identified by name and optionally by ports, protocols, direction, and remote IP. .. versionadded:: Neon Args: name (str): The name of the rule to delete. If the name ``all`` is used you must specify additional parameters. localport (Optional[str]): The port of the rule. If protocol is not specified, protocol will be set to ``tcp`` protocol (Optional[str]): The protocol of the rule. Default is ``tcp`` when ``localport`` is specified dir (Optional[str]): The direction of the rule. remoteip (Optional[str]): The remote IP of the rule. Example: .. code-block:: yaml delete_smb_port_rule: win_firewall.delete_rule: - name: SMB (445) ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} # Check if rule exists if __salt__['firewall.rule_exists'](name): ret['changes'] = {'delete rule': name} else: ret['comment'] = 'A rule with that name does not exist' return ret if __opts__['test']: ret['result'] = not ret['changes'] or None ret['comment'] = ret['changes'] ret['changes'] = {} return ret # Delete rule try: __salt__['firewall.delete_rule']( name, localport, protocol, dir, remoteip) except CommandExecutionError: ret['comment'] = 'Could not delete rule' return ret
[ "def", "delete_rule", "(", "name", ",", "localport", "=", "None", ",", "protocol", "=", "None", ",", "dir", "=", "None", ",", "remoteip", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'changes'", ...
Delete an existing firewall rule identified by name and optionally by ports, protocols, direction, and remote IP. .. versionadded:: Neon Args: name (str): The name of the rule to delete. If the name ``all`` is used you must specify additional parameters. localport (Optional[str]): The port of the rule. If protocol is not specified, protocol will be set to ``tcp`` protocol (Optional[str]): The protocol of the rule. Default is ``tcp`` when ``localport`` is specified dir (Optional[str]): The direction of the rule. remoteip (Optional[str]): The remote IP of the rule. Example: .. code-block:: yaml delete_smb_port_rule: win_firewall.delete_rule: - name: SMB (445)
[ "Delete", "an", "existing", "firewall", "rule", "identified", "by", "name", "and", "optionally", "by", "ports", "protocols", "direction", "and", "remote", "IP", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_firewall.py#L187-L246
train
saltstack/salt
salt/states/win_firewall.py
enabled
def enabled(name='allprofiles'): ''' Enable all the firewall profiles (Windows only) Args: profile (Optional[str]): The name of the profile to enable. Default is ``allprofiles``. Valid options are: - allprofiles - domainprofile - privateprofile - publicprofile Example: .. code-block:: yaml # To enable the domain profile enable_domain: win_firewall.enabled: - name: domainprofile # To enable all profiles enable_all: win_firewall.enabled: - name: allprofiles ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} profile_map = {'domainprofile': 'Domain', 'privateprofile': 'Private', 'publicprofile': 'Public', 'allprofiles': 'All'} # Make sure the profile name is valid if name not in profile_map: raise SaltInvocationError('Invalid profile name: {0}'.format(name)) current_config = __salt__['firewall.get_config']() if name != 'allprofiles' and profile_map[name] not in current_config: ret['result'] = False ret['comment'] = 'Profile {0} does not exist in firewall.get_config' \ ''.format(name) return ret for key in current_config: if not current_config[key]: if name == 'allprofiles' or key == profile_map[name]: ret['changes'][key] = 'enabled' if __opts__['test']: ret['result'] = not ret['changes'] or None ret['comment'] = ret['changes'] ret['changes'] = {} return ret # Enable it if ret['changes']: try: ret['result'] = __salt__['firewall.enable'](name) except CommandExecutionError: ret['comment'] = 'Firewall Profile {0} could not be enabled' \ ''.format(profile_map[name]) else: if name == 'allprofiles': msg = 'All the firewall profiles are enabled' else: msg = 'Firewall profile {0} is enabled'.format(name) ret['comment'] = msg return ret
python
def enabled(name='allprofiles'): ''' Enable all the firewall profiles (Windows only) Args: profile (Optional[str]): The name of the profile to enable. Default is ``allprofiles``. Valid options are: - allprofiles - domainprofile - privateprofile - publicprofile Example: .. code-block:: yaml # To enable the domain profile enable_domain: win_firewall.enabled: - name: domainprofile # To enable all profiles enable_all: win_firewall.enabled: - name: allprofiles ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} profile_map = {'domainprofile': 'Domain', 'privateprofile': 'Private', 'publicprofile': 'Public', 'allprofiles': 'All'} # Make sure the profile name is valid if name not in profile_map: raise SaltInvocationError('Invalid profile name: {0}'.format(name)) current_config = __salt__['firewall.get_config']() if name != 'allprofiles' and profile_map[name] not in current_config: ret['result'] = False ret['comment'] = 'Profile {0} does not exist in firewall.get_config' \ ''.format(name) return ret for key in current_config: if not current_config[key]: if name == 'allprofiles' or key == profile_map[name]: ret['changes'][key] = 'enabled' if __opts__['test']: ret['result'] = not ret['changes'] or None ret['comment'] = ret['changes'] ret['changes'] = {} return ret # Enable it if ret['changes']: try: ret['result'] = __salt__['firewall.enable'](name) except CommandExecutionError: ret['comment'] = 'Firewall Profile {0} could not be enabled' \ ''.format(profile_map[name]) else: if name == 'allprofiles': msg = 'All the firewall profiles are enabled' else: msg = 'Firewall profile {0} is enabled'.format(name) ret['comment'] = msg return ret
[ "def", "enabled", "(", "name", "=", "'allprofiles'", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", "}", "profile_map", "=", "{", "'domainprofile'", ":", "...
Enable all the firewall profiles (Windows only) Args: profile (Optional[str]): The name of the profile to enable. Default is ``allprofiles``. Valid options are: - allprofiles - domainprofile - privateprofile - publicprofile Example: .. code-block:: yaml # To enable the domain profile enable_domain: win_firewall.enabled: - name: domainprofile # To enable all profiles enable_all: win_firewall.enabled: - name: allprofiles
[ "Enable", "all", "the", "firewall", "profiles", "(", "Windows", "only", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_firewall.py#L249-L322
train
saltstack/salt
salt/runners/mattermost.py
post_message
def post_message(message, channel=None, username=None, api_url=None, hook=None): ''' Send a message to a Mattermost channel. :param channel: The channel name, either will work. :param username: The username of the poster. :param message: The message to send to the Mattermost channel. :param api_url: The Mattermost api url, if not specified in the configuration. :param hook: The Mattermost hook, if not specified in the configuration. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt-run mattermost.post_message message='Build is done' ''' if not api_url: api_url = _get_api_url() if not hook: hook = _get_hook() if not username: username = _get_username() if not channel: channel = _get_channel() if not message: log.error('message is a required option.') parameters = dict() if channel: parameters['channel'] = channel if username: parameters['username'] = username parameters['text'] = '```' + message + '```' # pre-formatted, fixed-width text log.debug('Parameters: %s', parameters) data = salt.utils.json.dumps(parameters) result = salt.utils.mattermost.query( api_url=api_url, hook=hook, data=str('payload={0}').format(data)) # future lint: blacklisted-function if result: return True else: return result
python
def post_message(message, channel=None, username=None, api_url=None, hook=None): ''' Send a message to a Mattermost channel. :param channel: The channel name, either will work. :param username: The username of the poster. :param message: The message to send to the Mattermost channel. :param api_url: The Mattermost api url, if not specified in the configuration. :param hook: The Mattermost hook, if not specified in the configuration. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt-run mattermost.post_message message='Build is done' ''' if not api_url: api_url = _get_api_url() if not hook: hook = _get_hook() if not username: username = _get_username() if not channel: channel = _get_channel() if not message: log.error('message is a required option.') parameters = dict() if channel: parameters['channel'] = channel if username: parameters['username'] = username parameters['text'] = '```' + message + '```' # pre-formatted, fixed-width text log.debug('Parameters: %s', parameters) data = salt.utils.json.dumps(parameters) result = salt.utils.mattermost.query( api_url=api_url, hook=hook, data=str('payload={0}').format(data)) # future lint: blacklisted-function if result: return True else: return result
[ "def", "post_message", "(", "message", ",", "channel", "=", "None", ",", "username", "=", "None", ",", "api_url", "=", "None", ",", "hook", "=", "None", ")", ":", "if", "not", "api_url", ":", "api_url", "=", "_get_api_url", "(", ")", "if", "not", "ho...
Send a message to a Mattermost channel. :param channel: The channel name, either will work. :param username: The username of the poster. :param message: The message to send to the Mattermost channel. :param api_url: The Mattermost api url, if not specified in the configuration. :param hook: The Mattermost hook, if not specified in the configuration. :return: Boolean if message was sent successfully. CLI Example: .. code-block:: bash salt-run mattermost.post_message message='Build is done'
[ "Send", "a", "message", "to", "a", "Mattermost", "channel", ".", ":", "param", "channel", ":", "The", "channel", "name", "either", "will", "work", ".", ":", "param", "username", ":", "The", "username", "of", "the", "poster", ".", ":", "param", "message",...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/mattermost.py#L95-L146
train
saltstack/salt
salt/runners/mattermost.py
post_event
def post_event(event, channel=None, username=None, api_url=None, hook=None): ''' Send an event to a Mattermost channel. :param channel: The channel name, either will work. :param username: The username of the poster. :param event: The event to send to the Mattermost channel. :param api_url: The Mattermost api url, if not specified in the configuration. :param hook: The Mattermost hook, if not specified in the configuration. :return: Boolean if message was sent successfully. ''' if not api_url: api_url = _get_api_url() if not hook: hook = _get_hook() if not username: username = _get_username() if not channel: channel = _get_channel() if not event: log.error('message is a required option.') log.debug('Event: %s', event) log.debug('Event data: %s', event['data']) message = 'tag: {0}\r\n'.format(event['tag']) for key, value in six.iteritems(event['data']): message += '{0}: {1}\r\n'.format(key, value) result = post_message(channel, username, message, api_url, hook) return bool(result)
python
def post_event(event, channel=None, username=None, api_url=None, hook=None): ''' Send an event to a Mattermost channel. :param channel: The channel name, either will work. :param username: The username of the poster. :param event: The event to send to the Mattermost channel. :param api_url: The Mattermost api url, if not specified in the configuration. :param hook: The Mattermost hook, if not specified in the configuration. :return: Boolean if message was sent successfully. ''' if not api_url: api_url = _get_api_url() if not hook: hook = _get_hook() if not username: username = _get_username() if not channel: channel = _get_channel() if not event: log.error('message is a required option.') log.debug('Event: %s', event) log.debug('Event data: %s', event['data']) message = 'tag: {0}\r\n'.format(event['tag']) for key, value in six.iteritems(event['data']): message += '{0}: {1}\r\n'.format(key, value) result = post_message(channel, username, message, api_url, hook) return bool(result)
[ "def", "post_event", "(", "event", ",", "channel", "=", "None", ",", "username", "=", "None", ",", "api_url", "=", "None", ",", "hook", "=", "None", ")", ":", "if", "not", "api_url", ":", "api_url", "=", "_get_api_url", "(", ")", "if", "not", "hook",...
Send an event to a Mattermost channel. :param channel: The channel name, either will work. :param username: The username of the poster. :param event: The event to send to the Mattermost channel. :param api_url: The Mattermost api url, if not specified in the configuration. :param hook: The Mattermost hook, if not specified in the configuration. :return: Boolean if message was sent successfully.
[ "Send", "an", "event", "to", "a", "Mattermost", "channel", ".", ":", "param", "channel", ":", "The", "channel", "name", "either", "will", "work", ".", ":", "param", "username", ":", "The", "username", "of", "the", "poster", ".", ":", "param", "event", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/mattermost.py#L149-L188
train
saltstack/salt
salt/modules/vault.py
read_secret
def read_secret(path, key=None): ''' Return the value of key at path in vault, or entire secret Jinja Example: .. code-block:: jinja my-secret: {{ salt['vault'].read_secret('secret/my/secret', 'some-key') }} .. code-block:: jinja {% set supersecret = salt['vault'].read_secret('secret/my/secret') %} secrets: first: {{ supersecret.first }} second: {{ supersecret.second }} ''' log.debug('Reading Vault secret for %s at %s', __grains__['id'], path) try: url = 'v1/{0}'.format(path) response = __utils__['vault.make_request']('GET', url) if response.status_code != 200: response.raise_for_status() data = response.json()['data'] if key is not None: return data[key] return data except Exception as err: log.error('Failed to read secret! %s: %s', type(err).__name__, err) return None
python
def read_secret(path, key=None): ''' Return the value of key at path in vault, or entire secret Jinja Example: .. code-block:: jinja my-secret: {{ salt['vault'].read_secret('secret/my/secret', 'some-key') }} .. code-block:: jinja {% set supersecret = salt['vault'].read_secret('secret/my/secret') %} secrets: first: {{ supersecret.first }} second: {{ supersecret.second }} ''' log.debug('Reading Vault secret for %s at %s', __grains__['id'], path) try: url = 'v1/{0}'.format(path) response = __utils__['vault.make_request']('GET', url) if response.status_code != 200: response.raise_for_status() data = response.json()['data'] if key is not None: return data[key] return data except Exception as err: log.error('Failed to read secret! %s: %s', type(err).__name__, err) return None
[ "def", "read_secret", "(", "path", ",", "key", "=", "None", ")", ":", "log", ".", "debug", "(", "'Reading Vault secret for %s at %s'", ",", "__grains__", "[", "'id'", "]", ",", "path", ")", "try", ":", "url", "=", "'v1/{0}'", ".", "format", "(", "path", ...
Return the value of key at path in vault, or entire secret Jinja Example: .. code-block:: jinja my-secret: {{ salt['vault'].read_secret('secret/my/secret', 'some-key') }} .. code-block:: jinja {% set supersecret = salt['vault'].read_secret('secret/my/secret') %} secrets: first: {{ supersecret.first }} second: {{ supersecret.second }}
[ "Return", "the", "value", "of", "key", "at", "path", "in", "vault", "or", "entire", "secret" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vault.py#L142-L172
train
saltstack/salt
salt/modules/vault.py
write_secret
def write_secret(path, **kwargs): ''' Set secret at the path in vault. The vault policy used must allow this. CLI Example: .. code-block:: bash salt '*' vault.write_secret "secret/my/secret" user="foo" password="bar" ''' log.debug('Writing vault secrets for %s at %s', __grains__['id'], path) data = dict([(x, y) for x, y in kwargs.items() if not x.startswith('__')]) try: url = 'v1/{0}'.format(path) response = __utils__['vault.make_request']('POST', url, json=data) if response.status_code == 200: return response.json()['data'] elif response.status_code != 204: response.raise_for_status() return True except Exception as err: log.error('Failed to write secret! %s: %s', type(err).__name__, err) return False
python
def write_secret(path, **kwargs): ''' Set secret at the path in vault. The vault policy used must allow this. CLI Example: .. code-block:: bash salt '*' vault.write_secret "secret/my/secret" user="foo" password="bar" ''' log.debug('Writing vault secrets for %s at %s', __grains__['id'], path) data = dict([(x, y) for x, y in kwargs.items() if not x.startswith('__')]) try: url = 'v1/{0}'.format(path) response = __utils__['vault.make_request']('POST', url, json=data) if response.status_code == 200: return response.json()['data'] elif response.status_code != 204: response.raise_for_status() return True except Exception as err: log.error('Failed to write secret! %s: %s', type(err).__name__, err) return False
[ "def", "write_secret", "(", "path", ",", "*", "*", "kwargs", ")", ":", "log", ".", "debug", "(", "'Writing vault secrets for %s at %s'", ",", "__grains__", "[", "'id'", "]", ",", "path", ")", "data", "=", "dict", "(", "[", "(", "x", ",", "y", ")", "f...
Set secret at the path in vault. The vault policy used must allow this. CLI Example: .. code-block:: bash salt '*' vault.write_secret "secret/my/secret" user="foo" password="bar"
[ "Set", "secret", "at", "the", "path", "in", "vault", ".", "The", "vault", "policy", "used", "must", "allow", "this", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vault.py#L175-L197
train
saltstack/salt
salt/modules/vault.py
write_raw
def write_raw(path, raw): ''' Set raw data at the path in vault. The vault policy used must allow this. CLI Example: .. code-block:: bash salt '*' vault.write_raw "secret/my/secret" '{"user":"foo","password": "bar"}' ''' log.debug('Writing vault secrets for %s at %s', __grains__['id'], path) try: url = 'v1/{0}'.format(path) response = __utils__['vault.make_request']('POST', url, json=raw) if response.status_code == 200: return response.json()['data'] elif response.status_code != 204: response.raise_for_status() return True except Exception as err: log.error('Failed to write secret! %s: %s', type(err).__name__, err) return False
python
def write_raw(path, raw): ''' Set raw data at the path in vault. The vault policy used must allow this. CLI Example: .. code-block:: bash salt '*' vault.write_raw "secret/my/secret" '{"user":"foo","password": "bar"}' ''' log.debug('Writing vault secrets for %s at %s', __grains__['id'], path) try: url = 'v1/{0}'.format(path) response = __utils__['vault.make_request']('POST', url, json=raw) if response.status_code == 200: return response.json()['data'] elif response.status_code != 204: response.raise_for_status() return True except Exception as err: log.error('Failed to write secret! %s: %s', type(err).__name__, err) return False
[ "def", "write_raw", "(", "path", ",", "raw", ")", ":", "log", ".", "debug", "(", "'Writing vault secrets for %s at %s'", ",", "__grains__", "[", "'id'", "]", ",", "path", ")", "try", ":", "url", "=", "'v1/{0}'", ".", "format", "(", "path", ")", "response...
Set raw data at the path in vault. The vault policy used must allow this. CLI Example: .. code-block:: bash salt '*' vault.write_raw "secret/my/secret" '{"user":"foo","password": "bar"}'
[ "Set", "raw", "data", "at", "the", "path", "in", "vault", ".", "The", "vault", "policy", "used", "must", "allow", "this", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vault.py#L200-L221
train
saltstack/salt
salt/states/mdadm_raid.py
present
def present(name, level, devices, **kwargs): ''' Verify that the raid is present .. versionchanged:: 2014.7.0 name The name of raid device to be created level The RAID level to use when creating the raid. devices A list of devices used to build the array. kwargs Optional arguments to be passed to mdadm. Example: .. code-block:: yaml /dev/md0: raid.present: - level: 5 - devices: - /dev/xvdd - /dev/xvde - /dev/xvdf - chunk: 256 - run: True ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} # Device exists raids = __salt__['raid.list']() present = raids.get(name) # Decide whether to create or assemble missing = [] uuid_dict = {} new_devices = [] for dev in devices: if dev == 'missing' or not __salt__['file.access'](dev, 'f'): missing.append(dev) continue superblock = __salt__['raid.examine'](dev, quiet=True) if 'MD_UUID' in superblock: uuid = superblock['MD_UUID'] if uuid not in uuid_dict: uuid_dict[uuid] = [] uuid_dict[uuid].append(dev) else: new_devices.append(dev) if len(uuid_dict) > 1: ret['comment'] = 'Devices are a mix of RAID constituents with multiple MD_UUIDs: {0}.'.format( sorted(uuid_dict.keys())) ret['result'] = False return ret elif len(uuid_dict) == 1: uuid = list(uuid_dict.keys())[0] if present and present['uuid'] != uuid: ret['comment'] = 'Devices MD_UUIDs: {0} differs from present RAID uuid {1}.'.format(uuid, present['uuid']) ret['result'] = False return ret devices_with_superblock = uuid_dict[uuid] else: devices_with_superblock = [] if present: do_assemble = False do_create = False elif devices_with_superblock: do_assemble = True do_create = False verb = 'assembled' else: if not new_devices: ret['comment'] = 'All devices are missing: {0}.'.format(missing) ret['result'] = False return ret do_assemble = False do_create = True verb = 'created' # If running with test use the test_mode with create or assemble if __opts__['test']: if do_assemble: res = __salt__['raid.assemble'](name, devices_with_superblock, test_mode=True, **kwargs) elif do_create: res = __salt__['raid.create'](name, level, new_devices + ['missing'] * len(missing), test_mode=True, **kwargs) if present: ret['comment'] = 'Raid {0} already present.'.format(name) if do_assemble or do_create: ret['comment'] = 'Raid will be {0} with: {1}'.format(verb, res) ret['result'] = None if (do_assemble or present) and new_devices: ret['comment'] += ' New devices will be added: {0}'.format(new_devices) ret['result'] = None if missing: ret['comment'] += ' Missing devices: {0}'.format(missing) return ret # Attempt to create or assemble the array if do_assemble: __salt__['raid.assemble'](name, devices_with_superblock, **kwargs) elif do_create: __salt__['raid.create'](name, level, new_devices + ['missing'] * len(missing), **kwargs) if not present: raids = __salt__['raid.list']() changes = raids.get(name) if changes: ret['comment'] = 'Raid {0} {1}.'.format(name, verb) ret['changes'] = changes # Saving config __salt__['raid.save_config']() else: ret['comment'] = 'Raid {0} failed to be {1}.'.format(name, verb) ret['result'] = False else: ret['comment'] = 'Raid {0} already present.'.format(name) if (do_assemble or present) and new_devices and ret['result']: for d in new_devices: res = __salt__['raid.add'](name, d) if not res: ret['comment'] += ' Unable to add {0} to {1}.\n'.format(d, name) ret['result'] = False else: ret['comment'] += ' Added new device {0} to {1}.\n'.format(d, name) if ret['result']: ret['changes']['added'] = new_devices if missing: ret['comment'] += ' Missing devices: {0}'.format(missing) return ret
python
def present(name, level, devices, **kwargs): ''' Verify that the raid is present .. versionchanged:: 2014.7.0 name The name of raid device to be created level The RAID level to use when creating the raid. devices A list of devices used to build the array. kwargs Optional arguments to be passed to mdadm. Example: .. code-block:: yaml /dev/md0: raid.present: - level: 5 - devices: - /dev/xvdd - /dev/xvde - /dev/xvdf - chunk: 256 - run: True ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} # Device exists raids = __salt__['raid.list']() present = raids.get(name) # Decide whether to create or assemble missing = [] uuid_dict = {} new_devices = [] for dev in devices: if dev == 'missing' or not __salt__['file.access'](dev, 'f'): missing.append(dev) continue superblock = __salt__['raid.examine'](dev, quiet=True) if 'MD_UUID' in superblock: uuid = superblock['MD_UUID'] if uuid not in uuid_dict: uuid_dict[uuid] = [] uuid_dict[uuid].append(dev) else: new_devices.append(dev) if len(uuid_dict) > 1: ret['comment'] = 'Devices are a mix of RAID constituents with multiple MD_UUIDs: {0}.'.format( sorted(uuid_dict.keys())) ret['result'] = False return ret elif len(uuid_dict) == 1: uuid = list(uuid_dict.keys())[0] if present and present['uuid'] != uuid: ret['comment'] = 'Devices MD_UUIDs: {0} differs from present RAID uuid {1}.'.format(uuid, present['uuid']) ret['result'] = False return ret devices_with_superblock = uuid_dict[uuid] else: devices_with_superblock = [] if present: do_assemble = False do_create = False elif devices_with_superblock: do_assemble = True do_create = False verb = 'assembled' else: if not new_devices: ret['comment'] = 'All devices are missing: {0}.'.format(missing) ret['result'] = False return ret do_assemble = False do_create = True verb = 'created' # If running with test use the test_mode with create or assemble if __opts__['test']: if do_assemble: res = __salt__['raid.assemble'](name, devices_with_superblock, test_mode=True, **kwargs) elif do_create: res = __salt__['raid.create'](name, level, new_devices + ['missing'] * len(missing), test_mode=True, **kwargs) if present: ret['comment'] = 'Raid {0} already present.'.format(name) if do_assemble or do_create: ret['comment'] = 'Raid will be {0} with: {1}'.format(verb, res) ret['result'] = None if (do_assemble or present) and new_devices: ret['comment'] += ' New devices will be added: {0}'.format(new_devices) ret['result'] = None if missing: ret['comment'] += ' Missing devices: {0}'.format(missing) return ret # Attempt to create or assemble the array if do_assemble: __salt__['raid.assemble'](name, devices_with_superblock, **kwargs) elif do_create: __salt__['raid.create'](name, level, new_devices + ['missing'] * len(missing), **kwargs) if not present: raids = __salt__['raid.list']() changes = raids.get(name) if changes: ret['comment'] = 'Raid {0} {1}.'.format(name, verb) ret['changes'] = changes # Saving config __salt__['raid.save_config']() else: ret['comment'] = 'Raid {0} failed to be {1}.'.format(name, verb) ret['result'] = False else: ret['comment'] = 'Raid {0} already present.'.format(name) if (do_assemble or present) and new_devices and ret['result']: for d in new_devices: res = __salt__['raid.add'](name, d) if not res: ret['comment'] += ' Unable to add {0} to {1}.\n'.format(d, name) ret['result'] = False else: ret['comment'] += ' Added new device {0} to {1}.\n'.format(d, name) if ret['result']: ret['changes']['added'] = new_devices if missing: ret['comment'] += ' Missing devices: {0}'.format(missing) return ret
[ "def", "present", "(", "name", ",", "level", ",", "devices", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", ",", "'name'", ":", "name", ",", "'result'", ":", "True", "}", "# Device exist...
Verify that the raid is present .. versionchanged:: 2014.7.0 name The name of raid device to be created level The RAID level to use when creating the raid. devices A list of devices used to build the array. kwargs Optional arguments to be passed to mdadm. Example: .. code-block:: yaml /dev/md0: raid.present: - level: 5 - devices: - /dev/xvdd - /dev/xvde - /dev/xvdf - chunk: 256 - run: True
[ "Verify", "that", "the", "raid", "is", "present" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mdadm_raid.py#L48-L212
train
saltstack/salt
salt/renderers/hjson.py
render
def render(hjson_data, saltenv='base', sls='', **kws): ''' Accepts HJSON as a string or as a file object and runs it through the HJSON parser. :rtype: A Python data structure ''' if not isinstance(hjson_data, six.string_types): hjson_data = hjson_data.read() if hjson_data.startswith('#!'): hjson_data = hjson_data[(hjson_data.find('\n') + 1):] if not hjson_data.strip(): return {} return hjson.loads(hjson_data)
python
def render(hjson_data, saltenv='base', sls='', **kws): ''' Accepts HJSON as a string or as a file object and runs it through the HJSON parser. :rtype: A Python data structure ''' if not isinstance(hjson_data, six.string_types): hjson_data = hjson_data.read() if hjson_data.startswith('#!'): hjson_data = hjson_data[(hjson_data.find('\n') + 1):] if not hjson_data.strip(): return {} return hjson.loads(hjson_data)
[ "def", "render", "(", "hjson_data", ",", "saltenv", "=", "'base'", ",", "sls", "=", "''", ",", "*", "*", "kws", ")", ":", "if", "not", "isinstance", "(", "hjson_data", ",", "six", ".", "string_types", ")", ":", "hjson_data", "=", "hjson_data", ".", "...
Accepts HJSON as a string or as a file object and runs it through the HJSON parser. :rtype: A Python data structure
[ "Accepts", "HJSON", "as", "a", "string", "or", "as", "a", "file", "object", "and", "runs", "it", "through", "the", "HJSON", "parser", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/hjson.py#L23-L37
train
saltstack/salt
salt/states/boto_lambda.py
function_present
def function_present(name, FunctionName, Runtime, Role, Handler, ZipFile=None, S3Bucket=None, S3Key=None, S3ObjectVersion=None, Description='', Timeout=3, MemorySize=128, Permissions=None, RoleRetries=5, region=None, key=None, keyid=None, profile=None, VpcConfig=None, Environment=None): ''' Ensure function exists. name The name of the state definition FunctionName Name of the Function. Runtime The Runtime environment for the function. One of 'nodejs', 'java8', or 'python2.7' Role The name or ARN of the IAM role that the function assumes when it executes your function to access any other AWS resources. Handler The function within your code that Lambda calls to begin execution. For Node.js it is the module-name.*export* value in your function. For Java, it can be package.classname::handler or package.class-name. ZipFile A path to a .zip file containing your deployment package. If this is specified, S3Bucket and S3Key must not be specified. S3Bucket Amazon S3 bucket name where the .zip file containing your package is stored. If this is specified, S3Key must be specified and ZipFile must NOT be specified. S3Key The Amazon S3 object (the deployment package) key name you want to upload. If this is specified, S3Key must be specified and ZipFile must NOT be specified. S3ObjectVersion The version of S3 object to use. Optional, should only be specified if S3Bucket and S3Key are specified. Description A short, user-defined function description. Lambda does not use this value. Assign a meaningful description as you see fit. Timeout The function execution time at which Lambda should terminate this function. Because the execution time has cost implications, we recommend you set this value based on your expected execution time. The default is 3 seconds. MemorySize The amount of memory, in MB, your function is given. Lambda uses this memory size to infer the amount of CPU and memory allocated to your function. Your function use-case determines your CPU and memory requirements. For example, a database operation might need less memory compared to an image processing function. The default value is 128 MB. The value must be a multiple of 64 MB. VpcConfig If your Lambda function accesses resources in a VPC, you must provide this parameter identifying the list of security group IDs/Names and subnet IDs/Name. These must all belong to the same VPC. This is a dict of the form: .. code-block:: yaml VpcConfig: SecurityGroupNames: - mysecgroup1 - mysecgroup2 SecurityGroupIds: - sg-abcdef1234 SubnetNames: - mysubnet1 SubnetIds: - subnet-1234abcd - subnet-abcd1234 If VpcConfig is provided at all, you MUST pass at least one security group and one subnet. Permissions A list of permission definitions to be added to the function's policy RoleRetries IAM Roles may take some time to propagate to all regions once created. During that time function creation may fail; this state will atuomatically retry this number of times. The default is 5. Environment The parent object that contains your environment's configuration settings. This is a dictionary of the form: .. code-block:: python { 'Variables': { 'VariableName': 'VariableValue' } } .. versionadded:: 2017.7.0 region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': FunctionName, 'result': True, 'comment': '', 'changes': {} } if Permissions is not None: if isinstance(Permissions, six.string_types): Permissions = salt.utils.json.loads(Permissions) required_keys = set(('Action', 'Principal')) optional_keys = set(('SourceArn', 'SourceAccount', 'Qualifier')) for sid, permission in six.iteritems(Permissions): keyset = set(permission.keys()) if not keyset.issuperset(required_keys): raise SaltInvocationError('{0} are required for each permission ' 'specification'.format(', '.join(required_keys))) keyset = keyset - required_keys keyset = keyset - optional_keys if bool(keyset): raise SaltInvocationError( 'Invalid permission value {0}'.format(', '.join(keyset))) r = __salt__['boto_lambda.function_exists']( FunctionName=FunctionName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = ('Failed to create function: ' '{0}.'.format(r['error']['message'])) return ret if not r.get('exists'): if __opts__['test']: ret['comment'] = 'Function {0} is set to be created.'.format( FunctionName) ret['result'] = None return ret r = __salt__['boto_lambda.create_function']( FunctionName=FunctionName, Runtime=Runtime, Role=Role, Handler=Handler, ZipFile=ZipFile, S3Bucket=S3Bucket, S3Key=S3Key, S3ObjectVersion=S3ObjectVersion, Description=Description, Timeout=Timeout, MemorySize=MemorySize, VpcConfig=VpcConfig, Environment=Environment, WaitForRole=True, RoleRetries=RoleRetries, region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = ('Failed to create function: ' '{0}.'.format(r['error']['message'])) return ret if Permissions: for sid, permission in six.iteritems(Permissions): r = __salt__['boto_lambda.add_permission']( FunctionName=FunctionName, StatementId=sid, region=region, key=key, keyid=keyid, profile=profile, **permission) if not r.get('updated'): ret['result'] = False ret['comment'] = ('Failed to create function: ' '{0}.'.format(r['error']['message'])) _describe = __salt__['boto_lambda.describe_function']( FunctionName, region=region, key=key, keyid=keyid, profile=profile) _describe['function']['Permissions'] = ( __salt__['boto_lambda.get_permissions']( FunctionName, region=region, key=key, keyid=keyid, profile=profile)['permissions']) ret['changes']['old'] = {'function': None} ret['changes']['new'] = _describe ret['comment'] = 'Function {0} created.'.format(FunctionName) return ret ret['comment'] = os.linesep.join( [ret['comment'], 'Function {0} is present.'.format(FunctionName)]) ret['changes'] = {} # function exists, ensure config matches _ret = _function_config_present(FunctionName, Role, Handler, Description, Timeout, MemorySize, VpcConfig, Environment, region, key, keyid, profile, RoleRetries) if not _ret.get('result'): ret['result'] = _ret.get('result', False) ret['comment'] = _ret['comment'] ret['changes'] = {} return ret ret['changes'] = dictupdate.update(ret['changes'], _ret['changes']) ret['comment'] = ' '.join([ret['comment'], _ret['comment']]) _ret = _function_code_present(FunctionName, ZipFile, S3Bucket, S3Key, S3ObjectVersion, region, key, keyid, profile) if not _ret.get('result'): ret['result'] = _ret.get('result', False) ret['comment'] = _ret['comment'] ret['changes'] = {} return ret ret['changes'] = dictupdate.update(ret['changes'], _ret['changes']) ret['comment'] = ' '.join([ret['comment'], _ret['comment']]) _ret = _function_permissions_present(FunctionName, Permissions, region, key, keyid, profile) if not _ret.get('result'): ret['result'] = _ret.get('result', False) ret['comment'] = _ret['comment'] ret['changes'] = {} return ret ret['changes'] = dictupdate.update(ret['changes'], _ret['changes']) ret['comment'] = ' '.join([ret['comment'], _ret['comment']]) return ret
python
def function_present(name, FunctionName, Runtime, Role, Handler, ZipFile=None, S3Bucket=None, S3Key=None, S3ObjectVersion=None, Description='', Timeout=3, MemorySize=128, Permissions=None, RoleRetries=5, region=None, key=None, keyid=None, profile=None, VpcConfig=None, Environment=None): ''' Ensure function exists. name The name of the state definition FunctionName Name of the Function. Runtime The Runtime environment for the function. One of 'nodejs', 'java8', or 'python2.7' Role The name or ARN of the IAM role that the function assumes when it executes your function to access any other AWS resources. Handler The function within your code that Lambda calls to begin execution. For Node.js it is the module-name.*export* value in your function. For Java, it can be package.classname::handler or package.class-name. ZipFile A path to a .zip file containing your deployment package. If this is specified, S3Bucket and S3Key must not be specified. S3Bucket Amazon S3 bucket name where the .zip file containing your package is stored. If this is specified, S3Key must be specified and ZipFile must NOT be specified. S3Key The Amazon S3 object (the deployment package) key name you want to upload. If this is specified, S3Key must be specified and ZipFile must NOT be specified. S3ObjectVersion The version of S3 object to use. Optional, should only be specified if S3Bucket and S3Key are specified. Description A short, user-defined function description. Lambda does not use this value. Assign a meaningful description as you see fit. Timeout The function execution time at which Lambda should terminate this function. Because the execution time has cost implications, we recommend you set this value based on your expected execution time. The default is 3 seconds. MemorySize The amount of memory, in MB, your function is given. Lambda uses this memory size to infer the amount of CPU and memory allocated to your function. Your function use-case determines your CPU and memory requirements. For example, a database operation might need less memory compared to an image processing function. The default value is 128 MB. The value must be a multiple of 64 MB. VpcConfig If your Lambda function accesses resources in a VPC, you must provide this parameter identifying the list of security group IDs/Names and subnet IDs/Name. These must all belong to the same VPC. This is a dict of the form: .. code-block:: yaml VpcConfig: SecurityGroupNames: - mysecgroup1 - mysecgroup2 SecurityGroupIds: - sg-abcdef1234 SubnetNames: - mysubnet1 SubnetIds: - subnet-1234abcd - subnet-abcd1234 If VpcConfig is provided at all, you MUST pass at least one security group and one subnet. Permissions A list of permission definitions to be added to the function's policy RoleRetries IAM Roles may take some time to propagate to all regions once created. During that time function creation may fail; this state will atuomatically retry this number of times. The default is 5. Environment The parent object that contains your environment's configuration settings. This is a dictionary of the form: .. code-block:: python { 'Variables': { 'VariableName': 'VariableValue' } } .. versionadded:: 2017.7.0 region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': FunctionName, 'result': True, 'comment': '', 'changes': {} } if Permissions is not None: if isinstance(Permissions, six.string_types): Permissions = salt.utils.json.loads(Permissions) required_keys = set(('Action', 'Principal')) optional_keys = set(('SourceArn', 'SourceAccount', 'Qualifier')) for sid, permission in six.iteritems(Permissions): keyset = set(permission.keys()) if not keyset.issuperset(required_keys): raise SaltInvocationError('{0} are required for each permission ' 'specification'.format(', '.join(required_keys))) keyset = keyset - required_keys keyset = keyset - optional_keys if bool(keyset): raise SaltInvocationError( 'Invalid permission value {0}'.format(', '.join(keyset))) r = __salt__['boto_lambda.function_exists']( FunctionName=FunctionName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = ('Failed to create function: ' '{0}.'.format(r['error']['message'])) return ret if not r.get('exists'): if __opts__['test']: ret['comment'] = 'Function {0} is set to be created.'.format( FunctionName) ret['result'] = None return ret r = __salt__['boto_lambda.create_function']( FunctionName=FunctionName, Runtime=Runtime, Role=Role, Handler=Handler, ZipFile=ZipFile, S3Bucket=S3Bucket, S3Key=S3Key, S3ObjectVersion=S3ObjectVersion, Description=Description, Timeout=Timeout, MemorySize=MemorySize, VpcConfig=VpcConfig, Environment=Environment, WaitForRole=True, RoleRetries=RoleRetries, region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = ('Failed to create function: ' '{0}.'.format(r['error']['message'])) return ret if Permissions: for sid, permission in six.iteritems(Permissions): r = __salt__['boto_lambda.add_permission']( FunctionName=FunctionName, StatementId=sid, region=region, key=key, keyid=keyid, profile=profile, **permission) if not r.get('updated'): ret['result'] = False ret['comment'] = ('Failed to create function: ' '{0}.'.format(r['error']['message'])) _describe = __salt__['boto_lambda.describe_function']( FunctionName, region=region, key=key, keyid=keyid, profile=profile) _describe['function']['Permissions'] = ( __salt__['boto_lambda.get_permissions']( FunctionName, region=region, key=key, keyid=keyid, profile=profile)['permissions']) ret['changes']['old'] = {'function': None} ret['changes']['new'] = _describe ret['comment'] = 'Function {0} created.'.format(FunctionName) return ret ret['comment'] = os.linesep.join( [ret['comment'], 'Function {0} is present.'.format(FunctionName)]) ret['changes'] = {} # function exists, ensure config matches _ret = _function_config_present(FunctionName, Role, Handler, Description, Timeout, MemorySize, VpcConfig, Environment, region, key, keyid, profile, RoleRetries) if not _ret.get('result'): ret['result'] = _ret.get('result', False) ret['comment'] = _ret['comment'] ret['changes'] = {} return ret ret['changes'] = dictupdate.update(ret['changes'], _ret['changes']) ret['comment'] = ' '.join([ret['comment'], _ret['comment']]) _ret = _function_code_present(FunctionName, ZipFile, S3Bucket, S3Key, S3ObjectVersion, region, key, keyid, profile) if not _ret.get('result'): ret['result'] = _ret.get('result', False) ret['comment'] = _ret['comment'] ret['changes'] = {} return ret ret['changes'] = dictupdate.update(ret['changes'], _ret['changes']) ret['comment'] = ' '.join([ret['comment'], _ret['comment']]) _ret = _function_permissions_present(FunctionName, Permissions, region, key, keyid, profile) if not _ret.get('result'): ret['result'] = _ret.get('result', False) ret['comment'] = _ret['comment'] ret['changes'] = {} return ret ret['changes'] = dictupdate.update(ret['changes'], _ret['changes']) ret['comment'] = ' '.join([ret['comment'], _ret['comment']]) return ret
[ "def", "function_present", "(", "name", ",", "FunctionName", ",", "Runtime", ",", "Role", ",", "Handler", ",", "ZipFile", "=", "None", ",", "S3Bucket", "=", "None", ",", "S3Key", "=", "None", ",", "S3ObjectVersion", "=", "None", ",", "Description", "=", ...
Ensure function exists. name The name of the state definition FunctionName Name of the Function. Runtime The Runtime environment for the function. One of 'nodejs', 'java8', or 'python2.7' Role The name or ARN of the IAM role that the function assumes when it executes your function to access any other AWS resources. Handler The function within your code that Lambda calls to begin execution. For Node.js it is the module-name.*export* value in your function. For Java, it can be package.classname::handler or package.class-name. ZipFile A path to a .zip file containing your deployment package. If this is specified, S3Bucket and S3Key must not be specified. S3Bucket Amazon S3 bucket name where the .zip file containing your package is stored. If this is specified, S3Key must be specified and ZipFile must NOT be specified. S3Key The Amazon S3 object (the deployment package) key name you want to upload. If this is specified, S3Key must be specified and ZipFile must NOT be specified. S3ObjectVersion The version of S3 object to use. Optional, should only be specified if S3Bucket and S3Key are specified. Description A short, user-defined function description. Lambda does not use this value. Assign a meaningful description as you see fit. Timeout The function execution time at which Lambda should terminate this function. Because the execution time has cost implications, we recommend you set this value based on your expected execution time. The default is 3 seconds. MemorySize The amount of memory, in MB, your function is given. Lambda uses this memory size to infer the amount of CPU and memory allocated to your function. Your function use-case determines your CPU and memory requirements. For example, a database operation might need less memory compared to an image processing function. The default value is 128 MB. The value must be a multiple of 64 MB. VpcConfig If your Lambda function accesses resources in a VPC, you must provide this parameter identifying the list of security group IDs/Names and subnet IDs/Name. These must all belong to the same VPC. This is a dict of the form: .. code-block:: yaml VpcConfig: SecurityGroupNames: - mysecgroup1 - mysecgroup2 SecurityGroupIds: - sg-abcdef1234 SubnetNames: - mysubnet1 SubnetIds: - subnet-1234abcd - subnet-abcd1234 If VpcConfig is provided at all, you MUST pass at least one security group and one subnet. Permissions A list of permission definitions to be added to the function's policy RoleRetries IAM Roles may take some time to propagate to all regions once created. During that time function creation may fail; this state will atuomatically retry this number of times. The default is 5. Environment The parent object that contains your environment's configuration settings. This is a dictionary of the form: .. code-block:: python { 'Variables': { 'VariableName': 'VariableValue' } } .. versionadded:: 2017.7.0 region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid.
[ "Ensure", "function", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_lambda.py#L87-L311
train
saltstack/salt
salt/states/boto_lambda.py
alias_present
def alias_present(name, FunctionName, Name, FunctionVersion, Description='', region=None, key=None, keyid=None, profile=None): ''' Ensure alias exists. name The name of the state definition. FunctionName Name of the function for which you want to create an alias. Name The name of the alias to be created. FunctionVersion Function version for which you are creating the alias. Description A short, user-defined function description. Lambda does not use this value. Assign a meaningful description as you see fit. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': Name, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_lambda.alias_exists']( FunctionName=FunctionName, Name=Name, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = ('Failed to create alias: ' '{0}.'.format(r['error']['message'])) return ret if not r.get('exists'): if __opts__['test']: ret['comment'] = 'Alias {0} is set to be created.'.format(Name) ret['result'] = None return ret r = __salt__['boto_lambda.create_alias'](FunctionName, Name, FunctionVersion, Description, region, key, keyid, profile) if not r.get('created'): ret['result'] = False ret['comment'] = ('Failed to create alias: ' '{0}.'.format(r['error']['message'])) return ret _describe = __salt__['boto_lambda.describe_alias']( FunctionName, Name, region=region, key=key, keyid=keyid, profile=profile) ret['changes']['old'] = {'alias': None} ret['changes']['new'] = _describe ret['comment'] = 'Alias {0} created.'.format(Name) return ret ret['comment'] = os.linesep.join( [ret['comment'], 'Alias {0} is present.'.format(Name)]) ret['changes'] = {} _describe = __salt__['boto_lambda.describe_alias']( FunctionName, Name, region=region, key=key, keyid=keyid, profile=profile)['alias'] need_update = False options = {'FunctionVersion': FunctionVersion, 'Description': Description} for key, val in six.iteritems(options): if _describe[key] != val: need_update = True ret['changes'].setdefault('old', {})[key] = _describe[key] ret['changes'].setdefault('new', {})[key] = val if need_update: ret['comment'] = os.linesep.join( [ret['comment'], 'Alias config to be modified']) if __opts__['test']: ret['comment'] = 'Alias {0} set to be modified.'.format(Name) ret['result'] = None return ret _r = __salt__['boto_lambda.update_alias']( FunctionName=FunctionName, Name=Name, FunctionVersion=FunctionVersion, Description=Description, region=region, key=key, keyid=keyid, profile=profile) if not _r.get('updated'): ret['result'] = False ret['comment'] = ('Failed to update alias: ' '{0}.'.format(_r['error']['message'])) ret['changes'] = {} return ret
python
def alias_present(name, FunctionName, Name, FunctionVersion, Description='', region=None, key=None, keyid=None, profile=None): ''' Ensure alias exists. name The name of the state definition. FunctionName Name of the function for which you want to create an alias. Name The name of the alias to be created. FunctionVersion Function version for which you are creating the alias. Description A short, user-defined function description. Lambda does not use this value. Assign a meaningful description as you see fit. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': Name, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_lambda.alias_exists']( FunctionName=FunctionName, Name=Name, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = ('Failed to create alias: ' '{0}.'.format(r['error']['message'])) return ret if not r.get('exists'): if __opts__['test']: ret['comment'] = 'Alias {0} is set to be created.'.format(Name) ret['result'] = None return ret r = __salt__['boto_lambda.create_alias'](FunctionName, Name, FunctionVersion, Description, region, key, keyid, profile) if not r.get('created'): ret['result'] = False ret['comment'] = ('Failed to create alias: ' '{0}.'.format(r['error']['message'])) return ret _describe = __salt__['boto_lambda.describe_alias']( FunctionName, Name, region=region, key=key, keyid=keyid, profile=profile) ret['changes']['old'] = {'alias': None} ret['changes']['new'] = _describe ret['comment'] = 'Alias {0} created.'.format(Name) return ret ret['comment'] = os.linesep.join( [ret['comment'], 'Alias {0} is present.'.format(Name)]) ret['changes'] = {} _describe = __salt__['boto_lambda.describe_alias']( FunctionName, Name, region=region, key=key, keyid=keyid, profile=profile)['alias'] need_update = False options = {'FunctionVersion': FunctionVersion, 'Description': Description} for key, val in six.iteritems(options): if _describe[key] != val: need_update = True ret['changes'].setdefault('old', {})[key] = _describe[key] ret['changes'].setdefault('new', {})[key] = val if need_update: ret['comment'] = os.linesep.join( [ret['comment'], 'Alias config to be modified']) if __opts__['test']: ret['comment'] = 'Alias {0} set to be modified.'.format(Name) ret['result'] = None return ret _r = __salt__['boto_lambda.update_alias']( FunctionName=FunctionName, Name=Name, FunctionVersion=FunctionVersion, Description=Description, region=region, key=key, keyid=keyid, profile=profile) if not _r.get('updated'): ret['result'] = False ret['comment'] = ('Failed to update alias: ' '{0}.'.format(_r['error']['message'])) ret['changes'] = {} return ret
[ "def", "alias_present", "(", "name", ",", "FunctionName", ",", "Name", ",", "FunctionVersion", ",", "Description", "=", "''", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", ...
Ensure alias exists. name The name of the state definition. FunctionName Name of the function for which you want to create an alias. Name The name of the alias to be created. FunctionVersion Function version for which you are creating the alias. Description A short, user-defined function description. Lambda does not use this value. Assign a meaningful description as you see fit. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid.
[ "Ensure", "alias", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_lambda.py#L572-L675
train
saltstack/salt
salt/states/boto_lambda.py
event_source_mapping_present
def event_source_mapping_present(name, EventSourceArn, FunctionName, StartingPosition, Enabled=True, BatchSize=100, region=None, key=None, keyid=None, profile=None): ''' Ensure event source mapping exists. name The name of the state definition. EventSourceArn The Amazon Resource Name (ARN) of the Amazon Kinesis or the Amazon DynamoDB stream that is the event source. FunctionName The Lambda function to invoke when AWS Lambda detects an event on the stream. You can specify an unqualified function name (for example, "Thumbnail") or you can specify Amazon Resource Name (ARN) of the function (for example, "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail"). Note that the length constraint applies only to the ARN. If you specify only the function name, it is limited to 64 character in length. StartingPosition The position in the stream where AWS Lambda should start reading. (TRIM_HORIZON | LATEST) Enabled Indicates whether AWS Lambda should begin polling the event source. By default, Enabled is true. BatchSize The largest number of records that AWS Lambda will retrieve from your event source at the time of invoking your function. Your function receives an event with all the retrieved records. The default is 100 records. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': None, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_lambda.event_source_mapping_exists']( EventSourceArn=EventSourceArn, FunctionName=FunctionName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = ('Failed to create event source mapping: ' '{0}.'.format(r['error']['message'])) return ret if not r.get('exists'): if __opts__['test']: ret['comment'] = ('Event source mapping {0} is set ' 'to be created.'.format(FunctionName)) ret['result'] = None return ret r = __salt__['boto_lambda.create_event_source_mapping']( EventSourceArn=EventSourceArn, FunctionName=FunctionName, StartingPosition=StartingPosition, Enabled=Enabled, BatchSize=BatchSize, region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = ('Failed to create event source mapping: ' '{0}.'.format(r['error']['message'])) return ret _describe = __salt__['boto_lambda.describe_event_source_mapping']( EventSourceArn=EventSourceArn, FunctionName=FunctionName, region=region, key=key, keyid=keyid, profile=profile) ret['name'] = _describe['event_source_mapping']['UUID'] ret['changes']['old'] = {'event_source_mapping': None} ret['changes']['new'] = _describe ret['comment'] = ('Event source mapping {0} ' 'created.'.format(ret['name'])) return ret ret['comment'] = os.linesep.join( [ret['comment'], 'Event source mapping is present.']) ret['changes'] = {} _describe = __salt__['boto_lambda.describe_event_source_mapping']( EventSourceArn=EventSourceArn, FunctionName=FunctionName, region=region, key=key, keyid=keyid, profile=profile)['event_source_mapping'] need_update = False options = {'BatchSize': BatchSize} for key, val in six.iteritems(options): if _describe[key] != val: need_update = True ret['changes'].setdefault('old', {})[key] = _describe[key] ret['changes'].setdefault('new', {})[key] = val # verify FunctionName against FunctionArn function_arn = _get_function_arn(FunctionName, region=region, key=key, keyid=keyid, profile=profile) if _describe['FunctionArn'] != function_arn: need_update = True ret['changes'].setdefault('new', {})['FunctionArn'] = function_arn ret['changes'].setdefault('old', {})['FunctionArn'] = _describe[ 'FunctionArn'] # TODO check for 'Enabled', since it doesn't directly map to a specific # state if need_update: ret['comment'] = os.linesep.join( [ret['comment'], 'Event source mapping to be modified']) if __opts__['test']: ret['comment'] = ( 'Event source mapping {0} set to be modified.'.format( _describe['UUID'] ) ) ret['result'] = None return ret _r = __salt__['boto_lambda.update_event_source_mapping']( UUID=_describe['UUID'], FunctionName=FunctionName, Enabled=Enabled, BatchSize=BatchSize, region=region, key=key, keyid=keyid, profile=profile) if not _r.get('updated'): ret['result'] = False ret['comment'] = ('Failed to update mapping: ' '{0}.'.format(_r['error']['message'])) ret['changes'] = {} return ret
python
def event_source_mapping_present(name, EventSourceArn, FunctionName, StartingPosition, Enabled=True, BatchSize=100, region=None, key=None, keyid=None, profile=None): ''' Ensure event source mapping exists. name The name of the state definition. EventSourceArn The Amazon Resource Name (ARN) of the Amazon Kinesis or the Amazon DynamoDB stream that is the event source. FunctionName The Lambda function to invoke when AWS Lambda detects an event on the stream. You can specify an unqualified function name (for example, "Thumbnail") or you can specify Amazon Resource Name (ARN) of the function (for example, "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail"). Note that the length constraint applies only to the ARN. If you specify only the function name, it is limited to 64 character in length. StartingPosition The position in the stream where AWS Lambda should start reading. (TRIM_HORIZON | LATEST) Enabled Indicates whether AWS Lambda should begin polling the event source. By default, Enabled is true. BatchSize The largest number of records that AWS Lambda will retrieve from your event source at the time of invoking your function. Your function receives an event with all the retrieved records. The default is 100 records. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': None, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_lambda.event_source_mapping_exists']( EventSourceArn=EventSourceArn, FunctionName=FunctionName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = ('Failed to create event source mapping: ' '{0}.'.format(r['error']['message'])) return ret if not r.get('exists'): if __opts__['test']: ret['comment'] = ('Event source mapping {0} is set ' 'to be created.'.format(FunctionName)) ret['result'] = None return ret r = __salt__['boto_lambda.create_event_source_mapping']( EventSourceArn=EventSourceArn, FunctionName=FunctionName, StartingPosition=StartingPosition, Enabled=Enabled, BatchSize=BatchSize, region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = ('Failed to create event source mapping: ' '{0}.'.format(r['error']['message'])) return ret _describe = __salt__['boto_lambda.describe_event_source_mapping']( EventSourceArn=EventSourceArn, FunctionName=FunctionName, region=region, key=key, keyid=keyid, profile=profile) ret['name'] = _describe['event_source_mapping']['UUID'] ret['changes']['old'] = {'event_source_mapping': None} ret['changes']['new'] = _describe ret['comment'] = ('Event source mapping {0} ' 'created.'.format(ret['name'])) return ret ret['comment'] = os.linesep.join( [ret['comment'], 'Event source mapping is present.']) ret['changes'] = {} _describe = __salt__['boto_lambda.describe_event_source_mapping']( EventSourceArn=EventSourceArn, FunctionName=FunctionName, region=region, key=key, keyid=keyid, profile=profile)['event_source_mapping'] need_update = False options = {'BatchSize': BatchSize} for key, val in six.iteritems(options): if _describe[key] != val: need_update = True ret['changes'].setdefault('old', {})[key] = _describe[key] ret['changes'].setdefault('new', {})[key] = val # verify FunctionName against FunctionArn function_arn = _get_function_arn(FunctionName, region=region, key=key, keyid=keyid, profile=profile) if _describe['FunctionArn'] != function_arn: need_update = True ret['changes'].setdefault('new', {})['FunctionArn'] = function_arn ret['changes'].setdefault('old', {})['FunctionArn'] = _describe[ 'FunctionArn'] # TODO check for 'Enabled', since it doesn't directly map to a specific # state if need_update: ret['comment'] = os.linesep.join( [ret['comment'], 'Event source mapping to be modified']) if __opts__['test']: ret['comment'] = ( 'Event source mapping {0} set to be modified.'.format( _describe['UUID'] ) ) ret['result'] = None return ret _r = __salt__['boto_lambda.update_event_source_mapping']( UUID=_describe['UUID'], FunctionName=FunctionName, Enabled=Enabled, BatchSize=BatchSize, region=region, key=key, keyid=keyid, profile=profile) if not _r.get('updated'): ret['result'] = False ret['comment'] = ('Failed to update mapping: ' '{0}.'.format(_r['error']['message'])) ret['changes'] = {} return ret
[ "def", "event_source_mapping_present", "(", "name", ",", "EventSourceArn", ",", "FunctionName", ",", "StartingPosition", ",", "Enabled", "=", "True", ",", "BatchSize", "=", "100", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None"...
Ensure event source mapping exists. name The name of the state definition. EventSourceArn The Amazon Resource Name (ARN) of the Amazon Kinesis or the Amazon DynamoDB stream that is the event source. FunctionName The Lambda function to invoke when AWS Lambda detects an event on the stream. You can specify an unqualified function name (for example, "Thumbnail") or you can specify Amazon Resource Name (ARN) of the function (for example, "arn:aws:lambda:us-west-2:account-id:function:ThumbNail"). AWS Lambda also allows you to specify only the account ID qualifier (for example, "account-id:Thumbnail"). Note that the length constraint applies only to the ARN. If you specify only the function name, it is limited to 64 character in length. StartingPosition The position in the stream where AWS Lambda should start reading. (TRIM_HORIZON | LATEST) Enabled Indicates whether AWS Lambda should begin polling the event source. By default, Enabled is true. BatchSize The largest number of records that AWS Lambda will retrieve from your event source at the time of invoking your function. Your function receives an event with all the retrieved records. The default is 100 records. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid.
[ "Ensure", "event", "source", "mapping", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_lambda.py#L756-L897
train
saltstack/salt
salt/states/boto_lambda.py
event_source_mapping_absent
def event_source_mapping_absent(name, EventSourceArn, FunctionName, region=None, key=None, keyid=None, profile=None): ''' Ensure event source mapping with passed properties is absent. name The name of the state definition. EventSourceArn ARN of the event source. FunctionName Name of the lambda function. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': None, 'result': True, 'comment': '', 'changes': {} } desc = __salt__['boto_lambda.describe_event_source_mapping']( EventSourceArn=EventSourceArn, FunctionName=FunctionName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in desc: ret['result'] = False ret['comment'] = ('Failed to delete event source mapping: ' '{0}.'.format(desc['error']['message'])) return ret if not desc.get('event_source_mapping'): ret['comment'] = 'Event source mapping does not exist.' return ret ret['name'] = desc['event_source_mapping']['UUID'] if __opts__['test']: ret['comment'] = 'Event source mapping is set to be removed.' ret['result'] = None return ret r = __salt__['boto_lambda.delete_event_source_mapping']( EventSourceArn=EventSourceArn, FunctionName=FunctionName, region=region, key=key, keyid=keyid, profile=profile) if not r['deleted']: ret['result'] = False ret['comment'] = 'Failed to delete event source mapping: {0}.'.format(r['error'][ 'message']) return ret ret['changes']['old'] = desc ret['changes']['new'] = {'event_source_mapping': None} ret['comment'] = 'Event source mapping deleted.' return ret
python
def event_source_mapping_absent(name, EventSourceArn, FunctionName, region=None, key=None, keyid=None, profile=None): ''' Ensure event source mapping with passed properties is absent. name The name of the state definition. EventSourceArn ARN of the event source. FunctionName Name of the lambda function. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': None, 'result': True, 'comment': '', 'changes': {} } desc = __salt__['boto_lambda.describe_event_source_mapping']( EventSourceArn=EventSourceArn, FunctionName=FunctionName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in desc: ret['result'] = False ret['comment'] = ('Failed to delete event source mapping: ' '{0}.'.format(desc['error']['message'])) return ret if not desc.get('event_source_mapping'): ret['comment'] = 'Event source mapping does not exist.' return ret ret['name'] = desc['event_source_mapping']['UUID'] if __opts__['test']: ret['comment'] = 'Event source mapping is set to be removed.' ret['result'] = None return ret r = __salt__['boto_lambda.delete_event_source_mapping']( EventSourceArn=EventSourceArn, FunctionName=FunctionName, region=region, key=key, keyid=keyid, profile=profile) if not r['deleted']: ret['result'] = False ret['comment'] = 'Failed to delete event source mapping: {0}.'.format(r['error'][ 'message']) return ret ret['changes']['old'] = desc ret['changes']['new'] = {'event_source_mapping': None} ret['comment'] = 'Event source mapping deleted.' return ret
[ "def", "event_source_mapping_absent", "(", "name", ",", "EventSourceArn", ",", "FunctionName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "None", ...
Ensure event source mapping with passed properties is absent. name The name of the state definition. EventSourceArn ARN of the event source. FunctionName Name of the lambda function. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid.
[ "Ensure", "event", "source", "mapping", "with", "passed", "properties", "is", "absent", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_lambda.py#L900-L963
train
saltstack/salt
salt/modules/libcloud_loadbalancer.py
list_balancers
def list_balancers(profile, **libcloud_kwargs): ''' Return a list of load balancers. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_balancers method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_balancers profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) balancers = conn.list_balancers(**libcloud_kwargs) ret = [] for balancer in balancers: ret.append(_simple_balancer(balancer)) return ret
python
def list_balancers(profile, **libcloud_kwargs): ''' Return a list of load balancers. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_balancers method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_balancers profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) balancers = conn.list_balancers(**libcloud_kwargs) ret = [] for balancer in balancers: ret.append(_simple_balancer(balancer)) return ret
[ "def", "list_balancers", "(", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*", "libcloud_k...
Return a list of load balancers. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_balancers method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_balancers profile1
[ "Return", "a", "list", "of", "load", "balancers", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_loadbalancer.py#L104-L126
train
saltstack/salt
salt/modules/libcloud_loadbalancer.py
list_protocols
def list_protocols(profile, **libcloud_kwargs): ''' Return a list of supported protocols. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_protocols method :type libcloud_kwargs: ``dict`` :return: a list of supported protocols :rtype: ``list`` of ``str`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_protocols profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) return conn.list_protocols(**libcloud_kwargs)
python
def list_protocols(profile, **libcloud_kwargs): ''' Return a list of supported protocols. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_protocols method :type libcloud_kwargs: ``dict`` :return: a list of supported protocols :rtype: ``list`` of ``str`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_protocols profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) return conn.list_protocols(**libcloud_kwargs)
[ "def", "list_protocols", "(", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*", "libcloud_k...
Return a list of supported protocols. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_protocols method :type libcloud_kwargs: ``dict`` :return: a list of supported protocols :rtype: ``list`` of ``str`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_protocols profile1
[ "Return", "a", "list", "of", "supported", "protocols", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_loadbalancer.py#L129-L150
train
saltstack/salt
salt/modules/libcloud_loadbalancer.py
create_balancer
def create_balancer(name, port, protocol, profile, algorithm=None, members=None, **libcloud_kwargs): ''' Create a new load balancer instance :param name: Name of the new load balancer (required) :type name: ``str`` :param port: Port the load balancer should listen on, defaults to 80 :type port: ``str`` :param protocol: Loadbalancer protocol, defaults to http. :type protocol: ``str`` :param algorithm: Load balancing algorithm, defaults to ROUND_ROBIN. See Algorithm type in Libcloud documentation for a full listing. :type algorithm: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_balancer method :type libcloud_kwargs: ``dict`` :return: The details of the new balancer CLI Example: .. code-block:: bash salt myminion libcloud_storage.create_balancer my_balancer 80 http profile1 ''' if algorithm is None: algorithm = Algorithm.ROUND_ROBIN else: if isinstance(algorithm, six.string_types): algorithm = _algorithm_maps()[algorithm] starting_members = [] if members is not None: if isinstance(members, list): for m in members: starting_members.append(Member(id=None, ip=m['ip'], port=m['port'])) else: raise ValueError("members must be of type list") libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) conn = _get_driver(profile=profile) balancer = conn.create_balancer(name, port, protocol, algorithm, starting_members, **libcloud_kwargs) return _simple_balancer(balancer)
python
def create_balancer(name, port, protocol, profile, algorithm=None, members=None, **libcloud_kwargs): ''' Create a new load balancer instance :param name: Name of the new load balancer (required) :type name: ``str`` :param port: Port the load balancer should listen on, defaults to 80 :type port: ``str`` :param protocol: Loadbalancer protocol, defaults to http. :type protocol: ``str`` :param algorithm: Load balancing algorithm, defaults to ROUND_ROBIN. See Algorithm type in Libcloud documentation for a full listing. :type algorithm: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_balancer method :type libcloud_kwargs: ``dict`` :return: The details of the new balancer CLI Example: .. code-block:: bash salt myminion libcloud_storage.create_balancer my_balancer 80 http profile1 ''' if algorithm is None: algorithm = Algorithm.ROUND_ROBIN else: if isinstance(algorithm, six.string_types): algorithm = _algorithm_maps()[algorithm] starting_members = [] if members is not None: if isinstance(members, list): for m in members: starting_members.append(Member(id=None, ip=m['ip'], port=m['port'])) else: raise ValueError("members must be of type list") libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) conn = _get_driver(profile=profile) balancer = conn.create_balancer(name, port, protocol, algorithm, starting_members, **libcloud_kwargs) return _simple_balancer(balancer)
[ "def", "create_balancer", "(", "name", ",", "port", ",", "protocol", ",", "profile", ",", "algorithm", "=", "None", ",", "members", "=", "None", ",", "*", "*", "libcloud_kwargs", ")", ":", "if", "algorithm", "is", "None", ":", "algorithm", "=", "Algorith...
Create a new load balancer instance :param name: Name of the new load balancer (required) :type name: ``str`` :param port: Port the load balancer should listen on, defaults to 80 :type port: ``str`` :param protocol: Loadbalancer protocol, defaults to http. :type protocol: ``str`` :param algorithm: Load balancing algorithm, defaults to ROUND_ROBIN. See Algorithm type in Libcloud documentation for a full listing. :type algorithm: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_balancer method :type libcloud_kwargs: ``dict`` :return: The details of the new balancer CLI Example: .. code-block:: bash salt myminion libcloud_storage.create_balancer my_balancer 80 http profile1
[ "Create", "a", "new", "load", "balancer", "instance" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_loadbalancer.py#L153-L200
train
saltstack/salt
salt/modules/libcloud_loadbalancer.py
destroy_balancer
def destroy_balancer(balancer_id, profile, **libcloud_kwargs): ''' Destroy a load balancer :param balancer_id: LoadBalancer ID which should be used :type balancer_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's destroy_balancer method :type libcloud_kwargs: ``dict`` :return: ``True`` if the destroy was successful, otherwise ``False``. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.destroy_balancer balancer_1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) balancer = conn.get_balancer(balancer_id) return conn.destroy_balancer(balancer, **libcloud_kwargs)
python
def destroy_balancer(balancer_id, profile, **libcloud_kwargs): ''' Destroy a load balancer :param balancer_id: LoadBalancer ID which should be used :type balancer_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's destroy_balancer method :type libcloud_kwargs: ``dict`` :return: ``True`` if the destroy was successful, otherwise ``False``. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.destroy_balancer balancer_1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) balancer = conn.get_balancer(balancer_id) return conn.destroy_balancer(balancer, **libcloud_kwargs)
[ "def", "destroy_balancer", "(", "balancer_id", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", ...
Destroy a load balancer :param balancer_id: LoadBalancer ID which should be used :type balancer_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's destroy_balancer method :type libcloud_kwargs: ``dict`` :return: ``True`` if the destroy was successful, otherwise ``False``. :rtype: ``bool`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.destroy_balancer balancer_1 profile1
[ "Destroy", "a", "load", "balancer" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_loadbalancer.py#L203-L228
train
saltstack/salt
salt/modules/libcloud_loadbalancer.py
get_balancer_by_name
def get_balancer_by_name(name, profile, **libcloud_kwargs): ''' Get the details for a load balancer by name :param name: Name of a load balancer you want to fetch :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_balancers method :type libcloud_kwargs: ``dict`` :return: the load balancer details CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_balancer_by_name my_balancer profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) balancers = conn.list_balancers(**libcloud_kwargs) match = [b for b in balancers if b.name == name] if len(match) == 1: return _simple_balancer(match[0]) elif len(match) > 1: raise ValueError("Ambiguous argument, found mulitple records") else: raise ValueError("Bad argument, found no records")
python
def get_balancer_by_name(name, profile, **libcloud_kwargs): ''' Get the details for a load balancer by name :param name: Name of a load balancer you want to fetch :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_balancers method :type libcloud_kwargs: ``dict`` :return: the load balancer details CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_balancer_by_name my_balancer profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) balancers = conn.list_balancers(**libcloud_kwargs) match = [b for b in balancers if b.name == name] if len(match) == 1: return _simple_balancer(match[0]) elif len(match) > 1: raise ValueError("Ambiguous argument, found mulitple records") else: raise ValueError("Bad argument, found no records")
[ "def", "get_balancer_by_name", "(", "name", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*...
Get the details for a load balancer by name :param name: Name of a load balancer you want to fetch :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_balancers method :type libcloud_kwargs: ``dict`` :return: the load balancer details CLI Example: .. code-block:: bash salt myminion libcloud_storage.get_balancer_by_name my_balancer profile1
[ "Get", "the", "details", "for", "a", "load", "balancer", "by", "name" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_loadbalancer.py#L231-L261
train
saltstack/salt
salt/modules/libcloud_loadbalancer.py
balancer_attach_member
def balancer_attach_member(balancer_id, ip, port, profile, extra=None, **libcloud_kwargs): ''' Add a new member to the load balancer :param balancer_id: id of a load balancer you want to fetch :type balancer_id: ``str`` :param ip: IP address for the new member :type ip: ``str`` :param port: Port for the new member :type port: ``int`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's balancer_attach_member method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.balancer_attach_member balancer123 1.2.3.4 80 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) member = Member(id=None, ip=ip, port=port, balancer=None, extra=extra) balancer = conn.get_balancer(balancer_id) member_saved = conn.balancer_attach_member(balancer, member, **libcloud_kwargs) return _simple_member(member_saved)
python
def balancer_attach_member(balancer_id, ip, port, profile, extra=None, **libcloud_kwargs): ''' Add a new member to the load balancer :param balancer_id: id of a load balancer you want to fetch :type balancer_id: ``str`` :param ip: IP address for the new member :type ip: ``str`` :param port: Port for the new member :type port: ``int`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's balancer_attach_member method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.balancer_attach_member balancer123 1.2.3.4 80 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) member = Member(id=None, ip=ip, port=port, balancer=None, extra=extra) balancer = conn.get_balancer(balancer_id) member_saved = conn.balancer_attach_member(balancer, member, **libcloud_kwargs) return _simple_member(member_saved)
[ "def", "balancer_attach_member", "(", "balancer_id", ",", "ip", ",", "port", ",", "profile", ",", "extra", "=", "None", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "sa...
Add a new member to the load balancer :param balancer_id: id of a load balancer you want to fetch :type balancer_id: ``str`` :param ip: IP address for the new member :type ip: ``str`` :param port: Port for the new member :type port: ``int`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's balancer_attach_member method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.balancer_attach_member balancer123 1.2.3.4 80 profile1
[ "Add", "a", "new", "member", "to", "the", "load", "balancer" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_loadbalancer.py#L314-L344
train
saltstack/salt
salt/modules/libcloud_loadbalancer.py
balancer_detach_member
def balancer_detach_member(balancer_id, member_id, profile, **libcloud_kwargs): ''' Add a new member to the load balancer :param balancer_id: id of a load balancer you want to fetch :type balancer_id: ``str`` :param ip: IP address for the new member :type ip: ``str`` :param port: Port for the new member :type port: ``int`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's balancer_detach_member method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.balancer_detach_member balancer123 member123 profile1 ''' conn = _get_driver(profile=profile) balancer = conn.get_balancer(balancer_id) members = conn.balancer_list_members(balancer=balancer) match = [member for member in members if member.id == member_id] if len(match) > 1: raise ValueError("Ambiguous argument, found mulitple records") elif not match: raise ValueError("Bad argument, found no records") else: member = match[0] libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) return conn.balancer_detach_member(balancer=balancer, member=member, **libcloud_kwargs)
python
def balancer_detach_member(balancer_id, member_id, profile, **libcloud_kwargs): ''' Add a new member to the load balancer :param balancer_id: id of a load balancer you want to fetch :type balancer_id: ``str`` :param ip: IP address for the new member :type ip: ``str`` :param port: Port for the new member :type port: ``int`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's balancer_detach_member method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.balancer_detach_member balancer123 member123 profile1 ''' conn = _get_driver(profile=profile) balancer = conn.get_balancer(balancer_id) members = conn.balancer_list_members(balancer=balancer) match = [member for member in members if member.id == member_id] if len(match) > 1: raise ValueError("Ambiguous argument, found mulitple records") elif not match: raise ValueError("Bad argument, found no records") else: member = match[0] libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) return conn.balancer_detach_member(balancer=balancer, member=member, **libcloud_kwargs)
[ "def", "balancer_detach_member", "(", "balancer_id", ",", "member_id", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "balancer", "=", "conn", ".", "get_balancer", "(", "balancer_id"...
Add a new member to the load balancer :param balancer_id: id of a load balancer you want to fetch :type balancer_id: ``str`` :param ip: IP address for the new member :type ip: ``str`` :param port: Port for the new member :type port: ``int`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's balancer_detach_member method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.balancer_detach_member balancer123 member123 profile1
[ "Add", "a", "new", "member", "to", "the", "load", "balancer" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_loadbalancer.py#L347-L383
train
saltstack/salt
salt/modules/libcloud_loadbalancer.py
list_balancer_members
def list_balancer_members(balancer_id, profile, **libcloud_kwargs): ''' List the members of a load balancer :param balancer_id: id of a load balancer you want to fetch :type balancer_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_balancer_members method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_balancer_members balancer123 profile1 ''' conn = _get_driver(profile=profile) balancer = conn.get_balancer(balancer_id) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) members = conn.balancer_list_members(balancer=balancer, **libcloud_kwargs) return [_simple_member(member) for member in members]
python
def list_balancer_members(balancer_id, profile, **libcloud_kwargs): ''' List the members of a load balancer :param balancer_id: id of a load balancer you want to fetch :type balancer_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_balancer_members method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_balancer_members balancer123 profile1 ''' conn = _get_driver(profile=profile) balancer = conn.get_balancer(balancer_id) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) members = conn.balancer_list_members(balancer=balancer, **libcloud_kwargs) return [_simple_member(member) for member in members]
[ "def", "list_balancer_members", "(", "balancer_id", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "balancer", "=", "conn", ".", "get_balancer", "(", "balancer_id", ")", "libcloud_kw...
List the members of a load balancer :param balancer_id: id of a load balancer you want to fetch :type balancer_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_balancer_members method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_storage.list_balancer_members balancer123 profile1
[ "List", "the", "members", "of", "a", "load", "balancer" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_loadbalancer.py#L386-L409
train
saltstack/salt
salt/modules/libcloud_loadbalancer.py
extra
def extra(method, profile, **libcloud_kwargs): ''' Call an extended method on the driver :param method: Driver's method name :type method: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_loadbalancer.extra ex_get_permissions google container_name=my_container object_name=me.jpg --out=yaml ''' libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) conn = _get_driver(profile=profile) connection_method = getattr(conn, method) return connection_method(**libcloud_kwargs)
python
def extra(method, profile, **libcloud_kwargs): ''' Call an extended method on the driver :param method: Driver's method name :type method: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_loadbalancer.extra ex_get_permissions google container_name=my_container object_name=me.jpg --out=yaml ''' libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) conn = _get_driver(profile=profile) connection_method = getattr(conn, method) return connection_method(**libcloud_kwargs)
[ "def", "extra", "(", "method", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*", "libcloud_kwargs", ")", "conn", "=", "_get_driver", "(", "profile", ...
Call an extended method on the driver :param method: Driver's method name :type method: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_loadbalancer.extra ex_get_permissions google container_name=my_container object_name=me.jpg --out=yaml
[ "Call", "an", "extended", "method", "on", "the", "driver" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_loadbalancer.py#L412-L434
train
saltstack/salt
salt/states/alternatives.py
install
def install(name, link, path, priority): ''' Install new alternative for defined <name> name is the master name for this link group (e.g. pager) link is the symlink pointing to /etc/alternatives/<name>. (e.g. /usr/bin/pager) path is the location of the new alternative target. NB: This file / directory must already exist. (e.g. /usr/bin/less) priority is an integer; options with higher numbers have higher priority in automatic mode. ''' ret = {'name': name, 'link': link, 'path': path, 'priority': priority, 'result': True, 'changes': {}, 'comment': ''} if __salt__['alternatives.check_exists'](name, path): ret['comment'] = 'Alternative {0} for {1} is already registered'.format(path, name) else: if __opts__['test']: ret['comment'] = ( 'Alternative will be set for {0} to {1} with priority {2}' ).format(name, path, priority) ret['result'] = None return ret out = __salt__['alternatives.install'](name, link, path, priority) if __salt__['alternatives.check_exists'](name, path): if __salt__['alternatives.check_installed'](name, path): ret['comment'] = ( 'Alternative for {0} set to path {1} with priority {2}' ).format(name, path, priority) else: ret['comment'] = ( 'Alternative {0} for {1} registered with priority {2} and not set to default' ).format(path, name, priority) ret['changes'] = {'name': name, 'link': link, 'path': path, 'priority': priority} else: ret['result'] = False ret['comment'] = ( 'Alternative for {0} not installed: {1}' ).format(name, out) return ret
python
def install(name, link, path, priority): ''' Install new alternative for defined <name> name is the master name for this link group (e.g. pager) link is the symlink pointing to /etc/alternatives/<name>. (e.g. /usr/bin/pager) path is the location of the new alternative target. NB: This file / directory must already exist. (e.g. /usr/bin/less) priority is an integer; options with higher numbers have higher priority in automatic mode. ''' ret = {'name': name, 'link': link, 'path': path, 'priority': priority, 'result': True, 'changes': {}, 'comment': ''} if __salt__['alternatives.check_exists'](name, path): ret['comment'] = 'Alternative {0} for {1} is already registered'.format(path, name) else: if __opts__['test']: ret['comment'] = ( 'Alternative will be set for {0} to {1} with priority {2}' ).format(name, path, priority) ret['result'] = None return ret out = __salt__['alternatives.install'](name, link, path, priority) if __salt__['alternatives.check_exists'](name, path): if __salt__['alternatives.check_installed'](name, path): ret['comment'] = ( 'Alternative for {0} set to path {1} with priority {2}' ).format(name, path, priority) else: ret['comment'] = ( 'Alternative {0} for {1} registered with priority {2} and not set to default' ).format(path, name, priority) ret['changes'] = {'name': name, 'link': link, 'path': path, 'priority': priority} else: ret['result'] = False ret['comment'] = ( 'Alternative for {0} not installed: {1}' ).format(name, out) return ret
[ "def", "install", "(", "name", ",", "link", ",", "path", ",", "priority", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'link'", ":", "link", ",", "'path'", ":", "path", ",", "'priority'", ":", "priority", ",", "'result'", ":", "True", ",...
Install new alternative for defined <name> name is the master name for this link group (e.g. pager) link is the symlink pointing to /etc/alternatives/<name>. (e.g. /usr/bin/pager) path is the location of the new alternative target. NB: This file / directory must already exist. (e.g. /usr/bin/less) priority is an integer; options with higher numbers have higher priority in automatic mode.
[ "Install", "new", "alternative", "for", "defined", "<name", ">" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/alternatives.py#L44-L103
train
saltstack/salt
salt/states/alternatives.py
remove
def remove(name, path): ''' Removes installed alternative for defined <name> and <path> or fallback to default alternative, if some defined before. name is the master name for this link group (e.g. pager) path is the location of one of the alternative target files. (e.g. /usr/bin/less) ''' ret = {'name': name, 'path': path, 'result': True, 'changes': {}, 'comment': ''} isinstalled = __salt__['alternatives.check_exists'](name, path) if isinstalled: if __opts__['test']: ret['comment'] = ('Alternative for {0} will be removed' .format(name)) ret['result'] = None return ret __salt__['alternatives.remove'](name, path) current = __salt__['alternatives.show_current'](name) if current: ret['result'] = True ret['comment'] = ( 'Alternative for {0} removed. Falling back to path {1}' ).format(name, current) ret['changes'] = {'path': current} return ret ret['comment'] = 'Alternative for {0} removed'.format(name) ret['changes'] = {} return ret current = __salt__['alternatives.show_current'](name) if current: ret['result'] = True ret['comment'] = ( 'Alternative for {0} is set to it\'s default path {1}' ).format(name, current) return ret ret['result'] = False ret['comment'] = ( 'Alternative for {0} doesn\'t exist' ).format(name) return ret
python
def remove(name, path): ''' Removes installed alternative for defined <name> and <path> or fallback to default alternative, if some defined before. name is the master name for this link group (e.g. pager) path is the location of one of the alternative target files. (e.g. /usr/bin/less) ''' ret = {'name': name, 'path': path, 'result': True, 'changes': {}, 'comment': ''} isinstalled = __salt__['alternatives.check_exists'](name, path) if isinstalled: if __opts__['test']: ret['comment'] = ('Alternative for {0} will be removed' .format(name)) ret['result'] = None return ret __salt__['alternatives.remove'](name, path) current = __salt__['alternatives.show_current'](name) if current: ret['result'] = True ret['comment'] = ( 'Alternative for {0} removed. Falling back to path {1}' ).format(name, current) ret['changes'] = {'path': current} return ret ret['comment'] = 'Alternative for {0} removed'.format(name) ret['changes'] = {} return ret current = __salt__['alternatives.show_current'](name) if current: ret['result'] = True ret['comment'] = ( 'Alternative for {0} is set to it\'s default path {1}' ).format(name, current) return ret ret['result'] = False ret['comment'] = ( 'Alternative for {0} doesn\'t exist' ).format(name) return ret
[ "def", "remove", "(", "name", ",", "path", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'path'", ":", "path", ",", "'result'", ":", "True", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", "}", "isinstalled", "=", "__salt__"...
Removes installed alternative for defined <name> and <path> or fallback to default alternative, if some defined before. name is the master name for this link group (e.g. pager) path is the location of one of the alternative target files. (e.g. /usr/bin/less)
[ "Removes", "installed", "alternative", "for", "defined", "<name", ">", "and", "<path", ">", "or", "fallback", "to", "default", "alternative", "if", "some", "defined", "before", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/alternatives.py#L106-L159
train
saltstack/salt
salt/states/alternatives.py
auto
def auto(name): ''' .. versionadded:: 0.17.0 Instruct alternatives to use the highest priority path for <name> name is the master name for this link group (e.g. pager) ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} display = __salt__['alternatives.display'](name) line = display.splitlines()[0] if line.endswith(' auto mode'): ret['comment'] = '{0} already in auto mode'.format(name) return ret if __opts__['test']: ret['comment'] = '{0} will be put in auto mode'.format(name) ret['result'] = None return ret ret['changes']['result'] = __salt__['alternatives.auto'](name) return ret
python
def auto(name): ''' .. versionadded:: 0.17.0 Instruct alternatives to use the highest priority path for <name> name is the master name for this link group (e.g. pager) ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} display = __salt__['alternatives.display'](name) line = display.splitlines()[0] if line.endswith(' auto mode'): ret['comment'] = '{0} already in auto mode'.format(name) return ret if __opts__['test']: ret['comment'] = '{0} will be put in auto mode'.format(name) ret['result'] = None return ret ret['changes']['result'] = __salt__['alternatives.auto'](name) return ret
[ "def", "auto", "(", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "display", "=", "__salt__", "[", "'alternatives.display'", "]", "(", "name"...
.. versionadded:: 0.17.0 Instruct alternatives to use the highest priority path for <name> name is the master name for this link group (e.g. pager)
[ "..", "versionadded", "::", "0", ".", "17", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/alternatives.py#L162-L190
train
saltstack/salt
salt/states/alternatives.py
set_
def set_(name, path): ''' .. versionadded:: 0.17.0 Sets alternative for <name> to <path>, if <path> is defined as an alternative for <name>. name is the master name for this link group (e.g. pager) path is the location of one of the alternative target files. (e.g. /usr/bin/less) .. code-block:: yaml foo: alternatives.set: - path: /usr/bin/foo-2.0 ''' ret = {'name': name, 'path': path, 'result': True, 'changes': {}, 'comment': ''} current = __salt__['alternatives.show_current'](name) if current == path: ret['comment'] = 'Alternative for {0} already set to {1}'.format(name, path) return ret display = __salt__['alternatives.display'](name) isinstalled = False for line in display.splitlines(): if line.startswith(path): isinstalled = True break if isinstalled: if __opts__['test']: ret['comment'] = ( 'Alternative for {0} will be set to path {1}' ).format(name, path) ret['result'] = None return ret __salt__['alternatives.set'](name, path) current = __salt__['alternatives.show_current'](name) if current == path: ret['comment'] = ( 'Alternative for {0} set to path {1}' ).format(name, current) ret['changes'] = {'path': current} else: ret['comment'] = 'Alternative for {0} not updated'.format(name) return ret else: ret['result'] = False ret['comment'] = ( 'Alternative {0} for {1} doesn\'t exist' ).format(path, name) return ret
python
def set_(name, path): ''' .. versionadded:: 0.17.0 Sets alternative for <name> to <path>, if <path> is defined as an alternative for <name>. name is the master name for this link group (e.g. pager) path is the location of one of the alternative target files. (e.g. /usr/bin/less) .. code-block:: yaml foo: alternatives.set: - path: /usr/bin/foo-2.0 ''' ret = {'name': name, 'path': path, 'result': True, 'changes': {}, 'comment': ''} current = __salt__['alternatives.show_current'](name) if current == path: ret['comment'] = 'Alternative for {0} already set to {1}'.format(name, path) return ret display = __salt__['alternatives.display'](name) isinstalled = False for line in display.splitlines(): if line.startswith(path): isinstalled = True break if isinstalled: if __opts__['test']: ret['comment'] = ( 'Alternative for {0} will be set to path {1}' ).format(name, path) ret['result'] = None return ret __salt__['alternatives.set'](name, path) current = __salt__['alternatives.show_current'](name) if current == path: ret['comment'] = ( 'Alternative for {0} set to path {1}' ).format(name, current) ret['changes'] = {'path': current} else: ret['comment'] = 'Alternative for {0} not updated'.format(name) return ret else: ret['result'] = False ret['comment'] = ( 'Alternative {0} for {1} doesn\'t exist' ).format(path, name) return ret
[ "def", "set_", "(", "name", ",", "path", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'path'", ":", "path", ",", "'result'", ":", "True", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", "}", "current", "=", "__salt__", "[...
.. versionadded:: 0.17.0 Sets alternative for <name> to <path>, if <path> is defined as an alternative for <name>. name is the master name for this link group (e.g. pager) path is the location of one of the alternative target files. (e.g. /usr/bin/less) .. code-block:: yaml foo: alternatives.set: - path: /usr/bin/foo-2.0
[ "..", "versionadded", "::", "0", ".", "17", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/alternatives.py#L193-L257
train
saltstack/salt
salt/states/grafana4_datasource.py
present
def present(name, type, url, access=None, user=None, password=None, database=None, basic_auth=None, basic_auth_user=None, basic_auth_password=None, tls_auth=None, json_data=None, is_default=None, with_credentials=None, type_logo_url=None, orgname=None, profile='grafana'): ''' Ensure that a data source is present. name Name of the data source. type Type of the datasource ('graphite', 'influxdb' etc.). access Use proxy or direct. Default: proxy url The URL to the data source API. user Optional - user to authenticate with the data source. password Optional - password to authenticate with the data source. database Optional - database to use with the data source. basic_auth Optional - set to True to use HTTP basic auth to authenticate with the data source. basic_auth_user Optional - HTTP basic auth username. basic_auth_password Optional - HTTP basic auth password. json_data Optional - additional json data to post (eg. "timeInterval"). is_default Optional - set data source as default. with_credentials Optional - Whether credentials such as cookies or auth headers should be sent with cross-site requests. type_logo_url Optional - Logo to use for this datasource. orgname Name of the organization in which the data source should be present. profile Configuration profile used to connect to the Grafana instance. Default is 'grafana'. ''' if isinstance(profile, string_types): profile = __salt__['config.option'](profile) ret = {'name': name, 'result': None, 'comment': None, 'changes': {}} datasource = __salt__['grafana4.get_datasource'](name, orgname, profile) data = _get_json_data( name=name, type=type, url=url, access=access, user=user, password=password, database=database, basicAuth=basic_auth, basicAuthUser=basic_auth_user, basicAuthPassword=basic_auth_password, tlsAuth=tls_auth, jsonData=json_data, isDefault=is_default, withCredentials=with_credentials, typeLogoUrl=type_logo_url, defaults=datasource) if not datasource: if __opts__['test']: ret['comment'] = 'Datasource {0} will be created'.format(name) return ret __salt__['grafana4.create_datasource'](profile=profile, **data) datasource = __salt__['grafana4.get_datasource'](name, profile=profile) ret['result'] = True ret['comment'] = 'New data source {0} added'.format(name) ret['changes'] = data return ret # At this stage, the datasource exists; however, the object provided by # Grafana may lack some null keys compared to our "data" dict: for key in data: if key not in datasource: datasource[key] = None if data == datasource: ret['comment'] = 'Data source {0} already up-to-date'.format(name) return ret if __opts__['test']: ret['comment'] = 'Datasource {0} will be updated'.format(name) return ret __salt__['grafana4.update_datasource']( datasource['id'], profile=profile, **data) ret['result'] = True ret['changes'] = deep_diff(datasource, data, ignore=['id', 'orgId', 'readOnly']) ret['comment'] = 'Data source {0} updated'.format(name) return ret
python
def present(name, type, url, access=None, user=None, password=None, database=None, basic_auth=None, basic_auth_user=None, basic_auth_password=None, tls_auth=None, json_data=None, is_default=None, with_credentials=None, type_logo_url=None, orgname=None, profile='grafana'): ''' Ensure that a data source is present. name Name of the data source. type Type of the datasource ('graphite', 'influxdb' etc.). access Use proxy or direct. Default: proxy url The URL to the data source API. user Optional - user to authenticate with the data source. password Optional - password to authenticate with the data source. database Optional - database to use with the data source. basic_auth Optional - set to True to use HTTP basic auth to authenticate with the data source. basic_auth_user Optional - HTTP basic auth username. basic_auth_password Optional - HTTP basic auth password. json_data Optional - additional json data to post (eg. "timeInterval"). is_default Optional - set data source as default. with_credentials Optional - Whether credentials such as cookies or auth headers should be sent with cross-site requests. type_logo_url Optional - Logo to use for this datasource. orgname Name of the organization in which the data source should be present. profile Configuration profile used to connect to the Grafana instance. Default is 'grafana'. ''' if isinstance(profile, string_types): profile = __salt__['config.option'](profile) ret = {'name': name, 'result': None, 'comment': None, 'changes': {}} datasource = __salt__['grafana4.get_datasource'](name, orgname, profile) data = _get_json_data( name=name, type=type, url=url, access=access, user=user, password=password, database=database, basicAuth=basic_auth, basicAuthUser=basic_auth_user, basicAuthPassword=basic_auth_password, tlsAuth=tls_auth, jsonData=json_data, isDefault=is_default, withCredentials=with_credentials, typeLogoUrl=type_logo_url, defaults=datasource) if not datasource: if __opts__['test']: ret['comment'] = 'Datasource {0} will be created'.format(name) return ret __salt__['grafana4.create_datasource'](profile=profile, **data) datasource = __salt__['grafana4.get_datasource'](name, profile=profile) ret['result'] = True ret['comment'] = 'New data source {0} added'.format(name) ret['changes'] = data return ret # At this stage, the datasource exists; however, the object provided by # Grafana may lack some null keys compared to our "data" dict: for key in data: if key not in datasource: datasource[key] = None if data == datasource: ret['comment'] = 'Data source {0} already up-to-date'.format(name) return ret if __opts__['test']: ret['comment'] = 'Datasource {0} will be updated'.format(name) return ret __salt__['grafana4.update_datasource']( datasource['id'], profile=profile, **data) ret['result'] = True ret['changes'] = deep_diff(datasource, data, ignore=['id', 'orgId', 'readOnly']) ret['comment'] = 'Data source {0} updated'.format(name) return ret
[ "def", "present", "(", "name", ",", "type", ",", "url", ",", "access", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "database", "=", "None", ",", "basic_auth", "=", "None", ",", "basic_auth_user", "=", "None", ",", "basic...
Ensure that a data source is present. name Name of the data source. type Type of the datasource ('graphite', 'influxdb' etc.). access Use proxy or direct. Default: proxy url The URL to the data source API. user Optional - user to authenticate with the data source. password Optional - password to authenticate with the data source. database Optional - database to use with the data source. basic_auth Optional - set to True to use HTTP basic auth to authenticate with the data source. basic_auth_user Optional - HTTP basic auth username. basic_auth_password Optional - HTTP basic auth password. json_data Optional - additional json data to post (eg. "timeInterval"). is_default Optional - set data source as default. with_credentials Optional - Whether credentials such as cookies or auth headers should be sent with cross-site requests. type_logo_url Optional - Logo to use for this datasource. orgname Name of the organization in which the data source should be present. profile Configuration profile used to connect to the Grafana instance. Default is 'grafana'.
[ "Ensure", "that", "a", "data", "source", "is", "present", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana4_datasource.py#L57-L180
train
saltstack/salt
salt/states/grafana4_datasource.py
absent
def absent(name, orgname=None, profile='grafana'): ''' Ensure that a data source is present. name Name of the data source to remove. orgname Name of the organization from which the data source should be absent. profile Configuration profile used to connect to the Grafana instance. Default is 'grafana'. ''' if isinstance(profile, string_types): profile = __salt__['config.option'](profile) ret = {'name': name, 'result': None, 'comment': None, 'changes': {}} datasource = __salt__['grafana4.get_datasource'](name, orgname, profile) if not datasource: ret['result'] = True ret['comment'] = 'Data source {0} already absent'.format(name) return ret if __opts__['test']: ret['comment'] = 'Datasource {0} will be deleted'.format(name) return ret __salt__['grafana4.delete_datasource'](datasource['id'], profile=profile) ret['result'] = True ret['changes'][name] = 'Absent' ret['comment'] = 'Data source {0} was deleted'.format(name) return ret
python
def absent(name, orgname=None, profile='grafana'): ''' Ensure that a data source is present. name Name of the data source to remove. orgname Name of the organization from which the data source should be absent. profile Configuration profile used to connect to the Grafana instance. Default is 'grafana'. ''' if isinstance(profile, string_types): profile = __salt__['config.option'](profile) ret = {'name': name, 'result': None, 'comment': None, 'changes': {}} datasource = __salt__['grafana4.get_datasource'](name, orgname, profile) if not datasource: ret['result'] = True ret['comment'] = 'Data source {0} already absent'.format(name) return ret if __opts__['test']: ret['comment'] = 'Datasource {0} will be deleted'.format(name) return ret __salt__['grafana4.delete_datasource'](datasource['id'], profile=profile) ret['result'] = True ret['changes'][name] = 'Absent' ret['comment'] = 'Data source {0} was deleted'.format(name) return ret
[ "def", "absent", "(", "name", ",", "orgname", "=", "None", ",", "profile", "=", "'grafana'", ")", ":", "if", "isinstance", "(", "profile", ",", "string_types", ")", ":", "profile", "=", "__salt__", "[", "'config.option'", "]", "(", "profile", ")", "ret",...
Ensure that a data source is present. name Name of the data source to remove. orgname Name of the organization from which the data source should be absent. profile Configuration profile used to connect to the Grafana instance. Default is 'grafana'.
[ "Ensure", "that", "a", "data", "source", "is", "present", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grafana4_datasource.py#L183-L217
train
saltstack/salt
salt/auth/__init__.py
LoadAuth.load_name
def load_name(self, load): ''' Return the primary name associate with the load, if an empty string is returned then the load does not match the function ''' if 'eauth' not in load: return '' fstr = '{0}.auth'.format(load['eauth']) if fstr not in self.auth: return '' try: pname_arg = salt.utils.args.arg_lookup(self.auth[fstr])['args'][0] return load[pname_arg] except IndexError: return ''
python
def load_name(self, load): ''' Return the primary name associate with the load, if an empty string is returned then the load does not match the function ''' if 'eauth' not in load: return '' fstr = '{0}.auth'.format(load['eauth']) if fstr not in self.auth: return '' try: pname_arg = salt.utils.args.arg_lookup(self.auth[fstr])['args'][0] return load[pname_arg] except IndexError: return ''
[ "def", "load_name", "(", "self", ",", "load", ")", ":", "if", "'eauth'", "not", "in", "load", ":", "return", "''", "fstr", "=", "'{0}.auth'", ".", "format", "(", "load", "[", "'eauth'", "]", ")", "if", "fstr", "not", "in", "self", ".", "auth", ":",...
Return the primary name associate with the load, if an empty string is returned then the load does not match the function
[ "Return", "the", "primary", "name", "associate", "with", "the", "load", "if", "an", "empty", "string", "is", "returned", "then", "the", "load", "does", "not", "match", "the", "function" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L70-L84
train
saltstack/salt
salt/auth/__init__.py
LoadAuth.__auth_call
def __auth_call(self, load): ''' Return the token and set the cache data for use Do not call this directly! Use the time_auth method to overcome timing attacks ''' if 'eauth' not in load: return False fstr = '{0}.auth'.format(load['eauth']) if fstr not in self.auth: return False # When making auth calls, only username, password, auth, and token # are valid, so we strip anything else out. _valid = ['username', 'password', 'eauth', 'token'] _load = {key: value for (key, value) in load.items() if key in _valid} fcall = salt.utils.args.format_call( self.auth[fstr], _load, expected_extra_kws=AUTH_INTERNAL_KEYWORDS) try: if 'kwargs' in fcall: return self.auth[fstr](*fcall['args'], **fcall['kwargs']) else: return self.auth[fstr](*fcall['args']) except Exception as e: log.debug('Authentication module threw %s', e) return False
python
def __auth_call(self, load): ''' Return the token and set the cache data for use Do not call this directly! Use the time_auth method to overcome timing attacks ''' if 'eauth' not in load: return False fstr = '{0}.auth'.format(load['eauth']) if fstr not in self.auth: return False # When making auth calls, only username, password, auth, and token # are valid, so we strip anything else out. _valid = ['username', 'password', 'eauth', 'token'] _load = {key: value for (key, value) in load.items() if key in _valid} fcall = salt.utils.args.format_call( self.auth[fstr], _load, expected_extra_kws=AUTH_INTERNAL_KEYWORDS) try: if 'kwargs' in fcall: return self.auth[fstr](*fcall['args'], **fcall['kwargs']) else: return self.auth[fstr](*fcall['args']) except Exception as e: log.debug('Authentication module threw %s', e) return False
[ "def", "__auth_call", "(", "self", ",", "load", ")", ":", "if", "'eauth'", "not", "in", "load", ":", "return", "False", "fstr", "=", "'{0}.auth'", ".", "format", "(", "load", "[", "'eauth'", "]", ")", "if", "fstr", "not", "in", "self", ".", "auth", ...
Return the token and set the cache data for use Do not call this directly! Use the time_auth method to overcome timing attacks
[ "Return", "the", "token", "and", "set", "the", "cache", "data", "for", "use" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L86-L114
train
saltstack/salt
salt/auth/__init__.py
LoadAuth.time_auth
def time_auth(self, load): ''' Make sure that all failures happen in the same amount of time ''' start = time.time() ret = self.__auth_call(load) if ret: return ret f_time = time.time() - start if f_time > self.max_fail: self.max_fail = f_time deviation = self.max_fail / 4 r_time = random.SystemRandom().uniform( self.max_fail - deviation, self.max_fail + deviation ) while start + r_time > time.time(): time.sleep(0.001) return False
python
def time_auth(self, load): ''' Make sure that all failures happen in the same amount of time ''' start = time.time() ret = self.__auth_call(load) if ret: return ret f_time = time.time() - start if f_time > self.max_fail: self.max_fail = f_time deviation = self.max_fail / 4 r_time = random.SystemRandom().uniform( self.max_fail - deviation, self.max_fail + deviation ) while start + r_time > time.time(): time.sleep(0.001) return False
[ "def", "time_auth", "(", "self", ",", "load", ")", ":", "start", "=", "time", ".", "time", "(", ")", "ret", "=", "self", ".", "__auth_call", "(", "load", ")", "if", "ret", ":", "return", "ret", "f_time", "=", "time", ".", "time", "(", ")", "-", ...
Make sure that all failures happen in the same amount of time
[ "Make", "sure", "that", "all", "failures", "happen", "in", "the", "same", "amount", "of", "time" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L116-L134
train
saltstack/salt
salt/auth/__init__.py
LoadAuth.__get_acl
def __get_acl(self, load): ''' Returns ACL for a specific user. Returns None if eauth doesn't provide any for the user. I. e. None means: use acl declared in master config. ''' if 'eauth' not in load: return None mod = self.opts['eauth_acl_module'] if not mod: mod = load['eauth'] fstr = '{0}.acl'.format(mod) if fstr not in self.auth: return None fcall = salt.utils.args.format_call( self.auth[fstr], load, expected_extra_kws=AUTH_INTERNAL_KEYWORDS) try: return self.auth[fstr](*fcall['args'], **fcall['kwargs']) except Exception as e: log.debug('Authentication module threw %s', e) return None
python
def __get_acl(self, load): ''' Returns ACL for a specific user. Returns None if eauth doesn't provide any for the user. I. e. None means: use acl declared in master config. ''' if 'eauth' not in load: return None mod = self.opts['eauth_acl_module'] if not mod: mod = load['eauth'] fstr = '{0}.acl'.format(mod) if fstr not in self.auth: return None fcall = salt.utils.args.format_call( self.auth[fstr], load, expected_extra_kws=AUTH_INTERNAL_KEYWORDS) try: return self.auth[fstr](*fcall['args'], **fcall['kwargs']) except Exception as e: log.debug('Authentication module threw %s', e) return None
[ "def", "__get_acl", "(", "self", ",", "load", ")", ":", "if", "'eauth'", "not", "in", "load", ":", "return", "None", "mod", "=", "self", ".", "opts", "[", "'eauth_acl_module'", "]", "if", "not", "mod", ":", "mod", "=", "load", "[", "'eauth'", "]", ...
Returns ACL for a specific user. Returns None if eauth doesn't provide any for the user. I. e. None means: use acl declared in master config.
[ "Returns", "ACL", "for", "a", "specific", "user", ".", "Returns", "None", "if", "eauth", "doesn", "t", "provide", "any", "for", "the", "user", ".", "I", ".", "e", ".", "None", "means", ":", "use", "acl", "declared", "in", "master", "config", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L136-L158
train
saltstack/salt
salt/auth/__init__.py
LoadAuth.__process_acl
def __process_acl(self, load, auth_list): ''' Allows eauth module to modify the access list right before it'll be applied to the request. For example ldap auth module expands entries ''' if 'eauth' not in load: return auth_list fstr = '{0}.process_acl'.format(load['eauth']) if fstr not in self.auth: return auth_list try: return self.auth[fstr](auth_list, self.opts) except Exception as e: log.debug('Authentication module threw %s', e) return auth_list
python
def __process_acl(self, load, auth_list): ''' Allows eauth module to modify the access list right before it'll be applied to the request. For example ldap auth module expands entries ''' if 'eauth' not in load: return auth_list fstr = '{0}.process_acl'.format(load['eauth']) if fstr not in self.auth: return auth_list try: return self.auth[fstr](auth_list, self.opts) except Exception as e: log.debug('Authentication module threw %s', e) return auth_list
[ "def", "__process_acl", "(", "self", ",", "load", ",", "auth_list", ")", ":", "if", "'eauth'", "not", "in", "load", ":", "return", "auth_list", "fstr", "=", "'{0}.process_acl'", ".", "format", "(", "load", "[", "'eauth'", "]", ")", "if", "fstr", "not", ...
Allows eauth module to modify the access list right before it'll be applied to the request. For example ldap auth module expands entries
[ "Allows", "eauth", "module", "to", "modify", "the", "access", "list", "right", "before", "it", "ll", "be", "applied", "to", "the", "request", ".", "For", "example", "ldap", "auth", "module", "expands", "entries" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L160-L174
train
saltstack/salt
salt/auth/__init__.py
LoadAuth.get_groups
def get_groups(self, load): ''' Read in a load and return the groups a user is a member of by asking the appropriate provider ''' if 'eauth' not in load: return False fstr = '{0}.groups'.format(load['eauth']) if fstr not in self.auth: return False fcall = salt.utils.args.format_call( self.auth[fstr], load, expected_extra_kws=AUTH_INTERNAL_KEYWORDS) try: return self.auth[fstr](*fcall['args'], **fcall['kwargs']) except IndexError: return False except Exception: return None
python
def get_groups(self, load): ''' Read in a load and return the groups a user is a member of by asking the appropriate provider ''' if 'eauth' not in load: return False fstr = '{0}.groups'.format(load['eauth']) if fstr not in self.auth: return False fcall = salt.utils.args.format_call( self.auth[fstr], load, expected_extra_kws=AUTH_INTERNAL_KEYWORDS) try: return self.auth[fstr](*fcall['args'], **fcall['kwargs']) except IndexError: return False except Exception: return None
[ "def", "get_groups", "(", "self", ",", "load", ")", ":", "if", "'eauth'", "not", "in", "load", ":", "return", "False", "fstr", "=", "'{0}.groups'", ".", "format", "(", "load", "[", "'eauth'", "]", ")", "if", "fstr", "not", "in", "self", ".", "auth", ...
Read in a load and return the groups a user is a member of by asking the appropriate provider
[ "Read", "in", "a", "load", "and", "return", "the", "groups", "a", "user", "is", "a", "member", "of", "by", "asking", "the", "appropriate", "provider" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L176-L195
train
saltstack/salt
salt/auth/__init__.py
LoadAuth._allow_custom_expire
def _allow_custom_expire(self, load): ''' Return bool if requesting user is allowed to set custom expire ''' expire_override = self.opts.get('token_expire_user_override', False) if expire_override is True: return True if isinstance(expire_override, collections.Mapping): expire_whitelist = expire_override.get(load['eauth'], []) if isinstance(expire_whitelist, collections.Iterable): if load.get('username') in expire_whitelist: return True return False
python
def _allow_custom_expire(self, load): ''' Return bool if requesting user is allowed to set custom expire ''' expire_override = self.opts.get('token_expire_user_override', False) if expire_override is True: return True if isinstance(expire_override, collections.Mapping): expire_whitelist = expire_override.get(load['eauth'], []) if isinstance(expire_whitelist, collections.Iterable): if load.get('username') in expire_whitelist: return True return False
[ "def", "_allow_custom_expire", "(", "self", ",", "load", ")", ":", "expire_override", "=", "self", ".", "opts", ".", "get", "(", "'token_expire_user_override'", ",", "False", ")", "if", "expire_override", "is", "True", ":", "return", "True", "if", "isinstance"...
Return bool if requesting user is allowed to set custom expire
[ "Return", "bool", "if", "requesting", "user", "is", "allowed", "to", "set", "custom", "expire" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L197-L212
train
saltstack/salt
salt/auth/__init__.py
LoadAuth.mk_token
def mk_token(self, load): ''' Run time_auth and create a token. Return False or the token ''' if not self.authenticate_eauth(load): return {} if self._allow_custom_expire(load): token_expire = load.pop('token_expire', self.opts['token_expire']) else: _ = load.pop('token_expire', None) token_expire = self.opts['token_expire'] tdata = {'start': time.time(), 'expire': time.time() + token_expire, 'name': self.load_name(load), 'eauth': load['eauth']} if self.opts['keep_acl_in_token']: acl_ret = self.__get_acl(load) tdata['auth_list'] = acl_ret groups = self.get_groups(load) if groups: tdata['groups'] = groups return self.tokens["{0}.mk_token".format(self.opts['eauth_tokens'])](self.opts, tdata)
python
def mk_token(self, load): ''' Run time_auth and create a token. Return False or the token ''' if not self.authenticate_eauth(load): return {} if self._allow_custom_expire(load): token_expire = load.pop('token_expire', self.opts['token_expire']) else: _ = load.pop('token_expire', None) token_expire = self.opts['token_expire'] tdata = {'start': time.time(), 'expire': time.time() + token_expire, 'name': self.load_name(load), 'eauth': load['eauth']} if self.opts['keep_acl_in_token']: acl_ret = self.__get_acl(load) tdata['auth_list'] = acl_ret groups = self.get_groups(load) if groups: tdata['groups'] = groups return self.tokens["{0}.mk_token".format(self.opts['eauth_tokens'])](self.opts, tdata)
[ "def", "mk_token", "(", "self", ",", "load", ")", ":", "if", "not", "self", ".", "authenticate_eauth", "(", "load", ")", ":", "return", "{", "}", "if", "self", ".", "_allow_custom_expire", "(", "load", ")", ":", "token_expire", "=", "load", ".", "pop",...
Run time_auth and create a token. Return False or the token
[ "Run", "time_auth", "and", "create", "a", "token", ".", "Return", "False", "or", "the", "token" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L214-L240
train
saltstack/salt
salt/auth/__init__.py
LoadAuth.get_tok
def get_tok(self, tok): ''' Return the name associated with the token, or False if the token is not valid ''' tdata = self.tokens["{0}.get_token".format(self.opts['eauth_tokens'])](self.opts, tok) if not tdata: return {} rm_tok = False if 'expire' not in tdata: # invalid token, delete it! rm_tok = True if tdata.get('expire', '0') < time.time(): rm_tok = True if rm_tok: self.rm_token(tok) return tdata
python
def get_tok(self, tok): ''' Return the name associated with the token, or False if the token is not valid ''' tdata = self.tokens["{0}.get_token".format(self.opts['eauth_tokens'])](self.opts, tok) if not tdata: return {} rm_tok = False if 'expire' not in tdata: # invalid token, delete it! rm_tok = True if tdata.get('expire', '0') < time.time(): rm_tok = True if rm_tok: self.rm_token(tok) return tdata
[ "def", "get_tok", "(", "self", ",", "tok", ")", ":", "tdata", "=", "self", ".", "tokens", "[", "\"{0}.get_token\"", ".", "format", "(", "self", ".", "opts", "[", "'eauth_tokens'", "]", ")", "]", "(", "self", ".", "opts", ",", "tok", ")", "if", "not...
Return the name associated with the token, or False if the token is not valid
[ "Return", "the", "name", "associated", "with", "the", "token", "or", "False", "if", "the", "token", "is", "not", "valid" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L242-L260
train
saltstack/salt
salt/auth/__init__.py
LoadAuth.rm_token
def rm_token(self, tok): ''' Remove the given token from token storage. ''' self.tokens["{0}.rm_token".format(self.opts['eauth_tokens'])](self.opts, tok)
python
def rm_token(self, tok): ''' Remove the given token from token storage. ''' self.tokens["{0}.rm_token".format(self.opts['eauth_tokens'])](self.opts, tok)
[ "def", "rm_token", "(", "self", ",", "tok", ")", ":", "self", ".", "tokens", "[", "\"{0}.rm_token\"", ".", "format", "(", "self", ".", "opts", "[", "'eauth_tokens'", "]", ")", "]", "(", "self", ".", "opts", ",", "tok", ")" ]
Remove the given token from token storage.
[ "Remove", "the", "given", "token", "from", "token", "storage", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L268-L272
train
saltstack/salt
salt/auth/__init__.py
LoadAuth.authenticate_token
def authenticate_token(self, load): ''' Authenticate a user by the token specified in load. Return the token object or False if auth failed. ''' token = self.get_tok(load['token']) # Bail if the token is empty or if the eauth type specified is not allowed if not token or token['eauth'] not in self.opts['external_auth']: log.warning('Authentication failure of type "token" occurred.') return False return token
python
def authenticate_token(self, load): ''' Authenticate a user by the token specified in load. Return the token object or False if auth failed. ''' token = self.get_tok(load['token']) # Bail if the token is empty or if the eauth type specified is not allowed if not token or token['eauth'] not in self.opts['external_auth']: log.warning('Authentication failure of type "token" occurred.') return False return token
[ "def", "authenticate_token", "(", "self", ",", "load", ")", ":", "token", "=", "self", ".", "get_tok", "(", "load", "[", "'token'", "]", ")", "# Bail if the token is empty or if the eauth type specified is not allowed", "if", "not", "token", "or", "token", "[", "'...
Authenticate a user by the token specified in load. Return the token object or False if auth failed.
[ "Authenticate", "a", "user", "by", "the", "token", "specified", "in", "load", ".", "Return", "the", "token", "object", "or", "False", "if", "auth", "failed", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L274-L286
train
saltstack/salt
salt/auth/__init__.py
LoadAuth.authenticate_eauth
def authenticate_eauth(self, load): ''' Authenticate a user by the external auth module specified in load. Return True on success or False on failure. ''' if 'eauth' not in load: log.warning('Authentication failure of type "eauth" occurred.') return False if load['eauth'] not in self.opts['external_auth']: log.warning('The eauth system "%s" is not enabled', load['eauth']) log.warning('Authentication failure of type "eauth" occurred.') return False # Perform the actual authentication. If we fail here, do not # continue. if not self.time_auth(load): log.warning('Authentication failure of type "eauth" occurred.') return False return True
python
def authenticate_eauth(self, load): ''' Authenticate a user by the external auth module specified in load. Return True on success or False on failure. ''' if 'eauth' not in load: log.warning('Authentication failure of type "eauth" occurred.') return False if load['eauth'] not in self.opts['external_auth']: log.warning('The eauth system "%s" is not enabled', load['eauth']) log.warning('Authentication failure of type "eauth" occurred.') return False # Perform the actual authentication. If we fail here, do not # continue. if not self.time_auth(load): log.warning('Authentication failure of type "eauth" occurred.') return False return True
[ "def", "authenticate_eauth", "(", "self", ",", "load", ")", ":", "if", "'eauth'", "not", "in", "load", ":", "log", ".", "warning", "(", "'Authentication failure of type \"eauth\" occurred.'", ")", "return", "False", "if", "load", "[", "'eauth'", "]", "not", "i...
Authenticate a user by the external auth module specified in load. Return True on success or False on failure.
[ "Authenticate", "a", "user", "by", "the", "external", "auth", "module", "specified", "in", "load", ".", "Return", "True", "on", "success", "or", "False", "on", "failure", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L288-L308
train
saltstack/salt
salt/auth/__init__.py
LoadAuth.authenticate_key
def authenticate_key(self, load, key): ''' Authenticate a user by the key passed in load. Return the effective user id (name) if it's different from the specified one (for sudo). If the effective user id is the same as the passed one, return True on success or False on failure. ''' error_msg = 'Authentication failure of type "user" occurred.' auth_key = load.pop('key', None) if auth_key is None: log.warning(error_msg) return False if 'user' in load: auth_user = AuthUser(load['user']) if auth_user.is_sudo(): # If someone sudos check to make sure there is no ACL's around their username if auth_key != key[self.opts.get('user', 'root')]: log.warning(error_msg) return False return auth_user.sudo_name() elif load['user'] == self.opts.get('user', 'root') or load['user'] == 'root': if auth_key != key[self.opts.get('user', 'root')]: log.warning(error_msg) return False elif auth_user.is_running_user(): if auth_key != key.get(load['user']): log.warning(error_msg) return False elif auth_key == key.get('root'): pass else: if load['user'] in key: # User is authorised, check key and check perms if auth_key != key[load['user']]: log.warning(error_msg) return False return load['user'] else: log.warning(error_msg) return False else: if auth_key != key[salt.utils.user.get_user()]: log.warning(error_msg) return False return True
python
def authenticate_key(self, load, key): ''' Authenticate a user by the key passed in load. Return the effective user id (name) if it's different from the specified one (for sudo). If the effective user id is the same as the passed one, return True on success or False on failure. ''' error_msg = 'Authentication failure of type "user" occurred.' auth_key = load.pop('key', None) if auth_key is None: log.warning(error_msg) return False if 'user' in load: auth_user = AuthUser(load['user']) if auth_user.is_sudo(): # If someone sudos check to make sure there is no ACL's around their username if auth_key != key[self.opts.get('user', 'root')]: log.warning(error_msg) return False return auth_user.sudo_name() elif load['user'] == self.opts.get('user', 'root') or load['user'] == 'root': if auth_key != key[self.opts.get('user', 'root')]: log.warning(error_msg) return False elif auth_user.is_running_user(): if auth_key != key.get(load['user']): log.warning(error_msg) return False elif auth_key == key.get('root'): pass else: if load['user'] in key: # User is authorised, check key and check perms if auth_key != key[load['user']]: log.warning(error_msg) return False return load['user'] else: log.warning(error_msg) return False else: if auth_key != key[salt.utils.user.get_user()]: log.warning(error_msg) return False return True
[ "def", "authenticate_key", "(", "self", ",", "load", ",", "key", ")", ":", "error_msg", "=", "'Authentication failure of type \"user\" occurred.'", "auth_key", "=", "load", ".", "pop", "(", "'key'", ",", "None", ")", "if", "auth_key", "is", "None", ":", "log",...
Authenticate a user by the key passed in load. Return the effective user id (name) if it's different from the specified one (for sudo). If the effective user id is the same as the passed one, return True on success or False on failure.
[ "Authenticate", "a", "user", "by", "the", "key", "passed", "in", "load", ".", "Return", "the", "effective", "user", "id", "(", "name", ")", "if", "it", "s", "different", "from", "the", "specified", "one", "(", "for", "sudo", ")", ".", "If", "the", "e...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L310-L355
train
saltstack/salt
salt/auth/__init__.py
LoadAuth.get_auth_list
def get_auth_list(self, load, token=None): ''' Retrieve access list for the user specified in load. The list is built by eauth module or from master eauth configuration. Return None if current configuration doesn't provide any ACL for the user. Return an empty list if the user has no rights to execute anything on this master and returns non-empty list if user is allowed to execute particular functions. ''' # Get auth list from token if token and self.opts['keep_acl_in_token'] and 'auth_list' in token: return token['auth_list'] # Get acl from eauth module. auth_list = self.__get_acl(load) if auth_list is not None: return auth_list eauth = token['eauth'] if token else load['eauth'] if eauth not in self.opts['external_auth']: # No matching module is allowed in config log.debug('The eauth system "%s" is not enabled', eauth) log.warning('Authorization failure occurred.') return None if token: name = token['name'] groups = token.get('groups') else: name = self.load_name(load) # The username we are attempting to auth with groups = self.get_groups(load) # The groups this user belongs to eauth_config = self.opts['external_auth'][eauth] if not eauth_config: log.debug('eauth "%s" configuration is empty', eauth) if not groups: groups = [] # We now have an authenticated session and it is time to determine # what the user has access to. auth_list = self.ckminions.fill_auth_list( eauth_config, name, groups) auth_list = self.__process_acl(load, auth_list) log.trace('Compiled auth_list: %s', auth_list) return auth_list
python
def get_auth_list(self, load, token=None): ''' Retrieve access list for the user specified in load. The list is built by eauth module or from master eauth configuration. Return None if current configuration doesn't provide any ACL for the user. Return an empty list if the user has no rights to execute anything on this master and returns non-empty list if user is allowed to execute particular functions. ''' # Get auth list from token if token and self.opts['keep_acl_in_token'] and 'auth_list' in token: return token['auth_list'] # Get acl from eauth module. auth_list = self.__get_acl(load) if auth_list is not None: return auth_list eauth = token['eauth'] if token else load['eauth'] if eauth not in self.opts['external_auth']: # No matching module is allowed in config log.debug('The eauth system "%s" is not enabled', eauth) log.warning('Authorization failure occurred.') return None if token: name = token['name'] groups = token.get('groups') else: name = self.load_name(load) # The username we are attempting to auth with groups = self.get_groups(load) # The groups this user belongs to eauth_config = self.opts['external_auth'][eauth] if not eauth_config: log.debug('eauth "%s" configuration is empty', eauth) if not groups: groups = [] # We now have an authenticated session and it is time to determine # what the user has access to. auth_list = self.ckminions.fill_auth_list( eauth_config, name, groups) auth_list = self.__process_acl(load, auth_list) log.trace('Compiled auth_list: %s', auth_list) return auth_list
[ "def", "get_auth_list", "(", "self", ",", "load", ",", "token", "=", "None", ")", ":", "# Get auth list from token", "if", "token", "and", "self", ".", "opts", "[", "'keep_acl_in_token'", "]", "and", "'auth_list'", "in", "token", ":", "return", "token", "[",...
Retrieve access list for the user specified in load. The list is built by eauth module or from master eauth configuration. Return None if current configuration doesn't provide any ACL for the user. Return an empty list if the user has no rights to execute anything on this master and returns non-empty list if user is allowed to execute particular functions.
[ "Retrieve", "access", "list", "for", "the", "user", "specified", "in", "load", ".", "The", "list", "is", "built", "by", "eauth", "module", "or", "from", "master", "eauth", "configuration", ".", "Return", "None", "if", "current", "configuration", "doesn", "t"...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L357-L404
train
saltstack/salt
salt/auth/__init__.py
LoadAuth.check_authentication
def check_authentication(self, load, auth_type, key=None, show_username=False): ''' .. versionadded:: 2018.3.0 Go through various checks to see if the token/eauth/user can be authenticated. Returns a dictionary containing the following keys: - auth_list - username - error If an error is encountered, return immediately with the relevant error dictionary as authentication has failed. Otherwise, return the username and valid auth_list. ''' auth_list = [] username = load.get('username', 'UNKNOWN') ret = {'auth_list': auth_list, 'username': username, 'error': {}} # Authenticate if auth_type == 'token': token = self.authenticate_token(load) if not token: ret['error'] = {'name': 'TokenAuthenticationError', 'message': 'Authentication failure of type "token" occurred.'} return ret # Update username for token username = token['name'] ret['username'] = username auth_list = self.get_auth_list(load, token=token) elif auth_type == 'eauth': if not self.authenticate_eauth(load): ret['error'] = {'name': 'EauthAuthenticationError', 'message': 'Authentication failure of type "eauth" occurred for ' 'user {0}.'.format(username)} return ret auth_list = self.get_auth_list(load) elif auth_type == 'user': auth_ret = self.authenticate_key(load, key) msg = 'Authentication failure of type "user" occurred' if not auth_ret: # auth_ret can be a boolean or the effective user id if show_username: msg = '{0} for user {1}.'.format(msg, username) ret['error'] = {'name': 'UserAuthenticationError', 'message': msg} return ret # Verify that the caller has root on master if auth_ret is not True: if AuthUser(load['user']).is_sudo(): if not self.opts['sudo_acl'] or not self.opts['publisher_acl']: auth_ret = True if auth_ret is not True: # Avoid a circular import import salt.utils.master auth_list = salt.utils.master.get_values_of_matching_keys( self.opts['publisher_acl'], auth_ret) if not auth_list: ret['error'] = {'name': 'UserAuthenticationError', 'message': msg} return ret else: ret['error'] = {'name': 'SaltInvocationError', 'message': 'Authentication type not supported.'} return ret # Authentication checks passed ret['auth_list'] = auth_list return ret
python
def check_authentication(self, load, auth_type, key=None, show_username=False): ''' .. versionadded:: 2018.3.0 Go through various checks to see if the token/eauth/user can be authenticated. Returns a dictionary containing the following keys: - auth_list - username - error If an error is encountered, return immediately with the relevant error dictionary as authentication has failed. Otherwise, return the username and valid auth_list. ''' auth_list = [] username = load.get('username', 'UNKNOWN') ret = {'auth_list': auth_list, 'username': username, 'error': {}} # Authenticate if auth_type == 'token': token = self.authenticate_token(load) if not token: ret['error'] = {'name': 'TokenAuthenticationError', 'message': 'Authentication failure of type "token" occurred.'} return ret # Update username for token username = token['name'] ret['username'] = username auth_list = self.get_auth_list(load, token=token) elif auth_type == 'eauth': if not self.authenticate_eauth(load): ret['error'] = {'name': 'EauthAuthenticationError', 'message': 'Authentication failure of type "eauth" occurred for ' 'user {0}.'.format(username)} return ret auth_list = self.get_auth_list(load) elif auth_type == 'user': auth_ret = self.authenticate_key(load, key) msg = 'Authentication failure of type "user" occurred' if not auth_ret: # auth_ret can be a boolean or the effective user id if show_username: msg = '{0} for user {1}.'.format(msg, username) ret['error'] = {'name': 'UserAuthenticationError', 'message': msg} return ret # Verify that the caller has root on master if auth_ret is not True: if AuthUser(load['user']).is_sudo(): if not self.opts['sudo_acl'] or not self.opts['publisher_acl']: auth_ret = True if auth_ret is not True: # Avoid a circular import import salt.utils.master auth_list = salt.utils.master.get_values_of_matching_keys( self.opts['publisher_acl'], auth_ret) if not auth_list: ret['error'] = {'name': 'UserAuthenticationError', 'message': msg} return ret else: ret['error'] = {'name': 'SaltInvocationError', 'message': 'Authentication type not supported.'} return ret # Authentication checks passed ret['auth_list'] = auth_list return ret
[ "def", "check_authentication", "(", "self", ",", "load", ",", "auth_type", ",", "key", "=", "None", ",", "show_username", "=", "False", ")", ":", "auth_list", "=", "[", "]", "username", "=", "load", ".", "get", "(", "'username'", ",", "'UNKNOWN'", ")", ...
.. versionadded:: 2018.3.0 Go through various checks to see if the token/eauth/user can be authenticated. Returns a dictionary containing the following keys: - auth_list - username - error If an error is encountered, return immediately with the relevant error dictionary as authentication has failed. Otherwise, return the username and valid auth_list.
[ "..", "versionadded", "::", "2018", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L406-L477
train
saltstack/salt
salt/auth/__init__.py
Authorize.auth_data
def auth_data(self): ''' Gather and create the authorization data sets We're looking at several constructs here. Standard eauth: allow jsmith to auth via pam, and execute any command on server web1 external_auth: pam: jsmith: - web1: - .* Django eauth: Import the django library, dynamically load the Django model called 'model'. That model returns a data structure that matches the above for standard eauth. This is what determines who can do what to which machines django: ^model: <stuff returned from django> Active Directory Extended: Users in the AD group 'webadmins' can run any command on server1 Users in the AD group 'webadmins' can run test.ping and service.restart on machines that have a computer object in the AD 'webservers' OU Users in the AD group 'webadmins' can run commands defined in the custom attribute (custom attribute not implemented yet, this is for future use) ldap: webadmins%: <all users in the AD 'webadmins' group> - server1: - .* - ldap(OU=webservers,dc=int,dc=bigcompany,dc=com): - test.ping - service.restart - ldap(OU=Domain Controllers,dc=int,dc=bigcompany,dc=com): - allowed_fn_list_attribute^ ''' auth_data = self.opts['external_auth'] merge_lists = self.opts['pillar_merge_lists'] if 'django' in auth_data and '^model' in auth_data['django']: auth_from_django = salt.auth.django.retrieve_auth_entries() auth_data = salt.utils.dictupdate.merge(auth_data, auth_from_django, strategy='list', merge_lists=merge_lists) if 'ldap' in auth_data and __opts__.get('auth.ldap.activedirectory', False): auth_data['ldap'] = salt.auth.ldap.__expand_ldap_entries(auth_data['ldap']) log.debug(auth_data['ldap']) #for auth_back in self.opts.get('external_auth_sources', []): # fstr = '{0}.perms'.format(auth_back) # if fstr in self.loadauth.auth: # auth_data.append(getattr(self.loadauth.auth)()) return auth_data
python
def auth_data(self): ''' Gather and create the authorization data sets We're looking at several constructs here. Standard eauth: allow jsmith to auth via pam, and execute any command on server web1 external_auth: pam: jsmith: - web1: - .* Django eauth: Import the django library, dynamically load the Django model called 'model'. That model returns a data structure that matches the above for standard eauth. This is what determines who can do what to which machines django: ^model: <stuff returned from django> Active Directory Extended: Users in the AD group 'webadmins' can run any command on server1 Users in the AD group 'webadmins' can run test.ping and service.restart on machines that have a computer object in the AD 'webservers' OU Users in the AD group 'webadmins' can run commands defined in the custom attribute (custom attribute not implemented yet, this is for future use) ldap: webadmins%: <all users in the AD 'webadmins' group> - server1: - .* - ldap(OU=webservers,dc=int,dc=bigcompany,dc=com): - test.ping - service.restart - ldap(OU=Domain Controllers,dc=int,dc=bigcompany,dc=com): - allowed_fn_list_attribute^ ''' auth_data = self.opts['external_auth'] merge_lists = self.opts['pillar_merge_lists'] if 'django' in auth_data and '^model' in auth_data['django']: auth_from_django = salt.auth.django.retrieve_auth_entries() auth_data = salt.utils.dictupdate.merge(auth_data, auth_from_django, strategy='list', merge_lists=merge_lists) if 'ldap' in auth_data and __opts__.get('auth.ldap.activedirectory', False): auth_data['ldap'] = salt.auth.ldap.__expand_ldap_entries(auth_data['ldap']) log.debug(auth_data['ldap']) #for auth_back in self.opts.get('external_auth_sources', []): # fstr = '{0}.perms'.format(auth_back) # if fstr in self.loadauth.auth: # auth_data.append(getattr(self.loadauth.auth)()) return auth_data
[ "def", "auth_data", "(", "self", ")", ":", "auth_data", "=", "self", ".", "opts", "[", "'external_auth'", "]", "merge_lists", "=", "self", ".", "opts", "[", "'pillar_merge_lists'", "]", "if", "'django'", "in", "auth_data", "and", "'^model'", "in", "auth_data...
Gather and create the authorization data sets We're looking at several constructs here. Standard eauth: allow jsmith to auth via pam, and execute any command on server web1 external_auth: pam: jsmith: - web1: - .* Django eauth: Import the django library, dynamically load the Django model called 'model'. That model returns a data structure that matches the above for standard eauth. This is what determines who can do what to which machines django: ^model: <stuff returned from django> Active Directory Extended: Users in the AD group 'webadmins' can run any command on server1 Users in the AD group 'webadmins' can run test.ping and service.restart on machines that have a computer object in the AD 'webservers' OU Users in the AD group 'webadmins' can run commands defined in the custom attribute (custom attribute not implemented yet, this is for future use) ldap: webadmins%: <all users in the AD 'webadmins' group> - server1: - .* - ldap(OU=webservers,dc=int,dc=bigcompany,dc=com): - test.ping - service.restart - ldap(OU=Domain Controllers,dc=int,dc=bigcompany,dc=com): - allowed_fn_list_attribute^
[ "Gather", "and", "create", "the", "authorization", "data", "sets" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L501-L560
train
saltstack/salt
salt/auth/__init__.py
Authorize.token
def token(self, adata, load): ''' Determine if token auth is valid and yield the adata ''' try: token = self.loadauth.get_tok(load['token']) except Exception as exc: log.error('Exception occurred when generating auth token: %s', exc) yield {} if not token: log.warning('Authentication failure of type "token" occurred.') yield {} for sub_auth in adata: for sub_adata in adata: if token['eauth'] not in adata: continue if not ((token['name'] in adata[token['eauth']]) | ('*' in adata[token['eauth']])): continue yield {'sub_auth': sub_auth, 'token': token} yield {}
python
def token(self, adata, load): ''' Determine if token auth is valid and yield the adata ''' try: token = self.loadauth.get_tok(load['token']) except Exception as exc: log.error('Exception occurred when generating auth token: %s', exc) yield {} if not token: log.warning('Authentication failure of type "token" occurred.') yield {} for sub_auth in adata: for sub_adata in adata: if token['eauth'] not in adata: continue if not ((token['name'] in adata[token['eauth']]) | ('*' in adata[token['eauth']])): continue yield {'sub_auth': sub_auth, 'token': token} yield {}
[ "def", "token", "(", "self", ",", "adata", ",", "load", ")", ":", "try", ":", "token", "=", "self", ".", "loadauth", ".", "get_tok", "(", "load", "[", "'token'", "]", ")", "except", "Exception", "as", "exc", ":", "log", ".", "error", "(", "'Excepti...
Determine if token auth is valid and yield the adata
[ "Determine", "if", "token", "auth", "is", "valid", "and", "yield", "the", "adata" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L562-L582
train
saltstack/salt
salt/auth/__init__.py
Authorize.eauth
def eauth(self, adata, load): ''' Determine if the given eauth is valid and yield the adata ''' for sub_auth in [adata]: if load['eauth'] not in sub_auth: continue try: name = self.loadauth.load_name(load) if not ((name in sub_auth[load['eauth']]) | ('*' in sub_auth[load['eauth']])): continue if not self.loadauth.time_auth(load): continue except Exception as exc: log.error('Exception occurred while authenticating: %s', exc) continue yield {'sub_auth': sub_auth, 'name': name} yield {}
python
def eauth(self, adata, load): ''' Determine if the given eauth is valid and yield the adata ''' for sub_auth in [adata]: if load['eauth'] not in sub_auth: continue try: name = self.loadauth.load_name(load) if not ((name in sub_auth[load['eauth']]) | ('*' in sub_auth[load['eauth']])): continue if not self.loadauth.time_auth(load): continue except Exception as exc: log.error('Exception occurred while authenticating: %s', exc) continue yield {'sub_auth': sub_auth, 'name': name} yield {}
[ "def", "eauth", "(", "self", ",", "adata", ",", "load", ")", ":", "for", "sub_auth", "in", "[", "adata", "]", ":", "if", "load", "[", "'eauth'", "]", "not", "in", "sub_auth", ":", "continue", "try", ":", "name", "=", "self", ".", "loadauth", ".", ...
Determine if the given eauth is valid and yield the adata
[ "Determine", "if", "the", "given", "eauth", "is", "valid", "and", "yield", "the", "adata" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L584-L602
train
saltstack/salt
salt/auth/__init__.py
Authorize.rights_check
def rights_check(self, form, sub_auth, name, load, eauth=None): ''' Read in the access system to determine if the validated user has requested rights ''' if load.get('eauth'): sub_auth = sub_auth[load['eauth']] good = self.ckminions.any_auth( form, sub_auth[name] if name in sub_auth else sub_auth['*'], load.get('fun', None), load.get('arg', None), load.get('tgt', None), load.get('tgt_type', 'glob')) # Handle possible return of dict data structure from any_auth call to # avoid a stacktrace. As mentioned in PR #43181, this entire class is # dead code and is marked for removal in Salt Neon. But until then, we # should handle the dict return, which is an error and should return # False until this class is removed. if isinstance(good, dict): return False if not good: # Accept find_job so the CLI will function cleanly if load.get('fun', '') != 'saltutil.find_job': return good return good
python
def rights_check(self, form, sub_auth, name, load, eauth=None): ''' Read in the access system to determine if the validated user has requested rights ''' if load.get('eauth'): sub_auth = sub_auth[load['eauth']] good = self.ckminions.any_auth( form, sub_auth[name] if name in sub_auth else sub_auth['*'], load.get('fun', None), load.get('arg', None), load.get('tgt', None), load.get('tgt_type', 'glob')) # Handle possible return of dict data structure from any_auth call to # avoid a stacktrace. As mentioned in PR #43181, this entire class is # dead code and is marked for removal in Salt Neon. But until then, we # should handle the dict return, which is an error and should return # False until this class is removed. if isinstance(good, dict): return False if not good: # Accept find_job so the CLI will function cleanly if load.get('fun', '') != 'saltutil.find_job': return good return good
[ "def", "rights_check", "(", "self", ",", "form", ",", "sub_auth", ",", "name", ",", "load", ",", "eauth", "=", "None", ")", ":", "if", "load", ".", "get", "(", "'eauth'", ")", ":", "sub_auth", "=", "sub_auth", "[", "load", "[", "'eauth'", "]", "]",...
Read in the access system to determine if the validated user has requested rights
[ "Read", "in", "the", "access", "system", "to", "determine", "if", "the", "validated", "user", "has", "requested", "rights" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L604-L631
train
saltstack/salt
salt/auth/__init__.py
Authorize.rights
def rights(self, form, load): ''' Determine what type of authentication is being requested and pass authorization Note: this will check that the user has at least one right that will let the user execute "load", this does not deal with conflicting rules ''' adata = self.auth_data good = False if load.get('token', False): for sub_auth in self.token(self.auth_data, load): if sub_auth: if self.rights_check( form, self.auth_data[sub_auth['token']['eauth']], sub_auth['token']['name'], load, sub_auth['token']['eauth']): return True log.warning( 'Authentication failure of type "token" occurred.' ) elif load.get('eauth'): for sub_auth in self.eauth(self.auth_data, load): if sub_auth: if self.rights_check( form, sub_auth['sub_auth'], sub_auth['name'], load, load['eauth']): return True log.warning( 'Authentication failure of type "eauth" occurred.' ) return False
python
def rights(self, form, load): ''' Determine what type of authentication is being requested and pass authorization Note: this will check that the user has at least one right that will let the user execute "load", this does not deal with conflicting rules ''' adata = self.auth_data good = False if load.get('token', False): for sub_auth in self.token(self.auth_data, load): if sub_auth: if self.rights_check( form, self.auth_data[sub_auth['token']['eauth']], sub_auth['token']['name'], load, sub_auth['token']['eauth']): return True log.warning( 'Authentication failure of type "token" occurred.' ) elif load.get('eauth'): for sub_auth in self.eauth(self.auth_data, load): if sub_auth: if self.rights_check( form, sub_auth['sub_auth'], sub_auth['name'], load, load['eauth']): return True log.warning( 'Authentication failure of type "eauth" occurred.' ) return False
[ "def", "rights", "(", "self", ",", "form", ",", "load", ")", ":", "adata", "=", "self", ".", "auth_data", "good", "=", "False", "if", "load", ".", "get", "(", "'token'", ",", "False", ")", ":", "for", "sub_auth", "in", "self", ".", "token", "(", ...
Determine what type of authentication is being requested and pass authorization Note: this will check that the user has at least one right that will let the user execute "load", this does not deal with conflicting rules
[ "Determine", "what", "type", "of", "authentication", "is", "being", "requested", "and", "pass", "authorization" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L633-L670
train
saltstack/salt
salt/auth/__init__.py
Resolver.cli
def cli(self, eauth): ''' Execute the CLI options to fill in the extra data needed for the defined eauth system ''' ret = {} if not eauth: print('External authentication system has not been specified') return ret fstr = '{0}.auth'.format(eauth) if fstr not in self.auth: print(('The specified external authentication system "{0}" is ' 'not available').format(eauth)) print("Available eauth types: {0}".format(", ".join(self.auth.file_mapping.keys()))) return ret args = salt.utils.args.arg_lookup(self.auth[fstr]) for arg in args['args']: if arg in self.opts: ret[arg] = self.opts[arg] elif arg.startswith('pass'): ret[arg] = getpass.getpass('{0}: '.format(arg)) else: ret[arg] = input('{0}: '.format(arg)) for kwarg, default in list(args['kwargs'].items()): if kwarg in self.opts: ret['kwarg'] = self.opts[kwarg] else: ret[kwarg] = input('{0} [{1}]: '.format(kwarg, default)) # Use current user if empty if 'username' in ret and not ret['username']: ret['username'] = salt.utils.user.get_user() return ret
python
def cli(self, eauth): ''' Execute the CLI options to fill in the extra data needed for the defined eauth system ''' ret = {} if not eauth: print('External authentication system has not been specified') return ret fstr = '{0}.auth'.format(eauth) if fstr not in self.auth: print(('The specified external authentication system "{0}" is ' 'not available').format(eauth)) print("Available eauth types: {0}".format(", ".join(self.auth.file_mapping.keys()))) return ret args = salt.utils.args.arg_lookup(self.auth[fstr]) for arg in args['args']: if arg in self.opts: ret[arg] = self.opts[arg] elif arg.startswith('pass'): ret[arg] = getpass.getpass('{0}: '.format(arg)) else: ret[arg] = input('{0}: '.format(arg)) for kwarg, default in list(args['kwargs'].items()): if kwarg in self.opts: ret['kwarg'] = self.opts[kwarg] else: ret[kwarg] = input('{0} [{1}]: '.format(kwarg, default)) # Use current user if empty if 'username' in ret and not ret['username']: ret['username'] = salt.utils.user.get_user() return ret
[ "def", "cli", "(", "self", ",", "eauth", ")", ":", "ret", "=", "{", "}", "if", "not", "eauth", ":", "print", "(", "'External authentication system has not been specified'", ")", "return", "ret", "fstr", "=", "'{0}.auth'", ".", "format", "(", "eauth", ")", ...
Execute the CLI options to fill in the extra data needed for the defined eauth system
[ "Execute", "the", "CLI", "options", "to", "fill", "in", "the", "extra", "data", "needed", "for", "the", "defined", "eauth", "system" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L690-L724
train
saltstack/salt
salt/auth/__init__.py
Resolver.token_cli
def token_cli(self, eauth, load): ''' Create the token from the CLI and request the correct data to authenticate via the passed authentication mechanism ''' load['cmd'] = 'mk_token' load['eauth'] = eauth tdata = self._send_token_request(load) if 'token' not in tdata: return tdata try: with salt.utils.files.set_umask(0o177): with salt.utils.files.fopen(self.opts['token_file'], 'w+') as fp_: fp_.write(tdata['token']) except (IOError, OSError): pass return tdata
python
def token_cli(self, eauth, load): ''' Create the token from the CLI and request the correct data to authenticate via the passed authentication mechanism ''' load['cmd'] = 'mk_token' load['eauth'] = eauth tdata = self._send_token_request(load) if 'token' not in tdata: return tdata try: with salt.utils.files.set_umask(0o177): with salt.utils.files.fopen(self.opts['token_file'], 'w+') as fp_: fp_.write(tdata['token']) except (IOError, OSError): pass return tdata
[ "def", "token_cli", "(", "self", ",", "eauth", ",", "load", ")", ":", "load", "[", "'cmd'", "]", "=", "'mk_token'", "load", "[", "'eauth'", "]", "=", "eauth", "tdata", "=", "self", ".", "_send_token_request", "(", "load", ")", "if", "'token'", "not", ...
Create the token from the CLI and request the correct data to authenticate via the passed authentication mechanism
[ "Create", "the", "token", "from", "the", "CLI", "and", "request", "the", "correct", "data", "to", "authenticate", "via", "the", "passed", "authentication", "mechanism" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L726-L742
train
saltstack/salt
salt/auth/__init__.py
Resolver.get_token
def get_token(self, token): ''' Request a token from the master ''' load = {} load['token'] = token load['cmd'] = 'get_token' tdata = self._send_token_request(load) return tdata
python
def get_token(self, token): ''' Request a token from the master ''' load = {} load['token'] = token load['cmd'] = 'get_token' tdata = self._send_token_request(load) return tdata
[ "def", "get_token", "(", "self", ",", "token", ")", ":", "load", "=", "{", "}", "load", "[", "'token'", "]", "=", "token", "load", "[", "'cmd'", "]", "=", "'get_token'", "tdata", "=", "self", ".", "_send_token_request", "(", "load", ")", "return", "t...
Request a token from the master
[ "Request", "a", "token", "from", "the", "master" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/__init__.py#L752-L760
train
saltstack/salt
salt/modules/boto3_sns.py
list_topics
def list_topics(region=None, key=None, keyid=None, profile=None): ''' Returns a list of the requester's topics CLI example:: salt myminion boto3_sns.list_topics ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) res = {} NextToken = '' while NextToken is not None: ret = conn.list_topics(NextToken=NextToken) NextToken = ret.get('NextToken', None) arns = jmespath.search('Topics[*].TopicArn', ret) for t in arns: short_name = t.split(':')[-1] res[short_name] = t return res
python
def list_topics(region=None, key=None, keyid=None, profile=None): ''' Returns a list of the requester's topics CLI example:: salt myminion boto3_sns.list_topics ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) res = {} NextToken = '' while NextToken is not None: ret = conn.list_topics(NextToken=NextToken) NextToken = ret.get('NextToken', None) arns = jmespath.search('Topics[*].TopicArn', ret) for t in arns: short_name = t.split(':')[-1] res[short_name] = t return res
[ "def", "list_topics", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid",...
Returns a list of the requester's topics CLI example:: salt myminion boto3_sns.list_topics
[ "Returns", "a", "list", "of", "the", "requester", "s", "topics" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_sns.py#L78-L96
train
saltstack/salt
salt/modules/boto3_sns.py
describe_topic
def describe_topic(name, region=None, key=None, keyid=None, profile=None): ''' Returns details about a specific SNS topic, specified by name or ARN. CLI example:: salt my_favorite_client boto3_sns.describe_topic a_sns_topic_of_my_choice ''' topics = list_topics(region=region, key=key, keyid=keyid, profile=profile) ret = {} for topic, arn in topics.items(): if name in (topic, arn): ret = {'TopicArn': arn} ret['Attributes'] = get_topic_attributes(arn, region=region, key=key, keyid=keyid, profile=profile) ret['Subscriptions'] = list_subscriptions_by_topic(arn, region=region, key=key, keyid=keyid, profile=profile) # Grab extended attributes for the above subscriptions for sub in range(len(ret['Subscriptions'])): sub_arn = ret['Subscriptions'][sub]['SubscriptionArn'] if not sub_arn.startswith('arn:aws:sns:'): # Sometimes a sub is in e.g. PendingAccept or other # wierd states and doesn't have an ARN yet log.debug('Subscription with invalid ARN %s skipped...', sub_arn) continue deets = get_subscription_attributes(SubscriptionArn=sub_arn, region=region, key=key, keyid=keyid, profile=profile) ret['Subscriptions'][sub].update(deets) return ret
python
def describe_topic(name, region=None, key=None, keyid=None, profile=None): ''' Returns details about a specific SNS topic, specified by name or ARN. CLI example:: salt my_favorite_client boto3_sns.describe_topic a_sns_topic_of_my_choice ''' topics = list_topics(region=region, key=key, keyid=keyid, profile=profile) ret = {} for topic, arn in topics.items(): if name in (topic, arn): ret = {'TopicArn': arn} ret['Attributes'] = get_topic_attributes(arn, region=region, key=key, keyid=keyid, profile=profile) ret['Subscriptions'] = list_subscriptions_by_topic(arn, region=region, key=key, keyid=keyid, profile=profile) # Grab extended attributes for the above subscriptions for sub in range(len(ret['Subscriptions'])): sub_arn = ret['Subscriptions'][sub]['SubscriptionArn'] if not sub_arn.startswith('arn:aws:sns:'): # Sometimes a sub is in e.g. PendingAccept or other # wierd states and doesn't have an ARN yet log.debug('Subscription with invalid ARN %s skipped...', sub_arn) continue deets = get_subscription_attributes(SubscriptionArn=sub_arn, region=region, key=key, keyid=keyid, profile=profile) ret['Subscriptions'][sub].update(deets) return ret
[ "def", "describe_topic", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "topics", "=", "list_topics", "(", "region", "=", "region", ",", "key", "=", "key", ",", "k...
Returns details about a specific SNS topic, specified by name or ARN. CLI example:: salt my_favorite_client boto3_sns.describe_topic a_sns_topic_of_my_choice
[ "Returns", "details", "about", "a", "specific", "SNS", "topic", "specified", "by", "name", "or", "ARN", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_sns.py#L99-L127
train
saltstack/salt
salt/modules/boto3_sns.py
topic_exists
def topic_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an SNS topic exists. CLI example:: salt myminion boto3_sns.topic_exists mytopic region=us-east-1 ''' topics = list_topics(region=region, key=key, keyid=keyid, profile=profile) return name in list(topics.values() + topics.keys())
python
def topic_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an SNS topic exists. CLI example:: salt myminion boto3_sns.topic_exists mytopic region=us-east-1 ''' topics = list_topics(region=region, key=key, keyid=keyid, profile=profile) return name in list(topics.values() + topics.keys())
[ "def", "topic_exists", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "topics", "=", "list_topics", "(", "region", "=", "region", ",", "key", "=", "key", ",", "key...
Check to see if an SNS topic exists. CLI example:: salt myminion boto3_sns.topic_exists mytopic region=us-east-1
[ "Check", "to", "see", "if", "an", "SNS", "topic", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_sns.py#L130-L139
train
saltstack/salt
salt/modules/boto3_sns.py
create_topic
def create_topic(Name, region=None, key=None, keyid=None, profile=None): ''' Create an SNS topic. CLI example:: salt myminion boto3_sns.create_topic mytopic region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.create_topic(Name=Name) log.info('SNS topic %s created with ARN %s', Name, ret['TopicArn']) return ret['TopicArn'] except botocore.exceptions.ClientError as e: log.error('Failed to create SNS topic %s: %s', Name, e) return None except KeyError: log.error('Failed to create SNS topic %s', Name) return None
python
def create_topic(Name, region=None, key=None, keyid=None, profile=None): ''' Create an SNS topic. CLI example:: salt myminion boto3_sns.create_topic mytopic region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.create_topic(Name=Name) log.info('SNS topic %s created with ARN %s', Name, ret['TopicArn']) return ret['TopicArn'] except botocore.exceptions.ClientError as e: log.error('Failed to create SNS topic %s: %s', Name, e) return None except KeyError: log.error('Failed to create SNS topic %s', Name) return None
[ "def", "create_topic", "(", "Name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid",...
Create an SNS topic. CLI example:: salt myminion boto3_sns.create_topic mytopic region=us-east-1
[ "Create", "an", "SNS", "topic", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_sns.py#L142-L160
train
saltstack/salt
salt/modules/boto3_sns.py
delete_topic
def delete_topic(TopicArn, region=None, key=None, keyid=None, profile=None): ''' Delete an SNS topic. CLI example:: salt myminion boto3_sns.delete_topic mytopic region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_topic(TopicArn=TopicArn) log.info('SNS topic %s deleted', TopicArn) return True except botocore.exceptions.ClientError as e: log.error('Failed to delete SNS topic %s: %s', name, e) return False
python
def delete_topic(TopicArn, region=None, key=None, keyid=None, profile=None): ''' Delete an SNS topic. CLI example:: salt myminion boto3_sns.delete_topic mytopic region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.delete_topic(TopicArn=TopicArn) log.info('SNS topic %s deleted', TopicArn) return True except botocore.exceptions.ClientError as e: log.error('Failed to delete SNS topic %s: %s', name, e) return False
[ "def", "delete_topic", "(", "TopicArn", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "key...
Delete an SNS topic. CLI example:: salt myminion boto3_sns.delete_topic mytopic region=us-east-1
[ "Delete", "an", "SNS", "topic", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_sns.py#L163-L178
train
saltstack/salt
salt/modules/boto3_sns.py
get_topic_attributes
def get_topic_attributes(TopicArn, region=None, key=None, keyid=None, profile=None): ''' Returns all of the properties of a topic. Topic properties returned might differ based on the authorization of the user. CLI example:: salt myminion boto3_sns.get_topic_attributes someTopic region=us-west-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_topic_attributes(TopicArn=TopicArn).get('Attributes') except botocore.exceptions.ClientError as e: log.error('Failed to garner attributes for SNS topic %s: %s', TopicArn, e) return None
python
def get_topic_attributes(TopicArn, region=None, key=None, keyid=None, profile=None): ''' Returns all of the properties of a topic. Topic properties returned might differ based on the authorization of the user. CLI example:: salt myminion boto3_sns.get_topic_attributes someTopic region=us-west-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return conn.get_topic_attributes(TopicArn=TopicArn).get('Attributes') except botocore.exceptions.ClientError as e: log.error('Failed to garner attributes for SNS topic %s: %s', TopicArn, e) return None
[ "def", "get_topic_attributes", "(", "TopicArn", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ","...
Returns all of the properties of a topic. Topic properties returned might differ based on the authorization of the user. CLI example:: salt myminion boto3_sns.get_topic_attributes someTopic region=us-west-1
[ "Returns", "all", "of", "the", "properties", "of", "a", "topic", ".", "Topic", "properties", "returned", "might", "differ", "based", "on", "the", "authorization", "of", "the", "user", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_sns.py#L181-L195
train
saltstack/salt
salt/modules/boto3_sns.py
set_topic_attributes
def set_topic_attributes(TopicArn, AttributeName, AttributeValue, region=None, key=None, keyid=None, profile=None): ''' Set an attribute of a topic to a new value. CLI example:: salt myminion boto3_sns.set_topic_attributes someTopic DisplayName myDisplayNameValue ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.set_topic_attributes(TopicArn=TopicArn, AttributeName=AttributeName, AttributeValue=AttributeValue) log.debug('Set attribute %s=%s on SNS topic %s', AttributeName, AttributeValue, TopicArn) return True except botocore.exceptions.ClientError as e: log.error('Failed to set attribute %s=%s for SNS topic %s: %s', AttributeName, AttributeValue, TopicArn, e) return False
python
def set_topic_attributes(TopicArn, AttributeName, AttributeValue, region=None, key=None, keyid=None, profile=None): ''' Set an attribute of a topic to a new value. CLI example:: salt myminion boto3_sns.set_topic_attributes someTopic DisplayName myDisplayNameValue ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.set_topic_attributes(TopicArn=TopicArn, AttributeName=AttributeName, AttributeValue=AttributeValue) log.debug('Set attribute %s=%s on SNS topic %s', AttributeName, AttributeValue, TopicArn) return True except botocore.exceptions.ClientError as e: log.error('Failed to set attribute %s=%s for SNS topic %s: %s', AttributeName, AttributeValue, TopicArn, e) return False
[ "def", "set_topic_attributes", "(", "TopicArn", ",", "AttributeName", ",", "AttributeValue", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "...
Set an attribute of a topic to a new value. CLI example:: salt myminion boto3_sns.set_topic_attributes someTopic DisplayName myDisplayNameValue
[ "Set", "an", "attribute", "of", "a", "topic", "to", "a", "new", "value", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_sns.py#L198-L217
train
saltstack/salt
salt/modules/boto3_sns.py
list_subscriptions_by_topic
def list_subscriptions_by_topic(TopicArn, region=None, key=None, keyid=None, profile=None): ''' Returns a list of the subscriptions to a specific topic CLI example:: salt myminion boto3_sns.list_subscriptions_by_topic mytopic region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) NextToken = '' res = [] try: while NextToken is not None: ret = conn.list_subscriptions_by_topic(TopicArn=TopicArn, NextToken=NextToken) NextToken = ret.get('NextToken', None) subs = ret.get('Subscriptions', []) res += subs except botocore.exceptions.ClientError as e: log.error('Failed to list subscriptions for SNS topic %s: %s', TopicArn, e) return None return res
python
def list_subscriptions_by_topic(TopicArn, region=None, key=None, keyid=None, profile=None): ''' Returns a list of the subscriptions to a specific topic CLI example:: salt myminion boto3_sns.list_subscriptions_by_topic mytopic region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) NextToken = '' res = [] try: while NextToken is not None: ret = conn.list_subscriptions_by_topic(TopicArn=TopicArn, NextToken=NextToken) NextToken = ret.get('NextToken', None) subs = ret.get('Subscriptions', []) res += subs except botocore.exceptions.ClientError as e: log.error('Failed to list subscriptions for SNS topic %s: %s', TopicArn, e) return None return res
[ "def", "list_subscriptions_by_topic", "(", "TopicArn", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key"...
Returns a list of the subscriptions to a specific topic CLI example:: salt myminion boto3_sns.list_subscriptions_by_topic mytopic region=us-east-1
[ "Returns", "a", "list", "of", "the", "subscriptions", "to", "a", "specific", "topic" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_sns.py#L220-L240
train
saltstack/salt
salt/modules/boto3_sns.py
get_subscription_attributes
def get_subscription_attributes(SubscriptionArn, region=None, key=None, keyid=None, profile=None): ''' Returns all of the properties of a subscription. CLI example:: salt myminion boto3_sns.get_subscription_attributes somesubscription region=us-west-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_subscription_attributes(SubscriptionArn=SubscriptionArn) return ret['Attributes'] except botocore.exceptions.ClientError as e: log.error('Failed to list attributes for SNS subscription %s: %s', SubscriptionArn, e) return None except KeyError: log.error('Failed to list attributes for SNS subscription %s', SubscriptionArn) return None
python
def get_subscription_attributes(SubscriptionArn, region=None, key=None, keyid=None, profile=None): ''' Returns all of the properties of a subscription. CLI example:: salt myminion boto3_sns.get_subscription_attributes somesubscription region=us-west-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_subscription_attributes(SubscriptionArn=SubscriptionArn) return ret['Attributes'] except botocore.exceptions.ClientError as e: log.error('Failed to list attributes for SNS subscription %s: %s', SubscriptionArn, e) return None except KeyError: log.error('Failed to list attributes for SNS subscription %s', SubscriptionArn) return None
[ "def", "get_subscription_attributes", "(", "SubscriptionArn", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", ...
Returns all of the properties of a subscription. CLI example:: salt myminion boto3_sns.get_subscription_attributes somesubscription region=us-west-1
[ "Returns", "all", "of", "the", "properties", "of", "a", "subscription", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_sns.py#L266-L285
train
saltstack/salt
salt/modules/boto3_sns.py
subscribe
def subscribe(TopicArn=None, Protocol=None, Endpoint=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Subscribe to a Topic. CLI example:: salt myminion boto3_sns.subscribe mytopic https https://www.example.com/sns-endpoint ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')} ## Begin warn_until() if any((TopicArn, Protocol, Endpoint)): if all((TopicArn, Protocol, Endpoint)): salt.utils.versions.warn_until('Sodium', 'Passing positional parameters is deprecated.' ' Please update code to use keyword style arguments' ' instead. This will become mandatory in salt version' ' {version}.') kwargs.update({'TopicArn': TopicArn, 'Protocol': Protocol, 'Endpoint': Endpoint}) else: ## Previous function def required EXACTLY three args raise SaltInvocationError('When passed as positional parameters, all three of ' '`TopicArn`, `Protocol`, and `Endpoint` are required.') ## End warn_until() for arg in ('TopicArn', 'Protocol', 'Endpoint'): if arg not in kwargs: raise SaltInvocationError('`{}` is a required parameter.'.format(arg)) try: ret = conn.subscribe(**kwargs) log.info('Subscribed %s %s to topic %s with SubscriptionArn %s', kwargs['Protocol'], kwargs['Endpoint'], kwargs['TopicArn'], ret['SubscriptionArn']) return ret['SubscriptionArn'] except botocore.exceptions.ClientError as e: log.error('Failed to create subscription to SNS topic %s: %s', kwargs['TopicArn'], e) return None except KeyError: log.error('Failed to create subscription to SNS topic %s', kwargs['TopicArn']) return None
python
def subscribe(TopicArn=None, Protocol=None, Endpoint=None, region=None, key=None, keyid=None, profile=None, **kwargs): ''' Subscribe to a Topic. CLI example:: salt myminion boto3_sns.subscribe mytopic https https://www.example.com/sns-endpoint ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')} ## Begin warn_until() if any((TopicArn, Protocol, Endpoint)): if all((TopicArn, Protocol, Endpoint)): salt.utils.versions.warn_until('Sodium', 'Passing positional parameters is deprecated.' ' Please update code to use keyword style arguments' ' instead. This will become mandatory in salt version' ' {version}.') kwargs.update({'TopicArn': TopicArn, 'Protocol': Protocol, 'Endpoint': Endpoint}) else: ## Previous function def required EXACTLY three args raise SaltInvocationError('When passed as positional parameters, all three of ' '`TopicArn`, `Protocol`, and `Endpoint` are required.') ## End warn_until() for arg in ('TopicArn', 'Protocol', 'Endpoint'): if arg not in kwargs: raise SaltInvocationError('`{}` is a required parameter.'.format(arg)) try: ret = conn.subscribe(**kwargs) log.info('Subscribed %s %s to topic %s with SubscriptionArn %s', kwargs['Protocol'], kwargs['Endpoint'], kwargs['TopicArn'], ret['SubscriptionArn']) return ret['SubscriptionArn'] except botocore.exceptions.ClientError as e: log.error('Failed to create subscription to SNS topic %s: %s', kwargs['TopicArn'], e) return None except KeyError: log.error('Failed to create subscription to SNS topic %s', kwargs['TopicArn']) return None
[ "def", "subscribe", "(", "TopicArn", "=", "None", ",", "Protocol", "=", "None", ",", "Endpoint", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")",...
Subscribe to a Topic. CLI example:: salt myminion boto3_sns.subscribe mytopic https https://www.example.com/sns-endpoint
[ "Subscribe", "to", "a", "Topic", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_sns.py#L310-L347
train
saltstack/salt
salt/modules/boto3_sns.py
unsubscribe
def unsubscribe(SubscriptionArn, region=None, key=None, keyid=None, profile=None): ''' Unsubscribe a specific SubscriptionArn of a topic. CLI Example: .. code-block:: bash salt myminion boto3_sns.unsubscribe my_subscription_arn region=us-east-1 ''' if not SubscriptionArn.startswith('arn:aws:sns:'): # Grrr, AWS sent us an ARN that's NOT and ARN.... # This can happen if, for instance, a subscription is left in PendingAcceptance or similar # Note that anything left in PendingConfirmation will be auto-deleted by AWS after 30 days # anyway, so this isn't as ugly a hack as it might seem at first... log.info('Invalid subscription ARN `%s` passed - likely a PendingConfirmaton or such. ' 'Skipping unsubscribe attempt as it would almost certainly fail...', SubscriptionArn) return True subs = list_subscriptions(region=region, key=key, keyid=keyid, profile=profile) sub = [s for s in subs if s.get('SubscriptionArn') == SubscriptionArn] if not sub: log.error('Subscription ARN %s not found', SubscriptionArn) return False TopicArn = sub[0]['TopicArn'] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.unsubscribe(SubscriptionArn=SubscriptionArn) log.info('Deleted subscription %s from SNS topic %s', SubscriptionArn, TopicArn) return True except botocore.exceptions.ClientError as e: log.error('Failed to delete subscription %s: %s', SubscriptionArn, e) return False
python
def unsubscribe(SubscriptionArn, region=None, key=None, keyid=None, profile=None): ''' Unsubscribe a specific SubscriptionArn of a topic. CLI Example: .. code-block:: bash salt myminion boto3_sns.unsubscribe my_subscription_arn region=us-east-1 ''' if not SubscriptionArn.startswith('arn:aws:sns:'): # Grrr, AWS sent us an ARN that's NOT and ARN.... # This can happen if, for instance, a subscription is left in PendingAcceptance or similar # Note that anything left in PendingConfirmation will be auto-deleted by AWS after 30 days # anyway, so this isn't as ugly a hack as it might seem at first... log.info('Invalid subscription ARN `%s` passed - likely a PendingConfirmaton or such. ' 'Skipping unsubscribe attempt as it would almost certainly fail...', SubscriptionArn) return True subs = list_subscriptions(region=region, key=key, keyid=keyid, profile=profile) sub = [s for s in subs if s.get('SubscriptionArn') == SubscriptionArn] if not sub: log.error('Subscription ARN %s not found', SubscriptionArn) return False TopicArn = sub[0]['TopicArn'] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: conn.unsubscribe(SubscriptionArn=SubscriptionArn) log.info('Deleted subscription %s from SNS topic %s', SubscriptionArn, TopicArn) return True except botocore.exceptions.ClientError as e: log.error('Failed to delete subscription %s: %s', SubscriptionArn, e) return False
[ "def", "unsubscribe", "(", "SubscriptionArn", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "not", "SubscriptionArn", ".", "startswith", "(", "'arn:aws:sns:'", ")", ":", "# Gr...
Unsubscribe a specific SubscriptionArn of a topic. CLI Example: .. code-block:: bash salt myminion boto3_sns.unsubscribe my_subscription_arn region=us-east-1
[ "Unsubscribe", "a", "specific", "SubscriptionArn", "of", "a", "topic", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_sns.py#L350-L383
train
saltstack/salt
salt/utils/win_update.py
needs_reboot
def needs_reboot(): ''' Determines if the system needs to be rebooted. Returns: bool: True if the system requires a reboot, False if not CLI Examples: .. code-block:: bash import salt.utils.win_update salt.utils.win_update.needs_reboot() ''' # Initialize the PyCom system with salt.utils.winapi.Com(): # Create an AutoUpdate object obj_sys = win32com.client.Dispatch('Microsoft.Update.SystemInfo') return salt.utils.data.is_true(obj_sys.RebootRequired)
python
def needs_reboot(): ''' Determines if the system needs to be rebooted. Returns: bool: True if the system requires a reboot, False if not CLI Examples: .. code-block:: bash import salt.utils.win_update salt.utils.win_update.needs_reboot() ''' # Initialize the PyCom system with salt.utils.winapi.Com(): # Create an AutoUpdate object obj_sys = win32com.client.Dispatch('Microsoft.Update.SystemInfo') return salt.utils.data.is_true(obj_sys.RebootRequired)
[ "def", "needs_reboot", "(", ")", ":", "# Initialize the PyCom system", "with", "salt", ".", "utils", ".", "winapi", ".", "Com", "(", ")", ":", "# Create an AutoUpdate object", "obj_sys", "=", "win32com", ".", "client", ".", "Dispatch", "(", "'Microsoft.Update.Syst...
Determines if the system needs to be rebooted. Returns: bool: True if the system requires a reboot, False if not CLI Examples: .. code-block:: bash import salt.utils.win_update salt.utils.win_update.needs_reboot()
[ "Determines", "if", "the", "system", "needs", "to", "be", "rebooted", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_update.py#L998-L1019
train
saltstack/salt
salt/utils/win_update.py
Updates.list
def list(self): ''' Create a dictionary with the details for the updates in the collection. Returns: dict: Details about each update .. code-block:: cfg List of Updates: {'<GUID>': {'Title': <title>, 'KB': <KB>, 'GUID': <the globally unique identifier for the update> 'Description': <description>, 'Downloaded': <has the update been downloaded>, 'Installed': <has the update been installed>, 'Mandatory': <is the update mandatory>, 'UserInput': <is user input required>, 'EULAAccepted': <has the EULA been accepted>, 'Severity': <update severity>, 'NeedsReboot': <is the update installed and awaiting reboot>, 'RebootBehavior': <will the update require a reboot>, 'Categories': [ '<category 1>', '<category 2>', ...] } } Code Example: .. code-block:: python import salt.utils.win_update updates = salt.utils.win_update.Updates() updates.list() ''' # https://msdn.microsoft.com/en-us/library/windows/desktop/aa386099(v=vs.85).aspx if self.count() == 0: return 'Nothing to return' log.debug('Building a detailed report of the results.') # Build a dictionary containing details for each update results = {} for update in self.updates: results[update.Identity.UpdateID] = { 'guid': update.Identity.UpdateID, 'Title': six.text_type(update.Title), 'Type': self.update_types[update.Type], 'Description': update.Description, 'Downloaded': bool(update.IsDownloaded), 'Installed': bool(update.IsInstalled), 'Mandatory': bool(update.IsMandatory), 'EULAAccepted': bool(update.EulaAccepted), 'NeedsReboot': bool(update.RebootRequired), 'Severity': six.text_type(update.MsrcSeverity), 'UserInput': bool(update.InstallationBehavior.CanRequestUserInput), 'RebootBehavior': self.reboot_behavior[ update.InstallationBehavior.RebootBehavior], 'KBs': ['KB' + item for item in update.KBArticleIDs], 'Categories': [item.Name for item in update.Categories] } return results
python
def list(self): ''' Create a dictionary with the details for the updates in the collection. Returns: dict: Details about each update .. code-block:: cfg List of Updates: {'<GUID>': {'Title': <title>, 'KB': <KB>, 'GUID': <the globally unique identifier for the update> 'Description': <description>, 'Downloaded': <has the update been downloaded>, 'Installed': <has the update been installed>, 'Mandatory': <is the update mandatory>, 'UserInput': <is user input required>, 'EULAAccepted': <has the EULA been accepted>, 'Severity': <update severity>, 'NeedsReboot': <is the update installed and awaiting reboot>, 'RebootBehavior': <will the update require a reboot>, 'Categories': [ '<category 1>', '<category 2>', ...] } } Code Example: .. code-block:: python import salt.utils.win_update updates = salt.utils.win_update.Updates() updates.list() ''' # https://msdn.microsoft.com/en-us/library/windows/desktop/aa386099(v=vs.85).aspx if self.count() == 0: return 'Nothing to return' log.debug('Building a detailed report of the results.') # Build a dictionary containing details for each update results = {} for update in self.updates: results[update.Identity.UpdateID] = { 'guid': update.Identity.UpdateID, 'Title': six.text_type(update.Title), 'Type': self.update_types[update.Type], 'Description': update.Description, 'Downloaded': bool(update.IsDownloaded), 'Installed': bool(update.IsInstalled), 'Mandatory': bool(update.IsMandatory), 'EULAAccepted': bool(update.EulaAccepted), 'NeedsReboot': bool(update.RebootRequired), 'Severity': six.text_type(update.MsrcSeverity), 'UserInput': bool(update.InstallationBehavior.CanRequestUserInput), 'RebootBehavior': self.reboot_behavior[ update.InstallationBehavior.RebootBehavior], 'KBs': ['KB' + item for item in update.KBArticleIDs], 'Categories': [item.Name for item in update.Categories] } return results
[ "def", "list", "(", "self", ")", ":", "# https://msdn.microsoft.com/en-us/library/windows/desktop/aa386099(v=vs.85).aspx", "if", "self", ".", "count", "(", ")", "==", "0", ":", "return", "'Nothing to return'", "log", ".", "debug", "(", "'Building a detailed report of the ...
Create a dictionary with the details for the updates in the collection. Returns: dict: Details about each update .. code-block:: cfg List of Updates: {'<GUID>': {'Title': <title>, 'KB': <KB>, 'GUID': <the globally unique identifier for the update> 'Description': <description>, 'Downloaded': <has the update been downloaded>, 'Installed': <has the update been installed>, 'Mandatory': <is the update mandatory>, 'UserInput': <is user input required>, 'EULAAccepted': <has the EULA been accepted>, 'Severity': <update severity>, 'NeedsReboot': <is the update installed and awaiting reboot>, 'RebootBehavior': <will the update require a reboot>, 'Categories': [ '<category 1>', '<category 2>', ...] } } Code Example: .. code-block:: python import salt.utils.win_update updates = salt.utils.win_update.Updates() updates.list()
[ "Create", "a", "dictionary", "with", "the", "details", "for", "the", "updates", "in", "the", "collection", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_update.py#L101-L167
train
saltstack/salt
salt/utils/win_update.py
Updates.summary
def summary(self): ''' Create a dictionary with a summary of the updates in the collection. Returns: dict: Summary of the contents of the collection .. code-block:: cfg Summary of Updates: {'Total': <total number of updates returned>, 'Available': <updates that are not downloaded or installed>, 'Downloaded': <updates that are downloaded but not installed>, 'Installed': <updates installed (usually 0 unless installed=True)>, 'Categories': { <category 1>: <total for that category>, <category 2>: <total for category 2>, ... } } Code Example: .. code-block:: python import salt.utils.win_update updates = salt.utils.win_update.Updates() updates.summary() ''' # https://msdn.microsoft.com/en-us/library/windows/desktop/aa386099(v=vs.85).aspx if self.count() == 0: return 'Nothing to return' # Build a dictionary containing a summary of updates available results = {'Total': 0, 'Available': 0, 'Downloaded': 0, 'Installed': 0, 'Categories': {}, 'Severity': {}} for update in self.updates: # Count the total number of updates available results['Total'] += 1 # Updates available for download if not salt.utils.data.is_true(update.IsDownloaded) \ and not salt.utils.data.is_true(update.IsInstalled): results['Available'] += 1 # Updates downloaded awaiting install if salt.utils.data.is_true(update.IsDownloaded) \ and not salt.utils.data.is_true(update.IsInstalled): results['Downloaded'] += 1 # Updates installed if salt.utils.data.is_true(update.IsInstalled): results['Installed'] += 1 # Add Categories and increment total for each one # The sum will be more than the total because each update can have # multiple categories for category in update.Categories: if category.Name in results['Categories']: results['Categories'][category.Name] += 1 else: results['Categories'][category.Name] = 1 # Add Severity Summary if update.MsrcSeverity: if update.MsrcSeverity in results['Severity']: results['Severity'][update.MsrcSeverity] += 1 else: results['Severity'][update.MsrcSeverity] = 1 return results
python
def summary(self): ''' Create a dictionary with a summary of the updates in the collection. Returns: dict: Summary of the contents of the collection .. code-block:: cfg Summary of Updates: {'Total': <total number of updates returned>, 'Available': <updates that are not downloaded or installed>, 'Downloaded': <updates that are downloaded but not installed>, 'Installed': <updates installed (usually 0 unless installed=True)>, 'Categories': { <category 1>: <total for that category>, <category 2>: <total for category 2>, ... } } Code Example: .. code-block:: python import salt.utils.win_update updates = salt.utils.win_update.Updates() updates.summary() ''' # https://msdn.microsoft.com/en-us/library/windows/desktop/aa386099(v=vs.85).aspx if self.count() == 0: return 'Nothing to return' # Build a dictionary containing a summary of updates available results = {'Total': 0, 'Available': 0, 'Downloaded': 0, 'Installed': 0, 'Categories': {}, 'Severity': {}} for update in self.updates: # Count the total number of updates available results['Total'] += 1 # Updates available for download if not salt.utils.data.is_true(update.IsDownloaded) \ and not salt.utils.data.is_true(update.IsInstalled): results['Available'] += 1 # Updates downloaded awaiting install if salt.utils.data.is_true(update.IsDownloaded) \ and not salt.utils.data.is_true(update.IsInstalled): results['Downloaded'] += 1 # Updates installed if salt.utils.data.is_true(update.IsInstalled): results['Installed'] += 1 # Add Categories and increment total for each one # The sum will be more than the total because each update can have # multiple categories for category in update.Categories: if category.Name in results['Categories']: results['Categories'][category.Name] += 1 else: results['Categories'][category.Name] = 1 # Add Severity Summary if update.MsrcSeverity: if update.MsrcSeverity in results['Severity']: results['Severity'][update.MsrcSeverity] += 1 else: results['Severity'][update.MsrcSeverity] = 1 return results
[ "def", "summary", "(", "self", ")", ":", "# https://msdn.microsoft.com/en-us/library/windows/desktop/aa386099(v=vs.85).aspx", "if", "self", ".", "count", "(", ")", "==", "0", ":", "return", "'Nothing to return'", "# Build a dictionary containing a summary of updates available", ...
Create a dictionary with a summary of the updates in the collection. Returns: dict: Summary of the contents of the collection .. code-block:: cfg Summary of Updates: {'Total': <total number of updates returned>, 'Available': <updates that are not downloaded or installed>, 'Downloaded': <updates that are downloaded but not installed>, 'Installed': <updates installed (usually 0 unless installed=True)>, 'Categories': { <category 1>: <total for that category>, <category 2>: <total for category 2>, ... } } Code Example: .. code-block:: python import salt.utils.win_update updates = salt.utils.win_update.Updates() updates.summary()
[ "Create", "a", "dictionary", "with", "a", "summary", "of", "the", "updates", "in", "the", "collection", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_update.py#L169-L242
train
saltstack/salt
salt/utils/win_update.py
WindowsUpdateAgent.updates
def updates(self): ''' Get the contents of ``_updates`` (all updates) and puts them in an Updates class to expose the list and summary functions. Returns: Updates: An instance of the Updates class with all updates for the system. .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() updates = wua.updates() # To get a list updates.list() # To get a summary updates.summary() ''' updates = Updates() found = updates.updates for update in self._updates: found.Add(update) return updates
python
def updates(self): ''' Get the contents of ``_updates`` (all updates) and puts them in an Updates class to expose the list and summary functions. Returns: Updates: An instance of the Updates class with all updates for the system. .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() updates = wua.updates() # To get a list updates.list() # To get a summary updates.summary() ''' updates = Updates() found = updates.updates for update in self._updates: found.Add(update) return updates
[ "def", "updates", "(", "self", ")", ":", "updates", "=", "Updates", "(", ")", "found", "=", "updates", ".", "updates", "for", "update", "in", "self", ".", "_updates", ":", "found", ".", "Add", "(", "update", ")", "return", "updates" ]
Get the contents of ``_updates`` (all updates) and puts them in an Updates class to expose the list and summary functions. Returns: Updates: An instance of the Updates class with all updates for the system. .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() updates = wua.updates() # To get a list updates.list() # To get a summary updates.summary()
[ "Get", "the", "contents", "of", "_updates", "(", "all", "updates", ")", "and", "puts", "them", "in", "an", "Updates", "class", "to", "expose", "the", "list", "and", "summary", "functions", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_update.py#L298-L325
train
saltstack/salt
salt/utils/win_update.py
WindowsUpdateAgent.refresh
def refresh(self): ''' Refresh the contents of the ``_updates`` collection. This gets all updates in the Windows Update system and loads them into the collection. This is the part that is slow. Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() wua.refresh() ''' # https://msdn.microsoft.com/en-us/library/windows/desktop/aa386526(v=vs.85).aspx search_string = 'Type=\'Software\' or ' \ 'Type=\'Driver\'' # Create searcher object searcher = self._session.CreateUpdateSearcher() self._session.ClientApplicationID = 'Salt: Load Updates' # Load all updates into the updates collection try: results = searcher.Search(search_string) if results.Updates.Count == 0: log.debug('No Updates found for:\n\t\t%s', search_string) return 'No Updates found: {0}'.format(search_string) except pywintypes.com_error as error: # Something happened, raise an error hr, msg, exc, arg = error.args # pylint: disable=W0633 try: failure_code = self.fail_codes[exc[5]] except KeyError: failure_code = 'Unknown Failure: {0}'.format(error) log.error('Search Failed: %s\n\t\t%s', failure_code, search_string) raise CommandExecutionError(failure_code) self._updates = results.Updates
python
def refresh(self): ''' Refresh the contents of the ``_updates`` collection. This gets all updates in the Windows Update system and loads them into the collection. This is the part that is slow. Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() wua.refresh() ''' # https://msdn.microsoft.com/en-us/library/windows/desktop/aa386526(v=vs.85).aspx search_string = 'Type=\'Software\' or ' \ 'Type=\'Driver\'' # Create searcher object searcher = self._session.CreateUpdateSearcher() self._session.ClientApplicationID = 'Salt: Load Updates' # Load all updates into the updates collection try: results = searcher.Search(search_string) if results.Updates.Count == 0: log.debug('No Updates found for:\n\t\t%s', search_string) return 'No Updates found: {0}'.format(search_string) except pywintypes.com_error as error: # Something happened, raise an error hr, msg, exc, arg = error.args # pylint: disable=W0633 try: failure_code = self.fail_codes[exc[5]] except KeyError: failure_code = 'Unknown Failure: {0}'.format(error) log.error('Search Failed: %s\n\t\t%s', failure_code, search_string) raise CommandExecutionError(failure_code) self._updates = results.Updates
[ "def", "refresh", "(", "self", ")", ":", "# https://msdn.microsoft.com/en-us/library/windows/desktop/aa386526(v=vs.85).aspx", "search_string", "=", "'Type=\\'Software\\' or '", "'Type=\\'Driver\\''", "# Create searcher object", "searcher", "=", "self", ".", "_session", ".", "Crea...
Refresh the contents of the ``_updates`` collection. This gets all updates in the Windows Update system and loads them into the collection. This is the part that is slow. Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() wua.refresh()
[ "Refresh", "the", "contents", "of", "the", "_updates", "collection", ".", "This", "gets", "all", "updates", "in", "the", "Windows", "Update", "system", "and", "loads", "them", "into", "the", "collection", ".", "This", "is", "the", "part", "that", "is", "sl...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_update.py#L327-L366
train
saltstack/salt
salt/utils/win_update.py
WindowsUpdateAgent.available
def available(self, skip_hidden=True, skip_installed=True, skip_mandatory=False, skip_reboot=False, software=True, drivers=True, categories=None, severities=None): ''' Gets a list of all updates available on the system that match the passed criteria. Args: skip_hidden (bool): Skip hidden updates. Default is True skip_installed (bool): Skip installed updates. Default is True skip_mandatory (bool): Skip mandatory updates. Default is False skip_reboot (bool): Skip updates that can or do require reboot. Default is False software (bool): Include software updates. Default is True drivers (bool): Include driver updates. Default is True categories (list): Include updates that have these categories. Default is none (all categories). Categories include the following: * Critical Updates * Definition Updates * Drivers (make sure you set drivers=True) * Feature Packs * Security Updates * Update Rollups * Updates * Update Rollups * Windows 7 * Windows 8.1 * Windows 8.1 drivers * Windows 8.1 and later drivers * Windows Defender severities (list): Include updates that have these severities. Default is none (all severities). Severities include the following: * Critical * Important .. note:: All updates are either software or driver updates. If both ``software`` and ``drivers`` is False, nothing will be returned. Returns: Updates: An instance of Updates with the results of the search. Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # Gets all updates and shows a summary updates = wua.available updates.summary() # Get a list of Critical updates updates = wua.available(categories=['Critical Updates']) updates.list() ''' # https://msdn.microsoft.com/en-us/library/windows/desktop/aa386099(v=vs.85).aspx updates = Updates() found = updates.updates for update in self._updates: if salt.utils.data.is_true(update.IsHidden) and skip_hidden: continue if salt.utils.data.is_true(update.IsInstalled) and skip_installed: continue if salt.utils.data.is_true(update.IsMandatory) and skip_mandatory: continue if salt.utils.data.is_true( update.InstallationBehavior.RebootBehavior) and skip_reboot: continue if not software and update.Type == 1: continue if not drivers and update.Type == 2: continue if categories is not None: match = False for category in update.Categories: if category.Name in categories: match = True if not match: continue if severities is not None: if update.MsrcSeverity not in severities: continue found.Add(update) return updates
python
def available(self, skip_hidden=True, skip_installed=True, skip_mandatory=False, skip_reboot=False, software=True, drivers=True, categories=None, severities=None): ''' Gets a list of all updates available on the system that match the passed criteria. Args: skip_hidden (bool): Skip hidden updates. Default is True skip_installed (bool): Skip installed updates. Default is True skip_mandatory (bool): Skip mandatory updates. Default is False skip_reboot (bool): Skip updates that can or do require reboot. Default is False software (bool): Include software updates. Default is True drivers (bool): Include driver updates. Default is True categories (list): Include updates that have these categories. Default is none (all categories). Categories include the following: * Critical Updates * Definition Updates * Drivers (make sure you set drivers=True) * Feature Packs * Security Updates * Update Rollups * Updates * Update Rollups * Windows 7 * Windows 8.1 * Windows 8.1 drivers * Windows 8.1 and later drivers * Windows Defender severities (list): Include updates that have these severities. Default is none (all severities). Severities include the following: * Critical * Important .. note:: All updates are either software or driver updates. If both ``software`` and ``drivers`` is False, nothing will be returned. Returns: Updates: An instance of Updates with the results of the search. Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # Gets all updates and shows a summary updates = wua.available updates.summary() # Get a list of Critical updates updates = wua.available(categories=['Critical Updates']) updates.list() ''' # https://msdn.microsoft.com/en-us/library/windows/desktop/aa386099(v=vs.85).aspx updates = Updates() found = updates.updates for update in self._updates: if salt.utils.data.is_true(update.IsHidden) and skip_hidden: continue if salt.utils.data.is_true(update.IsInstalled) and skip_installed: continue if salt.utils.data.is_true(update.IsMandatory) and skip_mandatory: continue if salt.utils.data.is_true( update.InstallationBehavior.RebootBehavior) and skip_reboot: continue if not software and update.Type == 1: continue if not drivers and update.Type == 2: continue if categories is not None: match = False for category in update.Categories: if category.Name in categories: match = True if not match: continue if severities is not None: if update.MsrcSeverity not in severities: continue found.Add(update) return updates
[ "def", "available", "(", "self", ",", "skip_hidden", "=", "True", ",", "skip_installed", "=", "True", ",", "skip_mandatory", "=", "False", ",", "skip_reboot", "=", "False", ",", "software", "=", "True", ",", "drivers", "=", "True", ",", "categories", "=", ...
Gets a list of all updates available on the system that match the passed criteria. Args: skip_hidden (bool): Skip hidden updates. Default is True skip_installed (bool): Skip installed updates. Default is True skip_mandatory (bool): Skip mandatory updates. Default is False skip_reboot (bool): Skip updates that can or do require reboot. Default is False software (bool): Include software updates. Default is True drivers (bool): Include driver updates. Default is True categories (list): Include updates that have these categories. Default is none (all categories). Categories include the following: * Critical Updates * Definition Updates * Drivers (make sure you set drivers=True) * Feature Packs * Security Updates * Update Rollups * Updates * Update Rollups * Windows 7 * Windows 8.1 * Windows 8.1 drivers * Windows 8.1 and later drivers * Windows Defender severities (list): Include updates that have these severities. Default is none (all severities). Severities include the following: * Critical * Important .. note:: All updates are either software or driver updates. If both ``software`` and ``drivers`` is False, nothing will be returned. Returns: Updates: An instance of Updates with the results of the search. Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # Gets all updates and shows a summary updates = wua.available updates.summary() # Get a list of Critical updates updates = wua.available(categories=['Critical Updates']) updates.list()
[ "Gets", "a", "list", "of", "all", "updates", "available", "on", "the", "system", "that", "match", "the", "passed", "criteria", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_update.py#L368-L484
train
saltstack/salt
salt/utils/win_update.py
WindowsUpdateAgent.search
def search(self, search_string): ''' Search for either a single update or a specific list of updates. GUIDs are searched first, then KB numbers, and finally Titles. Args: search_string (str, list): The search string to use to find the update. This can be the GUID or KB of the update (preferred). It can also be the full Title of the update or any part of the Title. A partial Title search is less specific and can return multiple results. Returns: Updates: An instance of Updates with the results of the search Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # search for a single update and show its details updates = wua.search('KB3194343') updates.list() # search for a list of updates and show their details updates = wua.search(['KB3195432', '12345678-abcd-1234-abcd-1234567890ab']) updates.list() ''' updates = Updates() found = updates.updates if isinstance(search_string, six.string_types): search_string = [search_string] if isinstance(search_string, six.integer_types): search_string = [six.text_type(search_string)] for update in self._updates: for find in search_string: # Search by GUID if find == update.Identity.UpdateID: found.Add(update) continue # Search by KB if find in ['KB' + item for item in update.KBArticleIDs]: found.Add(update) continue # Search by KB without the KB in front if find in [item for item in update.KBArticleIDs]: found.Add(update) continue # Search by Title if find in update.Title: found.Add(update) continue return updates
python
def search(self, search_string): ''' Search for either a single update or a specific list of updates. GUIDs are searched first, then KB numbers, and finally Titles. Args: search_string (str, list): The search string to use to find the update. This can be the GUID or KB of the update (preferred). It can also be the full Title of the update or any part of the Title. A partial Title search is less specific and can return multiple results. Returns: Updates: An instance of Updates with the results of the search Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # search for a single update and show its details updates = wua.search('KB3194343') updates.list() # search for a list of updates and show their details updates = wua.search(['KB3195432', '12345678-abcd-1234-abcd-1234567890ab']) updates.list() ''' updates = Updates() found = updates.updates if isinstance(search_string, six.string_types): search_string = [search_string] if isinstance(search_string, six.integer_types): search_string = [six.text_type(search_string)] for update in self._updates: for find in search_string: # Search by GUID if find == update.Identity.UpdateID: found.Add(update) continue # Search by KB if find in ['KB' + item for item in update.KBArticleIDs]: found.Add(update) continue # Search by KB without the KB in front if find in [item for item in update.KBArticleIDs]: found.Add(update) continue # Search by Title if find in update.Title: found.Add(update) continue return updates
[ "def", "search", "(", "self", ",", "search_string", ")", ":", "updates", "=", "Updates", "(", ")", "found", "=", "updates", ".", "updates", "if", "isinstance", "(", "search_string", ",", "six", ".", "string_types", ")", ":", "search_string", "=", "[", "s...
Search for either a single update or a specific list of updates. GUIDs are searched first, then KB numbers, and finally Titles. Args: search_string (str, list): The search string to use to find the update. This can be the GUID or KB of the update (preferred). It can also be the full Title of the update or any part of the Title. A partial Title search is less specific and can return multiple results. Returns: Updates: An instance of Updates with the results of the search Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # search for a single update and show its details updates = wua.search('KB3194343') updates.list() # search for a list of updates and show their details updates = wua.search(['KB3195432', '12345678-abcd-1234-abcd-1234567890ab']) updates.list()
[ "Search", "for", "either", "a", "single", "update", "or", "a", "specific", "list", "of", "updates", ".", "GUIDs", "are", "searched", "first", "then", "KB", "numbers", "and", "finally", "Titles", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_update.py#L486-L550
train
saltstack/salt
salt/utils/win_update.py
WindowsUpdateAgent.download
def download(self, updates): ''' Download the updates passed in the updates collection. Load the updates collection using ``search`` or ``available`` Args: updates (Updates): An instance of the Updates class containing a the updates to be downloaded. Returns: dict: A dictionary containing the results of the download Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # Download KB3195454 updates = wua.search('KB3195454') results = wua.download(updates) ''' # Check for empty list if updates.count() == 0: ret = {'Success': False, 'Updates': 'Nothing to download'} return ret # Initialize the downloader object and list collection downloader = self._session.CreateUpdateDownloader() self._session.ClientApplicationID = 'Salt: Download Update' with salt.utils.winapi.Com(): download_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl') ret = {'Updates': {}} # Check for updates that aren't already downloaded for update in updates.updates: # Define uid to keep the lines shorter uid = update.Identity.UpdateID ret['Updates'][uid] = {} ret['Updates'][uid]['Title'] = update.Title ret['Updates'][uid]['AlreadyDownloaded'] = \ bool(update.IsDownloaded) # Accept EULA if not salt.utils.data.is_true(update.EulaAccepted): log.debug('Accepting EULA: %s', update.Title) update.AcceptEula() # pylint: disable=W0104 # Update already downloaded if not salt.utils.data.is_true(update.IsDownloaded): log.debug('To Be Downloaded: %s', uid) log.debug('\tTitle: %s', update.Title) download_list.Add(update) # Check the download list if download_list.Count == 0: ret = {'Success': True, 'Updates': 'Nothing to download'} return ret # Send the list to the downloader downloader.Updates = download_list # Download the list try: log.debug('Downloading Updates') result = downloader.Download() except pywintypes.com_error as error: # Something happened, raise an error hr, msg, exc, arg = error.args # pylint: disable=W0633 try: failure_code = self.fail_codes[exc[5]] except KeyError: failure_code = 'Unknown Failure: {0}'.format(error) log.error('Download Failed: %s', failure_code) raise CommandExecutionError(failure_code) # Lookup dictionary result_code = {0: 'Download Not Started', 1: 'Download In Progress', 2: 'Download Succeeded', 3: 'Download Succeeded With Errors', 4: 'Download Failed', 5: 'Download Aborted'} log.debug('Download Complete') log.debug(result_code[result.ResultCode]) ret['Message'] = result_code[result.ResultCode] # Was the download successful? if result.ResultCode in [2, 3]: log.debug('Downloaded Successfully') ret['Success'] = True else: log.debug('Download Failed') ret['Success'] = False # Report results for each update for i in range(download_list.Count): uid = download_list.Item(i).Identity.UpdateID ret['Updates'][uid]['Result'] = \ result_code[result.GetUpdateResult(i).ResultCode] return ret
python
def download(self, updates): ''' Download the updates passed in the updates collection. Load the updates collection using ``search`` or ``available`` Args: updates (Updates): An instance of the Updates class containing a the updates to be downloaded. Returns: dict: A dictionary containing the results of the download Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # Download KB3195454 updates = wua.search('KB3195454') results = wua.download(updates) ''' # Check for empty list if updates.count() == 0: ret = {'Success': False, 'Updates': 'Nothing to download'} return ret # Initialize the downloader object and list collection downloader = self._session.CreateUpdateDownloader() self._session.ClientApplicationID = 'Salt: Download Update' with salt.utils.winapi.Com(): download_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl') ret = {'Updates': {}} # Check for updates that aren't already downloaded for update in updates.updates: # Define uid to keep the lines shorter uid = update.Identity.UpdateID ret['Updates'][uid] = {} ret['Updates'][uid]['Title'] = update.Title ret['Updates'][uid]['AlreadyDownloaded'] = \ bool(update.IsDownloaded) # Accept EULA if not salt.utils.data.is_true(update.EulaAccepted): log.debug('Accepting EULA: %s', update.Title) update.AcceptEula() # pylint: disable=W0104 # Update already downloaded if not salt.utils.data.is_true(update.IsDownloaded): log.debug('To Be Downloaded: %s', uid) log.debug('\tTitle: %s', update.Title) download_list.Add(update) # Check the download list if download_list.Count == 0: ret = {'Success': True, 'Updates': 'Nothing to download'} return ret # Send the list to the downloader downloader.Updates = download_list # Download the list try: log.debug('Downloading Updates') result = downloader.Download() except pywintypes.com_error as error: # Something happened, raise an error hr, msg, exc, arg = error.args # pylint: disable=W0633 try: failure_code = self.fail_codes[exc[5]] except KeyError: failure_code = 'Unknown Failure: {0}'.format(error) log.error('Download Failed: %s', failure_code) raise CommandExecutionError(failure_code) # Lookup dictionary result_code = {0: 'Download Not Started', 1: 'Download In Progress', 2: 'Download Succeeded', 3: 'Download Succeeded With Errors', 4: 'Download Failed', 5: 'Download Aborted'} log.debug('Download Complete') log.debug(result_code[result.ResultCode]) ret['Message'] = result_code[result.ResultCode] # Was the download successful? if result.ResultCode in [2, 3]: log.debug('Downloaded Successfully') ret['Success'] = True else: log.debug('Download Failed') ret['Success'] = False # Report results for each update for i in range(download_list.Count): uid = download_list.Item(i).Identity.UpdateID ret['Updates'][uid]['Result'] = \ result_code[result.GetUpdateResult(i).ResultCode] return ret
[ "def", "download", "(", "self", ",", "updates", ")", ":", "# Check for empty list", "if", "updates", ".", "count", "(", ")", "==", "0", ":", "ret", "=", "{", "'Success'", ":", "False", ",", "'Updates'", ":", "'Nothing to download'", "}", "return", "ret", ...
Download the updates passed in the updates collection. Load the updates collection using ``search`` or ``available`` Args: updates (Updates): An instance of the Updates class containing a the updates to be downloaded. Returns: dict: A dictionary containing the results of the download Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # Download KB3195454 updates = wua.search('KB3195454') results = wua.download(updates)
[ "Download", "the", "updates", "passed", "in", "the", "updates", "collection", ".", "Load", "the", "updates", "collection", "using", "search", "or", "available" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_update.py#L552-L662
train
saltstack/salt
salt/utils/win_update.py
WindowsUpdateAgent.install
def install(self, updates): ''' Install the updates passed in the updates collection. Load the updates collection using the ``search`` or ``available`` functions. If the updates need to be downloaded, use the ``download`` function. Args: updates (Updates): An instance of the Updates class containing a the updates to be installed. Returns: dict: A dictionary containing the results of the installation Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # install KB3195454 updates = wua.search('KB3195454') results = wua.download(updates) results = wua.install(updates) ''' # Check for empty list if updates.count() == 0: ret = {'Success': False, 'Updates': 'Nothing to install'} return ret installer = self._session.CreateUpdateInstaller() self._session.ClientApplicationID = 'Salt: Install Update' with salt.utils.winapi.Com(): install_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl') ret = {'Updates': {}} # Check for updates that aren't already installed for update in updates.updates: # Define uid to keep the lines shorter uid = update.Identity.UpdateID ret['Updates'][uid] = {} ret['Updates'][uid]['Title'] = update.Title ret['Updates'][uid]['AlreadyInstalled'] = bool(update.IsInstalled) # Make sure the update has actually been installed if not salt.utils.data.is_true(update.IsInstalled): log.debug('To Be Installed: %s', uid) log.debug('\tTitle: %s', update.Title) install_list.Add(update) # Check the install list if install_list.Count == 0: ret = {'Success': True, 'Updates': 'Nothing to install'} return ret # Send the list to the installer installer.Updates = install_list # Install the list try: log.debug('Installing Updates') result = installer.Install() except pywintypes.com_error as error: # Something happened, raise an error hr, msg, exc, arg = error.args # pylint: disable=W0633 try: failure_code = self.fail_codes[exc[5]] except KeyError: failure_code = 'Unknown Failure: {0}'.format(error) log.error('Install Failed: %s', failure_code) raise CommandExecutionError(failure_code) # Lookup dictionary result_code = {0: 'Installation Not Started', 1: 'Installation In Progress', 2: 'Installation Succeeded', 3: 'Installation Succeeded With Errors', 4: 'Installation Failed', 5: 'Installation Aborted'} log.debug('Install Complete') log.debug(result_code[result.ResultCode]) ret['Message'] = result_code[result.ResultCode] if result.ResultCode in [2, 3]: ret['Success'] = True ret['NeedsReboot'] = result.RebootRequired log.debug('NeedsReboot: %s', result.RebootRequired) else: log.debug('Install Failed') ret['Success'] = False reboot = {0: 'Never Reboot', 1: 'Always Reboot', 2: 'Poss Reboot'} for i in range(install_list.Count): uid = install_list.Item(i).Identity.UpdateID ret['Updates'][uid]['Result'] = \ result_code[result.GetUpdateResult(i).ResultCode] ret['Updates'][uid]['RebootBehavior'] = \ reboot[install_list.Item(i).InstallationBehavior.RebootBehavior] return ret
python
def install(self, updates): ''' Install the updates passed in the updates collection. Load the updates collection using the ``search`` or ``available`` functions. If the updates need to be downloaded, use the ``download`` function. Args: updates (Updates): An instance of the Updates class containing a the updates to be installed. Returns: dict: A dictionary containing the results of the installation Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # install KB3195454 updates = wua.search('KB3195454') results = wua.download(updates) results = wua.install(updates) ''' # Check for empty list if updates.count() == 0: ret = {'Success': False, 'Updates': 'Nothing to install'} return ret installer = self._session.CreateUpdateInstaller() self._session.ClientApplicationID = 'Salt: Install Update' with salt.utils.winapi.Com(): install_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl') ret = {'Updates': {}} # Check for updates that aren't already installed for update in updates.updates: # Define uid to keep the lines shorter uid = update.Identity.UpdateID ret['Updates'][uid] = {} ret['Updates'][uid]['Title'] = update.Title ret['Updates'][uid]['AlreadyInstalled'] = bool(update.IsInstalled) # Make sure the update has actually been installed if not salt.utils.data.is_true(update.IsInstalled): log.debug('To Be Installed: %s', uid) log.debug('\tTitle: %s', update.Title) install_list.Add(update) # Check the install list if install_list.Count == 0: ret = {'Success': True, 'Updates': 'Nothing to install'} return ret # Send the list to the installer installer.Updates = install_list # Install the list try: log.debug('Installing Updates') result = installer.Install() except pywintypes.com_error as error: # Something happened, raise an error hr, msg, exc, arg = error.args # pylint: disable=W0633 try: failure_code = self.fail_codes[exc[5]] except KeyError: failure_code = 'Unknown Failure: {0}'.format(error) log.error('Install Failed: %s', failure_code) raise CommandExecutionError(failure_code) # Lookup dictionary result_code = {0: 'Installation Not Started', 1: 'Installation In Progress', 2: 'Installation Succeeded', 3: 'Installation Succeeded With Errors', 4: 'Installation Failed', 5: 'Installation Aborted'} log.debug('Install Complete') log.debug(result_code[result.ResultCode]) ret['Message'] = result_code[result.ResultCode] if result.ResultCode in [2, 3]: ret['Success'] = True ret['NeedsReboot'] = result.RebootRequired log.debug('NeedsReboot: %s', result.RebootRequired) else: log.debug('Install Failed') ret['Success'] = False reboot = {0: 'Never Reboot', 1: 'Always Reboot', 2: 'Poss Reboot'} for i in range(install_list.Count): uid = install_list.Item(i).Identity.UpdateID ret['Updates'][uid]['Result'] = \ result_code[result.GetUpdateResult(i).ResultCode] ret['Updates'][uid]['RebootBehavior'] = \ reboot[install_list.Item(i).InstallationBehavior.RebootBehavior] return ret
[ "def", "install", "(", "self", ",", "updates", ")", ":", "# Check for empty list", "if", "updates", ".", "count", "(", ")", "==", "0", ":", "ret", "=", "{", "'Success'", ":", "False", ",", "'Updates'", ":", "'Nothing to install'", "}", "return", "ret", "...
Install the updates passed in the updates collection. Load the updates collection using the ``search`` or ``available`` functions. If the updates need to be downloaded, use the ``download`` function. Args: updates (Updates): An instance of the Updates class containing a the updates to be installed. Returns: dict: A dictionary containing the results of the installation Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # install KB3195454 updates = wua.search('KB3195454') results = wua.download(updates) results = wua.install(updates)
[ "Install", "the", "updates", "passed", "in", "the", "updates", "collection", ".", "Load", "the", "updates", "collection", "using", "the", "search", "or", "available", "functions", ".", "If", "the", "updates", "need", "to", "be", "downloaded", "use", "the", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_update.py#L664-L773
train
saltstack/salt
salt/utils/win_update.py
WindowsUpdateAgent.uninstall
def uninstall(self, updates): ''' Uninstall the updates passed in the updates collection. Load the updates collection using the ``search`` or ``available`` functions. .. note:: Starting with Windows 10 the Windows Update Agent is unable to uninstall updates. An ``Uninstall Not Allowed`` error is returned. If this error is encountered this function will instead attempt to use ``dism.exe`` to perform the uninstallation. ``dism.exe`` may fail to to find the KB number for the package. In that case, removal will fail. Args: updates (Updates): An instance of the Updates class containing a the updates to be uninstalled. Returns: dict: A dictionary containing the results of the uninstallation Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # uninstall KB3195454 updates = wua.search('KB3195454') results = wua.uninstall(updates) ''' # This doesn't work with the WUA API since Windows 10. It always returns # "0x80240028 # Uninstall not allowed". The full message is: "The update # could not be uninstalled because the request did not originate from a # Windows Server Update Services (WSUS) server. # Check for empty list if updates.count() == 0: ret = {'Success': False, 'Updates': 'Nothing to uninstall'} return ret installer = self._session.CreateUpdateInstaller() self._session.ClientApplicationID = 'Salt: Install Update' with salt.utils.winapi.Com(): uninstall_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl') ret = {'Updates': {}} # Check for updates that aren't already installed for update in updates.updates: # Define uid to keep the lines shorter uid = update.Identity.UpdateID ret['Updates'][uid] = {} ret['Updates'][uid]['Title'] = update.Title ret['Updates'][uid]['AlreadyUninstalled'] = \ not bool(update.IsInstalled) # Make sure the update has actually been Uninstalled if salt.utils.data.is_true(update.IsInstalled): log.debug('To Be Uninstalled: %s', uid) log.debug('\tTitle: %s', update.Title) uninstall_list.Add(update) # Check the install list if uninstall_list.Count == 0: ret = {'Success': False, 'Updates': 'Nothing to uninstall'} return ret # Send the list to the installer installer.Updates = uninstall_list # Uninstall the list try: log.debug('Uninstalling Updates') result = installer.Uninstall() except pywintypes.com_error as error: # Something happened, return error or try using DISM hr, msg, exc, arg = error.args # pylint: disable=W0633 try: failure_code = self.fail_codes[exc[5]] except KeyError: failure_code = 'Unknown Failure: {0}'.format(error) # If "Uninstall Not Allowed" error, try using DISM if exc[5] == -2145124312: log.debug('Uninstall Failed with WUA, attempting with DISM') try: # Go through each update... for item in uninstall_list: # Look for the KB numbers for kb in item.KBArticleIDs: # Get the list of packages cmd = ['dism', '/Online', '/Get-Packages'] pkg_list = self._run(cmd)[0].splitlines() # Find the KB in the pkg_list for item in pkg_list: # Uninstall if found if 'kb' + kb in item.lower(): pkg = item.split(' : ')[1] ret['DismPackage'] = pkg cmd = ['dism', '/Online', '/Remove-Package', '/PackageName:{0}'.format(pkg), '/Quiet', '/NoRestart'] self._run(cmd) except CommandExecutionError as exc: log.debug('Uninstall using DISM failed') log.debug('Command: %s', ' '.join(cmd)) log.debug('Error: %s', exc) raise CommandExecutionError( 'Uninstall using DISM failed: {0}'.format(exc)) # DISM Uninstall Completed Successfully log.debug('Uninstall Completed using DISM') # Populate the return dictionary ret['Success'] = True ret['Message'] = 'Uninstalled using DISM' ret['NeedsReboot'] = needs_reboot() log.debug('NeedsReboot: %s', ret['NeedsReboot']) # Refresh the Updates Table self.refresh() reboot = {0: 'Never Reboot', 1: 'Always Reboot', 2: 'Poss Reboot'} # Check the status of each update for update in self._updates: uid = update.Identity.UpdateID for item in uninstall_list: if item.Identity.UpdateID == uid: if not update.IsInstalled: ret['Updates'][uid]['Result'] = \ 'Uninstallation Succeeded' else: ret['Updates'][uid]['Result'] = \ 'Uninstallation Failed' ret['Updates'][uid]['RebootBehavior'] = \ reboot[update.InstallationBehavior.RebootBehavior] return ret # Found a differenct exception, Raise error log.error('Uninstall Failed: %s', failure_code) raise CommandExecutionError(failure_code) # Lookup dictionary result_code = {0: 'Uninstallation Not Started', 1: 'Uninstallation In Progress', 2: 'Uninstallation Succeeded', 3: 'Uninstallation Succeeded With Errors', 4: 'Uninstallation Failed', 5: 'Uninstallation Aborted'} log.debug('Uninstall Complete') log.debug(result_code[result.ResultCode]) ret['Message'] = result_code[result.ResultCode] if result.ResultCode in [2, 3]: ret['Success'] = True ret['NeedsReboot'] = result.RebootRequired log.debug('NeedsReboot: %s', result.RebootRequired) else: log.debug('Uninstall Failed') ret['Success'] = False reboot = {0: 'Never Reboot', 1: 'Always Reboot', 2: 'Poss Reboot'} for i in range(uninstall_list.Count): uid = uninstall_list.Item(i).Identity.UpdateID ret['Updates'][uid]['Result'] = \ result_code[result.GetUpdateResult(i).ResultCode] ret['Updates'][uid]['RebootBehavior'] = reboot[ uninstall_list.Item(i).InstallationBehavior.RebootBehavior] return ret
python
def uninstall(self, updates): ''' Uninstall the updates passed in the updates collection. Load the updates collection using the ``search`` or ``available`` functions. .. note:: Starting with Windows 10 the Windows Update Agent is unable to uninstall updates. An ``Uninstall Not Allowed`` error is returned. If this error is encountered this function will instead attempt to use ``dism.exe`` to perform the uninstallation. ``dism.exe`` may fail to to find the KB number for the package. In that case, removal will fail. Args: updates (Updates): An instance of the Updates class containing a the updates to be uninstalled. Returns: dict: A dictionary containing the results of the uninstallation Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # uninstall KB3195454 updates = wua.search('KB3195454') results = wua.uninstall(updates) ''' # This doesn't work with the WUA API since Windows 10. It always returns # "0x80240028 # Uninstall not allowed". The full message is: "The update # could not be uninstalled because the request did not originate from a # Windows Server Update Services (WSUS) server. # Check for empty list if updates.count() == 0: ret = {'Success': False, 'Updates': 'Nothing to uninstall'} return ret installer = self._session.CreateUpdateInstaller() self._session.ClientApplicationID = 'Salt: Install Update' with salt.utils.winapi.Com(): uninstall_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl') ret = {'Updates': {}} # Check for updates that aren't already installed for update in updates.updates: # Define uid to keep the lines shorter uid = update.Identity.UpdateID ret['Updates'][uid] = {} ret['Updates'][uid]['Title'] = update.Title ret['Updates'][uid]['AlreadyUninstalled'] = \ not bool(update.IsInstalled) # Make sure the update has actually been Uninstalled if salt.utils.data.is_true(update.IsInstalled): log.debug('To Be Uninstalled: %s', uid) log.debug('\tTitle: %s', update.Title) uninstall_list.Add(update) # Check the install list if uninstall_list.Count == 0: ret = {'Success': False, 'Updates': 'Nothing to uninstall'} return ret # Send the list to the installer installer.Updates = uninstall_list # Uninstall the list try: log.debug('Uninstalling Updates') result = installer.Uninstall() except pywintypes.com_error as error: # Something happened, return error or try using DISM hr, msg, exc, arg = error.args # pylint: disable=W0633 try: failure_code = self.fail_codes[exc[5]] except KeyError: failure_code = 'Unknown Failure: {0}'.format(error) # If "Uninstall Not Allowed" error, try using DISM if exc[5] == -2145124312: log.debug('Uninstall Failed with WUA, attempting with DISM') try: # Go through each update... for item in uninstall_list: # Look for the KB numbers for kb in item.KBArticleIDs: # Get the list of packages cmd = ['dism', '/Online', '/Get-Packages'] pkg_list = self._run(cmd)[0].splitlines() # Find the KB in the pkg_list for item in pkg_list: # Uninstall if found if 'kb' + kb in item.lower(): pkg = item.split(' : ')[1] ret['DismPackage'] = pkg cmd = ['dism', '/Online', '/Remove-Package', '/PackageName:{0}'.format(pkg), '/Quiet', '/NoRestart'] self._run(cmd) except CommandExecutionError as exc: log.debug('Uninstall using DISM failed') log.debug('Command: %s', ' '.join(cmd)) log.debug('Error: %s', exc) raise CommandExecutionError( 'Uninstall using DISM failed: {0}'.format(exc)) # DISM Uninstall Completed Successfully log.debug('Uninstall Completed using DISM') # Populate the return dictionary ret['Success'] = True ret['Message'] = 'Uninstalled using DISM' ret['NeedsReboot'] = needs_reboot() log.debug('NeedsReboot: %s', ret['NeedsReboot']) # Refresh the Updates Table self.refresh() reboot = {0: 'Never Reboot', 1: 'Always Reboot', 2: 'Poss Reboot'} # Check the status of each update for update in self._updates: uid = update.Identity.UpdateID for item in uninstall_list: if item.Identity.UpdateID == uid: if not update.IsInstalled: ret['Updates'][uid]['Result'] = \ 'Uninstallation Succeeded' else: ret['Updates'][uid]['Result'] = \ 'Uninstallation Failed' ret['Updates'][uid]['RebootBehavior'] = \ reboot[update.InstallationBehavior.RebootBehavior] return ret # Found a differenct exception, Raise error log.error('Uninstall Failed: %s', failure_code) raise CommandExecutionError(failure_code) # Lookup dictionary result_code = {0: 'Uninstallation Not Started', 1: 'Uninstallation In Progress', 2: 'Uninstallation Succeeded', 3: 'Uninstallation Succeeded With Errors', 4: 'Uninstallation Failed', 5: 'Uninstallation Aborted'} log.debug('Uninstall Complete') log.debug(result_code[result.ResultCode]) ret['Message'] = result_code[result.ResultCode] if result.ResultCode in [2, 3]: ret['Success'] = True ret['NeedsReboot'] = result.RebootRequired log.debug('NeedsReboot: %s', result.RebootRequired) else: log.debug('Uninstall Failed') ret['Success'] = False reboot = {0: 'Never Reboot', 1: 'Always Reboot', 2: 'Poss Reboot'} for i in range(uninstall_list.Count): uid = uninstall_list.Item(i).Identity.UpdateID ret['Updates'][uid]['Result'] = \ result_code[result.GetUpdateResult(i).ResultCode] ret['Updates'][uid]['RebootBehavior'] = reboot[ uninstall_list.Item(i).InstallationBehavior.RebootBehavior] return ret
[ "def", "uninstall", "(", "self", ",", "updates", ")", ":", "# This doesn't work with the WUA API since Windows 10. It always returns", "# \"0x80240028 # Uninstall not allowed\". The full message is: \"The update", "# could not be uninstalled because the request did not originate from a", "# Wi...
Uninstall the updates passed in the updates collection. Load the updates collection using the ``search`` or ``available`` functions. .. note:: Starting with Windows 10 the Windows Update Agent is unable to uninstall updates. An ``Uninstall Not Allowed`` error is returned. If this error is encountered this function will instead attempt to use ``dism.exe`` to perform the uninstallation. ``dism.exe`` may fail to to find the KB number for the package. In that case, removal will fail. Args: updates (Updates): An instance of the Updates class containing a the updates to be uninstalled. Returns: dict: A dictionary containing the results of the uninstallation Code Example: .. code-block:: python import salt.utils.win_update wua = salt.utils.win_update.WindowsUpdateAgent() # uninstall KB3195454 updates = wua.search('KB3195454') results = wua.uninstall(updates)
[ "Uninstall", "the", "updates", "passed", "in", "the", "updates", "collection", ".", "Load", "the", "updates", "collection", "using", "the", "search", "or", "available", "functions", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_update.py#L775-L967
train
saltstack/salt
salt/utils/win_update.py
WindowsUpdateAgent._run
def _run(self, cmd): ''' Internal function for running commands. Used by the uninstall function. Args: cmd (str, list): The command to run Returns: str: The stdout of the command ''' if isinstance(cmd, six.string_types): cmd = salt.utils.args.shlex_split(cmd) try: log.debug(cmd) p = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return p.communicate() except (OSError, IOError) as exc: log.debug('Command Failed: %s', ' '.join(cmd)) log.debug('Error: %s', exc) raise CommandExecutionError(exc)
python
def _run(self, cmd): ''' Internal function for running commands. Used by the uninstall function. Args: cmd (str, list): The command to run Returns: str: The stdout of the command ''' if isinstance(cmd, six.string_types): cmd = salt.utils.args.shlex_split(cmd) try: log.debug(cmd) p = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return p.communicate() except (OSError, IOError) as exc: log.debug('Command Failed: %s', ' '.join(cmd)) log.debug('Error: %s', exc) raise CommandExecutionError(exc)
[ "def", "_run", "(", "self", ",", "cmd", ")", ":", "if", "isinstance", "(", "cmd", ",", "six", ".", "string_types", ")", ":", "cmd", "=", "salt", ".", "utils", ".", "args", ".", "shlex_split", "(", "cmd", ")", "try", ":", "log", ".", "debug", "(",...
Internal function for running commands. Used by the uninstall function. Args: cmd (str, list): The command to run Returns: str: The stdout of the command
[ "Internal", "function", "for", "running", "commands", ".", "Used", "by", "the", "uninstall", "function", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_update.py#L969-L995
train
saltstack/salt
salt/renderers/yaml.py
render
def render(yaml_data, saltenv='base', sls='', argline='', **kws): ''' Accepts YAML as a string or as a file object and runs it through the YAML parser. :rtype: A Python data structure ''' if not isinstance(yaml_data, string_types): yaml_data = yaml_data.read() with warnings.catch_warnings(record=True) as warn_list: try: data = load(yaml_data, Loader=get_yaml_loader(argline)) except ScannerError as exc: err_type = _ERROR_MAP.get(exc.problem, exc.problem) line_num = exc.problem_mark.line + 1 raise SaltRenderError(err_type, line_num, exc.problem_mark.buffer) except (ParserError, ConstructorError) as exc: raise SaltRenderError(exc) if warn_list: for item in warn_list: log.warning( '%s found in %s saltenv=%s', item.message, salt.utils.url.create(sls), saltenv ) if not data: data = {} log.debug('Results of YAML rendering: \n%s', data) def _validate_data(data): ''' PyYAML will for some reason allow improper YAML to be formed into an unhashable dict (that is, one with a dict as a key). This function will recursively go through and check the keys to make sure they're not dicts. ''' if isinstance(data, dict): for key, value in six.iteritems(data): if isinstance(key, dict): raise SaltRenderError( 'Invalid YAML, possible double curly-brace') _validate_data(value) elif isinstance(data, list): for item in data: _validate_data(item) _validate_data(data) return data
python
def render(yaml_data, saltenv='base', sls='', argline='', **kws): ''' Accepts YAML as a string or as a file object and runs it through the YAML parser. :rtype: A Python data structure ''' if not isinstance(yaml_data, string_types): yaml_data = yaml_data.read() with warnings.catch_warnings(record=True) as warn_list: try: data = load(yaml_data, Loader=get_yaml_loader(argline)) except ScannerError as exc: err_type = _ERROR_MAP.get(exc.problem, exc.problem) line_num = exc.problem_mark.line + 1 raise SaltRenderError(err_type, line_num, exc.problem_mark.buffer) except (ParserError, ConstructorError) as exc: raise SaltRenderError(exc) if warn_list: for item in warn_list: log.warning( '%s found in %s saltenv=%s', item.message, salt.utils.url.create(sls), saltenv ) if not data: data = {} log.debug('Results of YAML rendering: \n%s', data) def _validate_data(data): ''' PyYAML will for some reason allow improper YAML to be formed into an unhashable dict (that is, one with a dict as a key). This function will recursively go through and check the keys to make sure they're not dicts. ''' if isinstance(data, dict): for key, value in six.iteritems(data): if isinstance(key, dict): raise SaltRenderError( 'Invalid YAML, possible double curly-brace') _validate_data(value) elif isinstance(data, list): for item in data: _validate_data(item) _validate_data(data) return data
[ "def", "render", "(", "yaml_data", ",", "saltenv", "=", "'base'", ",", "sls", "=", "''", ",", "argline", "=", "''", ",", "*", "*", "kws", ")", ":", "if", "not", "isinstance", "(", "yaml_data", ",", "string_types", ")", ":", "yaml_data", "=", "yaml_da...
Accepts YAML as a string or as a file object and runs it through the YAML parser. :rtype: A Python data structure
[ "Accepts", "YAML", "as", "a", "string", "or", "as", "a", "file", "object", "and", "runs", "it", "through", "the", "YAML", "parser", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/yaml.py#L42-L88
train
saltstack/salt
salt/modules/macdefaults.py
write
def write(domain, key, value, type='string', user=None): ''' Write a default to the system CLI Example: .. code-block:: bash salt '*' macdefaults.write com.apple.CrashReporter DialogType Server salt '*' macdefaults.write NSGlobalDomain ApplePersistence True type=bool domain The name of the domain to write to key The key of the given domain to write to value The value to write to the given key type The type of value to be written, valid types are string, data, int[eger], float, bool[ean], date, array, array-add, dict, dict-add user The user to write the defaults to ''' if type == 'bool' or type == 'boolean': if value is True: value = 'TRUE' elif value is False: value = 'FALSE' cmd = 'defaults write "{0}" "{1}" -{2} "{3}"'.format(domain, key, type, value) return __salt__['cmd.run_all'](cmd, runas=user)
python
def write(domain, key, value, type='string', user=None): ''' Write a default to the system CLI Example: .. code-block:: bash salt '*' macdefaults.write com.apple.CrashReporter DialogType Server salt '*' macdefaults.write NSGlobalDomain ApplePersistence True type=bool domain The name of the domain to write to key The key of the given domain to write to value The value to write to the given key type The type of value to be written, valid types are string, data, int[eger], float, bool[ean], date, array, array-add, dict, dict-add user The user to write the defaults to ''' if type == 'bool' or type == 'boolean': if value is True: value = 'TRUE' elif value is False: value = 'FALSE' cmd = 'defaults write "{0}" "{1}" -{2} "{3}"'.format(domain, key, type, value) return __salt__['cmd.run_all'](cmd, runas=user)
[ "def", "write", "(", "domain", ",", "key", ",", "value", ",", "type", "=", "'string'", ",", "user", "=", "None", ")", ":", "if", "type", "==", "'bool'", "or", "type", "==", "'boolean'", ":", "if", "value", "is", "True", ":", "value", "=", "'TRUE'",...
Write a default to the system CLI Example: .. code-block:: bash salt '*' macdefaults.write com.apple.CrashReporter DialogType Server salt '*' macdefaults.write NSGlobalDomain ApplePersistence True type=bool domain The name of the domain to write to key The key of the given domain to write to value The value to write to the given key type The type of value to be written, valid types are string, data, int[eger], float, bool[ean], date, array, array-add, dict, dict-add user The user to write the defaults to
[ "Write", "a", "default", "to", "the", "system" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/macdefaults.py#L27-L64
train
saltstack/salt
salt/modules/macdefaults.py
read
def read(domain, key, user=None): ''' Write a default to the system CLI Example: .. code-block:: bash salt '*' macdefaults.read com.apple.CrashReporter DialogType salt '*' macdefaults.read NSGlobalDomain ApplePersistence domain The name of the domain to read from key The key of the given domain to read from user The user to write the defaults to ''' cmd = 'defaults read "{0}" "{1}"'.format(domain, key) return __salt__['cmd.run'](cmd, runas=user)
python
def read(domain, key, user=None): ''' Write a default to the system CLI Example: .. code-block:: bash salt '*' macdefaults.read com.apple.CrashReporter DialogType salt '*' macdefaults.read NSGlobalDomain ApplePersistence domain The name of the domain to read from key The key of the given domain to read from user The user to write the defaults to ''' cmd = 'defaults read "{0}" "{1}"'.format(domain, key) return __salt__['cmd.run'](cmd, runas=user)
[ "def", "read", "(", "domain", ",", "key", ",", "user", "=", "None", ")", ":", "cmd", "=", "'defaults read \"{0}\" \"{1}\"'", ".", "format", "(", "domain", ",", "key", ")", "return", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ",", "runas", "=", "use...
Write a default to the system CLI Example: .. code-block:: bash salt '*' macdefaults.read com.apple.CrashReporter DialogType salt '*' macdefaults.read NSGlobalDomain ApplePersistence domain The name of the domain to read from key The key of the given domain to read from user The user to write the defaults to
[ "Write", "a", "default", "to", "the", "system" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/macdefaults.py#L67-L90
train
saltstack/salt
salt/modules/macdefaults.py
delete
def delete(domain, key, user=None): ''' Delete a default from the system CLI Example: .. code-block:: bash salt '*' macdefaults.delete com.apple.CrashReporter DialogType salt '*' macdefaults.delete NSGlobalDomain ApplePersistence domain The name of the domain to delete from key The key of the given domain to delete user The user to delete the defaults with ''' cmd = 'defaults delete "{0}" "{1}"'.format(domain, key) return __salt__['cmd.run_all'](cmd, runas=user, output_loglevel='debug')
python
def delete(domain, key, user=None): ''' Delete a default from the system CLI Example: .. code-block:: bash salt '*' macdefaults.delete com.apple.CrashReporter DialogType salt '*' macdefaults.delete NSGlobalDomain ApplePersistence domain The name of the domain to delete from key The key of the given domain to delete user The user to delete the defaults with ''' cmd = 'defaults delete "{0}" "{1}"'.format(domain, key) return __salt__['cmd.run_all'](cmd, runas=user, output_loglevel='debug')
[ "def", "delete", "(", "domain", ",", "key", ",", "user", "=", "None", ")", ":", "cmd", "=", "'defaults delete \"{0}\" \"{1}\"'", ".", "format", "(", "domain", ",", "key", ")", "return", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "runas", "="...
Delete a default from the system CLI Example: .. code-block:: bash salt '*' macdefaults.delete com.apple.CrashReporter DialogType salt '*' macdefaults.delete NSGlobalDomain ApplePersistence domain The name of the domain to delete from key The key of the given domain to delete user The user to delete the defaults with
[ "Delete", "a", "default", "from", "the", "system" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/macdefaults.py#L93-L116
train
saltstack/salt
salt/states/win_system.py
computer_desc
def computer_desc(name): ''' Manage the computer's description field name The desired computer description ''' # Just in case someone decides to enter a numeric description name = six.text_type(name) ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Computer description already set to \'{0}\''.format(name)} before_desc = __salt__['system.get_computer_desc']() if before_desc == name: return ret if __opts__['test']: ret['result'] = None ret['comment'] = ('Computer description will be changed to \'{0}\'' .format(name)) return ret result = __salt__['system.set_computer_desc'](name) if result['Computer Description'] == name: ret['comment'] = ('Computer description successfully changed to \'{0}\'' .format(name)) ret['changes'] = {'old': before_desc, 'new': name} else: ret['result'] = False ret['comment'] = ('Unable to set computer description to ' '\'{0}\''.format(name)) return ret
python
def computer_desc(name): ''' Manage the computer's description field name The desired computer description ''' # Just in case someone decides to enter a numeric description name = six.text_type(name) ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Computer description already set to \'{0}\''.format(name)} before_desc = __salt__['system.get_computer_desc']() if before_desc == name: return ret if __opts__['test']: ret['result'] = None ret['comment'] = ('Computer description will be changed to \'{0}\'' .format(name)) return ret result = __salt__['system.set_computer_desc'](name) if result['Computer Description'] == name: ret['comment'] = ('Computer description successfully changed to \'{0}\'' .format(name)) ret['changes'] = {'old': before_desc, 'new': name} else: ret['result'] = False ret['comment'] = ('Unable to set computer description to ' '\'{0}\''.format(name)) return ret
[ "def", "computer_desc", "(", "name", ")", ":", "# Just in case someone decides to enter a numeric description", "name", "=", "six", ".", "text_type", "(", "name", ")", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":...
Manage the computer's description field name The desired computer description
[ "Manage", "the", "computer", "s", "description", "field" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_system.py#L47-L82
train
saltstack/salt
salt/states/win_system.py
computer_name
def computer_name(name): ''' Manage the computer's name name The desired computer name ''' # Just in case someone decides to enter a numeric description name = six.text_type(name) ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Computer name already set to \'{0}\''.format(name)} before_name = __salt__['system.get_computer_name']() pending_name = __salt__['system.get_pending_computer_name']() if before_name == name and pending_name is None: return ret elif pending_name == name.upper(): ret['comment'] = ('The current computer name is \'{0}\', but will be ' 'changed to \'{1}\' on the next reboot' .format(before_name, name)) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Computer name will be changed to \'{0}\''.format(name) return ret result = __salt__['system.set_computer_name'](name) if result is not False: after_name = result['Computer Name']['Current'] after_pending = result['Computer Name'].get('Pending') if ((after_pending is not None and after_pending == name) or (after_pending is None and after_name == name)): ret['comment'] = 'Computer name successfully set to \'{0}\''.format(name) if after_pending is not None: ret['comment'] += ' (reboot required for change to take effect)' ret['changes'] = {'old': before_name, 'new': name} else: ret['result'] = False ret['comment'] = 'Unable to set computer name to \'{0}\''.format(name) return ret
python
def computer_name(name): ''' Manage the computer's name name The desired computer name ''' # Just in case someone decides to enter a numeric description name = six.text_type(name) ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Computer name already set to \'{0}\''.format(name)} before_name = __salt__['system.get_computer_name']() pending_name = __salt__['system.get_pending_computer_name']() if before_name == name and pending_name is None: return ret elif pending_name == name.upper(): ret['comment'] = ('The current computer name is \'{0}\', but will be ' 'changed to \'{1}\' on the next reboot' .format(before_name, name)) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Computer name will be changed to \'{0}\''.format(name) return ret result = __salt__['system.set_computer_name'](name) if result is not False: after_name = result['Computer Name']['Current'] after_pending = result['Computer Name'].get('Pending') if ((after_pending is not None and after_pending == name) or (after_pending is None and after_name == name)): ret['comment'] = 'Computer name successfully set to \'{0}\''.format(name) if after_pending is not None: ret['comment'] += ' (reboot required for change to take effect)' ret['changes'] = {'old': before_name, 'new': name} else: ret['result'] = False ret['comment'] = 'Unable to set computer name to \'{0}\''.format(name) return ret
[ "def", "computer_name", "(", "name", ")", ":", "# Just in case someone decides to enter a numeric description", "name", "=", "six", ".", "text_type", "(", "name", ")", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":...
Manage the computer's name name The desired computer name
[ "Manage", "the", "computer", "s", "name" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_system.py#L88-L132
train
saltstack/salt
salt/states/win_system.py
hostname
def hostname(name): ''' .. versionadded:: 2016.3.0 Manage the hostname of the computer name The hostname to set ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': '' } current_hostname = __salt__['system.get_hostname']() if current_hostname.upper() == name.upper(): ret['comment'] = "Hostname is already set to '{0}'".format(name) return ret out = __salt__['system.set_hostname'](name) if out: ret['comment'] = "The current hostname is '{0}', " \ "but will be changed to '{1}' on the next reboot".format(current_hostname, name) ret['changes'] = {'hostname': name} else: ret['result'] = False ret['comment'] = 'Unable to set hostname' return ret
python
def hostname(name): ''' .. versionadded:: 2016.3.0 Manage the hostname of the computer name The hostname to set ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': '' } current_hostname = __salt__['system.get_hostname']() if current_hostname.upper() == name.upper(): ret['comment'] = "Hostname is already set to '{0}'".format(name) return ret out = __salt__['system.set_hostname'](name) if out: ret['comment'] = "The current hostname is '{0}', " \ "but will be changed to '{1}' on the next reboot".format(current_hostname, name) ret['changes'] = {'hostname': name} else: ret['result'] = False ret['comment'] = 'Unable to set hostname' return ret
[ "def", "hostname", "(", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "current_hostname", "=", "__salt__", "[", "'system.get_hostname'", "]", "...
.. versionadded:: 2016.3.0 Manage the hostname of the computer name The hostname to set
[ "..", "versionadded", "::", "2016", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_system.py#L135-L167
train