repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
saltstack/salt
salt/client/api.py
APIClient.verify_token
python
def verify_token(self, token): ''' If token is valid Then returns user name associated with token Else False. ''' try: result = self.resolver.get_token(token) except Exception as ex: raise EauthAuthenticationError( "Token validation failed with {0}.".format(repr(ex))) return result
If token is valid Then returns user name associated with token Else False.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L295-L306
null
class APIClient(object): ''' Provide a uniform method of accessing the various client interfaces in Salt in the form of low-data data structures. For example: ''' def __init__(self, opts=None, listen=True): if not opts: opts = salt.config.client_config( os.environ.get( 'SALT_MASTER_CONFIG', os.path.join(syspaths.CONFIG_DIR, 'master') ) ) self.opts = opts self.localClient = salt.client.get_local_client(self.opts['conf_file']) self.runnerClient = salt.runner.RunnerClient(self.opts) self.wheelClient = salt.wheel.Wheel(self.opts) self.resolver = salt.auth.Resolver(self.opts) self.event = salt.utils.event.get_event( 'master', self.opts['sock_dir'], self.opts['transport'], opts=self.opts, listen=listen) def run(self, cmd): ''' Execute the salt command given by cmd dict. cmd is a dictionary of the following form: { 'mode': 'modestring', 'fun' : 'modulefunctionstring', 'kwarg': functionkeywordargdictionary, 'tgt' : 'targetpatternstring', 'tgt_type' : 'targetpatterntype', 'ret' : 'returner namestring', 'timeout': 'functiontimeout', 'arg' : 'functionpositionalarg sequence', 'token': 'salttokenstring', 'username': 'usernamestring', 'password': 'passwordstring', 'eauth': 'eauthtypestring', } Implied by the fun is which client is used to run the command, that is, either the master local minion client, the master runner client, or the master wheel client. The cmd dict items are as follows: mode: either 'sync' or 'asynchronous'. Defaults to 'asynchronous' if missing fun: required. If the function is to be run on the master using either a wheel or runner client then the fun: includes either 'wheel.' or 'runner.' as a prefix and has three parts separated by '.'. Otherwise the fun: specifies a module to be run on a minion via the local minion client. Example: fun of 'wheel.config.values' run with master wheel client fun of 'runner.manage.status' run with master runner client fun of 'test.ping' run with local minion client fun of 'wheel.foobar' run with with local minion client not wheel kwarg: A dictionary of keyword function parameters to be passed to the eventual salt function specified by fun: tgt: Pattern string specifying the targeted minions when the implied client is local tgt_type: Optional target pattern type string when client is local minion. Defaults to 'glob' if missing ret: Optional name string of returner when local minion client. arg: Optional positional argument string when local minion client token: the salt token. Either token: is required or the set of username:, password: , and eauth: username: the salt username. Required if token is missing. password: the user's password. Required if token is missing. eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing ''' cmd = dict(cmd) # make copy client = 'minion' # default to local minion client mode = cmd.get('mode', 'async') # check for wheel or runner prefix to fun name to use wheel or runner client funparts = cmd.get('fun', '').split('.') if len(funparts) > 2 and funparts[0] in ['wheel', 'runner']: # master client = funparts[0] cmd['fun'] = '.'.join(funparts[1:]) # strip prefix if not ('token' in cmd or ('eauth' in cmd and 'password' in cmd and 'username' in cmd)): raise EauthAuthenticationError('No authentication credentials given') executor = getattr(self, '{0}_{1}'.format(client, mode)) result = executor(**cmd) return result def minion_async(self, **kwargs): ''' Wrap LocalClient for running :ref:`execution modules <all-salt.modules>` and immediately return the job ID. The results of the job can then be retrieved at a later time. .. seealso:: :ref:`python-api` ''' return self.localClient.run_job(**kwargs) def minion_sync(self, **kwargs): ''' Wrap LocalClient for running :ref:`execution modules <all-salt.modules>` .. seealso:: :ref:`python-api` ''' return self.localClient.cmd(**kwargs) def runner_async(self, **kwargs): ''' Wrap RunnerClient for executing :ref:`runner modules <all-salt.runners>` Expects that one of the kwargs is key 'fun' whose value is the namestring of the function to call ''' return self.runnerClient.master_call(**kwargs) runner_sync = runner_async # always runner asynchronous, so works in either mode def wheel_sync(self, **kwargs): ''' Wrap Wheel to enable executing :ref:`wheel modules <all-salt.wheel>` Expects that one of the kwargs is key 'fun' whose value is the namestring of the function to call ''' return self.wheelClient.master_call(**kwargs) wheel_async = wheel_sync # always wheel_sync, so it works either mode def signature(self, cmd): ''' Convenience function that returns dict of function signature(s) specified by cmd. cmd is dict of the form: { 'module' : 'modulestring', 'tgt' : 'targetpatternstring', 'tgt_type' : 'targetpatterntype', 'token': 'salttokenstring', 'username': 'usernamestring', 'password': 'passwordstring', 'eauth': 'eauthtypestring', } The cmd dict items are as follows: module: required. This is either a module or module function name for the specified client. tgt: Optional pattern string specifying the targeted minions when client is 'minion' tgt_type: Optional target pattern type string when client is 'minion'. Example: 'glob' defaults to 'glob' if missing token: the salt token. Either token: is required or the set of username:, password: , and eauth: username: the salt username. Required if token is missing. password: the user's password. Required if token is missing. eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing Adds client per the command. ''' cmd['client'] = 'minion' if len(cmd['module'].split('.')) > 2 and cmd['module'].split('.')[0] in ['runner', 'wheel']: cmd['client'] = 'master' return self._signature(cmd) def _signature(self, cmd): ''' Expects everything that signature does and also a client type string. client can either be master or minion. ''' result = {} client = cmd.get('client', 'minion') if client == 'minion': cmd['fun'] = 'sys.argspec' cmd['kwarg'] = dict(module=cmd['module']) result = self.run(cmd) elif client == 'master': parts = cmd['module'].split('.') client = parts[0] module = '.'.join(parts[1:]) # strip prefix if client == 'wheel': functions = self.wheelClient.functions elif client == 'runner': functions = self.runnerClient.functions result = {'master': salt.utils.args.argspec_report(functions, module)} return result def create_token(self, creds): ''' Create token with creds. Token authorizes salt access if successful authentication with the credentials in creds. creds format is as follows: { 'username': 'namestring', 'password': 'passwordstring', 'eauth': 'eauthtypestring', } examples of valid eauth type strings: 'pam' or 'ldap' Returns dictionary of token information with the following format: { 'token': 'tokenstring', 'start': starttimeinfractionalseconds, 'expire': expiretimeinfractionalseconds, 'name': 'usernamestring', 'user': 'usernamestring', 'username': 'usernamestring', 'eauth': 'eauthtypestring', 'perms: permslistofstrings, } The perms list provides those parts of salt for which the user is authorised to execute. example perms list: [ "grains.*", "status.*", "sys.*", "test.*" ] ''' try: tokenage = self.resolver.mk_token(creds) except Exception as ex: raise EauthAuthenticationError( "Authentication failed with {0}.".format(repr(ex))) if 'token' not in tokenage: raise EauthAuthenticationError("Authentication failed with provided credentials.") # Grab eauth config for the current backend for the current user tokenage_eauth = self.opts['external_auth'][tokenage['eauth']] if tokenage['name'] in tokenage_eauth: tokenage['perms'] = tokenage_eauth[tokenage['name']] else: tokenage['perms'] = tokenage_eauth['*'] tokenage['user'] = tokenage['name'] tokenage['username'] = tokenage['name'] return tokenage def get_event(self, wait=0.25, tag='', full=False): ''' Get a single salt event. If no events are available, then block for up to ``wait`` seconds. Return the event if it matches the tag (or ``tag`` is empty) Otherwise return None If wait is 0 then block forever or until next event becomes available. ''' return self.event.get_event(wait=wait, tag=tag, full=full, auto_reconnect=True) def fire_event(self, data, tag): ''' fires event with data and tag This only works if api is running with same user permissions as master Need to convert this to a master call with appropriate authentication ''' return self.event.fire_event(data, salt.utils.event.tagify(tag, 'wui'))
saltstack/salt
salt/client/api.py
APIClient.get_event
python
def get_event(self, wait=0.25, tag='', full=False): ''' Get a single salt event. If no events are available, then block for up to ``wait`` seconds. Return the event if it matches the tag (or ``tag`` is empty) Otherwise return None If wait is 0 then block forever or until next event becomes available. ''' return self.event.get_event(wait=wait, tag=tag, full=full, auto_reconnect=True)
Get a single salt event. If no events are available, then block for up to ``wait`` seconds. Return the event if it matches the tag (or ``tag`` is empty) Otherwise return None If wait is 0 then block forever or until next event becomes available.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L308-L317
null
class APIClient(object): ''' Provide a uniform method of accessing the various client interfaces in Salt in the form of low-data data structures. For example: ''' def __init__(self, opts=None, listen=True): if not opts: opts = salt.config.client_config( os.environ.get( 'SALT_MASTER_CONFIG', os.path.join(syspaths.CONFIG_DIR, 'master') ) ) self.opts = opts self.localClient = salt.client.get_local_client(self.opts['conf_file']) self.runnerClient = salt.runner.RunnerClient(self.opts) self.wheelClient = salt.wheel.Wheel(self.opts) self.resolver = salt.auth.Resolver(self.opts) self.event = salt.utils.event.get_event( 'master', self.opts['sock_dir'], self.opts['transport'], opts=self.opts, listen=listen) def run(self, cmd): ''' Execute the salt command given by cmd dict. cmd is a dictionary of the following form: { 'mode': 'modestring', 'fun' : 'modulefunctionstring', 'kwarg': functionkeywordargdictionary, 'tgt' : 'targetpatternstring', 'tgt_type' : 'targetpatterntype', 'ret' : 'returner namestring', 'timeout': 'functiontimeout', 'arg' : 'functionpositionalarg sequence', 'token': 'salttokenstring', 'username': 'usernamestring', 'password': 'passwordstring', 'eauth': 'eauthtypestring', } Implied by the fun is which client is used to run the command, that is, either the master local minion client, the master runner client, or the master wheel client. The cmd dict items are as follows: mode: either 'sync' or 'asynchronous'. Defaults to 'asynchronous' if missing fun: required. If the function is to be run on the master using either a wheel or runner client then the fun: includes either 'wheel.' or 'runner.' as a prefix and has three parts separated by '.'. Otherwise the fun: specifies a module to be run on a minion via the local minion client. Example: fun of 'wheel.config.values' run with master wheel client fun of 'runner.manage.status' run with master runner client fun of 'test.ping' run with local minion client fun of 'wheel.foobar' run with with local minion client not wheel kwarg: A dictionary of keyword function parameters to be passed to the eventual salt function specified by fun: tgt: Pattern string specifying the targeted minions when the implied client is local tgt_type: Optional target pattern type string when client is local minion. Defaults to 'glob' if missing ret: Optional name string of returner when local minion client. arg: Optional positional argument string when local minion client token: the salt token. Either token: is required or the set of username:, password: , and eauth: username: the salt username. Required if token is missing. password: the user's password. Required if token is missing. eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing ''' cmd = dict(cmd) # make copy client = 'minion' # default to local minion client mode = cmd.get('mode', 'async') # check for wheel or runner prefix to fun name to use wheel or runner client funparts = cmd.get('fun', '').split('.') if len(funparts) > 2 and funparts[0] in ['wheel', 'runner']: # master client = funparts[0] cmd['fun'] = '.'.join(funparts[1:]) # strip prefix if not ('token' in cmd or ('eauth' in cmd and 'password' in cmd and 'username' in cmd)): raise EauthAuthenticationError('No authentication credentials given') executor = getattr(self, '{0}_{1}'.format(client, mode)) result = executor(**cmd) return result def minion_async(self, **kwargs): ''' Wrap LocalClient for running :ref:`execution modules <all-salt.modules>` and immediately return the job ID. The results of the job can then be retrieved at a later time. .. seealso:: :ref:`python-api` ''' return self.localClient.run_job(**kwargs) def minion_sync(self, **kwargs): ''' Wrap LocalClient for running :ref:`execution modules <all-salt.modules>` .. seealso:: :ref:`python-api` ''' return self.localClient.cmd(**kwargs) def runner_async(self, **kwargs): ''' Wrap RunnerClient for executing :ref:`runner modules <all-salt.runners>` Expects that one of the kwargs is key 'fun' whose value is the namestring of the function to call ''' return self.runnerClient.master_call(**kwargs) runner_sync = runner_async # always runner asynchronous, so works in either mode def wheel_sync(self, **kwargs): ''' Wrap Wheel to enable executing :ref:`wheel modules <all-salt.wheel>` Expects that one of the kwargs is key 'fun' whose value is the namestring of the function to call ''' return self.wheelClient.master_call(**kwargs) wheel_async = wheel_sync # always wheel_sync, so it works either mode def signature(self, cmd): ''' Convenience function that returns dict of function signature(s) specified by cmd. cmd is dict of the form: { 'module' : 'modulestring', 'tgt' : 'targetpatternstring', 'tgt_type' : 'targetpatterntype', 'token': 'salttokenstring', 'username': 'usernamestring', 'password': 'passwordstring', 'eauth': 'eauthtypestring', } The cmd dict items are as follows: module: required. This is either a module or module function name for the specified client. tgt: Optional pattern string specifying the targeted minions when client is 'minion' tgt_type: Optional target pattern type string when client is 'minion'. Example: 'glob' defaults to 'glob' if missing token: the salt token. Either token: is required or the set of username:, password: , and eauth: username: the salt username. Required if token is missing. password: the user's password. Required if token is missing. eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing Adds client per the command. ''' cmd['client'] = 'minion' if len(cmd['module'].split('.')) > 2 and cmd['module'].split('.')[0] in ['runner', 'wheel']: cmd['client'] = 'master' return self._signature(cmd) def _signature(self, cmd): ''' Expects everything that signature does and also a client type string. client can either be master or minion. ''' result = {} client = cmd.get('client', 'minion') if client == 'minion': cmd['fun'] = 'sys.argspec' cmd['kwarg'] = dict(module=cmd['module']) result = self.run(cmd) elif client == 'master': parts = cmd['module'].split('.') client = parts[0] module = '.'.join(parts[1:]) # strip prefix if client == 'wheel': functions = self.wheelClient.functions elif client == 'runner': functions = self.runnerClient.functions result = {'master': salt.utils.args.argspec_report(functions, module)} return result def create_token(self, creds): ''' Create token with creds. Token authorizes salt access if successful authentication with the credentials in creds. creds format is as follows: { 'username': 'namestring', 'password': 'passwordstring', 'eauth': 'eauthtypestring', } examples of valid eauth type strings: 'pam' or 'ldap' Returns dictionary of token information with the following format: { 'token': 'tokenstring', 'start': starttimeinfractionalseconds, 'expire': expiretimeinfractionalseconds, 'name': 'usernamestring', 'user': 'usernamestring', 'username': 'usernamestring', 'eauth': 'eauthtypestring', 'perms: permslistofstrings, } The perms list provides those parts of salt for which the user is authorised to execute. example perms list: [ "grains.*", "status.*", "sys.*", "test.*" ] ''' try: tokenage = self.resolver.mk_token(creds) except Exception as ex: raise EauthAuthenticationError( "Authentication failed with {0}.".format(repr(ex))) if 'token' not in tokenage: raise EauthAuthenticationError("Authentication failed with provided credentials.") # Grab eauth config for the current backend for the current user tokenage_eauth = self.opts['external_auth'][tokenage['eauth']] if tokenage['name'] in tokenage_eauth: tokenage['perms'] = tokenage_eauth[tokenage['name']] else: tokenage['perms'] = tokenage_eauth['*'] tokenage['user'] = tokenage['name'] tokenage['username'] = tokenage['name'] return tokenage def verify_token(self, token): ''' If token is valid Then returns user name associated with token Else False. ''' try: result = self.resolver.get_token(token) except Exception as ex: raise EauthAuthenticationError( "Token validation failed with {0}.".format(repr(ex))) return result def fire_event(self, data, tag): ''' fires event with data and tag This only works if api is running with same user permissions as master Need to convert this to a master call with appropriate authentication ''' return self.event.fire_event(data, salt.utils.event.tagify(tag, 'wui'))
saltstack/salt
salt/client/api.py
APIClient.fire_event
python
def fire_event(self, data, tag): ''' fires event with data and tag This only works if api is running with same user permissions as master Need to convert this to a master call with appropriate authentication ''' return self.event.fire_event(data, salt.utils.event.tagify(tag, 'wui'))
fires event with data and tag This only works if api is running with same user permissions as master Need to convert this to a master call with appropriate authentication
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L319-L326
[ "def tagify(suffix='', prefix='', base=SALT):\n '''\n convenience function to build a namespaced event tag string\n from joining with the TABPART character the base, prefix and suffix\n\n If string prefix is a valid key in TAGS Then use the value of key prefix\n Else use prefix string\n\n If suffix is a list Then join all string elements of suffix individually\n Else use string suffix\n\n '''\n parts = [base, TAGS.get(prefix, prefix)]\n if hasattr(suffix, 'append'): # list so extend parts\n parts.extend(suffix)\n else: # string so append\n parts.append(suffix)\n\n for index, _ in enumerate(parts):\n try:\n parts[index] = salt.utils.stringutils.to_str(parts[index])\n except TypeError:\n parts[index] = str(parts[index])\n return TAGPARTER.join([part for part in parts if part])\n" ]
class APIClient(object): ''' Provide a uniform method of accessing the various client interfaces in Salt in the form of low-data data structures. For example: ''' def __init__(self, opts=None, listen=True): if not opts: opts = salt.config.client_config( os.environ.get( 'SALT_MASTER_CONFIG', os.path.join(syspaths.CONFIG_DIR, 'master') ) ) self.opts = opts self.localClient = salt.client.get_local_client(self.opts['conf_file']) self.runnerClient = salt.runner.RunnerClient(self.opts) self.wheelClient = salt.wheel.Wheel(self.opts) self.resolver = salt.auth.Resolver(self.opts) self.event = salt.utils.event.get_event( 'master', self.opts['sock_dir'], self.opts['transport'], opts=self.opts, listen=listen) def run(self, cmd): ''' Execute the salt command given by cmd dict. cmd is a dictionary of the following form: { 'mode': 'modestring', 'fun' : 'modulefunctionstring', 'kwarg': functionkeywordargdictionary, 'tgt' : 'targetpatternstring', 'tgt_type' : 'targetpatterntype', 'ret' : 'returner namestring', 'timeout': 'functiontimeout', 'arg' : 'functionpositionalarg sequence', 'token': 'salttokenstring', 'username': 'usernamestring', 'password': 'passwordstring', 'eauth': 'eauthtypestring', } Implied by the fun is which client is used to run the command, that is, either the master local minion client, the master runner client, or the master wheel client. The cmd dict items are as follows: mode: either 'sync' or 'asynchronous'. Defaults to 'asynchronous' if missing fun: required. If the function is to be run on the master using either a wheel or runner client then the fun: includes either 'wheel.' or 'runner.' as a prefix and has three parts separated by '.'. Otherwise the fun: specifies a module to be run on a minion via the local minion client. Example: fun of 'wheel.config.values' run with master wheel client fun of 'runner.manage.status' run with master runner client fun of 'test.ping' run with local minion client fun of 'wheel.foobar' run with with local minion client not wheel kwarg: A dictionary of keyword function parameters to be passed to the eventual salt function specified by fun: tgt: Pattern string specifying the targeted minions when the implied client is local tgt_type: Optional target pattern type string when client is local minion. Defaults to 'glob' if missing ret: Optional name string of returner when local minion client. arg: Optional positional argument string when local minion client token: the salt token. Either token: is required or the set of username:, password: , and eauth: username: the salt username. Required if token is missing. password: the user's password. Required if token is missing. eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing ''' cmd = dict(cmd) # make copy client = 'minion' # default to local minion client mode = cmd.get('mode', 'async') # check for wheel or runner prefix to fun name to use wheel or runner client funparts = cmd.get('fun', '').split('.') if len(funparts) > 2 and funparts[0] in ['wheel', 'runner']: # master client = funparts[0] cmd['fun'] = '.'.join(funparts[1:]) # strip prefix if not ('token' in cmd or ('eauth' in cmd and 'password' in cmd and 'username' in cmd)): raise EauthAuthenticationError('No authentication credentials given') executor = getattr(self, '{0}_{1}'.format(client, mode)) result = executor(**cmd) return result def minion_async(self, **kwargs): ''' Wrap LocalClient for running :ref:`execution modules <all-salt.modules>` and immediately return the job ID. The results of the job can then be retrieved at a later time. .. seealso:: :ref:`python-api` ''' return self.localClient.run_job(**kwargs) def minion_sync(self, **kwargs): ''' Wrap LocalClient for running :ref:`execution modules <all-salt.modules>` .. seealso:: :ref:`python-api` ''' return self.localClient.cmd(**kwargs) def runner_async(self, **kwargs): ''' Wrap RunnerClient for executing :ref:`runner modules <all-salt.runners>` Expects that one of the kwargs is key 'fun' whose value is the namestring of the function to call ''' return self.runnerClient.master_call(**kwargs) runner_sync = runner_async # always runner asynchronous, so works in either mode def wheel_sync(self, **kwargs): ''' Wrap Wheel to enable executing :ref:`wheel modules <all-salt.wheel>` Expects that one of the kwargs is key 'fun' whose value is the namestring of the function to call ''' return self.wheelClient.master_call(**kwargs) wheel_async = wheel_sync # always wheel_sync, so it works either mode def signature(self, cmd): ''' Convenience function that returns dict of function signature(s) specified by cmd. cmd is dict of the form: { 'module' : 'modulestring', 'tgt' : 'targetpatternstring', 'tgt_type' : 'targetpatterntype', 'token': 'salttokenstring', 'username': 'usernamestring', 'password': 'passwordstring', 'eauth': 'eauthtypestring', } The cmd dict items are as follows: module: required. This is either a module or module function name for the specified client. tgt: Optional pattern string specifying the targeted minions when client is 'minion' tgt_type: Optional target pattern type string when client is 'minion'. Example: 'glob' defaults to 'glob' if missing token: the salt token. Either token: is required or the set of username:, password: , and eauth: username: the salt username. Required if token is missing. password: the user's password. Required if token is missing. eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing Adds client per the command. ''' cmd['client'] = 'minion' if len(cmd['module'].split('.')) > 2 and cmd['module'].split('.')[0] in ['runner', 'wheel']: cmd['client'] = 'master' return self._signature(cmd) def _signature(self, cmd): ''' Expects everything that signature does and also a client type string. client can either be master or minion. ''' result = {} client = cmd.get('client', 'minion') if client == 'minion': cmd['fun'] = 'sys.argspec' cmd['kwarg'] = dict(module=cmd['module']) result = self.run(cmd) elif client == 'master': parts = cmd['module'].split('.') client = parts[0] module = '.'.join(parts[1:]) # strip prefix if client == 'wheel': functions = self.wheelClient.functions elif client == 'runner': functions = self.runnerClient.functions result = {'master': salt.utils.args.argspec_report(functions, module)} return result def create_token(self, creds): ''' Create token with creds. Token authorizes salt access if successful authentication with the credentials in creds. creds format is as follows: { 'username': 'namestring', 'password': 'passwordstring', 'eauth': 'eauthtypestring', } examples of valid eauth type strings: 'pam' or 'ldap' Returns dictionary of token information with the following format: { 'token': 'tokenstring', 'start': starttimeinfractionalseconds, 'expire': expiretimeinfractionalseconds, 'name': 'usernamestring', 'user': 'usernamestring', 'username': 'usernamestring', 'eauth': 'eauthtypestring', 'perms: permslistofstrings, } The perms list provides those parts of salt for which the user is authorised to execute. example perms list: [ "grains.*", "status.*", "sys.*", "test.*" ] ''' try: tokenage = self.resolver.mk_token(creds) except Exception as ex: raise EauthAuthenticationError( "Authentication failed with {0}.".format(repr(ex))) if 'token' not in tokenage: raise EauthAuthenticationError("Authentication failed with provided credentials.") # Grab eauth config for the current backend for the current user tokenage_eauth = self.opts['external_auth'][tokenage['eauth']] if tokenage['name'] in tokenage_eauth: tokenage['perms'] = tokenage_eauth[tokenage['name']] else: tokenage['perms'] = tokenage_eauth['*'] tokenage['user'] = tokenage['name'] tokenage['username'] = tokenage['name'] return tokenage def verify_token(self, token): ''' If token is valid Then returns user name associated with token Else False. ''' try: result = self.resolver.get_token(token) except Exception as ex: raise EauthAuthenticationError( "Token validation failed with {0}.".format(repr(ex))) return result def get_event(self, wait=0.25, tag='', full=False): ''' Get a single salt event. If no events are available, then block for up to ``wait`` seconds. Return the event if it matches the tag (or ``tag`` is empty) Otherwise return None If wait is 0 then block forever or until next event becomes available. ''' return self.event.get_event(wait=wait, tag=tag, full=full, auto_reconnect=True)
saltstack/salt
salt/modules/win_timezone.py
get_zone
python
def get_zone(): ''' Get current timezone (i.e. America/Denver) Returns: str: Timezone in unix format Raises: CommandExecutionError: If timezone could not be gathered CLI Example: .. code-block:: bash salt '*' timezone.get_zone ''' cmd = ['tzutil', '/g'] res = __salt__['cmd.run_all'](cmd, python_shell=False) if res['retcode'] or not res['stdout']: raise CommandExecutionError('tzutil encountered an error getting ' 'timezone', info=res) return mapper.get_unix(res['stdout'].lower(), 'Unknown')
Get current timezone (i.e. America/Denver) Returns: str: Timezone in unix format Raises: CommandExecutionError: If timezone could not be gathered CLI Example: .. code-block:: bash salt '*' timezone.get_zone
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_timezone.py#L201-L223
[ "def get_unix(self, key, default=None):\n return self.win_to_unix.get(key.lower(), default)\n" ]
# -*- coding: utf-8 -*- ''' Module for managing timezone on Windows systems. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging from datetime import datetime # Import Salt libs from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import pytz HAS_PYTZ = True except ImportError: HAS_PYTZ = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'timezone' class TzMapper(object): def __init__(self, unix_to_win): self.win_to_unix = {k.lower(): v for k, v in unix_to_win.items()} self.unix_to_win = {v.lower(): k for k, v in unix_to_win.items()} def add(self, k, v): self.unix_to_win[k.lower()] = v self.win_to_unix[v.lower()] = k def remove(self, k): self.win_to_unix.pop(self.unix_to_win.pop(k.lower()).lower()) def get_win(self, key, default=None): return self.unix_to_win.get(key.lower(), default) def get_unix(self, key, default=None): return self.win_to_unix.get(key.lower(), default) def list_win(self): return sorted(self.unix_to_win.values()) def list_unix(self): return sorted(self.win_to_unix.values()) mapper = TzMapper({ 'AUS Central Standard Time': 'Australia/Darwin', 'AUS Eastern Standard Time': 'Australia/Sydney', 'Afghanistan Standard Time': 'Asia/Kabul', 'Alaskan Standard Time': 'America/Anchorage', 'Aleutian Standard Time': 'America/Adak', 'Altai Standard Time': 'Asia/Barnaul', 'Arab Standard Time': 'Asia/Riyadh', 'Arabian Standard Time': 'Asia/Dubai', 'Arabic Standard Time': 'Asia/Baghdad', 'Argentina Standard Time': 'America/Buenos_Aires', 'Astrakhan Standard Time': 'Europe/Astrakhan', 'Atlantic Standard Time': 'America/Halifax', 'Aus Central W. Standard Time': 'Australia/Eucla', 'Azerbaijan Standard Time': 'Asia/Baku', 'Azores Standard Time': 'Atlantic/Azores', 'Bahia Standard Time': 'America/Bahia', 'Bangladesh Standard Time': 'Asia/Dhaka', 'Belarus Standard Time': 'Europe/Minsk', 'Bougainville Standard Time': 'Pacific/Bougainville', 'Canada Central Standard Time': 'America/Regina', 'Cape Verde Standard Time': 'Atlantic/Cape_Verde', 'Caucasus Standard Time': 'Asia/Yerevan', 'Cen. Australia Standard Time': 'Australia/Adelaide', 'Central America Standard Time': 'America/Guatemala', 'Central Asia Standard Time': 'Asia/Almaty', 'Central Brazilian Standard Time': 'America/Cuiaba', 'Central Europe Standard Time': 'Europe/Budapest', 'Central European Standard Time': 'Europe/Warsaw', 'Central Pacific Standard Time': 'Pacific/Guadalcanal', 'Central Standard Time': 'America/Chicago', 'Central Standard Time (Mexico)': 'America/Mexico_City', 'Chatham Islands Standard Time': 'Pacific/Chatham', 'China Standard Time': 'Asia/Shanghai', 'Cuba Standard Time': 'America/Havana', 'Dateline Standard Time': 'Etc/GMT+12', 'E. Africa Standard Time': 'Africa/Nairobi', 'E. Australia Standard Time': 'Australia/Brisbane', 'E. Europe Standard Time': 'Europe/Chisinau', 'E. South America Standard Time': 'America/Sao_Paulo', 'Easter Island Standard Time': 'Pacific/Easter', 'Eastern Standard Time': 'America/New_York', 'Eastern Standard Time (Mexico)': 'America/Cancun', 'Egypt Standard Time': 'Africa/Cairo', 'Ekaterinburg Standard Time': 'Asia/Yekaterinburg', 'FLE Standard Time': 'Europe/Kiev', 'Fiji Standard Time': 'Pacific/Fiji', 'GMT Standard Time': 'Europe/London', 'GTB Standard Time': 'Europe/Bucharest', 'Georgian Standard Time': 'Asia/Tbilisi', 'Greenland Standard Time': 'America/Godthab', 'Greenwich Standard Time': 'Atlantic/Reykjavik', 'Haiti Standard Time': 'America/Port-au-Prince', 'Hawaiian Standard Time': 'Pacific/Honolulu', 'India Standard Time': 'Asia/Calcutta', 'Iran Standard Time': 'Asia/Tehran', 'Israel Standard Time': 'Asia/Jerusalem', 'Jordan Standard Time': 'Asia/Amman', 'Kaliningrad Standard Time': 'Europe/Kaliningrad', 'Korea Standard Time': 'Asia/Seoul', 'Libya Standard Time': 'Africa/Tripoli', 'Line Islands Standard Time': 'Pacific/Kiritimati', 'Lord Howe Standard Time': 'Australia/Lord_Howe', 'Magadan Standard Time': 'Asia/Magadan', 'Magallanes Standard Time': 'America/Punta_Arenas', 'Marquesas Standard Time': 'Pacific/Marquesas', 'Mauritius Standard Time': 'Indian/Mauritius', 'Middle East Standard Time': 'Asia/Beirut', 'Montevideo Standard Time': 'America/Montevideo', 'Morocco Standard Time': 'Africa/Casablanca', 'Mountain Standard Time': 'America/Denver', 'Mountain Standard Time (Mexico)': 'America/Chihuahua', 'Myanmar Standard Time': 'Asia/Rangoon', 'N. Central Asia Standard Time': 'Asia/Novosibirsk', 'Namibia Standard Time': 'Africa/Windhoek', 'Nepal Standard Time': 'Asia/Katmandu', 'New Zealand Standard Time': 'Pacific/Auckland', 'Newfoundland Standard Time': 'America/St_Johns', 'Norfolk Standard Time': 'Pacific/Norfolk', 'North Asia East Standard Time': 'Asia/Irkutsk', 'North Asia Standard Time': 'Asia/Krasnoyarsk', 'North Korea Standard Time': 'Asia/Pyongyang', 'Omsk Standard Time': 'Asia/Omsk', 'Pacific SA Standard Time': 'America/Santiago', 'Pacific Standard Time': 'America/Los_Angeles', 'Pacific Standard Time (Mexico)': 'America/Tijuana', 'Pakistan Standard Time': 'Asia/Karachi', 'Paraguay Standard Time': 'America/Asuncion', 'Romance Standard Time': 'Europe/Paris', 'Russia Time Zone 10': 'Asia/Srednekolymsk', 'Russia Time Zone 11': 'Asia/Kamchatka', 'Russia Time Zone 3': 'Europe/Samara', 'Russian Standard Time': 'Europe/Moscow', 'SA Eastern Standard Time': 'America/Cayenne', 'SA Pacific Standard Time': 'America/Bogota', 'SA Western Standard Time': 'America/La_Paz', 'SE Asia Standard Time': 'Asia/Bangkok', 'Saint Pierre Standard Time': 'America/Miquelon', 'Sakhalin Standard Time': 'Asia/Sakhalin', 'Samoa Standard Time': 'Pacific/Apia', 'Saratov Standard Time': 'Europe/Saratov', 'Singapore Standard Time': 'Asia/Singapore', 'South Africa Standard Time': 'Africa/Johannesburg', 'Sri Lanka Standard Time': 'Asia/Colombo', 'Syria Standard Time': 'Asia/Damascus', 'Taipei Standard Time': 'Asia/Taipei', 'Tasmania Standard Time': 'Australia/Hobart', 'Tocantins Standard Time': 'America/Araguaina', 'Tokyo Standard Time': 'Asia/Tokyo', 'Tomsk Standard Time': 'Asia/Tomsk', 'Tonga Standard Time': 'Pacific/Tongatapu', 'Transbaikal Standard Time': 'Asia/Chita', 'Turkey Standard Time': 'Europe/Istanbul', 'Turks And Caicos Standard Time': 'America/Grand_Turk', 'US Eastern Standard Time': 'America/Indianapolis', 'US Mountain Standard Time': 'America/Phoenix', 'UTC': 'Etc/GMT', 'UTC+12': 'Etc/GMT-12', 'UTC+13': 'Etc/GMT-13', 'UTC-02': 'Etc/GMT+2', 'UTC-08': 'Etc/GMT+8', 'UTC-09': 'Etc/GMT+9', 'UTC-11': 'Etc/GMT+11', 'Ulaanbaatar Standard Time': 'Asia/Ulaanbaatar', 'Venezuela Standard Time': 'America/Caracas', 'Vladivostok Standard Time': 'Asia/Vladivostok', 'W. Australia Standard Time': 'Australia/Perth', 'W. Central Africa Standard Time': 'Africa/Lagos', 'W. Europe Standard Time': 'Europe/Berlin', 'W. Mongolia Standard Time': 'Asia/Hovd', 'West Asia Standard Time': 'Asia/Tashkent', 'West Bank Standard Time': 'Asia/Hebron', 'West Pacific Standard Time': 'Pacific/Port_Moresby', 'Yakutsk Standard Time': 'Asia/Yakutsk'}) def __virtual__(): ''' Only load on windows ''' if not __utils__['platform.is_windows'](): return False, "Module win_timezone: Not on Windows client" if not HAS_PYTZ: return False, "Module win_timezone: pytz not found" if not __utils__['path.which']('tzutil'): return False, "Module win_timezone: tzutil not found" return __virtualname__ def get_offset(): ''' Get current numeric timezone offset from UTC (i.e. -0700) Returns: str: Offset from UTC CLI Example: .. code-block:: bash salt '*' timezone.get_offset ''' # http://craigglennie.com/programming/python/2013/07/21/working-with-timezones-using-Python-and-pytz-localize-vs-normalize/ tz_object = pytz.timezone(get_zone()) utc_time = pytz.utc.localize(datetime.utcnow()) loc_time = utc_time.astimezone(tz_object) norm_time = tz_object.normalize(loc_time) return norm_time.strftime('%z') def get_zonecode(): ''' Get current timezone (i.e. PST, MDT, etc) Returns: str: An abbreviated timezone code CLI Example: .. code-block:: bash salt '*' timezone.get_zonecode ''' tz_object = pytz.timezone(get_zone()) loc_time = tz_object.localize(datetime.utcnow()) return loc_time.tzname() def set_zone(timezone): ''' Sets the timezone using the tzutil. Args: timezone (str): A valid timezone Returns: bool: ``True`` if successful, otherwise ``False`` Raises: CommandExecutionError: If invalid timezone is passed CLI Example: .. code-block:: bash salt '*' timezone.set_zone 'America/Denver' ''' # if it's one of the key's just use it if timezone.lower() in mapper.win_to_unix: win_zone = timezone elif timezone.lower() in mapper.unix_to_win: # if it's one of the values, use the key win_zone = mapper.get_win(timezone) else: # Raise error because it's neither key nor value raise CommandExecutionError('Invalid timezone passed: {0}'.format(timezone)) # Set the value cmd = ['tzutil', '/s', win_zone] res = __salt__['cmd.run_all'](cmd, python_shell=False) if res['retcode']: raise CommandExecutionError('tzutil encountered an error setting ' 'timezone: {0}'.format(timezone), info=res) return zone_compare(timezone) def zone_compare(timezone): ''' Compares the given timezone with the machine timezone. Mostly useful for running state checks. Args: timezone (str): The timezone to compare. This can be in Windows or Unix format. Can be any of the values returned by the ``timezone.list`` function Returns: bool: ``True`` if they match, otherwise ``False`` Example: .. code-block:: bash salt '*' timezone.zone_compare 'America/Denver' ''' # if it's one of the key's just use it if timezone.lower() in mapper.win_to_unix: check_zone = timezone elif timezone.lower() in mapper.unix_to_win: # if it's one of the values, use the key check_zone = mapper.get_win(timezone) else: # Raise error because it's neither key nor value raise CommandExecutionError('Invalid timezone passed: {0}' ''.format(timezone)) return get_zone() == mapper.get_unix(check_zone, 'Unknown') def list(unix_style=True): ''' Return a list of Timezones that this module supports. These can be in either Unix or Windows format. .. versionadded:: 2018.3.3 Args: unix_style (bool): ``True`` returns Unix-style timezones. ``False`` returns Windows-style timezones. Default is ``True`` Returns: list: A list of supported timezones CLI Example: .. code-block:: bash # Unix-style timezones salt '*' timezone.list # Windows-style timezones salt '*' timezone.list unix_style=False ''' if unix_style: return mapper.list_unix() else: return mapper.list_win() def get_hwclock(): ''' Get current hardware clock setting (UTC or localtime) .. note:: The hardware clock is always local time on Windows so this will always return "localtime" CLI Example: .. code-block:: bash salt '*' timezone.get_hwclock ''' # The hardware clock is always localtime on Windows return 'localtime' def set_hwclock(clock): ''' Sets the hardware clock to be either UTC or localtime .. note:: The hardware clock is always local time on Windows so this will always return ``False`` CLI Example: .. code-block:: bash salt '*' timezone.set_hwclock UTC ''' # The hardware clock is always localtime on Windows return False
saltstack/salt
salt/modules/win_timezone.py
get_offset
python
def get_offset(): ''' Get current numeric timezone offset from UTC (i.e. -0700) Returns: str: Offset from UTC CLI Example: .. code-block:: bash salt '*' timezone.get_offset ''' # http://craigglennie.com/programming/python/2013/07/21/working-with-timezones-using-Python-and-pytz-localize-vs-normalize/ tz_object = pytz.timezone(get_zone()) utc_time = pytz.utc.localize(datetime.utcnow()) loc_time = utc_time.astimezone(tz_object) norm_time = tz_object.normalize(loc_time) return norm_time.strftime('%z')
Get current numeric timezone offset from UTC (i.e. -0700) Returns: str: Offset from UTC CLI Example: .. code-block:: bash salt '*' timezone.get_offset
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_timezone.py#L226-L244
[ "def get_zone():\n '''\n Get current timezone (i.e. America/Denver)\n\n Returns:\n str: Timezone in unix format\n\n Raises:\n CommandExecutionError: If timezone could not be gathered\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' timezone.get_zone\n '''\n cmd = ['tzutil', '/g']\n res = __salt__['cmd.run_all'](cmd, python_shell=False)\n if res['retcode'] or not res['stdout']:\n raise CommandExecutionError('tzutil encountered an error getting '\n 'timezone',\n info=res)\n return mapper.get_unix(res['stdout'].lower(), 'Unknown')\n" ]
# -*- coding: utf-8 -*- ''' Module for managing timezone on Windows systems. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging from datetime import datetime # Import Salt libs from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import pytz HAS_PYTZ = True except ImportError: HAS_PYTZ = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'timezone' class TzMapper(object): def __init__(self, unix_to_win): self.win_to_unix = {k.lower(): v for k, v in unix_to_win.items()} self.unix_to_win = {v.lower(): k for k, v in unix_to_win.items()} def add(self, k, v): self.unix_to_win[k.lower()] = v self.win_to_unix[v.lower()] = k def remove(self, k): self.win_to_unix.pop(self.unix_to_win.pop(k.lower()).lower()) def get_win(self, key, default=None): return self.unix_to_win.get(key.lower(), default) def get_unix(self, key, default=None): return self.win_to_unix.get(key.lower(), default) def list_win(self): return sorted(self.unix_to_win.values()) def list_unix(self): return sorted(self.win_to_unix.values()) mapper = TzMapper({ 'AUS Central Standard Time': 'Australia/Darwin', 'AUS Eastern Standard Time': 'Australia/Sydney', 'Afghanistan Standard Time': 'Asia/Kabul', 'Alaskan Standard Time': 'America/Anchorage', 'Aleutian Standard Time': 'America/Adak', 'Altai Standard Time': 'Asia/Barnaul', 'Arab Standard Time': 'Asia/Riyadh', 'Arabian Standard Time': 'Asia/Dubai', 'Arabic Standard Time': 'Asia/Baghdad', 'Argentina Standard Time': 'America/Buenos_Aires', 'Astrakhan Standard Time': 'Europe/Astrakhan', 'Atlantic Standard Time': 'America/Halifax', 'Aus Central W. Standard Time': 'Australia/Eucla', 'Azerbaijan Standard Time': 'Asia/Baku', 'Azores Standard Time': 'Atlantic/Azores', 'Bahia Standard Time': 'America/Bahia', 'Bangladesh Standard Time': 'Asia/Dhaka', 'Belarus Standard Time': 'Europe/Minsk', 'Bougainville Standard Time': 'Pacific/Bougainville', 'Canada Central Standard Time': 'America/Regina', 'Cape Verde Standard Time': 'Atlantic/Cape_Verde', 'Caucasus Standard Time': 'Asia/Yerevan', 'Cen. Australia Standard Time': 'Australia/Adelaide', 'Central America Standard Time': 'America/Guatemala', 'Central Asia Standard Time': 'Asia/Almaty', 'Central Brazilian Standard Time': 'America/Cuiaba', 'Central Europe Standard Time': 'Europe/Budapest', 'Central European Standard Time': 'Europe/Warsaw', 'Central Pacific Standard Time': 'Pacific/Guadalcanal', 'Central Standard Time': 'America/Chicago', 'Central Standard Time (Mexico)': 'America/Mexico_City', 'Chatham Islands Standard Time': 'Pacific/Chatham', 'China Standard Time': 'Asia/Shanghai', 'Cuba Standard Time': 'America/Havana', 'Dateline Standard Time': 'Etc/GMT+12', 'E. Africa Standard Time': 'Africa/Nairobi', 'E. Australia Standard Time': 'Australia/Brisbane', 'E. Europe Standard Time': 'Europe/Chisinau', 'E. South America Standard Time': 'America/Sao_Paulo', 'Easter Island Standard Time': 'Pacific/Easter', 'Eastern Standard Time': 'America/New_York', 'Eastern Standard Time (Mexico)': 'America/Cancun', 'Egypt Standard Time': 'Africa/Cairo', 'Ekaterinburg Standard Time': 'Asia/Yekaterinburg', 'FLE Standard Time': 'Europe/Kiev', 'Fiji Standard Time': 'Pacific/Fiji', 'GMT Standard Time': 'Europe/London', 'GTB Standard Time': 'Europe/Bucharest', 'Georgian Standard Time': 'Asia/Tbilisi', 'Greenland Standard Time': 'America/Godthab', 'Greenwich Standard Time': 'Atlantic/Reykjavik', 'Haiti Standard Time': 'America/Port-au-Prince', 'Hawaiian Standard Time': 'Pacific/Honolulu', 'India Standard Time': 'Asia/Calcutta', 'Iran Standard Time': 'Asia/Tehran', 'Israel Standard Time': 'Asia/Jerusalem', 'Jordan Standard Time': 'Asia/Amman', 'Kaliningrad Standard Time': 'Europe/Kaliningrad', 'Korea Standard Time': 'Asia/Seoul', 'Libya Standard Time': 'Africa/Tripoli', 'Line Islands Standard Time': 'Pacific/Kiritimati', 'Lord Howe Standard Time': 'Australia/Lord_Howe', 'Magadan Standard Time': 'Asia/Magadan', 'Magallanes Standard Time': 'America/Punta_Arenas', 'Marquesas Standard Time': 'Pacific/Marquesas', 'Mauritius Standard Time': 'Indian/Mauritius', 'Middle East Standard Time': 'Asia/Beirut', 'Montevideo Standard Time': 'America/Montevideo', 'Morocco Standard Time': 'Africa/Casablanca', 'Mountain Standard Time': 'America/Denver', 'Mountain Standard Time (Mexico)': 'America/Chihuahua', 'Myanmar Standard Time': 'Asia/Rangoon', 'N. Central Asia Standard Time': 'Asia/Novosibirsk', 'Namibia Standard Time': 'Africa/Windhoek', 'Nepal Standard Time': 'Asia/Katmandu', 'New Zealand Standard Time': 'Pacific/Auckland', 'Newfoundland Standard Time': 'America/St_Johns', 'Norfolk Standard Time': 'Pacific/Norfolk', 'North Asia East Standard Time': 'Asia/Irkutsk', 'North Asia Standard Time': 'Asia/Krasnoyarsk', 'North Korea Standard Time': 'Asia/Pyongyang', 'Omsk Standard Time': 'Asia/Omsk', 'Pacific SA Standard Time': 'America/Santiago', 'Pacific Standard Time': 'America/Los_Angeles', 'Pacific Standard Time (Mexico)': 'America/Tijuana', 'Pakistan Standard Time': 'Asia/Karachi', 'Paraguay Standard Time': 'America/Asuncion', 'Romance Standard Time': 'Europe/Paris', 'Russia Time Zone 10': 'Asia/Srednekolymsk', 'Russia Time Zone 11': 'Asia/Kamchatka', 'Russia Time Zone 3': 'Europe/Samara', 'Russian Standard Time': 'Europe/Moscow', 'SA Eastern Standard Time': 'America/Cayenne', 'SA Pacific Standard Time': 'America/Bogota', 'SA Western Standard Time': 'America/La_Paz', 'SE Asia Standard Time': 'Asia/Bangkok', 'Saint Pierre Standard Time': 'America/Miquelon', 'Sakhalin Standard Time': 'Asia/Sakhalin', 'Samoa Standard Time': 'Pacific/Apia', 'Saratov Standard Time': 'Europe/Saratov', 'Singapore Standard Time': 'Asia/Singapore', 'South Africa Standard Time': 'Africa/Johannesburg', 'Sri Lanka Standard Time': 'Asia/Colombo', 'Syria Standard Time': 'Asia/Damascus', 'Taipei Standard Time': 'Asia/Taipei', 'Tasmania Standard Time': 'Australia/Hobart', 'Tocantins Standard Time': 'America/Araguaina', 'Tokyo Standard Time': 'Asia/Tokyo', 'Tomsk Standard Time': 'Asia/Tomsk', 'Tonga Standard Time': 'Pacific/Tongatapu', 'Transbaikal Standard Time': 'Asia/Chita', 'Turkey Standard Time': 'Europe/Istanbul', 'Turks And Caicos Standard Time': 'America/Grand_Turk', 'US Eastern Standard Time': 'America/Indianapolis', 'US Mountain Standard Time': 'America/Phoenix', 'UTC': 'Etc/GMT', 'UTC+12': 'Etc/GMT-12', 'UTC+13': 'Etc/GMT-13', 'UTC-02': 'Etc/GMT+2', 'UTC-08': 'Etc/GMT+8', 'UTC-09': 'Etc/GMT+9', 'UTC-11': 'Etc/GMT+11', 'Ulaanbaatar Standard Time': 'Asia/Ulaanbaatar', 'Venezuela Standard Time': 'America/Caracas', 'Vladivostok Standard Time': 'Asia/Vladivostok', 'W. Australia Standard Time': 'Australia/Perth', 'W. Central Africa Standard Time': 'Africa/Lagos', 'W. Europe Standard Time': 'Europe/Berlin', 'W. Mongolia Standard Time': 'Asia/Hovd', 'West Asia Standard Time': 'Asia/Tashkent', 'West Bank Standard Time': 'Asia/Hebron', 'West Pacific Standard Time': 'Pacific/Port_Moresby', 'Yakutsk Standard Time': 'Asia/Yakutsk'}) def __virtual__(): ''' Only load on windows ''' if not __utils__['platform.is_windows'](): return False, "Module win_timezone: Not on Windows client" if not HAS_PYTZ: return False, "Module win_timezone: pytz not found" if not __utils__['path.which']('tzutil'): return False, "Module win_timezone: tzutil not found" return __virtualname__ def get_zone(): ''' Get current timezone (i.e. America/Denver) Returns: str: Timezone in unix format Raises: CommandExecutionError: If timezone could not be gathered CLI Example: .. code-block:: bash salt '*' timezone.get_zone ''' cmd = ['tzutil', '/g'] res = __salt__['cmd.run_all'](cmd, python_shell=False) if res['retcode'] or not res['stdout']: raise CommandExecutionError('tzutil encountered an error getting ' 'timezone', info=res) return mapper.get_unix(res['stdout'].lower(), 'Unknown') def get_zonecode(): ''' Get current timezone (i.e. PST, MDT, etc) Returns: str: An abbreviated timezone code CLI Example: .. code-block:: bash salt '*' timezone.get_zonecode ''' tz_object = pytz.timezone(get_zone()) loc_time = tz_object.localize(datetime.utcnow()) return loc_time.tzname() def set_zone(timezone): ''' Sets the timezone using the tzutil. Args: timezone (str): A valid timezone Returns: bool: ``True`` if successful, otherwise ``False`` Raises: CommandExecutionError: If invalid timezone is passed CLI Example: .. code-block:: bash salt '*' timezone.set_zone 'America/Denver' ''' # if it's one of the key's just use it if timezone.lower() in mapper.win_to_unix: win_zone = timezone elif timezone.lower() in mapper.unix_to_win: # if it's one of the values, use the key win_zone = mapper.get_win(timezone) else: # Raise error because it's neither key nor value raise CommandExecutionError('Invalid timezone passed: {0}'.format(timezone)) # Set the value cmd = ['tzutil', '/s', win_zone] res = __salt__['cmd.run_all'](cmd, python_shell=False) if res['retcode']: raise CommandExecutionError('tzutil encountered an error setting ' 'timezone: {0}'.format(timezone), info=res) return zone_compare(timezone) def zone_compare(timezone): ''' Compares the given timezone with the machine timezone. Mostly useful for running state checks. Args: timezone (str): The timezone to compare. This can be in Windows or Unix format. Can be any of the values returned by the ``timezone.list`` function Returns: bool: ``True`` if they match, otherwise ``False`` Example: .. code-block:: bash salt '*' timezone.zone_compare 'America/Denver' ''' # if it's one of the key's just use it if timezone.lower() in mapper.win_to_unix: check_zone = timezone elif timezone.lower() in mapper.unix_to_win: # if it's one of the values, use the key check_zone = mapper.get_win(timezone) else: # Raise error because it's neither key nor value raise CommandExecutionError('Invalid timezone passed: {0}' ''.format(timezone)) return get_zone() == mapper.get_unix(check_zone, 'Unknown') def list(unix_style=True): ''' Return a list of Timezones that this module supports. These can be in either Unix or Windows format. .. versionadded:: 2018.3.3 Args: unix_style (bool): ``True`` returns Unix-style timezones. ``False`` returns Windows-style timezones. Default is ``True`` Returns: list: A list of supported timezones CLI Example: .. code-block:: bash # Unix-style timezones salt '*' timezone.list # Windows-style timezones salt '*' timezone.list unix_style=False ''' if unix_style: return mapper.list_unix() else: return mapper.list_win() def get_hwclock(): ''' Get current hardware clock setting (UTC or localtime) .. note:: The hardware clock is always local time on Windows so this will always return "localtime" CLI Example: .. code-block:: bash salt '*' timezone.get_hwclock ''' # The hardware clock is always localtime on Windows return 'localtime' def set_hwclock(clock): ''' Sets the hardware clock to be either UTC or localtime .. note:: The hardware clock is always local time on Windows so this will always return ``False`` CLI Example: .. code-block:: bash salt '*' timezone.set_hwclock UTC ''' # The hardware clock is always localtime on Windows return False
saltstack/salt
salt/modules/win_timezone.py
get_zonecode
python
def get_zonecode(): ''' Get current timezone (i.e. PST, MDT, etc) Returns: str: An abbreviated timezone code CLI Example: .. code-block:: bash salt '*' timezone.get_zonecode ''' tz_object = pytz.timezone(get_zone()) loc_time = tz_object.localize(datetime.utcnow()) return loc_time.tzname()
Get current timezone (i.e. PST, MDT, etc) Returns: str: An abbreviated timezone code CLI Example: .. code-block:: bash salt '*' timezone.get_zonecode
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_timezone.py#L247-L262
[ "def get_zone():\n '''\n Get current timezone (i.e. America/Denver)\n\n Returns:\n str: Timezone in unix format\n\n Raises:\n CommandExecutionError: If timezone could not be gathered\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' timezone.get_zone\n '''\n cmd = ['tzutil', '/g']\n res = __salt__['cmd.run_all'](cmd, python_shell=False)\n if res['retcode'] or not res['stdout']:\n raise CommandExecutionError('tzutil encountered an error getting '\n 'timezone',\n info=res)\n return mapper.get_unix(res['stdout'].lower(), 'Unknown')\n" ]
# -*- coding: utf-8 -*- ''' Module for managing timezone on Windows systems. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging from datetime import datetime # Import Salt libs from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import pytz HAS_PYTZ = True except ImportError: HAS_PYTZ = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'timezone' class TzMapper(object): def __init__(self, unix_to_win): self.win_to_unix = {k.lower(): v for k, v in unix_to_win.items()} self.unix_to_win = {v.lower(): k for k, v in unix_to_win.items()} def add(self, k, v): self.unix_to_win[k.lower()] = v self.win_to_unix[v.lower()] = k def remove(self, k): self.win_to_unix.pop(self.unix_to_win.pop(k.lower()).lower()) def get_win(self, key, default=None): return self.unix_to_win.get(key.lower(), default) def get_unix(self, key, default=None): return self.win_to_unix.get(key.lower(), default) def list_win(self): return sorted(self.unix_to_win.values()) def list_unix(self): return sorted(self.win_to_unix.values()) mapper = TzMapper({ 'AUS Central Standard Time': 'Australia/Darwin', 'AUS Eastern Standard Time': 'Australia/Sydney', 'Afghanistan Standard Time': 'Asia/Kabul', 'Alaskan Standard Time': 'America/Anchorage', 'Aleutian Standard Time': 'America/Adak', 'Altai Standard Time': 'Asia/Barnaul', 'Arab Standard Time': 'Asia/Riyadh', 'Arabian Standard Time': 'Asia/Dubai', 'Arabic Standard Time': 'Asia/Baghdad', 'Argentina Standard Time': 'America/Buenos_Aires', 'Astrakhan Standard Time': 'Europe/Astrakhan', 'Atlantic Standard Time': 'America/Halifax', 'Aus Central W. Standard Time': 'Australia/Eucla', 'Azerbaijan Standard Time': 'Asia/Baku', 'Azores Standard Time': 'Atlantic/Azores', 'Bahia Standard Time': 'America/Bahia', 'Bangladesh Standard Time': 'Asia/Dhaka', 'Belarus Standard Time': 'Europe/Minsk', 'Bougainville Standard Time': 'Pacific/Bougainville', 'Canada Central Standard Time': 'America/Regina', 'Cape Verde Standard Time': 'Atlantic/Cape_Verde', 'Caucasus Standard Time': 'Asia/Yerevan', 'Cen. Australia Standard Time': 'Australia/Adelaide', 'Central America Standard Time': 'America/Guatemala', 'Central Asia Standard Time': 'Asia/Almaty', 'Central Brazilian Standard Time': 'America/Cuiaba', 'Central Europe Standard Time': 'Europe/Budapest', 'Central European Standard Time': 'Europe/Warsaw', 'Central Pacific Standard Time': 'Pacific/Guadalcanal', 'Central Standard Time': 'America/Chicago', 'Central Standard Time (Mexico)': 'America/Mexico_City', 'Chatham Islands Standard Time': 'Pacific/Chatham', 'China Standard Time': 'Asia/Shanghai', 'Cuba Standard Time': 'America/Havana', 'Dateline Standard Time': 'Etc/GMT+12', 'E. Africa Standard Time': 'Africa/Nairobi', 'E. Australia Standard Time': 'Australia/Brisbane', 'E. Europe Standard Time': 'Europe/Chisinau', 'E. South America Standard Time': 'America/Sao_Paulo', 'Easter Island Standard Time': 'Pacific/Easter', 'Eastern Standard Time': 'America/New_York', 'Eastern Standard Time (Mexico)': 'America/Cancun', 'Egypt Standard Time': 'Africa/Cairo', 'Ekaterinburg Standard Time': 'Asia/Yekaterinburg', 'FLE Standard Time': 'Europe/Kiev', 'Fiji Standard Time': 'Pacific/Fiji', 'GMT Standard Time': 'Europe/London', 'GTB Standard Time': 'Europe/Bucharest', 'Georgian Standard Time': 'Asia/Tbilisi', 'Greenland Standard Time': 'America/Godthab', 'Greenwich Standard Time': 'Atlantic/Reykjavik', 'Haiti Standard Time': 'America/Port-au-Prince', 'Hawaiian Standard Time': 'Pacific/Honolulu', 'India Standard Time': 'Asia/Calcutta', 'Iran Standard Time': 'Asia/Tehran', 'Israel Standard Time': 'Asia/Jerusalem', 'Jordan Standard Time': 'Asia/Amman', 'Kaliningrad Standard Time': 'Europe/Kaliningrad', 'Korea Standard Time': 'Asia/Seoul', 'Libya Standard Time': 'Africa/Tripoli', 'Line Islands Standard Time': 'Pacific/Kiritimati', 'Lord Howe Standard Time': 'Australia/Lord_Howe', 'Magadan Standard Time': 'Asia/Magadan', 'Magallanes Standard Time': 'America/Punta_Arenas', 'Marquesas Standard Time': 'Pacific/Marquesas', 'Mauritius Standard Time': 'Indian/Mauritius', 'Middle East Standard Time': 'Asia/Beirut', 'Montevideo Standard Time': 'America/Montevideo', 'Morocco Standard Time': 'Africa/Casablanca', 'Mountain Standard Time': 'America/Denver', 'Mountain Standard Time (Mexico)': 'America/Chihuahua', 'Myanmar Standard Time': 'Asia/Rangoon', 'N. Central Asia Standard Time': 'Asia/Novosibirsk', 'Namibia Standard Time': 'Africa/Windhoek', 'Nepal Standard Time': 'Asia/Katmandu', 'New Zealand Standard Time': 'Pacific/Auckland', 'Newfoundland Standard Time': 'America/St_Johns', 'Norfolk Standard Time': 'Pacific/Norfolk', 'North Asia East Standard Time': 'Asia/Irkutsk', 'North Asia Standard Time': 'Asia/Krasnoyarsk', 'North Korea Standard Time': 'Asia/Pyongyang', 'Omsk Standard Time': 'Asia/Omsk', 'Pacific SA Standard Time': 'America/Santiago', 'Pacific Standard Time': 'America/Los_Angeles', 'Pacific Standard Time (Mexico)': 'America/Tijuana', 'Pakistan Standard Time': 'Asia/Karachi', 'Paraguay Standard Time': 'America/Asuncion', 'Romance Standard Time': 'Europe/Paris', 'Russia Time Zone 10': 'Asia/Srednekolymsk', 'Russia Time Zone 11': 'Asia/Kamchatka', 'Russia Time Zone 3': 'Europe/Samara', 'Russian Standard Time': 'Europe/Moscow', 'SA Eastern Standard Time': 'America/Cayenne', 'SA Pacific Standard Time': 'America/Bogota', 'SA Western Standard Time': 'America/La_Paz', 'SE Asia Standard Time': 'Asia/Bangkok', 'Saint Pierre Standard Time': 'America/Miquelon', 'Sakhalin Standard Time': 'Asia/Sakhalin', 'Samoa Standard Time': 'Pacific/Apia', 'Saratov Standard Time': 'Europe/Saratov', 'Singapore Standard Time': 'Asia/Singapore', 'South Africa Standard Time': 'Africa/Johannesburg', 'Sri Lanka Standard Time': 'Asia/Colombo', 'Syria Standard Time': 'Asia/Damascus', 'Taipei Standard Time': 'Asia/Taipei', 'Tasmania Standard Time': 'Australia/Hobart', 'Tocantins Standard Time': 'America/Araguaina', 'Tokyo Standard Time': 'Asia/Tokyo', 'Tomsk Standard Time': 'Asia/Tomsk', 'Tonga Standard Time': 'Pacific/Tongatapu', 'Transbaikal Standard Time': 'Asia/Chita', 'Turkey Standard Time': 'Europe/Istanbul', 'Turks And Caicos Standard Time': 'America/Grand_Turk', 'US Eastern Standard Time': 'America/Indianapolis', 'US Mountain Standard Time': 'America/Phoenix', 'UTC': 'Etc/GMT', 'UTC+12': 'Etc/GMT-12', 'UTC+13': 'Etc/GMT-13', 'UTC-02': 'Etc/GMT+2', 'UTC-08': 'Etc/GMT+8', 'UTC-09': 'Etc/GMT+9', 'UTC-11': 'Etc/GMT+11', 'Ulaanbaatar Standard Time': 'Asia/Ulaanbaatar', 'Venezuela Standard Time': 'America/Caracas', 'Vladivostok Standard Time': 'Asia/Vladivostok', 'W. Australia Standard Time': 'Australia/Perth', 'W. Central Africa Standard Time': 'Africa/Lagos', 'W. Europe Standard Time': 'Europe/Berlin', 'W. Mongolia Standard Time': 'Asia/Hovd', 'West Asia Standard Time': 'Asia/Tashkent', 'West Bank Standard Time': 'Asia/Hebron', 'West Pacific Standard Time': 'Pacific/Port_Moresby', 'Yakutsk Standard Time': 'Asia/Yakutsk'}) def __virtual__(): ''' Only load on windows ''' if not __utils__['platform.is_windows'](): return False, "Module win_timezone: Not on Windows client" if not HAS_PYTZ: return False, "Module win_timezone: pytz not found" if not __utils__['path.which']('tzutil'): return False, "Module win_timezone: tzutil not found" return __virtualname__ def get_zone(): ''' Get current timezone (i.e. America/Denver) Returns: str: Timezone in unix format Raises: CommandExecutionError: If timezone could not be gathered CLI Example: .. code-block:: bash salt '*' timezone.get_zone ''' cmd = ['tzutil', '/g'] res = __salt__['cmd.run_all'](cmd, python_shell=False) if res['retcode'] or not res['stdout']: raise CommandExecutionError('tzutil encountered an error getting ' 'timezone', info=res) return mapper.get_unix(res['stdout'].lower(), 'Unknown') def get_offset(): ''' Get current numeric timezone offset from UTC (i.e. -0700) Returns: str: Offset from UTC CLI Example: .. code-block:: bash salt '*' timezone.get_offset ''' # http://craigglennie.com/programming/python/2013/07/21/working-with-timezones-using-Python-and-pytz-localize-vs-normalize/ tz_object = pytz.timezone(get_zone()) utc_time = pytz.utc.localize(datetime.utcnow()) loc_time = utc_time.astimezone(tz_object) norm_time = tz_object.normalize(loc_time) return norm_time.strftime('%z') def set_zone(timezone): ''' Sets the timezone using the tzutil. Args: timezone (str): A valid timezone Returns: bool: ``True`` if successful, otherwise ``False`` Raises: CommandExecutionError: If invalid timezone is passed CLI Example: .. code-block:: bash salt '*' timezone.set_zone 'America/Denver' ''' # if it's one of the key's just use it if timezone.lower() in mapper.win_to_unix: win_zone = timezone elif timezone.lower() in mapper.unix_to_win: # if it's one of the values, use the key win_zone = mapper.get_win(timezone) else: # Raise error because it's neither key nor value raise CommandExecutionError('Invalid timezone passed: {0}'.format(timezone)) # Set the value cmd = ['tzutil', '/s', win_zone] res = __salt__['cmd.run_all'](cmd, python_shell=False) if res['retcode']: raise CommandExecutionError('tzutil encountered an error setting ' 'timezone: {0}'.format(timezone), info=res) return zone_compare(timezone) def zone_compare(timezone): ''' Compares the given timezone with the machine timezone. Mostly useful for running state checks. Args: timezone (str): The timezone to compare. This can be in Windows or Unix format. Can be any of the values returned by the ``timezone.list`` function Returns: bool: ``True`` if they match, otherwise ``False`` Example: .. code-block:: bash salt '*' timezone.zone_compare 'America/Denver' ''' # if it's one of the key's just use it if timezone.lower() in mapper.win_to_unix: check_zone = timezone elif timezone.lower() in mapper.unix_to_win: # if it's one of the values, use the key check_zone = mapper.get_win(timezone) else: # Raise error because it's neither key nor value raise CommandExecutionError('Invalid timezone passed: {0}' ''.format(timezone)) return get_zone() == mapper.get_unix(check_zone, 'Unknown') def list(unix_style=True): ''' Return a list of Timezones that this module supports. These can be in either Unix or Windows format. .. versionadded:: 2018.3.3 Args: unix_style (bool): ``True`` returns Unix-style timezones. ``False`` returns Windows-style timezones. Default is ``True`` Returns: list: A list of supported timezones CLI Example: .. code-block:: bash # Unix-style timezones salt '*' timezone.list # Windows-style timezones salt '*' timezone.list unix_style=False ''' if unix_style: return mapper.list_unix() else: return mapper.list_win() def get_hwclock(): ''' Get current hardware clock setting (UTC or localtime) .. note:: The hardware clock is always local time on Windows so this will always return "localtime" CLI Example: .. code-block:: bash salt '*' timezone.get_hwclock ''' # The hardware clock is always localtime on Windows return 'localtime' def set_hwclock(clock): ''' Sets the hardware clock to be either UTC or localtime .. note:: The hardware clock is always local time on Windows so this will always return ``False`` CLI Example: .. code-block:: bash salt '*' timezone.set_hwclock UTC ''' # The hardware clock is always localtime on Windows return False
saltstack/salt
salt/modules/win_timezone.py
set_zone
python
def set_zone(timezone): ''' Sets the timezone using the tzutil. Args: timezone (str): A valid timezone Returns: bool: ``True`` if successful, otherwise ``False`` Raises: CommandExecutionError: If invalid timezone is passed CLI Example: .. code-block:: bash salt '*' timezone.set_zone 'America/Denver' ''' # if it's one of the key's just use it if timezone.lower() in mapper.win_to_unix: win_zone = timezone elif timezone.lower() in mapper.unix_to_win: # if it's one of the values, use the key win_zone = mapper.get_win(timezone) else: # Raise error because it's neither key nor value raise CommandExecutionError('Invalid timezone passed: {0}'.format(timezone)) # Set the value cmd = ['tzutil', '/s', win_zone] res = __salt__['cmd.run_all'](cmd, python_shell=False) if res['retcode']: raise CommandExecutionError('tzutil encountered an error setting ' 'timezone: {0}'.format(timezone), info=res) return zone_compare(timezone)
Sets the timezone using the tzutil. Args: timezone (str): A valid timezone Returns: bool: ``True`` if successful, otherwise ``False`` Raises: CommandExecutionError: If invalid timezone is passed CLI Example: .. code-block:: bash salt '*' timezone.set_zone 'America/Denver'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_timezone.py#L265-L303
[ "def zone_compare(timezone):\n '''\n Compares the given timezone with the machine timezone. Mostly useful for\n running state checks.\n\n Args:\n timezone (str):\n The timezone to compare. This can be in Windows or Unix format. Can\n be any of the values returned by the ``timezone.list`` function\n\n Returns:\n bool: ``True`` if they match, otherwise ``False``\n\n Example:\n\n .. code-block:: bash\n\n salt '*' timezone.zone_compare 'America/Denver'\n '''\n # if it's one of the key's just use it\n if timezone.lower() in mapper.win_to_unix:\n check_zone = timezone\n\n elif timezone.lower() in mapper.unix_to_win:\n # if it's one of the values, use the key\n check_zone = mapper.get_win(timezone)\n\n else:\n # Raise error because it's neither key nor value\n raise CommandExecutionError('Invalid timezone passed: {0}'\n ''.format(timezone))\n\n return get_zone() == mapper.get_unix(check_zone, 'Unknown')\n", "def get_win(self, key, default=None):\n return self.unix_to_win.get(key.lower(), default)\n" ]
# -*- coding: utf-8 -*- ''' Module for managing timezone on Windows systems. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging from datetime import datetime # Import Salt libs from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import pytz HAS_PYTZ = True except ImportError: HAS_PYTZ = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'timezone' class TzMapper(object): def __init__(self, unix_to_win): self.win_to_unix = {k.lower(): v for k, v in unix_to_win.items()} self.unix_to_win = {v.lower(): k for k, v in unix_to_win.items()} def add(self, k, v): self.unix_to_win[k.lower()] = v self.win_to_unix[v.lower()] = k def remove(self, k): self.win_to_unix.pop(self.unix_to_win.pop(k.lower()).lower()) def get_win(self, key, default=None): return self.unix_to_win.get(key.lower(), default) def get_unix(self, key, default=None): return self.win_to_unix.get(key.lower(), default) def list_win(self): return sorted(self.unix_to_win.values()) def list_unix(self): return sorted(self.win_to_unix.values()) mapper = TzMapper({ 'AUS Central Standard Time': 'Australia/Darwin', 'AUS Eastern Standard Time': 'Australia/Sydney', 'Afghanistan Standard Time': 'Asia/Kabul', 'Alaskan Standard Time': 'America/Anchorage', 'Aleutian Standard Time': 'America/Adak', 'Altai Standard Time': 'Asia/Barnaul', 'Arab Standard Time': 'Asia/Riyadh', 'Arabian Standard Time': 'Asia/Dubai', 'Arabic Standard Time': 'Asia/Baghdad', 'Argentina Standard Time': 'America/Buenos_Aires', 'Astrakhan Standard Time': 'Europe/Astrakhan', 'Atlantic Standard Time': 'America/Halifax', 'Aus Central W. Standard Time': 'Australia/Eucla', 'Azerbaijan Standard Time': 'Asia/Baku', 'Azores Standard Time': 'Atlantic/Azores', 'Bahia Standard Time': 'America/Bahia', 'Bangladesh Standard Time': 'Asia/Dhaka', 'Belarus Standard Time': 'Europe/Minsk', 'Bougainville Standard Time': 'Pacific/Bougainville', 'Canada Central Standard Time': 'America/Regina', 'Cape Verde Standard Time': 'Atlantic/Cape_Verde', 'Caucasus Standard Time': 'Asia/Yerevan', 'Cen. Australia Standard Time': 'Australia/Adelaide', 'Central America Standard Time': 'America/Guatemala', 'Central Asia Standard Time': 'Asia/Almaty', 'Central Brazilian Standard Time': 'America/Cuiaba', 'Central Europe Standard Time': 'Europe/Budapest', 'Central European Standard Time': 'Europe/Warsaw', 'Central Pacific Standard Time': 'Pacific/Guadalcanal', 'Central Standard Time': 'America/Chicago', 'Central Standard Time (Mexico)': 'America/Mexico_City', 'Chatham Islands Standard Time': 'Pacific/Chatham', 'China Standard Time': 'Asia/Shanghai', 'Cuba Standard Time': 'America/Havana', 'Dateline Standard Time': 'Etc/GMT+12', 'E. Africa Standard Time': 'Africa/Nairobi', 'E. Australia Standard Time': 'Australia/Brisbane', 'E. Europe Standard Time': 'Europe/Chisinau', 'E. South America Standard Time': 'America/Sao_Paulo', 'Easter Island Standard Time': 'Pacific/Easter', 'Eastern Standard Time': 'America/New_York', 'Eastern Standard Time (Mexico)': 'America/Cancun', 'Egypt Standard Time': 'Africa/Cairo', 'Ekaterinburg Standard Time': 'Asia/Yekaterinburg', 'FLE Standard Time': 'Europe/Kiev', 'Fiji Standard Time': 'Pacific/Fiji', 'GMT Standard Time': 'Europe/London', 'GTB Standard Time': 'Europe/Bucharest', 'Georgian Standard Time': 'Asia/Tbilisi', 'Greenland Standard Time': 'America/Godthab', 'Greenwich Standard Time': 'Atlantic/Reykjavik', 'Haiti Standard Time': 'America/Port-au-Prince', 'Hawaiian Standard Time': 'Pacific/Honolulu', 'India Standard Time': 'Asia/Calcutta', 'Iran Standard Time': 'Asia/Tehran', 'Israel Standard Time': 'Asia/Jerusalem', 'Jordan Standard Time': 'Asia/Amman', 'Kaliningrad Standard Time': 'Europe/Kaliningrad', 'Korea Standard Time': 'Asia/Seoul', 'Libya Standard Time': 'Africa/Tripoli', 'Line Islands Standard Time': 'Pacific/Kiritimati', 'Lord Howe Standard Time': 'Australia/Lord_Howe', 'Magadan Standard Time': 'Asia/Magadan', 'Magallanes Standard Time': 'America/Punta_Arenas', 'Marquesas Standard Time': 'Pacific/Marquesas', 'Mauritius Standard Time': 'Indian/Mauritius', 'Middle East Standard Time': 'Asia/Beirut', 'Montevideo Standard Time': 'America/Montevideo', 'Morocco Standard Time': 'Africa/Casablanca', 'Mountain Standard Time': 'America/Denver', 'Mountain Standard Time (Mexico)': 'America/Chihuahua', 'Myanmar Standard Time': 'Asia/Rangoon', 'N. Central Asia Standard Time': 'Asia/Novosibirsk', 'Namibia Standard Time': 'Africa/Windhoek', 'Nepal Standard Time': 'Asia/Katmandu', 'New Zealand Standard Time': 'Pacific/Auckland', 'Newfoundland Standard Time': 'America/St_Johns', 'Norfolk Standard Time': 'Pacific/Norfolk', 'North Asia East Standard Time': 'Asia/Irkutsk', 'North Asia Standard Time': 'Asia/Krasnoyarsk', 'North Korea Standard Time': 'Asia/Pyongyang', 'Omsk Standard Time': 'Asia/Omsk', 'Pacific SA Standard Time': 'America/Santiago', 'Pacific Standard Time': 'America/Los_Angeles', 'Pacific Standard Time (Mexico)': 'America/Tijuana', 'Pakistan Standard Time': 'Asia/Karachi', 'Paraguay Standard Time': 'America/Asuncion', 'Romance Standard Time': 'Europe/Paris', 'Russia Time Zone 10': 'Asia/Srednekolymsk', 'Russia Time Zone 11': 'Asia/Kamchatka', 'Russia Time Zone 3': 'Europe/Samara', 'Russian Standard Time': 'Europe/Moscow', 'SA Eastern Standard Time': 'America/Cayenne', 'SA Pacific Standard Time': 'America/Bogota', 'SA Western Standard Time': 'America/La_Paz', 'SE Asia Standard Time': 'Asia/Bangkok', 'Saint Pierre Standard Time': 'America/Miquelon', 'Sakhalin Standard Time': 'Asia/Sakhalin', 'Samoa Standard Time': 'Pacific/Apia', 'Saratov Standard Time': 'Europe/Saratov', 'Singapore Standard Time': 'Asia/Singapore', 'South Africa Standard Time': 'Africa/Johannesburg', 'Sri Lanka Standard Time': 'Asia/Colombo', 'Syria Standard Time': 'Asia/Damascus', 'Taipei Standard Time': 'Asia/Taipei', 'Tasmania Standard Time': 'Australia/Hobart', 'Tocantins Standard Time': 'America/Araguaina', 'Tokyo Standard Time': 'Asia/Tokyo', 'Tomsk Standard Time': 'Asia/Tomsk', 'Tonga Standard Time': 'Pacific/Tongatapu', 'Transbaikal Standard Time': 'Asia/Chita', 'Turkey Standard Time': 'Europe/Istanbul', 'Turks And Caicos Standard Time': 'America/Grand_Turk', 'US Eastern Standard Time': 'America/Indianapolis', 'US Mountain Standard Time': 'America/Phoenix', 'UTC': 'Etc/GMT', 'UTC+12': 'Etc/GMT-12', 'UTC+13': 'Etc/GMT-13', 'UTC-02': 'Etc/GMT+2', 'UTC-08': 'Etc/GMT+8', 'UTC-09': 'Etc/GMT+9', 'UTC-11': 'Etc/GMT+11', 'Ulaanbaatar Standard Time': 'Asia/Ulaanbaatar', 'Venezuela Standard Time': 'America/Caracas', 'Vladivostok Standard Time': 'Asia/Vladivostok', 'W. Australia Standard Time': 'Australia/Perth', 'W. Central Africa Standard Time': 'Africa/Lagos', 'W. Europe Standard Time': 'Europe/Berlin', 'W. Mongolia Standard Time': 'Asia/Hovd', 'West Asia Standard Time': 'Asia/Tashkent', 'West Bank Standard Time': 'Asia/Hebron', 'West Pacific Standard Time': 'Pacific/Port_Moresby', 'Yakutsk Standard Time': 'Asia/Yakutsk'}) def __virtual__(): ''' Only load on windows ''' if not __utils__['platform.is_windows'](): return False, "Module win_timezone: Not on Windows client" if not HAS_PYTZ: return False, "Module win_timezone: pytz not found" if not __utils__['path.which']('tzutil'): return False, "Module win_timezone: tzutil not found" return __virtualname__ def get_zone(): ''' Get current timezone (i.e. America/Denver) Returns: str: Timezone in unix format Raises: CommandExecutionError: If timezone could not be gathered CLI Example: .. code-block:: bash salt '*' timezone.get_zone ''' cmd = ['tzutil', '/g'] res = __salt__['cmd.run_all'](cmd, python_shell=False) if res['retcode'] or not res['stdout']: raise CommandExecutionError('tzutil encountered an error getting ' 'timezone', info=res) return mapper.get_unix(res['stdout'].lower(), 'Unknown') def get_offset(): ''' Get current numeric timezone offset from UTC (i.e. -0700) Returns: str: Offset from UTC CLI Example: .. code-block:: bash salt '*' timezone.get_offset ''' # http://craigglennie.com/programming/python/2013/07/21/working-with-timezones-using-Python-and-pytz-localize-vs-normalize/ tz_object = pytz.timezone(get_zone()) utc_time = pytz.utc.localize(datetime.utcnow()) loc_time = utc_time.astimezone(tz_object) norm_time = tz_object.normalize(loc_time) return norm_time.strftime('%z') def get_zonecode(): ''' Get current timezone (i.e. PST, MDT, etc) Returns: str: An abbreviated timezone code CLI Example: .. code-block:: bash salt '*' timezone.get_zonecode ''' tz_object = pytz.timezone(get_zone()) loc_time = tz_object.localize(datetime.utcnow()) return loc_time.tzname() def zone_compare(timezone): ''' Compares the given timezone with the machine timezone. Mostly useful for running state checks. Args: timezone (str): The timezone to compare. This can be in Windows or Unix format. Can be any of the values returned by the ``timezone.list`` function Returns: bool: ``True`` if they match, otherwise ``False`` Example: .. code-block:: bash salt '*' timezone.zone_compare 'America/Denver' ''' # if it's one of the key's just use it if timezone.lower() in mapper.win_to_unix: check_zone = timezone elif timezone.lower() in mapper.unix_to_win: # if it's one of the values, use the key check_zone = mapper.get_win(timezone) else: # Raise error because it's neither key nor value raise CommandExecutionError('Invalid timezone passed: {0}' ''.format(timezone)) return get_zone() == mapper.get_unix(check_zone, 'Unknown') def list(unix_style=True): ''' Return a list of Timezones that this module supports. These can be in either Unix or Windows format. .. versionadded:: 2018.3.3 Args: unix_style (bool): ``True`` returns Unix-style timezones. ``False`` returns Windows-style timezones. Default is ``True`` Returns: list: A list of supported timezones CLI Example: .. code-block:: bash # Unix-style timezones salt '*' timezone.list # Windows-style timezones salt '*' timezone.list unix_style=False ''' if unix_style: return mapper.list_unix() else: return mapper.list_win() def get_hwclock(): ''' Get current hardware clock setting (UTC or localtime) .. note:: The hardware clock is always local time on Windows so this will always return "localtime" CLI Example: .. code-block:: bash salt '*' timezone.get_hwclock ''' # The hardware clock is always localtime on Windows return 'localtime' def set_hwclock(clock): ''' Sets the hardware clock to be either UTC or localtime .. note:: The hardware clock is always local time on Windows so this will always return ``False`` CLI Example: .. code-block:: bash salt '*' timezone.set_hwclock UTC ''' # The hardware clock is always localtime on Windows return False
saltstack/salt
salt/modules/win_timezone.py
zone_compare
python
def zone_compare(timezone): ''' Compares the given timezone with the machine timezone. Mostly useful for running state checks. Args: timezone (str): The timezone to compare. This can be in Windows or Unix format. Can be any of the values returned by the ``timezone.list`` function Returns: bool: ``True`` if they match, otherwise ``False`` Example: .. code-block:: bash salt '*' timezone.zone_compare 'America/Denver' ''' # if it's one of the key's just use it if timezone.lower() in mapper.win_to_unix: check_zone = timezone elif timezone.lower() in mapper.unix_to_win: # if it's one of the values, use the key check_zone = mapper.get_win(timezone) else: # Raise error because it's neither key nor value raise CommandExecutionError('Invalid timezone passed: {0}' ''.format(timezone)) return get_zone() == mapper.get_unix(check_zone, 'Unknown')
Compares the given timezone with the machine timezone. Mostly useful for running state checks. Args: timezone (str): The timezone to compare. This can be in Windows or Unix format. Can be any of the values returned by the ``timezone.list`` function Returns: bool: ``True`` if they match, otherwise ``False`` Example: .. code-block:: bash salt '*' timezone.zone_compare 'America/Denver'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_timezone.py#L306-L338
[ "def get_zone():\n '''\n Get current timezone (i.e. America/Denver)\n\n Returns:\n str: Timezone in unix format\n\n Raises:\n CommandExecutionError: If timezone could not be gathered\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' timezone.get_zone\n '''\n cmd = ['tzutil', '/g']\n res = __salt__['cmd.run_all'](cmd, python_shell=False)\n if res['retcode'] or not res['stdout']:\n raise CommandExecutionError('tzutil encountered an error getting '\n 'timezone',\n info=res)\n return mapper.get_unix(res['stdout'].lower(), 'Unknown')\n", "def get_win(self, key, default=None):\n return self.unix_to_win.get(key.lower(), default)\n", "def get_unix(self, key, default=None):\n return self.win_to_unix.get(key.lower(), default)\n" ]
# -*- coding: utf-8 -*- ''' Module for managing timezone on Windows systems. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs import logging from datetime import datetime # Import Salt libs from salt.exceptions import CommandExecutionError # Import 3rd party libs try: import pytz HAS_PYTZ = True except ImportError: HAS_PYTZ = False log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'timezone' class TzMapper(object): def __init__(self, unix_to_win): self.win_to_unix = {k.lower(): v for k, v in unix_to_win.items()} self.unix_to_win = {v.lower(): k for k, v in unix_to_win.items()} def add(self, k, v): self.unix_to_win[k.lower()] = v self.win_to_unix[v.lower()] = k def remove(self, k): self.win_to_unix.pop(self.unix_to_win.pop(k.lower()).lower()) def get_win(self, key, default=None): return self.unix_to_win.get(key.lower(), default) def get_unix(self, key, default=None): return self.win_to_unix.get(key.lower(), default) def list_win(self): return sorted(self.unix_to_win.values()) def list_unix(self): return sorted(self.win_to_unix.values()) mapper = TzMapper({ 'AUS Central Standard Time': 'Australia/Darwin', 'AUS Eastern Standard Time': 'Australia/Sydney', 'Afghanistan Standard Time': 'Asia/Kabul', 'Alaskan Standard Time': 'America/Anchorage', 'Aleutian Standard Time': 'America/Adak', 'Altai Standard Time': 'Asia/Barnaul', 'Arab Standard Time': 'Asia/Riyadh', 'Arabian Standard Time': 'Asia/Dubai', 'Arabic Standard Time': 'Asia/Baghdad', 'Argentina Standard Time': 'America/Buenos_Aires', 'Astrakhan Standard Time': 'Europe/Astrakhan', 'Atlantic Standard Time': 'America/Halifax', 'Aus Central W. Standard Time': 'Australia/Eucla', 'Azerbaijan Standard Time': 'Asia/Baku', 'Azores Standard Time': 'Atlantic/Azores', 'Bahia Standard Time': 'America/Bahia', 'Bangladesh Standard Time': 'Asia/Dhaka', 'Belarus Standard Time': 'Europe/Minsk', 'Bougainville Standard Time': 'Pacific/Bougainville', 'Canada Central Standard Time': 'America/Regina', 'Cape Verde Standard Time': 'Atlantic/Cape_Verde', 'Caucasus Standard Time': 'Asia/Yerevan', 'Cen. Australia Standard Time': 'Australia/Adelaide', 'Central America Standard Time': 'America/Guatemala', 'Central Asia Standard Time': 'Asia/Almaty', 'Central Brazilian Standard Time': 'America/Cuiaba', 'Central Europe Standard Time': 'Europe/Budapest', 'Central European Standard Time': 'Europe/Warsaw', 'Central Pacific Standard Time': 'Pacific/Guadalcanal', 'Central Standard Time': 'America/Chicago', 'Central Standard Time (Mexico)': 'America/Mexico_City', 'Chatham Islands Standard Time': 'Pacific/Chatham', 'China Standard Time': 'Asia/Shanghai', 'Cuba Standard Time': 'America/Havana', 'Dateline Standard Time': 'Etc/GMT+12', 'E. Africa Standard Time': 'Africa/Nairobi', 'E. Australia Standard Time': 'Australia/Brisbane', 'E. Europe Standard Time': 'Europe/Chisinau', 'E. South America Standard Time': 'America/Sao_Paulo', 'Easter Island Standard Time': 'Pacific/Easter', 'Eastern Standard Time': 'America/New_York', 'Eastern Standard Time (Mexico)': 'America/Cancun', 'Egypt Standard Time': 'Africa/Cairo', 'Ekaterinburg Standard Time': 'Asia/Yekaterinburg', 'FLE Standard Time': 'Europe/Kiev', 'Fiji Standard Time': 'Pacific/Fiji', 'GMT Standard Time': 'Europe/London', 'GTB Standard Time': 'Europe/Bucharest', 'Georgian Standard Time': 'Asia/Tbilisi', 'Greenland Standard Time': 'America/Godthab', 'Greenwich Standard Time': 'Atlantic/Reykjavik', 'Haiti Standard Time': 'America/Port-au-Prince', 'Hawaiian Standard Time': 'Pacific/Honolulu', 'India Standard Time': 'Asia/Calcutta', 'Iran Standard Time': 'Asia/Tehran', 'Israel Standard Time': 'Asia/Jerusalem', 'Jordan Standard Time': 'Asia/Amman', 'Kaliningrad Standard Time': 'Europe/Kaliningrad', 'Korea Standard Time': 'Asia/Seoul', 'Libya Standard Time': 'Africa/Tripoli', 'Line Islands Standard Time': 'Pacific/Kiritimati', 'Lord Howe Standard Time': 'Australia/Lord_Howe', 'Magadan Standard Time': 'Asia/Magadan', 'Magallanes Standard Time': 'America/Punta_Arenas', 'Marquesas Standard Time': 'Pacific/Marquesas', 'Mauritius Standard Time': 'Indian/Mauritius', 'Middle East Standard Time': 'Asia/Beirut', 'Montevideo Standard Time': 'America/Montevideo', 'Morocco Standard Time': 'Africa/Casablanca', 'Mountain Standard Time': 'America/Denver', 'Mountain Standard Time (Mexico)': 'America/Chihuahua', 'Myanmar Standard Time': 'Asia/Rangoon', 'N. Central Asia Standard Time': 'Asia/Novosibirsk', 'Namibia Standard Time': 'Africa/Windhoek', 'Nepal Standard Time': 'Asia/Katmandu', 'New Zealand Standard Time': 'Pacific/Auckland', 'Newfoundland Standard Time': 'America/St_Johns', 'Norfolk Standard Time': 'Pacific/Norfolk', 'North Asia East Standard Time': 'Asia/Irkutsk', 'North Asia Standard Time': 'Asia/Krasnoyarsk', 'North Korea Standard Time': 'Asia/Pyongyang', 'Omsk Standard Time': 'Asia/Omsk', 'Pacific SA Standard Time': 'America/Santiago', 'Pacific Standard Time': 'America/Los_Angeles', 'Pacific Standard Time (Mexico)': 'America/Tijuana', 'Pakistan Standard Time': 'Asia/Karachi', 'Paraguay Standard Time': 'America/Asuncion', 'Romance Standard Time': 'Europe/Paris', 'Russia Time Zone 10': 'Asia/Srednekolymsk', 'Russia Time Zone 11': 'Asia/Kamchatka', 'Russia Time Zone 3': 'Europe/Samara', 'Russian Standard Time': 'Europe/Moscow', 'SA Eastern Standard Time': 'America/Cayenne', 'SA Pacific Standard Time': 'America/Bogota', 'SA Western Standard Time': 'America/La_Paz', 'SE Asia Standard Time': 'Asia/Bangkok', 'Saint Pierre Standard Time': 'America/Miquelon', 'Sakhalin Standard Time': 'Asia/Sakhalin', 'Samoa Standard Time': 'Pacific/Apia', 'Saratov Standard Time': 'Europe/Saratov', 'Singapore Standard Time': 'Asia/Singapore', 'South Africa Standard Time': 'Africa/Johannesburg', 'Sri Lanka Standard Time': 'Asia/Colombo', 'Syria Standard Time': 'Asia/Damascus', 'Taipei Standard Time': 'Asia/Taipei', 'Tasmania Standard Time': 'Australia/Hobart', 'Tocantins Standard Time': 'America/Araguaina', 'Tokyo Standard Time': 'Asia/Tokyo', 'Tomsk Standard Time': 'Asia/Tomsk', 'Tonga Standard Time': 'Pacific/Tongatapu', 'Transbaikal Standard Time': 'Asia/Chita', 'Turkey Standard Time': 'Europe/Istanbul', 'Turks And Caicos Standard Time': 'America/Grand_Turk', 'US Eastern Standard Time': 'America/Indianapolis', 'US Mountain Standard Time': 'America/Phoenix', 'UTC': 'Etc/GMT', 'UTC+12': 'Etc/GMT-12', 'UTC+13': 'Etc/GMT-13', 'UTC-02': 'Etc/GMT+2', 'UTC-08': 'Etc/GMT+8', 'UTC-09': 'Etc/GMT+9', 'UTC-11': 'Etc/GMT+11', 'Ulaanbaatar Standard Time': 'Asia/Ulaanbaatar', 'Venezuela Standard Time': 'America/Caracas', 'Vladivostok Standard Time': 'Asia/Vladivostok', 'W. Australia Standard Time': 'Australia/Perth', 'W. Central Africa Standard Time': 'Africa/Lagos', 'W. Europe Standard Time': 'Europe/Berlin', 'W. Mongolia Standard Time': 'Asia/Hovd', 'West Asia Standard Time': 'Asia/Tashkent', 'West Bank Standard Time': 'Asia/Hebron', 'West Pacific Standard Time': 'Pacific/Port_Moresby', 'Yakutsk Standard Time': 'Asia/Yakutsk'}) def __virtual__(): ''' Only load on windows ''' if not __utils__['platform.is_windows'](): return False, "Module win_timezone: Not on Windows client" if not HAS_PYTZ: return False, "Module win_timezone: pytz not found" if not __utils__['path.which']('tzutil'): return False, "Module win_timezone: tzutil not found" return __virtualname__ def get_zone(): ''' Get current timezone (i.e. America/Denver) Returns: str: Timezone in unix format Raises: CommandExecutionError: If timezone could not be gathered CLI Example: .. code-block:: bash salt '*' timezone.get_zone ''' cmd = ['tzutil', '/g'] res = __salt__['cmd.run_all'](cmd, python_shell=False) if res['retcode'] or not res['stdout']: raise CommandExecutionError('tzutil encountered an error getting ' 'timezone', info=res) return mapper.get_unix(res['stdout'].lower(), 'Unknown') def get_offset(): ''' Get current numeric timezone offset from UTC (i.e. -0700) Returns: str: Offset from UTC CLI Example: .. code-block:: bash salt '*' timezone.get_offset ''' # http://craigglennie.com/programming/python/2013/07/21/working-with-timezones-using-Python-and-pytz-localize-vs-normalize/ tz_object = pytz.timezone(get_zone()) utc_time = pytz.utc.localize(datetime.utcnow()) loc_time = utc_time.astimezone(tz_object) norm_time = tz_object.normalize(loc_time) return norm_time.strftime('%z') def get_zonecode(): ''' Get current timezone (i.e. PST, MDT, etc) Returns: str: An abbreviated timezone code CLI Example: .. code-block:: bash salt '*' timezone.get_zonecode ''' tz_object = pytz.timezone(get_zone()) loc_time = tz_object.localize(datetime.utcnow()) return loc_time.tzname() def set_zone(timezone): ''' Sets the timezone using the tzutil. Args: timezone (str): A valid timezone Returns: bool: ``True`` if successful, otherwise ``False`` Raises: CommandExecutionError: If invalid timezone is passed CLI Example: .. code-block:: bash salt '*' timezone.set_zone 'America/Denver' ''' # if it's one of the key's just use it if timezone.lower() in mapper.win_to_unix: win_zone = timezone elif timezone.lower() in mapper.unix_to_win: # if it's one of the values, use the key win_zone = mapper.get_win(timezone) else: # Raise error because it's neither key nor value raise CommandExecutionError('Invalid timezone passed: {0}'.format(timezone)) # Set the value cmd = ['tzutil', '/s', win_zone] res = __salt__['cmd.run_all'](cmd, python_shell=False) if res['retcode']: raise CommandExecutionError('tzutil encountered an error setting ' 'timezone: {0}'.format(timezone), info=res) return zone_compare(timezone) def list(unix_style=True): ''' Return a list of Timezones that this module supports. These can be in either Unix or Windows format. .. versionadded:: 2018.3.3 Args: unix_style (bool): ``True`` returns Unix-style timezones. ``False`` returns Windows-style timezones. Default is ``True`` Returns: list: A list of supported timezones CLI Example: .. code-block:: bash # Unix-style timezones salt '*' timezone.list # Windows-style timezones salt '*' timezone.list unix_style=False ''' if unix_style: return mapper.list_unix() else: return mapper.list_win() def get_hwclock(): ''' Get current hardware clock setting (UTC or localtime) .. note:: The hardware clock is always local time on Windows so this will always return "localtime" CLI Example: .. code-block:: bash salt '*' timezone.get_hwclock ''' # The hardware clock is always localtime on Windows return 'localtime' def set_hwclock(clock): ''' Sets the hardware clock to be either UTC or localtime .. note:: The hardware clock is always local time on Windows so this will always return ``False`` CLI Example: .. code-block:: bash salt '*' timezone.set_hwclock UTC ''' # The hardware clock is always localtime on Windows return False
saltstack/salt
salt/states/win_license.py
activate
python
def activate(name): ''' Install and activate the given product key name The 5x5 product key given to you by Microsoft ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} product_key = name license_info = __salt__['license.info']() licensed = False key_match = False if license_info is not None: licensed = license_info['licensed'] key_match = license_info['partial_key'] in product_key if not key_match: out = __salt__['license.install'](product_key) licensed = False if 'successfully' not in out: ret['result'] = False ret['comment'] += 'Unable to install the given product key is it valid?' return ret if not licensed: out = __salt__['license.activate']() if 'successfully' not in out: ret['result'] = False ret['comment'] += 'Unable to activate the given product key.' return ret ret['comment'] += 'Windows is now activated.' else: ret['comment'] += 'Windows is already activated.' return ret
Install and activate the given product key name The 5x5 product key given to you by Microsoft
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_license.py#L33-L71
null
# -*- coding: utf-8 -*- ''' Installation and activation of windows licenses =============================================== Install and activate windows licenses .. code-block:: yaml XXXXX-XXXXX-XXXXX-XXXXX-XXXXX: license.activate ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = 'license' def __virtual__(): ''' Only work on Windows ''' if salt.utils.platform.is_windows(): return __virtualname__ return False
saltstack/salt
salt/states/quota.py
mode
python
def mode(name, mode, quotatype): ''' Set the quota for the system name The filesystem to set the quota mode on mode Whether the quota system is on or off quotatype Must be ``user`` or ``group`` ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} fun = 'off' if mode is True: fun = 'on' if __salt__['quota.get_mode'](name)[name][quotatype] == fun: ret['result'] = True ret['comment'] = 'Quota for {0} already set to {1}'.format(name, fun) return ret if __opts__['test']: ret['comment'] = 'Quota for {0} needs to be set to {1}'.format(name, fun) return ret if __salt__['quota.{0}'.format(fun)](name): ret['changes'] = {'quota': name} ret['result'] = True ret['comment'] = 'Set quota for {0} to {1}'.format(name, fun) return ret else: ret['result'] = False ret['comment'] = 'Failed to set quota for {0} to {1}'.format(name, fun) return ret
Set the quota for the system name The filesystem to set the quota mode on mode Whether the quota system is on or off quotatype Must be ``user`` or ``group``
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/quota.py#L26-L62
null
# -*- coding: utf-8 -*- ''' Management of POSIX Quotas ========================== The quota can be managed for the system: .. code-block:: yaml /: quota.mode: mode: off quotatype: user ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): ''' Only load if the quota module is available in __salt__ ''' return 'quota' if 'quota.report' in __salt__ else False
saltstack/salt
salt/modules/quota.py
report
python
def report(mount): ''' Report on quotas for a specific volume CLI Example: .. code-block:: bash salt '*' quota.report /media/data ''' ret = {mount: {}} ret[mount]['User Quotas'] = _parse_quota(mount, '-u') ret[mount]['Group Quotas'] = _parse_quota(mount, '-g') return ret
Report on quotas for a specific volume CLI Example: .. code-block:: bash salt '*' quota.report /media/data
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/quota.py#L38-L51
[ "def _parse_quota(mount, opts):\n '''\n Parse the output from repquota. Requires that -u -g are passed in\n '''\n cmd = 'repquota -vp {0} {1}'.format(opts, mount)\n out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()\n mode = 'header'\n\n if '-u' in opts:\n quotatype = 'Users'\n elif '-g' in opts:\n quotatype = 'Groups'\n ret = {quotatype: {}}\n\n for line in out:\n if not line:\n continue\n comps = line.split()\n if mode == 'header':\n if 'Block grace time' in line:\n blockg, inodeg = line.split(';')\n blockgc = blockg.split(': ')\n inodegc = inodeg.split(': ')\n ret['Block Grace Time'] = blockgc[-1:]\n ret['Inode Grace Time'] = inodegc[-1:]\n elif line.startswith('-'):\n mode = 'quotas'\n elif mode == 'quotas':\n if len(comps) < 8:\n continue\n if not comps[0] in ret[quotatype]:\n ret[quotatype][comps[0]] = {}\n ret[quotatype][comps[0]]['block-used'] = comps[2]\n ret[quotatype][comps[0]]['block-soft-limit'] = comps[3]\n ret[quotatype][comps[0]]['block-hard-limit'] = comps[4]\n ret[quotatype][comps[0]]['block-grace'] = comps[5]\n ret[quotatype][comps[0]]['file-used'] = comps[6]\n ret[quotatype][comps[0]]['file-soft-limit'] = comps[7]\n ret[quotatype][comps[0]]['file-hard-limit'] = comps[8]\n ret[quotatype][comps[0]]['file-grace'] = comps[9]\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for managing quotas on POSIX-like systems. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import salt libs import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError log = logging.getLogger(__name__) # Define a function alias in order not to shadow built-in's __func_alias__ = { 'set_': 'set' } def __virtual__(): ''' Only work on POSIX-like systems with setquota binary available ''' if not salt.utils.platform.is_windows() \ and salt.utils.path.which('setquota'): return 'quota' return ( False, 'The quota execution module cannot be loaded: the module is only ' 'available on POSIX-like systems with the setquota binary available.' ) def _parse_quota(mount, opts): ''' Parse the output from repquota. Requires that -u -g are passed in ''' cmd = 'repquota -vp {0} {1}'.format(opts, mount) out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() mode = 'header' if '-u' in opts: quotatype = 'Users' elif '-g' in opts: quotatype = 'Groups' ret = {quotatype: {}} for line in out: if not line: continue comps = line.split() if mode == 'header': if 'Block grace time' in line: blockg, inodeg = line.split(';') blockgc = blockg.split(': ') inodegc = inodeg.split(': ') ret['Block Grace Time'] = blockgc[-1:] ret['Inode Grace Time'] = inodegc[-1:] elif line.startswith('-'): mode = 'quotas' elif mode == 'quotas': if len(comps) < 8: continue if not comps[0] in ret[quotatype]: ret[quotatype][comps[0]] = {} ret[quotatype][comps[0]]['block-used'] = comps[2] ret[quotatype][comps[0]]['block-soft-limit'] = comps[3] ret[quotatype][comps[0]]['block-hard-limit'] = comps[4] ret[quotatype][comps[0]]['block-grace'] = comps[5] ret[quotatype][comps[0]]['file-used'] = comps[6] ret[quotatype][comps[0]]['file-soft-limit'] = comps[7] ret[quotatype][comps[0]]['file-hard-limit'] = comps[8] ret[quotatype][comps[0]]['file-grace'] = comps[9] return ret def set_(device, **kwargs): ''' Calls out to setquota, for a specific user or group CLI Example: .. code-block:: bash salt '*' quota.set /media/data user=larry block-soft-limit=1048576 salt '*' quota.set /media/data group=painters file-hard-limit=1000 ''' empty = {'block-soft-limit': 0, 'block-hard-limit': 0, 'file-soft-limit': 0, 'file-hard-limit': 0} current = None cmd = 'setquota' if 'user' in kwargs: cmd += ' -u {0} '.format(kwargs['user']) parsed = _parse_quota(device, '-u') if kwargs['user'] in parsed: current = parsed['Users'][kwargs['user']] else: current = empty ret = 'User: {0}'.format(kwargs['user']) if 'group' in kwargs: if 'user' in kwargs: raise SaltInvocationError( 'Please specify a user or group, not both.' ) cmd += ' -g {0} '.format(kwargs['group']) parsed = _parse_quota(device, '-g') if kwargs['group'] in parsed: current = parsed['Groups'][kwargs['group']] else: current = empty ret = 'Group: {0}'.format(kwargs['group']) if not current: raise CommandExecutionError('A valid user or group was not found') for limit in ('block-soft-limit', 'block-hard-limit', 'file-soft-limit', 'file-hard-limit'): if limit in kwargs: current[limit] = kwargs[limit] cmd += '{0} {1} {2} {3} {4}'.format(current['block-soft-limit'], current['block-hard-limit'], current['file-soft-limit'], current['file-hard-limit'], device) result = __salt__['cmd.run_all'](cmd, python_shell=False) if result['retcode'] != 0: raise CommandExecutionError( 'Unable to set desired quota. Error follows: \n{0}' .format(result['stderr']) ) return {ret: current} def warn(): ''' Runs the warnquota command, to send warning emails to users who are over their quota limit. CLI Example: .. code-block:: bash salt '*' quota.warn ''' __salt__['cmd.run']('quotawarn') def stats(): ''' Runs the quotastats command, and returns the parsed output CLI Example: .. code-block:: bash salt '*' quota.stats ''' ret = {} out = __salt__['cmd.run']('quotastats').splitlines() for line in out: if not line: continue comps = line.split(': ') ret[comps[0]] = comps[1] return ret def on(device): ''' Turns on the quota system CLI Example: .. code-block:: bash salt '*' quota.on ''' cmd = 'quotaon {0}'.format(device) __salt__['cmd.run'](cmd, python_shell=False) return True def off(device): ''' Turns off the quota system CLI Example: .. code-block:: bash salt '*' quota.off ''' cmd = 'quotaoff {0}'.format(device) __salt__['cmd.run'](cmd, python_shell=False) return True def get_mode(device): ''' Report whether the quota system for this device is on or off CLI Example: .. code-block:: bash salt '*' quota.get_mode ''' ret = {} cmd = 'quotaon -p {0}'.format(device) out = __salt__['cmd.run'](cmd, python_shell=False) for line in out.splitlines(): comps = line.strip().split() if comps[3] not in ret: if comps[0].startswith('quotaon'): if comps[1].startswith('Mountpoint'): ret[comps[4]] = 'disabled' continue elif comps[1].startswith('Cannot'): ret[device] = 'Not found' return ret continue ret[comps[3]] = { 'device': comps[4].replace('(', '').replace(')', ''), } ret[comps[3]][comps[0]] = comps[6] return ret
saltstack/salt
salt/modules/quota.py
_parse_quota
python
def _parse_quota(mount, opts): ''' Parse the output from repquota. Requires that -u -g are passed in ''' cmd = 'repquota -vp {0} {1}'.format(opts, mount) out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() mode = 'header' if '-u' in opts: quotatype = 'Users' elif '-g' in opts: quotatype = 'Groups' ret = {quotatype: {}} for line in out: if not line: continue comps = line.split() if mode == 'header': if 'Block grace time' in line: blockg, inodeg = line.split(';') blockgc = blockg.split(': ') inodegc = inodeg.split(': ') ret['Block Grace Time'] = blockgc[-1:] ret['Inode Grace Time'] = inodegc[-1:] elif line.startswith('-'): mode = 'quotas' elif mode == 'quotas': if len(comps) < 8: continue if not comps[0] in ret[quotatype]: ret[quotatype][comps[0]] = {} ret[quotatype][comps[0]]['block-used'] = comps[2] ret[quotatype][comps[0]]['block-soft-limit'] = comps[3] ret[quotatype][comps[0]]['block-hard-limit'] = comps[4] ret[quotatype][comps[0]]['block-grace'] = comps[5] ret[quotatype][comps[0]]['file-used'] = comps[6] ret[quotatype][comps[0]]['file-soft-limit'] = comps[7] ret[quotatype][comps[0]]['file-hard-limit'] = comps[8] ret[quotatype][comps[0]]['file-grace'] = comps[9] return ret
Parse the output from repquota. Requires that -u -g are passed in
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/quota.py#L54-L94
null
# -*- coding: utf-8 -*- ''' Module for managing quotas on POSIX-like systems. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import salt libs import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError log = logging.getLogger(__name__) # Define a function alias in order not to shadow built-in's __func_alias__ = { 'set_': 'set' } def __virtual__(): ''' Only work on POSIX-like systems with setquota binary available ''' if not salt.utils.platform.is_windows() \ and salt.utils.path.which('setquota'): return 'quota' return ( False, 'The quota execution module cannot be loaded: the module is only ' 'available on POSIX-like systems with the setquota binary available.' ) def report(mount): ''' Report on quotas for a specific volume CLI Example: .. code-block:: bash salt '*' quota.report /media/data ''' ret = {mount: {}} ret[mount]['User Quotas'] = _parse_quota(mount, '-u') ret[mount]['Group Quotas'] = _parse_quota(mount, '-g') return ret def set_(device, **kwargs): ''' Calls out to setquota, for a specific user or group CLI Example: .. code-block:: bash salt '*' quota.set /media/data user=larry block-soft-limit=1048576 salt '*' quota.set /media/data group=painters file-hard-limit=1000 ''' empty = {'block-soft-limit': 0, 'block-hard-limit': 0, 'file-soft-limit': 0, 'file-hard-limit': 0} current = None cmd = 'setquota' if 'user' in kwargs: cmd += ' -u {0} '.format(kwargs['user']) parsed = _parse_quota(device, '-u') if kwargs['user'] in parsed: current = parsed['Users'][kwargs['user']] else: current = empty ret = 'User: {0}'.format(kwargs['user']) if 'group' in kwargs: if 'user' in kwargs: raise SaltInvocationError( 'Please specify a user or group, not both.' ) cmd += ' -g {0} '.format(kwargs['group']) parsed = _parse_quota(device, '-g') if kwargs['group'] in parsed: current = parsed['Groups'][kwargs['group']] else: current = empty ret = 'Group: {0}'.format(kwargs['group']) if not current: raise CommandExecutionError('A valid user or group was not found') for limit in ('block-soft-limit', 'block-hard-limit', 'file-soft-limit', 'file-hard-limit'): if limit in kwargs: current[limit] = kwargs[limit] cmd += '{0} {1} {2} {3} {4}'.format(current['block-soft-limit'], current['block-hard-limit'], current['file-soft-limit'], current['file-hard-limit'], device) result = __salt__['cmd.run_all'](cmd, python_shell=False) if result['retcode'] != 0: raise CommandExecutionError( 'Unable to set desired quota. Error follows: \n{0}' .format(result['stderr']) ) return {ret: current} def warn(): ''' Runs the warnquota command, to send warning emails to users who are over their quota limit. CLI Example: .. code-block:: bash salt '*' quota.warn ''' __salt__['cmd.run']('quotawarn') def stats(): ''' Runs the quotastats command, and returns the parsed output CLI Example: .. code-block:: bash salt '*' quota.stats ''' ret = {} out = __salt__['cmd.run']('quotastats').splitlines() for line in out: if not line: continue comps = line.split(': ') ret[comps[0]] = comps[1] return ret def on(device): ''' Turns on the quota system CLI Example: .. code-block:: bash salt '*' quota.on ''' cmd = 'quotaon {0}'.format(device) __salt__['cmd.run'](cmd, python_shell=False) return True def off(device): ''' Turns off the quota system CLI Example: .. code-block:: bash salt '*' quota.off ''' cmd = 'quotaoff {0}'.format(device) __salt__['cmd.run'](cmd, python_shell=False) return True def get_mode(device): ''' Report whether the quota system for this device is on or off CLI Example: .. code-block:: bash salt '*' quota.get_mode ''' ret = {} cmd = 'quotaon -p {0}'.format(device) out = __salt__['cmd.run'](cmd, python_shell=False) for line in out.splitlines(): comps = line.strip().split() if comps[3] not in ret: if comps[0].startswith('quotaon'): if comps[1].startswith('Mountpoint'): ret[comps[4]] = 'disabled' continue elif comps[1].startswith('Cannot'): ret[device] = 'Not found' return ret continue ret[comps[3]] = { 'device': comps[4].replace('(', '').replace(')', ''), } ret[comps[3]][comps[0]] = comps[6] return ret
saltstack/salt
salt/modules/quota.py
set_
python
def set_(device, **kwargs): ''' Calls out to setquota, for a specific user or group CLI Example: .. code-block:: bash salt '*' quota.set /media/data user=larry block-soft-limit=1048576 salt '*' quota.set /media/data group=painters file-hard-limit=1000 ''' empty = {'block-soft-limit': 0, 'block-hard-limit': 0, 'file-soft-limit': 0, 'file-hard-limit': 0} current = None cmd = 'setquota' if 'user' in kwargs: cmd += ' -u {0} '.format(kwargs['user']) parsed = _parse_quota(device, '-u') if kwargs['user'] in parsed: current = parsed['Users'][kwargs['user']] else: current = empty ret = 'User: {0}'.format(kwargs['user']) if 'group' in kwargs: if 'user' in kwargs: raise SaltInvocationError( 'Please specify a user or group, not both.' ) cmd += ' -g {0} '.format(kwargs['group']) parsed = _parse_quota(device, '-g') if kwargs['group'] in parsed: current = parsed['Groups'][kwargs['group']] else: current = empty ret = 'Group: {0}'.format(kwargs['group']) if not current: raise CommandExecutionError('A valid user or group was not found') for limit in ('block-soft-limit', 'block-hard-limit', 'file-soft-limit', 'file-hard-limit'): if limit in kwargs: current[limit] = kwargs[limit] cmd += '{0} {1} {2} {3} {4}'.format(current['block-soft-limit'], current['block-hard-limit'], current['file-soft-limit'], current['file-hard-limit'], device) result = __salt__['cmd.run_all'](cmd, python_shell=False) if result['retcode'] != 0: raise CommandExecutionError( 'Unable to set desired quota. Error follows: \n{0}' .format(result['stderr']) ) return {ret: current}
Calls out to setquota, for a specific user or group CLI Example: .. code-block:: bash salt '*' quota.set /media/data user=larry block-soft-limit=1048576 salt '*' quota.set /media/data group=painters file-hard-limit=1000
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/quota.py#L97-L155
[ "def _parse_quota(mount, opts):\n '''\n Parse the output from repquota. Requires that -u -g are passed in\n '''\n cmd = 'repquota -vp {0} {1}'.format(opts, mount)\n out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()\n mode = 'header'\n\n if '-u' in opts:\n quotatype = 'Users'\n elif '-g' in opts:\n quotatype = 'Groups'\n ret = {quotatype: {}}\n\n for line in out:\n if not line:\n continue\n comps = line.split()\n if mode == 'header':\n if 'Block grace time' in line:\n blockg, inodeg = line.split(';')\n blockgc = blockg.split(': ')\n inodegc = inodeg.split(': ')\n ret['Block Grace Time'] = blockgc[-1:]\n ret['Inode Grace Time'] = inodegc[-1:]\n elif line.startswith('-'):\n mode = 'quotas'\n elif mode == 'quotas':\n if len(comps) < 8:\n continue\n if not comps[0] in ret[quotatype]:\n ret[quotatype][comps[0]] = {}\n ret[quotatype][comps[0]]['block-used'] = comps[2]\n ret[quotatype][comps[0]]['block-soft-limit'] = comps[3]\n ret[quotatype][comps[0]]['block-hard-limit'] = comps[4]\n ret[quotatype][comps[0]]['block-grace'] = comps[5]\n ret[quotatype][comps[0]]['file-used'] = comps[6]\n ret[quotatype][comps[0]]['file-soft-limit'] = comps[7]\n ret[quotatype][comps[0]]['file-hard-limit'] = comps[8]\n ret[quotatype][comps[0]]['file-grace'] = comps[9]\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for managing quotas on POSIX-like systems. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import salt libs import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError log = logging.getLogger(__name__) # Define a function alias in order not to shadow built-in's __func_alias__ = { 'set_': 'set' } def __virtual__(): ''' Only work on POSIX-like systems with setquota binary available ''' if not salt.utils.platform.is_windows() \ and salt.utils.path.which('setquota'): return 'quota' return ( False, 'The quota execution module cannot be loaded: the module is only ' 'available on POSIX-like systems with the setquota binary available.' ) def report(mount): ''' Report on quotas for a specific volume CLI Example: .. code-block:: bash salt '*' quota.report /media/data ''' ret = {mount: {}} ret[mount]['User Quotas'] = _parse_quota(mount, '-u') ret[mount]['Group Quotas'] = _parse_quota(mount, '-g') return ret def _parse_quota(mount, opts): ''' Parse the output from repquota. Requires that -u -g are passed in ''' cmd = 'repquota -vp {0} {1}'.format(opts, mount) out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() mode = 'header' if '-u' in opts: quotatype = 'Users' elif '-g' in opts: quotatype = 'Groups' ret = {quotatype: {}} for line in out: if not line: continue comps = line.split() if mode == 'header': if 'Block grace time' in line: blockg, inodeg = line.split(';') blockgc = blockg.split(': ') inodegc = inodeg.split(': ') ret['Block Grace Time'] = blockgc[-1:] ret['Inode Grace Time'] = inodegc[-1:] elif line.startswith('-'): mode = 'quotas' elif mode == 'quotas': if len(comps) < 8: continue if not comps[0] in ret[quotatype]: ret[quotatype][comps[0]] = {} ret[quotatype][comps[0]]['block-used'] = comps[2] ret[quotatype][comps[0]]['block-soft-limit'] = comps[3] ret[quotatype][comps[0]]['block-hard-limit'] = comps[4] ret[quotatype][comps[0]]['block-grace'] = comps[5] ret[quotatype][comps[0]]['file-used'] = comps[6] ret[quotatype][comps[0]]['file-soft-limit'] = comps[7] ret[quotatype][comps[0]]['file-hard-limit'] = comps[8] ret[quotatype][comps[0]]['file-grace'] = comps[9] return ret def warn(): ''' Runs the warnquota command, to send warning emails to users who are over their quota limit. CLI Example: .. code-block:: bash salt '*' quota.warn ''' __salt__['cmd.run']('quotawarn') def stats(): ''' Runs the quotastats command, and returns the parsed output CLI Example: .. code-block:: bash salt '*' quota.stats ''' ret = {} out = __salt__['cmd.run']('quotastats').splitlines() for line in out: if not line: continue comps = line.split(': ') ret[comps[0]] = comps[1] return ret def on(device): ''' Turns on the quota system CLI Example: .. code-block:: bash salt '*' quota.on ''' cmd = 'quotaon {0}'.format(device) __salt__['cmd.run'](cmd, python_shell=False) return True def off(device): ''' Turns off the quota system CLI Example: .. code-block:: bash salt '*' quota.off ''' cmd = 'quotaoff {0}'.format(device) __salt__['cmd.run'](cmd, python_shell=False) return True def get_mode(device): ''' Report whether the quota system for this device is on or off CLI Example: .. code-block:: bash salt '*' quota.get_mode ''' ret = {} cmd = 'quotaon -p {0}'.format(device) out = __salt__['cmd.run'](cmd, python_shell=False) for line in out.splitlines(): comps = line.strip().split() if comps[3] not in ret: if comps[0].startswith('quotaon'): if comps[1].startswith('Mountpoint'): ret[comps[4]] = 'disabled' continue elif comps[1].startswith('Cannot'): ret[device] = 'Not found' return ret continue ret[comps[3]] = { 'device': comps[4].replace('(', '').replace(')', ''), } ret[comps[3]][comps[0]] = comps[6] return ret
saltstack/salt
salt/modules/quota.py
stats
python
def stats(): ''' Runs the quotastats command, and returns the parsed output CLI Example: .. code-block:: bash salt '*' quota.stats ''' ret = {} out = __salt__['cmd.run']('quotastats').splitlines() for line in out: if not line: continue comps = line.split(': ') ret[comps[0]] = comps[1] return ret
Runs the quotastats command, and returns the parsed output CLI Example: .. code-block:: bash salt '*' quota.stats
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/quota.py#L172-L190
null
# -*- coding: utf-8 -*- ''' Module for managing quotas on POSIX-like systems. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import salt libs import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError log = logging.getLogger(__name__) # Define a function alias in order not to shadow built-in's __func_alias__ = { 'set_': 'set' } def __virtual__(): ''' Only work on POSIX-like systems with setquota binary available ''' if not salt.utils.platform.is_windows() \ and salt.utils.path.which('setquota'): return 'quota' return ( False, 'The quota execution module cannot be loaded: the module is only ' 'available on POSIX-like systems with the setquota binary available.' ) def report(mount): ''' Report on quotas for a specific volume CLI Example: .. code-block:: bash salt '*' quota.report /media/data ''' ret = {mount: {}} ret[mount]['User Quotas'] = _parse_quota(mount, '-u') ret[mount]['Group Quotas'] = _parse_quota(mount, '-g') return ret def _parse_quota(mount, opts): ''' Parse the output from repquota. Requires that -u -g are passed in ''' cmd = 'repquota -vp {0} {1}'.format(opts, mount) out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() mode = 'header' if '-u' in opts: quotatype = 'Users' elif '-g' in opts: quotatype = 'Groups' ret = {quotatype: {}} for line in out: if not line: continue comps = line.split() if mode == 'header': if 'Block grace time' in line: blockg, inodeg = line.split(';') blockgc = blockg.split(': ') inodegc = inodeg.split(': ') ret['Block Grace Time'] = blockgc[-1:] ret['Inode Grace Time'] = inodegc[-1:] elif line.startswith('-'): mode = 'quotas' elif mode == 'quotas': if len(comps) < 8: continue if not comps[0] in ret[quotatype]: ret[quotatype][comps[0]] = {} ret[quotatype][comps[0]]['block-used'] = comps[2] ret[quotatype][comps[0]]['block-soft-limit'] = comps[3] ret[quotatype][comps[0]]['block-hard-limit'] = comps[4] ret[quotatype][comps[0]]['block-grace'] = comps[5] ret[quotatype][comps[0]]['file-used'] = comps[6] ret[quotatype][comps[0]]['file-soft-limit'] = comps[7] ret[quotatype][comps[0]]['file-hard-limit'] = comps[8] ret[quotatype][comps[0]]['file-grace'] = comps[9] return ret def set_(device, **kwargs): ''' Calls out to setquota, for a specific user or group CLI Example: .. code-block:: bash salt '*' quota.set /media/data user=larry block-soft-limit=1048576 salt '*' quota.set /media/data group=painters file-hard-limit=1000 ''' empty = {'block-soft-limit': 0, 'block-hard-limit': 0, 'file-soft-limit': 0, 'file-hard-limit': 0} current = None cmd = 'setquota' if 'user' in kwargs: cmd += ' -u {0} '.format(kwargs['user']) parsed = _parse_quota(device, '-u') if kwargs['user'] in parsed: current = parsed['Users'][kwargs['user']] else: current = empty ret = 'User: {0}'.format(kwargs['user']) if 'group' in kwargs: if 'user' in kwargs: raise SaltInvocationError( 'Please specify a user or group, not both.' ) cmd += ' -g {0} '.format(kwargs['group']) parsed = _parse_quota(device, '-g') if kwargs['group'] in parsed: current = parsed['Groups'][kwargs['group']] else: current = empty ret = 'Group: {0}'.format(kwargs['group']) if not current: raise CommandExecutionError('A valid user or group was not found') for limit in ('block-soft-limit', 'block-hard-limit', 'file-soft-limit', 'file-hard-limit'): if limit in kwargs: current[limit] = kwargs[limit] cmd += '{0} {1} {2} {3} {4}'.format(current['block-soft-limit'], current['block-hard-limit'], current['file-soft-limit'], current['file-hard-limit'], device) result = __salt__['cmd.run_all'](cmd, python_shell=False) if result['retcode'] != 0: raise CommandExecutionError( 'Unable to set desired quota. Error follows: \n{0}' .format(result['stderr']) ) return {ret: current} def warn(): ''' Runs the warnquota command, to send warning emails to users who are over their quota limit. CLI Example: .. code-block:: bash salt '*' quota.warn ''' __salt__['cmd.run']('quotawarn') def on(device): ''' Turns on the quota system CLI Example: .. code-block:: bash salt '*' quota.on ''' cmd = 'quotaon {0}'.format(device) __salt__['cmd.run'](cmd, python_shell=False) return True def off(device): ''' Turns off the quota system CLI Example: .. code-block:: bash salt '*' quota.off ''' cmd = 'quotaoff {0}'.format(device) __salt__['cmd.run'](cmd, python_shell=False) return True def get_mode(device): ''' Report whether the quota system for this device is on or off CLI Example: .. code-block:: bash salt '*' quota.get_mode ''' ret = {} cmd = 'quotaon -p {0}'.format(device) out = __salt__['cmd.run'](cmd, python_shell=False) for line in out.splitlines(): comps = line.strip().split() if comps[3] not in ret: if comps[0].startswith('quotaon'): if comps[1].startswith('Mountpoint'): ret[comps[4]] = 'disabled' continue elif comps[1].startswith('Cannot'): ret[device] = 'Not found' return ret continue ret[comps[3]] = { 'device': comps[4].replace('(', '').replace(')', ''), } ret[comps[3]][comps[0]] = comps[6] return ret
saltstack/salt
salt/modules/quota.py
on
python
def on(device): ''' Turns on the quota system CLI Example: .. code-block:: bash salt '*' quota.on ''' cmd = 'quotaon {0}'.format(device) __salt__['cmd.run'](cmd, python_shell=False) return True
Turns on the quota system CLI Example: .. code-block:: bash salt '*' quota.on
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/quota.py#L193-L205
null
# -*- coding: utf-8 -*- ''' Module for managing quotas on POSIX-like systems. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import salt libs import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError log = logging.getLogger(__name__) # Define a function alias in order not to shadow built-in's __func_alias__ = { 'set_': 'set' } def __virtual__(): ''' Only work on POSIX-like systems with setquota binary available ''' if not salt.utils.platform.is_windows() \ and salt.utils.path.which('setquota'): return 'quota' return ( False, 'The quota execution module cannot be loaded: the module is only ' 'available on POSIX-like systems with the setquota binary available.' ) def report(mount): ''' Report on quotas for a specific volume CLI Example: .. code-block:: bash salt '*' quota.report /media/data ''' ret = {mount: {}} ret[mount]['User Quotas'] = _parse_quota(mount, '-u') ret[mount]['Group Quotas'] = _parse_quota(mount, '-g') return ret def _parse_quota(mount, opts): ''' Parse the output from repquota. Requires that -u -g are passed in ''' cmd = 'repquota -vp {0} {1}'.format(opts, mount) out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() mode = 'header' if '-u' in opts: quotatype = 'Users' elif '-g' in opts: quotatype = 'Groups' ret = {quotatype: {}} for line in out: if not line: continue comps = line.split() if mode == 'header': if 'Block grace time' in line: blockg, inodeg = line.split(';') blockgc = blockg.split(': ') inodegc = inodeg.split(': ') ret['Block Grace Time'] = blockgc[-1:] ret['Inode Grace Time'] = inodegc[-1:] elif line.startswith('-'): mode = 'quotas' elif mode == 'quotas': if len(comps) < 8: continue if not comps[0] in ret[quotatype]: ret[quotatype][comps[0]] = {} ret[quotatype][comps[0]]['block-used'] = comps[2] ret[quotatype][comps[0]]['block-soft-limit'] = comps[3] ret[quotatype][comps[0]]['block-hard-limit'] = comps[4] ret[quotatype][comps[0]]['block-grace'] = comps[5] ret[quotatype][comps[0]]['file-used'] = comps[6] ret[quotatype][comps[0]]['file-soft-limit'] = comps[7] ret[quotatype][comps[0]]['file-hard-limit'] = comps[8] ret[quotatype][comps[0]]['file-grace'] = comps[9] return ret def set_(device, **kwargs): ''' Calls out to setquota, for a specific user or group CLI Example: .. code-block:: bash salt '*' quota.set /media/data user=larry block-soft-limit=1048576 salt '*' quota.set /media/data group=painters file-hard-limit=1000 ''' empty = {'block-soft-limit': 0, 'block-hard-limit': 0, 'file-soft-limit': 0, 'file-hard-limit': 0} current = None cmd = 'setquota' if 'user' in kwargs: cmd += ' -u {0} '.format(kwargs['user']) parsed = _parse_quota(device, '-u') if kwargs['user'] in parsed: current = parsed['Users'][kwargs['user']] else: current = empty ret = 'User: {0}'.format(kwargs['user']) if 'group' in kwargs: if 'user' in kwargs: raise SaltInvocationError( 'Please specify a user or group, not both.' ) cmd += ' -g {0} '.format(kwargs['group']) parsed = _parse_quota(device, '-g') if kwargs['group'] in parsed: current = parsed['Groups'][kwargs['group']] else: current = empty ret = 'Group: {0}'.format(kwargs['group']) if not current: raise CommandExecutionError('A valid user or group was not found') for limit in ('block-soft-limit', 'block-hard-limit', 'file-soft-limit', 'file-hard-limit'): if limit in kwargs: current[limit] = kwargs[limit] cmd += '{0} {1} {2} {3} {4}'.format(current['block-soft-limit'], current['block-hard-limit'], current['file-soft-limit'], current['file-hard-limit'], device) result = __salt__['cmd.run_all'](cmd, python_shell=False) if result['retcode'] != 0: raise CommandExecutionError( 'Unable to set desired quota. Error follows: \n{0}' .format(result['stderr']) ) return {ret: current} def warn(): ''' Runs the warnquota command, to send warning emails to users who are over their quota limit. CLI Example: .. code-block:: bash salt '*' quota.warn ''' __salt__['cmd.run']('quotawarn') def stats(): ''' Runs the quotastats command, and returns the parsed output CLI Example: .. code-block:: bash salt '*' quota.stats ''' ret = {} out = __salt__['cmd.run']('quotastats').splitlines() for line in out: if not line: continue comps = line.split(': ') ret[comps[0]] = comps[1] return ret def off(device): ''' Turns off the quota system CLI Example: .. code-block:: bash salt '*' quota.off ''' cmd = 'quotaoff {0}'.format(device) __salt__['cmd.run'](cmd, python_shell=False) return True def get_mode(device): ''' Report whether the quota system for this device is on or off CLI Example: .. code-block:: bash salt '*' quota.get_mode ''' ret = {} cmd = 'quotaon -p {0}'.format(device) out = __salt__['cmd.run'](cmd, python_shell=False) for line in out.splitlines(): comps = line.strip().split() if comps[3] not in ret: if comps[0].startswith('quotaon'): if comps[1].startswith('Mountpoint'): ret[comps[4]] = 'disabled' continue elif comps[1].startswith('Cannot'): ret[device] = 'Not found' return ret continue ret[comps[3]] = { 'device': comps[4].replace('(', '').replace(')', ''), } ret[comps[3]][comps[0]] = comps[6] return ret
saltstack/salt
salt/modules/quota.py
off
python
def off(device): ''' Turns off the quota system CLI Example: .. code-block:: bash salt '*' quota.off ''' cmd = 'quotaoff {0}'.format(device) __salt__['cmd.run'](cmd, python_shell=False) return True
Turns off the quota system CLI Example: .. code-block:: bash salt '*' quota.off
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/quota.py#L208-L220
null
# -*- coding: utf-8 -*- ''' Module for managing quotas on POSIX-like systems. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import salt libs import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError log = logging.getLogger(__name__) # Define a function alias in order not to shadow built-in's __func_alias__ = { 'set_': 'set' } def __virtual__(): ''' Only work on POSIX-like systems with setquota binary available ''' if not salt.utils.platform.is_windows() \ and salt.utils.path.which('setquota'): return 'quota' return ( False, 'The quota execution module cannot be loaded: the module is only ' 'available on POSIX-like systems with the setquota binary available.' ) def report(mount): ''' Report on quotas for a specific volume CLI Example: .. code-block:: bash salt '*' quota.report /media/data ''' ret = {mount: {}} ret[mount]['User Quotas'] = _parse_quota(mount, '-u') ret[mount]['Group Quotas'] = _parse_quota(mount, '-g') return ret def _parse_quota(mount, opts): ''' Parse the output from repquota. Requires that -u -g are passed in ''' cmd = 'repquota -vp {0} {1}'.format(opts, mount) out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() mode = 'header' if '-u' in opts: quotatype = 'Users' elif '-g' in opts: quotatype = 'Groups' ret = {quotatype: {}} for line in out: if not line: continue comps = line.split() if mode == 'header': if 'Block grace time' in line: blockg, inodeg = line.split(';') blockgc = blockg.split(': ') inodegc = inodeg.split(': ') ret['Block Grace Time'] = blockgc[-1:] ret['Inode Grace Time'] = inodegc[-1:] elif line.startswith('-'): mode = 'quotas' elif mode == 'quotas': if len(comps) < 8: continue if not comps[0] in ret[quotatype]: ret[quotatype][comps[0]] = {} ret[quotatype][comps[0]]['block-used'] = comps[2] ret[quotatype][comps[0]]['block-soft-limit'] = comps[3] ret[quotatype][comps[0]]['block-hard-limit'] = comps[4] ret[quotatype][comps[0]]['block-grace'] = comps[5] ret[quotatype][comps[0]]['file-used'] = comps[6] ret[quotatype][comps[0]]['file-soft-limit'] = comps[7] ret[quotatype][comps[0]]['file-hard-limit'] = comps[8] ret[quotatype][comps[0]]['file-grace'] = comps[9] return ret def set_(device, **kwargs): ''' Calls out to setquota, for a specific user or group CLI Example: .. code-block:: bash salt '*' quota.set /media/data user=larry block-soft-limit=1048576 salt '*' quota.set /media/data group=painters file-hard-limit=1000 ''' empty = {'block-soft-limit': 0, 'block-hard-limit': 0, 'file-soft-limit': 0, 'file-hard-limit': 0} current = None cmd = 'setquota' if 'user' in kwargs: cmd += ' -u {0} '.format(kwargs['user']) parsed = _parse_quota(device, '-u') if kwargs['user'] in parsed: current = parsed['Users'][kwargs['user']] else: current = empty ret = 'User: {0}'.format(kwargs['user']) if 'group' in kwargs: if 'user' in kwargs: raise SaltInvocationError( 'Please specify a user or group, not both.' ) cmd += ' -g {0} '.format(kwargs['group']) parsed = _parse_quota(device, '-g') if kwargs['group'] in parsed: current = parsed['Groups'][kwargs['group']] else: current = empty ret = 'Group: {0}'.format(kwargs['group']) if not current: raise CommandExecutionError('A valid user or group was not found') for limit in ('block-soft-limit', 'block-hard-limit', 'file-soft-limit', 'file-hard-limit'): if limit in kwargs: current[limit] = kwargs[limit] cmd += '{0} {1} {2} {3} {4}'.format(current['block-soft-limit'], current['block-hard-limit'], current['file-soft-limit'], current['file-hard-limit'], device) result = __salt__['cmd.run_all'](cmd, python_shell=False) if result['retcode'] != 0: raise CommandExecutionError( 'Unable to set desired quota. Error follows: \n{0}' .format(result['stderr']) ) return {ret: current} def warn(): ''' Runs the warnquota command, to send warning emails to users who are over their quota limit. CLI Example: .. code-block:: bash salt '*' quota.warn ''' __salt__['cmd.run']('quotawarn') def stats(): ''' Runs the quotastats command, and returns the parsed output CLI Example: .. code-block:: bash salt '*' quota.stats ''' ret = {} out = __salt__['cmd.run']('quotastats').splitlines() for line in out: if not line: continue comps = line.split(': ') ret[comps[0]] = comps[1] return ret def on(device): ''' Turns on the quota system CLI Example: .. code-block:: bash salt '*' quota.on ''' cmd = 'quotaon {0}'.format(device) __salt__['cmd.run'](cmd, python_shell=False) return True def get_mode(device): ''' Report whether the quota system for this device is on or off CLI Example: .. code-block:: bash salt '*' quota.get_mode ''' ret = {} cmd = 'quotaon -p {0}'.format(device) out = __salt__['cmd.run'](cmd, python_shell=False) for line in out.splitlines(): comps = line.strip().split() if comps[3] not in ret: if comps[0].startswith('quotaon'): if comps[1].startswith('Mountpoint'): ret[comps[4]] = 'disabled' continue elif comps[1].startswith('Cannot'): ret[device] = 'Not found' return ret continue ret[comps[3]] = { 'device': comps[4].replace('(', '').replace(')', ''), } ret[comps[3]][comps[0]] = comps[6] return ret
saltstack/salt
salt/modules/quota.py
get_mode
python
def get_mode(device): ''' Report whether the quota system for this device is on or off CLI Example: .. code-block:: bash salt '*' quota.get_mode ''' ret = {} cmd = 'quotaon -p {0}'.format(device) out = __salt__['cmd.run'](cmd, python_shell=False) for line in out.splitlines(): comps = line.strip().split() if comps[3] not in ret: if comps[0].startswith('quotaon'): if comps[1].startswith('Mountpoint'): ret[comps[4]] = 'disabled' continue elif comps[1].startswith('Cannot'): ret[device] = 'Not found' return ret continue ret[comps[3]] = { 'device': comps[4].replace('(', '').replace(')', ''), } ret[comps[3]][comps[0]] = comps[6] return ret
Report whether the quota system for this device is on or off CLI Example: .. code-block:: bash salt '*' quota.get_mode
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/quota.py#L223-L251
null
# -*- coding: utf-8 -*- ''' Module for managing quotas on POSIX-like systems. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging # Import salt libs import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError log = logging.getLogger(__name__) # Define a function alias in order not to shadow built-in's __func_alias__ = { 'set_': 'set' } def __virtual__(): ''' Only work on POSIX-like systems with setquota binary available ''' if not salt.utils.platform.is_windows() \ and salt.utils.path.which('setquota'): return 'quota' return ( False, 'The quota execution module cannot be loaded: the module is only ' 'available on POSIX-like systems with the setquota binary available.' ) def report(mount): ''' Report on quotas for a specific volume CLI Example: .. code-block:: bash salt '*' quota.report /media/data ''' ret = {mount: {}} ret[mount]['User Quotas'] = _parse_quota(mount, '-u') ret[mount]['Group Quotas'] = _parse_quota(mount, '-g') return ret def _parse_quota(mount, opts): ''' Parse the output from repquota. Requires that -u -g are passed in ''' cmd = 'repquota -vp {0} {1}'.format(opts, mount) out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() mode = 'header' if '-u' in opts: quotatype = 'Users' elif '-g' in opts: quotatype = 'Groups' ret = {quotatype: {}} for line in out: if not line: continue comps = line.split() if mode == 'header': if 'Block grace time' in line: blockg, inodeg = line.split(';') blockgc = blockg.split(': ') inodegc = inodeg.split(': ') ret['Block Grace Time'] = blockgc[-1:] ret['Inode Grace Time'] = inodegc[-1:] elif line.startswith('-'): mode = 'quotas' elif mode == 'quotas': if len(comps) < 8: continue if not comps[0] in ret[quotatype]: ret[quotatype][comps[0]] = {} ret[quotatype][comps[0]]['block-used'] = comps[2] ret[quotatype][comps[0]]['block-soft-limit'] = comps[3] ret[quotatype][comps[0]]['block-hard-limit'] = comps[4] ret[quotatype][comps[0]]['block-grace'] = comps[5] ret[quotatype][comps[0]]['file-used'] = comps[6] ret[quotatype][comps[0]]['file-soft-limit'] = comps[7] ret[quotatype][comps[0]]['file-hard-limit'] = comps[8] ret[quotatype][comps[0]]['file-grace'] = comps[9] return ret def set_(device, **kwargs): ''' Calls out to setquota, for a specific user or group CLI Example: .. code-block:: bash salt '*' quota.set /media/data user=larry block-soft-limit=1048576 salt '*' quota.set /media/data group=painters file-hard-limit=1000 ''' empty = {'block-soft-limit': 0, 'block-hard-limit': 0, 'file-soft-limit': 0, 'file-hard-limit': 0} current = None cmd = 'setquota' if 'user' in kwargs: cmd += ' -u {0} '.format(kwargs['user']) parsed = _parse_quota(device, '-u') if kwargs['user'] in parsed: current = parsed['Users'][kwargs['user']] else: current = empty ret = 'User: {0}'.format(kwargs['user']) if 'group' in kwargs: if 'user' in kwargs: raise SaltInvocationError( 'Please specify a user or group, not both.' ) cmd += ' -g {0} '.format(kwargs['group']) parsed = _parse_quota(device, '-g') if kwargs['group'] in parsed: current = parsed['Groups'][kwargs['group']] else: current = empty ret = 'Group: {0}'.format(kwargs['group']) if not current: raise CommandExecutionError('A valid user or group was not found') for limit in ('block-soft-limit', 'block-hard-limit', 'file-soft-limit', 'file-hard-limit'): if limit in kwargs: current[limit] = kwargs[limit] cmd += '{0} {1} {2} {3} {4}'.format(current['block-soft-limit'], current['block-hard-limit'], current['file-soft-limit'], current['file-hard-limit'], device) result = __salt__['cmd.run_all'](cmd, python_shell=False) if result['retcode'] != 0: raise CommandExecutionError( 'Unable to set desired quota. Error follows: \n{0}' .format(result['stderr']) ) return {ret: current} def warn(): ''' Runs the warnquota command, to send warning emails to users who are over their quota limit. CLI Example: .. code-block:: bash salt '*' quota.warn ''' __salt__['cmd.run']('quotawarn') def stats(): ''' Runs the quotastats command, and returns the parsed output CLI Example: .. code-block:: bash salt '*' quota.stats ''' ret = {} out = __salt__['cmd.run']('quotastats').splitlines() for line in out: if not line: continue comps = line.split(': ') ret[comps[0]] = comps[1] return ret def on(device): ''' Turns on the quota system CLI Example: .. code-block:: bash salt '*' quota.on ''' cmd = 'quotaon {0}'.format(device) __salt__['cmd.run'](cmd, python_shell=False) return True def off(device): ''' Turns off the quota system CLI Example: .. code-block:: bash salt '*' quota.off ''' cmd = 'quotaoff {0}'.format(device) __salt__['cmd.run'](cmd, python_shell=False) return True
saltstack/salt
salt/states/pagerduty_user.py
present
python
def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs): ''' Ensure pagerduty user exists. Arguments match those supported by https://developer.pagerduty.com/documentation/rest/users/create. ''' return __salt__['pagerduty_util.resource_present']('users', ['email', 'name', 'id'], None, profile, subdomain, api_key, **kwargs)
Ensure pagerduty user exists. Arguments match those supported by https://developer.pagerduty.com/documentation/rest/users/create.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_user.py#L28-L40
null
# -*- coding: utf-8 -*- ''' Manage PagerDuty users. Example: .. code-block:: yaml ensure bruce test user 1: pagerduty.user_present: - name: 'Bruce TestUser1' - email: bruce+test1@lyft.com - requester_id: P1GV5NT ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): ''' Only load if the pygerduty module is available in __salt__ ''' return 'pagerduty_user' if 'pagerduty_util.get_resource' in __salt__ else False def absent(profile='pagerduty', subdomain=None, api_key=None, **kwargs): ''' Ensure pagerduty user does not exist. Name can be pagerduty id, email address, or user name. ''' return __salt__['pagerduty_util.resource_absent']('users', ['email', 'name', 'id'], profile, subdomain, api_key, **kwargs)
saltstack/salt
salt/modules/rsync.py
_check
python
def _check(delete, force, update, passwordfile, exclude, excludefrom, dryrun, rsh): ''' Generate rsync options ''' options = ['-avz'] if delete: options.append('--delete') if force: options.append('--force') if update: options.append('--update') if rsh: options.append('--rsh={0}'.format(rsh)) if passwordfile: options.extend(['--password-file', passwordfile]) if excludefrom: options.extend(['--exclude-from', excludefrom]) if exclude: exclude = False if exclude: if isinstance(exclude, list): for ex_ in exclude: options.extend(['--exclude', ex_]) else: options.extend(['--exclude', exclude]) if dryrun: options.append('--dry-run') return options
Generate rsync options
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rsync.py#L38-L66
null
# -*- coding: utf-8 -*- ''' Wrapper for rsync .. versionadded:: 2014.1.0 This data can also be passed into :ref:`pillar <pillar-walk-through>`. Options passed into opts will overwrite options passed into pillar. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import errno import logging import re import tempfile # Import salt libs import salt.utils.files import salt.utils.path from salt.exceptions import CommandExecutionError, SaltInvocationError log = logging.getLogger(__name__) __virtualname__ = 'rsync' def __virtual__(): ''' Only load module if rsync binary is present ''' if salt.utils.path.which('rsync'): return __virtualname__ return (False, 'The rsync execution module cannot be loaded: ' 'the rsync binary is not in the path.') def rsync(src, dst, delete=False, force=False, update=False, passwordfile=None, exclude=None, excludefrom=None, dryrun=False, rsh=None, additional_opts=None, saltenv='base'): ''' .. versionchanged:: 2016.3.0 Return data now contains just the output of the rsync command, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Rsync files from src to dst src The source location where files will be rsynced from. dst The destination location where files will be rsynced to. delete : False Whether to enable the rsync `--delete` flag, which will delete extraneous files from dest dirs force : False Whether to enable the rsync `--force` flag, which will force deletion of dirs even if not empty. update : False Whether to enable the rsync `--update` flag, which forces rsync to skip any files which exist on the destination and have a modified time that is newer than the source file. passwordfile A file that contains a password for accessing an rsync daemon. The file should contain just the password. exclude Whether to enable the rsync `--exclude` flag, which will exclude files matching a PATTERN. excludefrom Whether to enable the rsync `--excludefrom` flag, which will read exclude patterns from a file. dryrun : False Whether to enable the rsync `--dry-run` flag, which will perform a trial run with no changes made. rsh Whether to enable the rsync `--rsh` flag, to specify the remote shell to use. additional_opts Any additional rsync options, should be specified as a list. saltenv Specify a salt fileserver environment to be used. CLI Example: .. code-block:: bash salt '*' rsync.rsync /path/to/src /path/to/dest delete=True update=True passwordfile=/etc/pass.crt exclude=exclude/dir salt '*' rsync.rsync /path/to/src delete=True excludefrom=/xx.ini salt '*' rsync.rsync /path/to/src delete=True exclude='[exclude1/dir,exclude2/dir]' additional_opts='["--partial", "--bwlimit=5000"]' ''' if not src: src = __salt__['config.option']('rsync.src') if not dst: dst = __salt__['config.option']('rsync.dst') if not delete: delete = __salt__['config.option']('rsync.delete') if not force: force = __salt__['config.option']('rsync.force') if not update: update = __salt__['config.option']('rsync.update') if not passwordfile: passwordfile = __salt__['config.option']('rsync.passwordfile') if not exclude: exclude = __salt__['config.option']('rsync.exclude') if not excludefrom: excludefrom = __salt__['config.option']('rsync.excludefrom') if not dryrun: dryrun = __salt__['config.option']('rsync.dryrun') if not rsh: rsh = __salt__['config.option']('rsync.rsh') if not src or not dst: raise SaltInvocationError('src and dst cannot be empty') tmp_src = None if src.startswith('salt://'): _src = src _path = re.sub('salt://', '', _src) src_is_dir = False if _path in __salt__['cp.list_master_dirs'](saltenv=saltenv): src_is_dir = True if src_is_dir: tmp_src = tempfile.mkdtemp() dir_src = __salt__['cp.get_dir'](_src, tmp_src, saltenv) if dir_src: src = tmp_src # Ensure src ends in / so we # get the contents not the tmpdir # itself. if not src.endswith('/'): src = '{0}/'.format(src) else: raise CommandExecutionError('{0} does not exist'.format(src)) else: tmp_src = salt.utils.files.mkstemp() file_src = __salt__['cp.get_file'](_src, tmp_src, saltenv) if file_src: src = tmp_src else: raise CommandExecutionError('{0} does not exist'.format(src)) option = _check(delete, force, update, passwordfile, exclude, excludefrom, dryrun, rsh) if additional_opts and isinstance(additional_opts, list): option = option + additional_opts cmd = ['rsync'] + option + [src, dst] log.debug('Running rsync command: %s', cmd) try: return __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) finally: if tmp_src: __salt__['file.remove'](tmp_src) def version(): ''' .. versionchanged:: 2016.3.0 Return data now contains just the version number as a string, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Returns rsync version CLI Example: .. code-block:: bash salt '*' rsync.version ''' try: out = __salt__['cmd.run_stdout']( ['rsync', '--version'], python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) try: return out.split('\n')[0].split()[2] except IndexError: raise CommandExecutionError('Unable to determine rsync version') def config(conf_path='/etc/rsyncd.conf'): ''' .. versionchanged:: 2016.3.0 Return data now contains just the contents of the rsyncd.conf as a string, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Returns the contents of the rsync config file conf_path : /etc/rsyncd.conf Path to the config file CLI Example: .. code-block:: bash salt '*' rsync.config ''' ret = '' try: with salt.utils.files.fopen(conf_path, 'r') as fp_: for line in fp_: ret += salt.utils.stringutils.to_unicode(line) except IOError as exc: if exc.errno == errno.ENOENT: raise CommandExecutionError('{0} does not exist'.format(conf_path)) elif exc.errno == errno.EACCES: raise CommandExecutionError( 'Unable to read {0}, access denied'.format(conf_path) ) elif exc.errno == errno.EISDIR: raise CommandExecutionError( 'Unable to read {0}, path is a directory'.format(conf_path) ) else: raise CommandExecutionError( 'Error {0}: {1}'.format(exc.errno, exc.strerror) ) else: return ret
saltstack/salt
salt/modules/rsync.py
rsync
python
def rsync(src, dst, delete=False, force=False, update=False, passwordfile=None, exclude=None, excludefrom=None, dryrun=False, rsh=None, additional_opts=None, saltenv='base'): ''' .. versionchanged:: 2016.3.0 Return data now contains just the output of the rsync command, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Rsync files from src to dst src The source location where files will be rsynced from. dst The destination location where files will be rsynced to. delete : False Whether to enable the rsync `--delete` flag, which will delete extraneous files from dest dirs force : False Whether to enable the rsync `--force` flag, which will force deletion of dirs even if not empty. update : False Whether to enable the rsync `--update` flag, which forces rsync to skip any files which exist on the destination and have a modified time that is newer than the source file. passwordfile A file that contains a password for accessing an rsync daemon. The file should contain just the password. exclude Whether to enable the rsync `--exclude` flag, which will exclude files matching a PATTERN. excludefrom Whether to enable the rsync `--excludefrom` flag, which will read exclude patterns from a file. dryrun : False Whether to enable the rsync `--dry-run` flag, which will perform a trial run with no changes made. rsh Whether to enable the rsync `--rsh` flag, to specify the remote shell to use. additional_opts Any additional rsync options, should be specified as a list. saltenv Specify a salt fileserver environment to be used. CLI Example: .. code-block:: bash salt '*' rsync.rsync /path/to/src /path/to/dest delete=True update=True passwordfile=/etc/pass.crt exclude=exclude/dir salt '*' rsync.rsync /path/to/src delete=True excludefrom=/xx.ini salt '*' rsync.rsync /path/to/src delete=True exclude='[exclude1/dir,exclude2/dir]' additional_opts='["--partial", "--bwlimit=5000"]' ''' if not src: src = __salt__['config.option']('rsync.src') if not dst: dst = __salt__['config.option']('rsync.dst') if not delete: delete = __salt__['config.option']('rsync.delete') if not force: force = __salt__['config.option']('rsync.force') if not update: update = __salt__['config.option']('rsync.update') if not passwordfile: passwordfile = __salt__['config.option']('rsync.passwordfile') if not exclude: exclude = __salt__['config.option']('rsync.exclude') if not excludefrom: excludefrom = __salt__['config.option']('rsync.excludefrom') if not dryrun: dryrun = __salt__['config.option']('rsync.dryrun') if not rsh: rsh = __salt__['config.option']('rsync.rsh') if not src or not dst: raise SaltInvocationError('src and dst cannot be empty') tmp_src = None if src.startswith('salt://'): _src = src _path = re.sub('salt://', '', _src) src_is_dir = False if _path in __salt__['cp.list_master_dirs'](saltenv=saltenv): src_is_dir = True if src_is_dir: tmp_src = tempfile.mkdtemp() dir_src = __salt__['cp.get_dir'](_src, tmp_src, saltenv) if dir_src: src = tmp_src # Ensure src ends in / so we # get the contents not the tmpdir # itself. if not src.endswith('/'): src = '{0}/'.format(src) else: raise CommandExecutionError('{0} does not exist'.format(src)) else: tmp_src = salt.utils.files.mkstemp() file_src = __salt__['cp.get_file'](_src, tmp_src, saltenv) if file_src: src = tmp_src else: raise CommandExecutionError('{0} does not exist'.format(src)) option = _check(delete, force, update, passwordfile, exclude, excludefrom, dryrun, rsh) if additional_opts and isinstance(additional_opts, list): option = option + additional_opts cmd = ['rsync'] + option + [src, dst] log.debug('Running rsync command: %s', cmd) try: return __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) finally: if tmp_src: __salt__['file.remove'](tmp_src)
.. versionchanged:: 2016.3.0 Return data now contains just the output of the rsync command, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Rsync files from src to dst src The source location where files will be rsynced from. dst The destination location where files will be rsynced to. delete : False Whether to enable the rsync `--delete` flag, which will delete extraneous files from dest dirs force : False Whether to enable the rsync `--force` flag, which will force deletion of dirs even if not empty. update : False Whether to enable the rsync `--update` flag, which forces rsync to skip any files which exist on the destination and have a modified time that is newer than the source file. passwordfile A file that contains a password for accessing an rsync daemon. The file should contain just the password. exclude Whether to enable the rsync `--exclude` flag, which will exclude files matching a PATTERN. excludefrom Whether to enable the rsync `--excludefrom` flag, which will read exclude patterns from a file. dryrun : False Whether to enable the rsync `--dry-run` flag, which will perform a trial run with no changes made. rsh Whether to enable the rsync `--rsh` flag, to specify the remote shell to use. additional_opts Any additional rsync options, should be specified as a list. saltenv Specify a salt fileserver environment to be used. CLI Example: .. code-block:: bash salt '*' rsync.rsync /path/to/src /path/to/dest delete=True update=True passwordfile=/etc/pass.crt exclude=exclude/dir salt '*' rsync.rsync /path/to/src delete=True excludefrom=/xx.ini salt '*' rsync.rsync /path/to/src delete=True exclude='[exclude1/dir,exclude2/dir]' additional_opts='["--partial", "--bwlimit=5000"]'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rsync.py#L69-L219
[ "def mkstemp(*args, **kwargs):\n '''\n Helper function which does exactly what ``tempfile.mkstemp()`` does but\n accepts another argument, ``close_fd``, which, by default, is true and closes\n the fd before returning the file path. Something commonly done throughout\n Salt's code.\n '''\n if 'prefix' not in kwargs:\n kwargs['prefix'] = '__salt.tmp.'\n close_fd = kwargs.pop('close_fd', True)\n fd_, f_path = tempfile.mkstemp(*args, **kwargs)\n if close_fd is False:\n return fd_, f_path\n os.close(fd_)\n del fd_\n return f_path\n", "def _check(delete, force, update, passwordfile, exclude, excludefrom, dryrun, rsh):\n '''\n Generate rsync options\n '''\n options = ['-avz']\n\n if delete:\n options.append('--delete')\n if force:\n options.append('--force')\n if update:\n options.append('--update')\n if rsh:\n options.append('--rsh={0}'.format(rsh))\n if passwordfile:\n options.extend(['--password-file', passwordfile])\n if excludefrom:\n options.extend(['--exclude-from', excludefrom])\n if exclude:\n exclude = False\n if exclude:\n if isinstance(exclude, list):\n for ex_ in exclude:\n options.extend(['--exclude', ex_])\n else:\n options.extend(['--exclude', exclude])\n if dryrun:\n options.append('--dry-run')\n return options\n" ]
# -*- coding: utf-8 -*- ''' Wrapper for rsync .. versionadded:: 2014.1.0 This data can also be passed into :ref:`pillar <pillar-walk-through>`. Options passed into opts will overwrite options passed into pillar. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import errno import logging import re import tempfile # Import salt libs import salt.utils.files import salt.utils.path from salt.exceptions import CommandExecutionError, SaltInvocationError log = logging.getLogger(__name__) __virtualname__ = 'rsync' def __virtual__(): ''' Only load module if rsync binary is present ''' if salt.utils.path.which('rsync'): return __virtualname__ return (False, 'The rsync execution module cannot be loaded: ' 'the rsync binary is not in the path.') def _check(delete, force, update, passwordfile, exclude, excludefrom, dryrun, rsh): ''' Generate rsync options ''' options = ['-avz'] if delete: options.append('--delete') if force: options.append('--force') if update: options.append('--update') if rsh: options.append('--rsh={0}'.format(rsh)) if passwordfile: options.extend(['--password-file', passwordfile]) if excludefrom: options.extend(['--exclude-from', excludefrom]) if exclude: exclude = False if exclude: if isinstance(exclude, list): for ex_ in exclude: options.extend(['--exclude', ex_]) else: options.extend(['--exclude', exclude]) if dryrun: options.append('--dry-run') return options def version(): ''' .. versionchanged:: 2016.3.0 Return data now contains just the version number as a string, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Returns rsync version CLI Example: .. code-block:: bash salt '*' rsync.version ''' try: out = __salt__['cmd.run_stdout']( ['rsync', '--version'], python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) try: return out.split('\n')[0].split()[2] except IndexError: raise CommandExecutionError('Unable to determine rsync version') def config(conf_path='/etc/rsyncd.conf'): ''' .. versionchanged:: 2016.3.0 Return data now contains just the contents of the rsyncd.conf as a string, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Returns the contents of the rsync config file conf_path : /etc/rsyncd.conf Path to the config file CLI Example: .. code-block:: bash salt '*' rsync.config ''' ret = '' try: with salt.utils.files.fopen(conf_path, 'r') as fp_: for line in fp_: ret += salt.utils.stringutils.to_unicode(line) except IOError as exc: if exc.errno == errno.ENOENT: raise CommandExecutionError('{0} does not exist'.format(conf_path)) elif exc.errno == errno.EACCES: raise CommandExecutionError( 'Unable to read {0}, access denied'.format(conf_path) ) elif exc.errno == errno.EISDIR: raise CommandExecutionError( 'Unable to read {0}, path is a directory'.format(conf_path) ) else: raise CommandExecutionError( 'Error {0}: {1}'.format(exc.errno, exc.strerror) ) else: return ret
saltstack/salt
salt/modules/rsync.py
version
python
def version(): ''' .. versionchanged:: 2016.3.0 Return data now contains just the version number as a string, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Returns rsync version CLI Example: .. code-block:: bash salt '*' rsync.version ''' try: out = __salt__['cmd.run_stdout']( ['rsync', '--version'], python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) try: return out.split('\n')[0].split()[2] except IndexError: raise CommandExecutionError('Unable to determine rsync version')
.. versionchanged:: 2016.3.0 Return data now contains just the version number as a string, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Returns rsync version CLI Example: .. code-block:: bash salt '*' rsync.version
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rsync.py#L222-L246
null
# -*- coding: utf-8 -*- ''' Wrapper for rsync .. versionadded:: 2014.1.0 This data can also be passed into :ref:`pillar <pillar-walk-through>`. Options passed into opts will overwrite options passed into pillar. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import errno import logging import re import tempfile # Import salt libs import salt.utils.files import salt.utils.path from salt.exceptions import CommandExecutionError, SaltInvocationError log = logging.getLogger(__name__) __virtualname__ = 'rsync' def __virtual__(): ''' Only load module if rsync binary is present ''' if salt.utils.path.which('rsync'): return __virtualname__ return (False, 'The rsync execution module cannot be loaded: ' 'the rsync binary is not in the path.') def _check(delete, force, update, passwordfile, exclude, excludefrom, dryrun, rsh): ''' Generate rsync options ''' options = ['-avz'] if delete: options.append('--delete') if force: options.append('--force') if update: options.append('--update') if rsh: options.append('--rsh={0}'.format(rsh)) if passwordfile: options.extend(['--password-file', passwordfile]) if excludefrom: options.extend(['--exclude-from', excludefrom]) if exclude: exclude = False if exclude: if isinstance(exclude, list): for ex_ in exclude: options.extend(['--exclude', ex_]) else: options.extend(['--exclude', exclude]) if dryrun: options.append('--dry-run') return options def rsync(src, dst, delete=False, force=False, update=False, passwordfile=None, exclude=None, excludefrom=None, dryrun=False, rsh=None, additional_opts=None, saltenv='base'): ''' .. versionchanged:: 2016.3.0 Return data now contains just the output of the rsync command, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Rsync files from src to dst src The source location where files will be rsynced from. dst The destination location where files will be rsynced to. delete : False Whether to enable the rsync `--delete` flag, which will delete extraneous files from dest dirs force : False Whether to enable the rsync `--force` flag, which will force deletion of dirs even if not empty. update : False Whether to enable the rsync `--update` flag, which forces rsync to skip any files which exist on the destination and have a modified time that is newer than the source file. passwordfile A file that contains a password for accessing an rsync daemon. The file should contain just the password. exclude Whether to enable the rsync `--exclude` flag, which will exclude files matching a PATTERN. excludefrom Whether to enable the rsync `--excludefrom` flag, which will read exclude patterns from a file. dryrun : False Whether to enable the rsync `--dry-run` flag, which will perform a trial run with no changes made. rsh Whether to enable the rsync `--rsh` flag, to specify the remote shell to use. additional_opts Any additional rsync options, should be specified as a list. saltenv Specify a salt fileserver environment to be used. CLI Example: .. code-block:: bash salt '*' rsync.rsync /path/to/src /path/to/dest delete=True update=True passwordfile=/etc/pass.crt exclude=exclude/dir salt '*' rsync.rsync /path/to/src delete=True excludefrom=/xx.ini salt '*' rsync.rsync /path/to/src delete=True exclude='[exclude1/dir,exclude2/dir]' additional_opts='["--partial", "--bwlimit=5000"]' ''' if not src: src = __salt__['config.option']('rsync.src') if not dst: dst = __salt__['config.option']('rsync.dst') if not delete: delete = __salt__['config.option']('rsync.delete') if not force: force = __salt__['config.option']('rsync.force') if not update: update = __salt__['config.option']('rsync.update') if not passwordfile: passwordfile = __salt__['config.option']('rsync.passwordfile') if not exclude: exclude = __salt__['config.option']('rsync.exclude') if not excludefrom: excludefrom = __salt__['config.option']('rsync.excludefrom') if not dryrun: dryrun = __salt__['config.option']('rsync.dryrun') if not rsh: rsh = __salt__['config.option']('rsync.rsh') if not src or not dst: raise SaltInvocationError('src and dst cannot be empty') tmp_src = None if src.startswith('salt://'): _src = src _path = re.sub('salt://', '', _src) src_is_dir = False if _path in __salt__['cp.list_master_dirs'](saltenv=saltenv): src_is_dir = True if src_is_dir: tmp_src = tempfile.mkdtemp() dir_src = __salt__['cp.get_dir'](_src, tmp_src, saltenv) if dir_src: src = tmp_src # Ensure src ends in / so we # get the contents not the tmpdir # itself. if not src.endswith('/'): src = '{0}/'.format(src) else: raise CommandExecutionError('{0} does not exist'.format(src)) else: tmp_src = salt.utils.files.mkstemp() file_src = __salt__['cp.get_file'](_src, tmp_src, saltenv) if file_src: src = tmp_src else: raise CommandExecutionError('{0} does not exist'.format(src)) option = _check(delete, force, update, passwordfile, exclude, excludefrom, dryrun, rsh) if additional_opts and isinstance(additional_opts, list): option = option + additional_opts cmd = ['rsync'] + option + [src, dst] log.debug('Running rsync command: %s', cmd) try: return __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) finally: if tmp_src: __salt__['file.remove'](tmp_src) def config(conf_path='/etc/rsyncd.conf'): ''' .. versionchanged:: 2016.3.0 Return data now contains just the contents of the rsyncd.conf as a string, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Returns the contents of the rsync config file conf_path : /etc/rsyncd.conf Path to the config file CLI Example: .. code-block:: bash salt '*' rsync.config ''' ret = '' try: with salt.utils.files.fopen(conf_path, 'r') as fp_: for line in fp_: ret += salt.utils.stringutils.to_unicode(line) except IOError as exc: if exc.errno == errno.ENOENT: raise CommandExecutionError('{0} does not exist'.format(conf_path)) elif exc.errno == errno.EACCES: raise CommandExecutionError( 'Unable to read {0}, access denied'.format(conf_path) ) elif exc.errno == errno.EISDIR: raise CommandExecutionError( 'Unable to read {0}, path is a directory'.format(conf_path) ) else: raise CommandExecutionError( 'Error {0}: {1}'.format(exc.errno, exc.strerror) ) else: return ret
saltstack/salt
salt/modules/rsync.py
config
python
def config(conf_path='/etc/rsyncd.conf'): ''' .. versionchanged:: 2016.3.0 Return data now contains just the contents of the rsyncd.conf as a string, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Returns the contents of the rsync config file conf_path : /etc/rsyncd.conf Path to the config file CLI Example: .. code-block:: bash salt '*' rsync.config ''' ret = '' try: with salt.utils.files.fopen(conf_path, 'r') as fp_: for line in fp_: ret += salt.utils.stringutils.to_unicode(line) except IOError as exc: if exc.errno == errno.ENOENT: raise CommandExecutionError('{0} does not exist'.format(conf_path)) elif exc.errno == errno.EACCES: raise CommandExecutionError( 'Unable to read {0}, access denied'.format(conf_path) ) elif exc.errno == errno.EISDIR: raise CommandExecutionError( 'Unable to read {0}, path is a directory'.format(conf_path) ) else: raise CommandExecutionError( 'Error {0}: {1}'.format(exc.errno, exc.strerror) ) else: return ret
.. versionchanged:: 2016.3.0 Return data now contains just the contents of the rsyncd.conf as a string, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Returns the contents of the rsync config file conf_path : /etc/rsyncd.conf Path to the config file CLI Example: .. code-block:: bash salt '*' rsync.config
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rsync.py#L249-L288
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# -*- coding: utf-8 -*- ''' Wrapper for rsync .. versionadded:: 2014.1.0 This data can also be passed into :ref:`pillar <pillar-walk-through>`. Options passed into opts will overwrite options passed into pillar. ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import errno import logging import re import tempfile # Import salt libs import salt.utils.files import salt.utils.path from salt.exceptions import CommandExecutionError, SaltInvocationError log = logging.getLogger(__name__) __virtualname__ = 'rsync' def __virtual__(): ''' Only load module if rsync binary is present ''' if salt.utils.path.which('rsync'): return __virtualname__ return (False, 'The rsync execution module cannot be loaded: ' 'the rsync binary is not in the path.') def _check(delete, force, update, passwordfile, exclude, excludefrom, dryrun, rsh): ''' Generate rsync options ''' options = ['-avz'] if delete: options.append('--delete') if force: options.append('--force') if update: options.append('--update') if rsh: options.append('--rsh={0}'.format(rsh)) if passwordfile: options.extend(['--password-file', passwordfile]) if excludefrom: options.extend(['--exclude-from', excludefrom]) if exclude: exclude = False if exclude: if isinstance(exclude, list): for ex_ in exclude: options.extend(['--exclude', ex_]) else: options.extend(['--exclude', exclude]) if dryrun: options.append('--dry-run') return options def rsync(src, dst, delete=False, force=False, update=False, passwordfile=None, exclude=None, excludefrom=None, dryrun=False, rsh=None, additional_opts=None, saltenv='base'): ''' .. versionchanged:: 2016.3.0 Return data now contains just the output of the rsync command, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Rsync files from src to dst src The source location where files will be rsynced from. dst The destination location where files will be rsynced to. delete : False Whether to enable the rsync `--delete` flag, which will delete extraneous files from dest dirs force : False Whether to enable the rsync `--force` flag, which will force deletion of dirs even if not empty. update : False Whether to enable the rsync `--update` flag, which forces rsync to skip any files which exist on the destination and have a modified time that is newer than the source file. passwordfile A file that contains a password for accessing an rsync daemon. The file should contain just the password. exclude Whether to enable the rsync `--exclude` flag, which will exclude files matching a PATTERN. excludefrom Whether to enable the rsync `--excludefrom` flag, which will read exclude patterns from a file. dryrun : False Whether to enable the rsync `--dry-run` flag, which will perform a trial run with no changes made. rsh Whether to enable the rsync `--rsh` flag, to specify the remote shell to use. additional_opts Any additional rsync options, should be specified as a list. saltenv Specify a salt fileserver environment to be used. CLI Example: .. code-block:: bash salt '*' rsync.rsync /path/to/src /path/to/dest delete=True update=True passwordfile=/etc/pass.crt exclude=exclude/dir salt '*' rsync.rsync /path/to/src delete=True excludefrom=/xx.ini salt '*' rsync.rsync /path/to/src delete=True exclude='[exclude1/dir,exclude2/dir]' additional_opts='["--partial", "--bwlimit=5000"]' ''' if not src: src = __salt__['config.option']('rsync.src') if not dst: dst = __salt__['config.option']('rsync.dst') if not delete: delete = __salt__['config.option']('rsync.delete') if not force: force = __salt__['config.option']('rsync.force') if not update: update = __salt__['config.option']('rsync.update') if not passwordfile: passwordfile = __salt__['config.option']('rsync.passwordfile') if not exclude: exclude = __salt__['config.option']('rsync.exclude') if not excludefrom: excludefrom = __salt__['config.option']('rsync.excludefrom') if not dryrun: dryrun = __salt__['config.option']('rsync.dryrun') if not rsh: rsh = __salt__['config.option']('rsync.rsh') if not src or not dst: raise SaltInvocationError('src and dst cannot be empty') tmp_src = None if src.startswith('salt://'): _src = src _path = re.sub('salt://', '', _src) src_is_dir = False if _path in __salt__['cp.list_master_dirs'](saltenv=saltenv): src_is_dir = True if src_is_dir: tmp_src = tempfile.mkdtemp() dir_src = __salt__['cp.get_dir'](_src, tmp_src, saltenv) if dir_src: src = tmp_src # Ensure src ends in / so we # get the contents not the tmpdir # itself. if not src.endswith('/'): src = '{0}/'.format(src) else: raise CommandExecutionError('{0} does not exist'.format(src)) else: tmp_src = salt.utils.files.mkstemp() file_src = __salt__['cp.get_file'](_src, tmp_src, saltenv) if file_src: src = tmp_src else: raise CommandExecutionError('{0} does not exist'.format(src)) option = _check(delete, force, update, passwordfile, exclude, excludefrom, dryrun, rsh) if additional_opts and isinstance(additional_opts, list): option = option + additional_opts cmd = ['rsync'] + option + [src, dst] log.debug('Running rsync command: %s', cmd) try: return __salt__['cmd.run_all'](cmd, python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) finally: if tmp_src: __salt__['file.remove'](tmp_src) def version(): ''' .. versionchanged:: 2016.3.0 Return data now contains just the version number as a string, instead of a dictionary as returned from :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>`. Returns rsync version CLI Example: .. code-block:: bash salt '*' rsync.version ''' try: out = __salt__['cmd.run_stdout']( ['rsync', '--version'], python_shell=False) except (IOError, OSError) as exc: raise CommandExecutionError(exc.strerror) try: return out.split('\n')[0].split()[2] except IndexError: raise CommandExecutionError('Unable to determine rsync version')
saltstack/salt
salt/states/keystone_role.py
present
python
def present(name, auth=None, **kwargs): ''' Ensure an role exists name Name of the role description An arbitrary description of the role ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} kwargs = __utils__['args.clean_kwargs'](**kwargs) __salt__['keystoneng.setup_clouds'](auth) kwargs['name'] = name role = __salt__['keystoneng.role_get'](**kwargs) if not role: if __opts__['test'] is True: ret['result'] = None ret['changes'] = kwargs ret['comment'] = 'Role will be created.' return ret role = __salt__['keystoneng.role_create'](**kwargs) ret['changes']['id'] = role.id ret['changes']['name'] = role.name ret['comment'] = 'Created role' return ret # NOTE(SamYaple): Update support pending https://review.openstack.org/#/c/496992/ return ret
Ensure an role exists name Name of the role description An arbitrary description of the role
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone_role.py#L40-L75
null
# -*- coding: utf-8 -*- ''' Management of OpenStack Keystone Roles ====================================== .. versionadded:: 2018.3.0 :depends: shade :configuration: see :py:mod:`salt.modules.keystoneng` for setup instructions Example States .. code-block:: yaml create role: keystone_role.present: - name: role1 delete role: keystone_role.absent: - name: role1 create role with optional params: keystone_role.present: - name: role1 - description: 'my group' ''' from __future__ import absolute_import, unicode_literals, print_function __virtualname__ = 'keystone_role' def __virtual__(): if 'keystoneng.role_get' in __salt__: return __virtualname__ return (False, 'The keystoneng execution module failed to load: shade python module is not available') def absent(name, auth=None, **kwargs): ''' Ensure role does not exist name Name of the role ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} __salt__['keystoneng.setup_clouds'](auth) kwargs['name'] = name role = __salt__['keystoneng.role_get'](**kwargs) if role: if __opts__['test'] is True: ret['result'] = None ret['changes'] = {'id': role.id} ret['comment'] = 'Role will be deleted.' return ret __salt__['keystoneng.role_delete'](name=role) ret['changes']['id'] = role.id ret['comment'] = 'Deleted role' return ret
saltstack/salt
salt/states/keystone_role.py
absent
python
def absent(name, auth=None, **kwargs): ''' Ensure role does not exist name Name of the role ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} __salt__['keystoneng.setup_clouds'](auth) kwargs['name'] = name role = __salt__['keystoneng.role_get'](**kwargs) if role: if __opts__['test'] is True: ret['result'] = None ret['changes'] = {'id': role.id} ret['comment'] = 'Role will be deleted.' return ret __salt__['keystoneng.role_delete'](name=role) ret['changes']['id'] = role.id ret['comment'] = 'Deleted role' return ret
Ensure role does not exist name Name of the role
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/keystone_role.py#L78-L106
null
# -*- coding: utf-8 -*- ''' Management of OpenStack Keystone Roles ====================================== .. versionadded:: 2018.3.0 :depends: shade :configuration: see :py:mod:`salt.modules.keystoneng` for setup instructions Example States .. code-block:: yaml create role: keystone_role.present: - name: role1 delete role: keystone_role.absent: - name: role1 create role with optional params: keystone_role.present: - name: role1 - description: 'my group' ''' from __future__ import absolute_import, unicode_literals, print_function __virtualname__ = 'keystone_role' def __virtual__(): if 'keystoneng.role_get' in __salt__: return __virtualname__ return (False, 'The keystoneng execution module failed to load: shade python module is not available') def present(name, auth=None, **kwargs): ''' Ensure an role exists name Name of the role description An arbitrary description of the role ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} kwargs = __utils__['args.clean_kwargs'](**kwargs) __salt__['keystoneng.setup_clouds'](auth) kwargs['name'] = name role = __salt__['keystoneng.role_get'](**kwargs) if not role: if __opts__['test'] is True: ret['result'] = None ret['changes'] = kwargs ret['comment'] = 'Role will be created.' return ret role = __salt__['keystoneng.role_create'](**kwargs) ret['changes']['id'] = role.id ret['changes']['name'] = role.name ret['comment'] = 'Created role' return ret # NOTE(SamYaple): Update support pending https://review.openstack.org/#/c/496992/ return ret
saltstack/salt
salt/modules/mac_assistive.py
install
python
def install(app_id, enable=True): ''' Install a bundle ID or command as being allowed to use assistive access. app_id The bundle ID or command to install for assistive access. enabled Sets enabled or disabled status. Default is ``True``. CLI Example: .. code-block:: bash salt '*' assistive.install /usr/bin/osascript salt '*' assistive.install com.smileonmymac.textexpander ''' ge_el_capitan = True if _LooseVersion(__grains__['osrelease']) >= salt.utils.stringutils.to_str('10.11') else False client_type = _client_type(app_id) enable_str = '1' if enable else '0' cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \ '"INSERT or REPLACE INTO access VALUES(\'kTCCServiceAccessibility\',\'{0}\',{1},{2},1,NULL{3})"'.\ format(app_id, client_type, enable_str, ',NULL' if ge_el_capitan else '') call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error installing app: {0}'.format(comment)) return True
Install a bundle ID or command as being allowed to use assistive access. app_id The bundle ID or command to install for assistive access. enabled Sets enabled or disabled status. Default is ``True``. CLI Example: .. code-block:: bash salt '*' assistive.install /usr/bin/osascript salt '*' assistive.install com.smileonmymac.textexpander
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_assistive.py#L39-L78
[ "def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n", "def _client_type(app_id):\n '''\n Determine whether the given ID is a bundle ID or a\n a path to a command\n '''\n return '1' if app_id[0] == '/' else '0'\n" ]
# -*- coding: utf-8 -*- ''' This module allows you to manage assistive access on macOS minions with 10.9+ .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' assistive.install /usr/bin/osascript ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import re import logging # Import salt libs import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.versions import LooseVersion as _LooseVersion log = logging.getLogger(__name__) __virtualname__ = 'assistive' def __virtual__(): ''' Only work on Mac OS ''' if not salt.utils.platform.is_darwin(): return False, 'Must be run on macOS' if _LooseVersion(__grains__['osrelease']) < salt.utils.stringutils.to_str('10.9'): return False, 'Must be run on macOS 10.9 or newer' return __virtualname__ def installed(app_id): ''' Check if a bundle ID or command is listed in assistive access. This will not check to see if it's enabled. app_id The bundle ID or command to check installed status. CLI Example: .. code-block:: bash salt '*' assistive.installed /usr/bin/osascript salt '*' assistive.installed com.smileonmymac.textexpander ''' for a in _get_assistive_access(): if app_id == a[0]: return True return False def enable(app_id, enabled=True): ''' Enable or disable an existing assistive access application. app_id The bundle ID or command to set assistive access status. enabled Sets enabled or disabled status. Default is ``True``. CLI Example: .. code-block:: bash salt '*' assistive.enable /usr/bin/osascript salt '*' assistive.enable com.smileonmymac.textexpander enabled=False ''' enable_str = '1' if enabled else '0' for a in _get_assistive_access(): if app_id == a[0]: cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \ '"UPDATE access SET allowed=\'{0}\' WHERE client=\'{1}\'"'.format(enable_str, app_id) call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error enabling app: {0}'.format(comment)) return True return False def enabled(app_id): ''' Check if a bundle ID or command is listed in assistive access and enabled. app_id The bundle ID or command to retrieve assistive access status. CLI Example: .. code-block:: bash salt '*' assistive.enabled /usr/bin/osascript salt '*' assistive.enabled com.smileonmymac.textexpander ''' for a in _get_assistive_access(): if app_id == a[0] and a[1] == '1': return True return False def remove(app_id): ''' Remove a bundle ID or command as being allowed to use assistive access. app_id The bundle ID or command to remove from assistive access list. CLI Example: .. code-block:: bash salt '*' assistive.remove /usr/bin/osascript salt '*' assistive.remove com.smileonmymac.textexpander ''' cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \ '"DELETE from access where client=\'{0}\'"'.format(app_id) call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error removing app: {0}'.format(comment)) return True def _client_type(app_id): ''' Determine whether the given ID is a bundle ID or a a path to a command ''' return '1' if app_id[0] == '/' else '0' def _get_assistive_access(): ''' Get a list of all of the assistive access applications installed, returns as a ternary showing whether each app is enabled or not. ''' cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" "SELECT * FROM access"' call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error: {0}'.format(comment)) out = call['stdout'] return re.findall(r'kTCCServiceAccessibility\|(.*)\|[0-9]{1}\|([0-9]{1})\|[0-9]{1}\|', out, re.MULTILINE)
saltstack/salt
salt/modules/mac_assistive.py
enable
python
def enable(app_id, enabled=True): ''' Enable or disable an existing assistive access application. app_id The bundle ID or command to set assistive access status. enabled Sets enabled or disabled status. Default is ``True``. CLI Example: .. code-block:: bash salt '*' assistive.enable /usr/bin/osascript salt '*' assistive.enable com.smileonmymac.textexpander enabled=False ''' enable_str = '1' if enabled else '0' for a in _get_assistive_access(): if app_id == a[0]: cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \ '"UPDATE access SET allowed=\'{0}\' WHERE client=\'{1}\'"'.format(enable_str, app_id) call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error enabling app: {0}'.format(comment)) return True return False
Enable or disable an existing assistive access application. app_id The bundle ID or command to set assistive access status. enabled Sets enabled or disabled status. Default is ``True``. CLI Example: .. code-block:: bash salt '*' assistive.enable /usr/bin/osascript salt '*' assistive.enable com.smileonmymac.textexpander enabled=False
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_assistive.py#L103-L143
[ "def _get_assistive_access():\n '''\n Get a list of all of the assistive access applications installed,\n returns as a ternary showing whether each app is enabled or not.\n '''\n cmd = 'sqlite3 \"/Library/Application Support/com.apple.TCC/TCC.db\" \"SELECT * FROM access\"'\n call = __salt__['cmd.run_all'](\n cmd,\n output_loglevel='debug',\n python_shell=False\n )\n\n if call['retcode'] != 0:\n comment = ''\n if 'stderr' in call:\n comment += call['stderr']\n if 'stdout' in call:\n comment += call['stdout']\n\n raise CommandExecutionError('Error: {0}'.format(comment))\n\n out = call['stdout']\n return re.findall(r'kTCCServiceAccessibility\\|(.*)\\|[0-9]{1}\\|([0-9]{1})\\|[0-9]{1}\\|', out, re.MULTILINE)\n" ]
# -*- coding: utf-8 -*- ''' This module allows you to manage assistive access on macOS minions with 10.9+ .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' assistive.install /usr/bin/osascript ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import re import logging # Import salt libs import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.versions import LooseVersion as _LooseVersion log = logging.getLogger(__name__) __virtualname__ = 'assistive' def __virtual__(): ''' Only work on Mac OS ''' if not salt.utils.platform.is_darwin(): return False, 'Must be run on macOS' if _LooseVersion(__grains__['osrelease']) < salt.utils.stringutils.to_str('10.9'): return False, 'Must be run on macOS 10.9 or newer' return __virtualname__ def install(app_id, enable=True): ''' Install a bundle ID or command as being allowed to use assistive access. app_id The bundle ID or command to install for assistive access. enabled Sets enabled or disabled status. Default is ``True``. CLI Example: .. code-block:: bash salt '*' assistive.install /usr/bin/osascript salt '*' assistive.install com.smileonmymac.textexpander ''' ge_el_capitan = True if _LooseVersion(__grains__['osrelease']) >= salt.utils.stringutils.to_str('10.11') else False client_type = _client_type(app_id) enable_str = '1' if enable else '0' cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \ '"INSERT or REPLACE INTO access VALUES(\'kTCCServiceAccessibility\',\'{0}\',{1},{2},1,NULL{3})"'.\ format(app_id, client_type, enable_str, ',NULL' if ge_el_capitan else '') call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error installing app: {0}'.format(comment)) return True def installed(app_id): ''' Check if a bundle ID or command is listed in assistive access. This will not check to see if it's enabled. app_id The bundle ID or command to check installed status. CLI Example: .. code-block:: bash salt '*' assistive.installed /usr/bin/osascript salt '*' assistive.installed com.smileonmymac.textexpander ''' for a in _get_assistive_access(): if app_id == a[0]: return True return False def enabled(app_id): ''' Check if a bundle ID or command is listed in assistive access and enabled. app_id The bundle ID or command to retrieve assistive access status. CLI Example: .. code-block:: bash salt '*' assistive.enabled /usr/bin/osascript salt '*' assistive.enabled com.smileonmymac.textexpander ''' for a in _get_assistive_access(): if app_id == a[0] and a[1] == '1': return True return False def remove(app_id): ''' Remove a bundle ID or command as being allowed to use assistive access. app_id The bundle ID or command to remove from assistive access list. CLI Example: .. code-block:: bash salt '*' assistive.remove /usr/bin/osascript salt '*' assistive.remove com.smileonmymac.textexpander ''' cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \ '"DELETE from access where client=\'{0}\'"'.format(app_id) call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error removing app: {0}'.format(comment)) return True def _client_type(app_id): ''' Determine whether the given ID is a bundle ID or a a path to a command ''' return '1' if app_id[0] == '/' else '0' def _get_assistive_access(): ''' Get a list of all of the assistive access applications installed, returns as a ternary showing whether each app is enabled or not. ''' cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" "SELECT * FROM access"' call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error: {0}'.format(comment)) out = call['stdout'] return re.findall(r'kTCCServiceAccessibility\|(.*)\|[0-9]{1}\|([0-9]{1})\|[0-9]{1}\|', out, re.MULTILINE)
saltstack/salt
salt/modules/mac_assistive.py
remove
python
def remove(app_id): ''' Remove a bundle ID or command as being allowed to use assistive access. app_id The bundle ID or command to remove from assistive access list. CLI Example: .. code-block:: bash salt '*' assistive.remove /usr/bin/osascript salt '*' assistive.remove com.smileonmymac.textexpander ''' cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \ '"DELETE from access where client=\'{0}\'"'.format(app_id) call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error removing app: {0}'.format(comment)) return True
Remove a bundle ID or command as being allowed to use assistive access. app_id The bundle ID or command to remove from assistive access list. CLI Example: .. code-block:: bash salt '*' assistive.remove /usr/bin/osascript salt '*' assistive.remove com.smileonmymac.textexpander
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_assistive.py#L168-L199
null
# -*- coding: utf-8 -*- ''' This module allows you to manage assistive access on macOS minions with 10.9+ .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' assistive.install /usr/bin/osascript ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import re import logging # Import salt libs import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.versions import LooseVersion as _LooseVersion log = logging.getLogger(__name__) __virtualname__ = 'assistive' def __virtual__(): ''' Only work on Mac OS ''' if not salt.utils.platform.is_darwin(): return False, 'Must be run on macOS' if _LooseVersion(__grains__['osrelease']) < salt.utils.stringutils.to_str('10.9'): return False, 'Must be run on macOS 10.9 or newer' return __virtualname__ def install(app_id, enable=True): ''' Install a bundle ID or command as being allowed to use assistive access. app_id The bundle ID or command to install for assistive access. enabled Sets enabled or disabled status. Default is ``True``. CLI Example: .. code-block:: bash salt '*' assistive.install /usr/bin/osascript salt '*' assistive.install com.smileonmymac.textexpander ''' ge_el_capitan = True if _LooseVersion(__grains__['osrelease']) >= salt.utils.stringutils.to_str('10.11') else False client_type = _client_type(app_id) enable_str = '1' if enable else '0' cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \ '"INSERT or REPLACE INTO access VALUES(\'kTCCServiceAccessibility\',\'{0}\',{1},{2},1,NULL{3})"'.\ format(app_id, client_type, enable_str, ',NULL' if ge_el_capitan else '') call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error installing app: {0}'.format(comment)) return True def installed(app_id): ''' Check if a bundle ID or command is listed in assistive access. This will not check to see if it's enabled. app_id The bundle ID or command to check installed status. CLI Example: .. code-block:: bash salt '*' assistive.installed /usr/bin/osascript salt '*' assistive.installed com.smileonmymac.textexpander ''' for a in _get_assistive_access(): if app_id == a[0]: return True return False def enable(app_id, enabled=True): ''' Enable or disable an existing assistive access application. app_id The bundle ID or command to set assistive access status. enabled Sets enabled or disabled status. Default is ``True``. CLI Example: .. code-block:: bash salt '*' assistive.enable /usr/bin/osascript salt '*' assistive.enable com.smileonmymac.textexpander enabled=False ''' enable_str = '1' if enabled else '0' for a in _get_assistive_access(): if app_id == a[0]: cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \ '"UPDATE access SET allowed=\'{0}\' WHERE client=\'{1}\'"'.format(enable_str, app_id) call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error enabling app: {0}'.format(comment)) return True return False def enabled(app_id): ''' Check if a bundle ID or command is listed in assistive access and enabled. app_id The bundle ID or command to retrieve assistive access status. CLI Example: .. code-block:: bash salt '*' assistive.enabled /usr/bin/osascript salt '*' assistive.enabled com.smileonmymac.textexpander ''' for a in _get_assistive_access(): if app_id == a[0] and a[1] == '1': return True return False def _client_type(app_id): ''' Determine whether the given ID is a bundle ID or a a path to a command ''' return '1' if app_id[0] == '/' else '0' def _get_assistive_access(): ''' Get a list of all of the assistive access applications installed, returns as a ternary showing whether each app is enabled or not. ''' cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" "SELECT * FROM access"' call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error: {0}'.format(comment)) out = call['stdout'] return re.findall(r'kTCCServiceAccessibility\|(.*)\|[0-9]{1}\|([0-9]{1})\|[0-9]{1}\|', out, re.MULTILINE)
saltstack/salt
salt/modules/mac_assistive.py
_get_assistive_access
python
def _get_assistive_access(): ''' Get a list of all of the assistive access applications installed, returns as a ternary showing whether each app is enabled or not. ''' cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" "SELECT * FROM access"' call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error: {0}'.format(comment)) out = call['stdout'] return re.findall(r'kTCCServiceAccessibility\|(.*)\|[0-9]{1}\|([0-9]{1})\|[0-9]{1}\|', out, re.MULTILINE)
Get a list of all of the assistive access applications installed, returns as a ternary showing whether each app is enabled or not.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_assistive.py#L210-L232
null
# -*- coding: utf-8 -*- ''' This module allows you to manage assistive access on macOS minions with 10.9+ .. versionadded:: 2016.3.0 .. code-block:: bash salt '*' assistive.install /usr/bin/osascript ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import re import logging # Import salt libs import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.versions import LooseVersion as _LooseVersion log = logging.getLogger(__name__) __virtualname__ = 'assistive' def __virtual__(): ''' Only work on Mac OS ''' if not salt.utils.platform.is_darwin(): return False, 'Must be run on macOS' if _LooseVersion(__grains__['osrelease']) < salt.utils.stringutils.to_str('10.9'): return False, 'Must be run on macOS 10.9 or newer' return __virtualname__ def install(app_id, enable=True): ''' Install a bundle ID or command as being allowed to use assistive access. app_id The bundle ID or command to install for assistive access. enabled Sets enabled or disabled status. Default is ``True``. CLI Example: .. code-block:: bash salt '*' assistive.install /usr/bin/osascript salt '*' assistive.install com.smileonmymac.textexpander ''' ge_el_capitan = True if _LooseVersion(__grains__['osrelease']) >= salt.utils.stringutils.to_str('10.11') else False client_type = _client_type(app_id) enable_str = '1' if enable else '0' cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \ '"INSERT or REPLACE INTO access VALUES(\'kTCCServiceAccessibility\',\'{0}\',{1},{2},1,NULL{3})"'.\ format(app_id, client_type, enable_str, ',NULL' if ge_el_capitan else '') call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error installing app: {0}'.format(comment)) return True def installed(app_id): ''' Check if a bundle ID or command is listed in assistive access. This will not check to see if it's enabled. app_id The bundle ID or command to check installed status. CLI Example: .. code-block:: bash salt '*' assistive.installed /usr/bin/osascript salt '*' assistive.installed com.smileonmymac.textexpander ''' for a in _get_assistive_access(): if app_id == a[0]: return True return False def enable(app_id, enabled=True): ''' Enable or disable an existing assistive access application. app_id The bundle ID or command to set assistive access status. enabled Sets enabled or disabled status. Default is ``True``. CLI Example: .. code-block:: bash salt '*' assistive.enable /usr/bin/osascript salt '*' assistive.enable com.smileonmymac.textexpander enabled=False ''' enable_str = '1' if enabled else '0' for a in _get_assistive_access(): if app_id == a[0]: cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \ '"UPDATE access SET allowed=\'{0}\' WHERE client=\'{1}\'"'.format(enable_str, app_id) call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error enabling app: {0}'.format(comment)) return True return False def enabled(app_id): ''' Check if a bundle ID or command is listed in assistive access and enabled. app_id The bundle ID or command to retrieve assistive access status. CLI Example: .. code-block:: bash salt '*' assistive.enabled /usr/bin/osascript salt '*' assistive.enabled com.smileonmymac.textexpander ''' for a in _get_assistive_access(): if app_id == a[0] and a[1] == '1': return True return False def remove(app_id): ''' Remove a bundle ID or command as being allowed to use assistive access. app_id The bundle ID or command to remove from assistive access list. CLI Example: .. code-block:: bash salt '*' assistive.remove /usr/bin/osascript salt '*' assistive.remove com.smileonmymac.textexpander ''' cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' \ '"DELETE from access where client=\'{0}\'"'.format(app_id) call = __salt__['cmd.run_all']( cmd, output_loglevel='debug', python_shell=False ) if call['retcode'] != 0: comment = '' if 'stderr' in call: comment += call['stderr'] if 'stdout' in call: comment += call['stdout'] raise CommandExecutionError('Error removing app: {0}'.format(comment)) return True def _client_type(app_id): ''' Determine whether the given ID is a bundle ID or a a path to a command ''' return '1' if app_id[0] == '/' else '0'
saltstack/salt
salt/serializers/yaml.py
deserialize
python
def deserialize(stream_or_string, **options): ''' Deserialize any string of stream like object into a Python data structure. :param stream_or_string: stream or string to deserialize. :param options: options given to lower yaml module. ''' options.setdefault('Loader', Loader) try: return yaml.load(stream_or_string, **options) except ScannerError as error: log.exception('Error encountered while deserializing') err_type = ERROR_MAP.get(error.problem, 'Unknown yaml render error') line_num = error.problem_mark.line + 1 raise DeserializationError(err_type, line_num, error.problem_mark.buffer) except ConstructorError as error: log.exception('Error encountered while deserializing') raise DeserializationError(error) except Exception as error: log.exception('Error encountered while deserializing') raise DeserializationError(error)
Deserialize any string of stream like object into a Python data structure. :param stream_or_string: stream or string to deserialize. :param options: options given to lower yaml module.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/serializers/yaml.py#L41-L64
null
# -*- coding: utf-8 -*- ''' salt.serializers.yaml ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Implements YAML serializer. Underneath, it is based on pyyaml and use the safe dumper and loader. It also use C bindings if they are available. ''' from __future__ import absolute_import, print_function, unicode_literals import datetime import logging import yaml from yaml.constructor import ConstructorError from yaml.scanner import ScannerError from salt.serializers import DeserializationError, SerializationError from salt.ext import six from salt.utils.odict import OrderedDict from salt.utils.thread_local_proxy import ThreadLocalProxy __all__ = ['deserialize', 'serialize', 'available'] log = logging.getLogger(__name__) available = True # prefer C bindings over python when available BaseLoader = getattr(yaml, 'CSafeLoader', yaml.SafeLoader) BaseDumper = getattr(yaml, 'CSafeDumper', yaml.SafeDumper) ERROR_MAP = { ("found character '\\t' " "that cannot start any token"): 'Illegal tab character' } def serialize(obj, **options): ''' Serialize Python data to YAML. :param obj: the data structure to serialize :param options: options given to lower yaml module. ''' options.setdefault('Dumper', Dumper) try: response = yaml.dump(obj, **options) if response.endswith('\n...\n'): return response[:-5] if response.endswith('\n'): return response[:-1] return response except Exception as error: log.exception('Error encountered while serializing') raise SerializationError(error) class EncryptedString(str): yaml_tag = '!encrypted' @staticmethod def yaml_constructor(loader, tag, node): return EncryptedString(loader.construct_scalar(node)) @staticmethod def yaml_dumper(dumper, data): return dumper.represent_scalar(EncryptedString.yaml_tag, data.__str__()) class Loader(BaseLoader): # pylint: disable=W0232 '''Overwrites Loader as not for pollute legacy Loader''' pass Loader.add_multi_constructor(EncryptedString.yaml_tag, EncryptedString.yaml_constructor) Loader.add_multi_constructor('tag:yaml.org,2002:null', Loader.construct_yaml_null) Loader.add_multi_constructor('tag:yaml.org,2002:bool', Loader.construct_yaml_bool) Loader.add_multi_constructor('tag:yaml.org,2002:int', Loader.construct_yaml_int) Loader.add_multi_constructor('tag:yaml.org,2002:float', Loader.construct_yaml_float) Loader.add_multi_constructor('tag:yaml.org,2002:binary', Loader.construct_yaml_binary) Loader.add_multi_constructor('tag:yaml.org,2002:timestamp', Loader.construct_yaml_timestamp) Loader.add_multi_constructor('tag:yaml.org,2002:omap', Loader.construct_yaml_omap) Loader.add_multi_constructor('tag:yaml.org,2002:pairs', Loader.construct_yaml_pairs) Loader.add_multi_constructor('tag:yaml.org,2002:set', Loader.construct_yaml_set) Loader.add_multi_constructor('tag:yaml.org,2002:str', Loader.construct_yaml_str) Loader.add_multi_constructor('tag:yaml.org,2002:seq', Loader.construct_yaml_seq) Loader.add_multi_constructor('tag:yaml.org,2002:map', Loader.construct_yaml_map) class Dumper(BaseDumper): # pylint: disable=W0232 '''Overwrites Dumper as not for pollute legacy Dumper''' pass Dumper.add_multi_representer(EncryptedString, EncryptedString.yaml_dumper) Dumper.add_multi_representer(type(None), Dumper.represent_none) Dumper.add_multi_representer(str, Dumper.represent_str) if six.PY2: Dumper.add_multi_representer(six.text_type, Dumper.represent_unicode) Dumper.add_multi_representer(int, Dumper.represent_long) Dumper.add_multi_representer(bool, Dumper.represent_bool) Dumper.add_multi_representer(int, Dumper.represent_int) Dumper.add_multi_representer(float, Dumper.represent_float) Dumper.add_multi_representer(list, Dumper.represent_list) Dumper.add_multi_representer(tuple, Dumper.represent_list) Dumper.add_multi_representer(dict, Dumper.represent_dict) Dumper.add_multi_representer(set, Dumper.represent_set) Dumper.add_multi_representer(datetime.date, Dumper.represent_date) Dumper.add_multi_representer(datetime.datetime, Dumper.represent_datetime) Dumper.add_multi_representer(None, Dumper.represent_undefined) Dumper.add_multi_representer(OrderedDict, Dumper.represent_dict) Dumper.add_representer( ThreadLocalProxy, lambda dumper, proxy: dumper.represent_data(ThreadLocalProxy.unproxy(proxy)))
saltstack/salt
salt/serializers/yaml.py
serialize
python
def serialize(obj, **options): ''' Serialize Python data to YAML. :param obj: the data structure to serialize :param options: options given to lower yaml module. ''' options.setdefault('Dumper', Dumper) try: response = yaml.dump(obj, **options) if response.endswith('\n...\n'): return response[:-5] if response.endswith('\n'): return response[:-1] return response except Exception as error: log.exception('Error encountered while serializing') raise SerializationError(error)
Serialize Python data to YAML. :param obj: the data structure to serialize :param options: options given to lower yaml module.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/serializers/yaml.py#L67-L85
null
# -*- coding: utf-8 -*- ''' salt.serializers.yaml ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Implements YAML serializer. Underneath, it is based on pyyaml and use the safe dumper and loader. It also use C bindings if they are available. ''' from __future__ import absolute_import, print_function, unicode_literals import datetime import logging import yaml from yaml.constructor import ConstructorError from yaml.scanner import ScannerError from salt.serializers import DeserializationError, SerializationError from salt.ext import six from salt.utils.odict import OrderedDict from salt.utils.thread_local_proxy import ThreadLocalProxy __all__ = ['deserialize', 'serialize', 'available'] log = logging.getLogger(__name__) available = True # prefer C bindings over python when available BaseLoader = getattr(yaml, 'CSafeLoader', yaml.SafeLoader) BaseDumper = getattr(yaml, 'CSafeDumper', yaml.SafeDumper) ERROR_MAP = { ("found character '\\t' " "that cannot start any token"): 'Illegal tab character' } def deserialize(stream_or_string, **options): ''' Deserialize any string of stream like object into a Python data structure. :param stream_or_string: stream or string to deserialize. :param options: options given to lower yaml module. ''' options.setdefault('Loader', Loader) try: return yaml.load(stream_or_string, **options) except ScannerError as error: log.exception('Error encountered while deserializing') err_type = ERROR_MAP.get(error.problem, 'Unknown yaml render error') line_num = error.problem_mark.line + 1 raise DeserializationError(err_type, line_num, error.problem_mark.buffer) except ConstructorError as error: log.exception('Error encountered while deserializing') raise DeserializationError(error) except Exception as error: log.exception('Error encountered while deserializing') raise DeserializationError(error) class EncryptedString(str): yaml_tag = '!encrypted' @staticmethod def yaml_constructor(loader, tag, node): return EncryptedString(loader.construct_scalar(node)) @staticmethod def yaml_dumper(dumper, data): return dumper.represent_scalar(EncryptedString.yaml_tag, data.__str__()) class Loader(BaseLoader): # pylint: disable=W0232 '''Overwrites Loader as not for pollute legacy Loader''' pass Loader.add_multi_constructor(EncryptedString.yaml_tag, EncryptedString.yaml_constructor) Loader.add_multi_constructor('tag:yaml.org,2002:null', Loader.construct_yaml_null) Loader.add_multi_constructor('tag:yaml.org,2002:bool', Loader.construct_yaml_bool) Loader.add_multi_constructor('tag:yaml.org,2002:int', Loader.construct_yaml_int) Loader.add_multi_constructor('tag:yaml.org,2002:float', Loader.construct_yaml_float) Loader.add_multi_constructor('tag:yaml.org,2002:binary', Loader.construct_yaml_binary) Loader.add_multi_constructor('tag:yaml.org,2002:timestamp', Loader.construct_yaml_timestamp) Loader.add_multi_constructor('tag:yaml.org,2002:omap', Loader.construct_yaml_omap) Loader.add_multi_constructor('tag:yaml.org,2002:pairs', Loader.construct_yaml_pairs) Loader.add_multi_constructor('tag:yaml.org,2002:set', Loader.construct_yaml_set) Loader.add_multi_constructor('tag:yaml.org,2002:str', Loader.construct_yaml_str) Loader.add_multi_constructor('tag:yaml.org,2002:seq', Loader.construct_yaml_seq) Loader.add_multi_constructor('tag:yaml.org,2002:map', Loader.construct_yaml_map) class Dumper(BaseDumper): # pylint: disable=W0232 '''Overwrites Dumper as not for pollute legacy Dumper''' pass Dumper.add_multi_representer(EncryptedString, EncryptedString.yaml_dumper) Dumper.add_multi_representer(type(None), Dumper.represent_none) Dumper.add_multi_representer(str, Dumper.represent_str) if six.PY2: Dumper.add_multi_representer(six.text_type, Dumper.represent_unicode) Dumper.add_multi_representer(int, Dumper.represent_long) Dumper.add_multi_representer(bool, Dumper.represent_bool) Dumper.add_multi_representer(int, Dumper.represent_int) Dumper.add_multi_representer(float, Dumper.represent_float) Dumper.add_multi_representer(list, Dumper.represent_list) Dumper.add_multi_representer(tuple, Dumper.represent_list) Dumper.add_multi_representer(dict, Dumper.represent_dict) Dumper.add_multi_representer(set, Dumper.represent_set) Dumper.add_multi_representer(datetime.date, Dumper.represent_date) Dumper.add_multi_representer(datetime.datetime, Dumper.represent_datetime) Dumper.add_multi_representer(None, Dumper.represent_undefined) Dumper.add_multi_representer(OrderedDict, Dumper.represent_dict) Dumper.add_representer( ThreadLocalProxy, lambda dumper, proxy: dumper.represent_data(ThreadLocalProxy.unproxy(proxy)))
saltstack/salt
salt/modules/win_certutil.py
get_cert_serial
python
def get_cert_serial(cert_file): ''' Get the serial number of a certificate file cert_file The certificate file to find the serial for CLI Example: .. code-block:: bash salt '*' certutil.get_cert_serial <certificate name> ''' cmd = "certutil.exe -silent -verify {0}".format(cert_file) out = __salt__['cmd.run'](cmd) # match serial number by paragraph to work with multiple languages matches = re.search(r":\s*(\w*)\r\n\r\n", out) if matches is not None: return matches.groups()[0].strip() else: return None
Get the serial number of a certificate file cert_file The certificate file to find the serial for CLI Example: .. code-block:: bash salt '*' certutil.get_cert_serial <certificate name>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_certutil.py#L32-L52
null
# -*- coding: utf-8 -*- ''' This module allows you to install certificates into the windows certificate manager. .. code-block:: bash salt '*' certutil.add_store salt://cert.cer "TrustedPublisher" ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import re import logging # Import Salt Libs import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = "certutil" def __virtual__(): ''' Only work on Windows ''' if salt.utils.platform.is_windows(): return __virtualname__ return False def get_stored_cert_serials(store): ''' Get all of the certificate serials in the specified store store The store to get all the certificate serials from CLI Example: .. code-block:: bash salt '*' certutil.get_stored_cert_serials <store> ''' cmd = "certutil.exe -store {0}".format(store) out = __salt__['cmd.run'](cmd) # match serial numbers by header position to work with multiple languages matches = re.findall(r"={16}\r\n.*:\s*(\w*)\r\n", out) return matches def add_store(source, store, saltenv='base'): ''' Add the given cert into the given Certificate Store source The source certificate file this can be in the form salt://path/to/file store The certificate store to add the certificate to saltenv The salt environment to use this is ignored if the path is local CLI Example: .. code-block:: bash salt '*' certutil.add_store salt://cert.cer TrustedPublisher ''' cert_file = __salt__['cp.cache_file'](source, saltenv) cmd = "certutil.exe -addstore {0} {1}".format(store, cert_file) return __salt__['cmd.run'](cmd) def del_store(source, store, saltenv='base'): ''' Delete the given cert into the given Certificate Store source The source certificate file this can be in the form salt://path/to/file store The certificate store to delete the certificate from saltenv The salt environment to use this is ignored if the path is local CLI Example: .. code-block:: bash salt '*' certutil.del_store salt://cert.cer TrustedPublisher ''' cert_file = __salt__['cp.cache_file'](source, saltenv) serial = get_cert_serial(cert_file) cmd = "certutil.exe -delstore {0} {1}".format(store, serial) return __salt__['cmd.run'](cmd)
saltstack/salt
salt/modules/win_certutil.py
get_stored_cert_serials
python
def get_stored_cert_serials(store): ''' Get all of the certificate serials in the specified store store The store to get all the certificate serials from CLI Example: .. code-block:: bash salt '*' certutil.get_stored_cert_serials <store> ''' cmd = "certutil.exe -store {0}".format(store) out = __salt__['cmd.run'](cmd) # match serial numbers by header position to work with multiple languages matches = re.findall(r"={16}\r\n.*:\s*(\w*)\r\n", out) return matches
Get all of the certificate serials in the specified store store The store to get all the certificate serials from CLI Example: .. code-block:: bash salt '*' certutil.get_stored_cert_serials <store>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_certutil.py#L55-L72
null
# -*- coding: utf-8 -*- ''' This module allows you to install certificates into the windows certificate manager. .. code-block:: bash salt '*' certutil.add_store salt://cert.cer "TrustedPublisher" ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import re import logging # Import Salt Libs import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = "certutil" def __virtual__(): ''' Only work on Windows ''' if salt.utils.platform.is_windows(): return __virtualname__ return False def get_cert_serial(cert_file): ''' Get the serial number of a certificate file cert_file The certificate file to find the serial for CLI Example: .. code-block:: bash salt '*' certutil.get_cert_serial <certificate name> ''' cmd = "certutil.exe -silent -verify {0}".format(cert_file) out = __salt__['cmd.run'](cmd) # match serial number by paragraph to work with multiple languages matches = re.search(r":\s*(\w*)\r\n\r\n", out) if matches is not None: return matches.groups()[0].strip() else: return None def add_store(source, store, saltenv='base'): ''' Add the given cert into the given Certificate Store source The source certificate file this can be in the form salt://path/to/file store The certificate store to add the certificate to saltenv The salt environment to use this is ignored if the path is local CLI Example: .. code-block:: bash salt '*' certutil.add_store salt://cert.cer TrustedPublisher ''' cert_file = __salt__['cp.cache_file'](source, saltenv) cmd = "certutil.exe -addstore {0} {1}".format(store, cert_file) return __salt__['cmd.run'](cmd) def del_store(source, store, saltenv='base'): ''' Delete the given cert into the given Certificate Store source The source certificate file this can be in the form salt://path/to/file store The certificate store to delete the certificate from saltenv The salt environment to use this is ignored if the path is local CLI Example: .. code-block:: bash salt '*' certutil.del_store salt://cert.cer TrustedPublisher ''' cert_file = __salt__['cp.cache_file'](source, saltenv) serial = get_cert_serial(cert_file) cmd = "certutil.exe -delstore {0} {1}".format(store, serial) return __salt__['cmd.run'](cmd)
saltstack/salt
salt/modules/win_certutil.py
add_store
python
def add_store(source, store, saltenv='base'): ''' Add the given cert into the given Certificate Store source The source certificate file this can be in the form salt://path/to/file store The certificate store to add the certificate to saltenv The salt environment to use this is ignored if the path is local CLI Example: .. code-block:: bash salt '*' certutil.add_store salt://cert.cer TrustedPublisher ''' cert_file = __salt__['cp.cache_file'](source, saltenv) cmd = "certutil.exe -addstore {0} {1}".format(store, cert_file) return __salt__['cmd.run'](cmd)
Add the given cert into the given Certificate Store source The source certificate file this can be in the form salt://path/to/file store The certificate store to add the certificate to saltenv The salt environment to use this is ignored if the path is local CLI Example: .. code-block:: bash salt '*' certutil.add_store salt://cert.cer TrustedPublisher
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_certutil.py#L75-L98
null
# -*- coding: utf-8 -*- ''' This module allows you to install certificates into the windows certificate manager. .. code-block:: bash salt '*' certutil.add_store salt://cert.cer "TrustedPublisher" ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import re import logging # Import Salt Libs import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = "certutil" def __virtual__(): ''' Only work on Windows ''' if salt.utils.platform.is_windows(): return __virtualname__ return False def get_cert_serial(cert_file): ''' Get the serial number of a certificate file cert_file The certificate file to find the serial for CLI Example: .. code-block:: bash salt '*' certutil.get_cert_serial <certificate name> ''' cmd = "certutil.exe -silent -verify {0}".format(cert_file) out = __salt__['cmd.run'](cmd) # match serial number by paragraph to work with multiple languages matches = re.search(r":\s*(\w*)\r\n\r\n", out) if matches is not None: return matches.groups()[0].strip() else: return None def get_stored_cert_serials(store): ''' Get all of the certificate serials in the specified store store The store to get all the certificate serials from CLI Example: .. code-block:: bash salt '*' certutil.get_stored_cert_serials <store> ''' cmd = "certutil.exe -store {0}".format(store) out = __salt__['cmd.run'](cmd) # match serial numbers by header position to work with multiple languages matches = re.findall(r"={16}\r\n.*:\s*(\w*)\r\n", out) return matches def del_store(source, store, saltenv='base'): ''' Delete the given cert into the given Certificate Store source The source certificate file this can be in the form salt://path/to/file store The certificate store to delete the certificate from saltenv The salt environment to use this is ignored if the path is local CLI Example: .. code-block:: bash salt '*' certutil.del_store salt://cert.cer TrustedPublisher ''' cert_file = __salt__['cp.cache_file'](source, saltenv) serial = get_cert_serial(cert_file) cmd = "certutil.exe -delstore {0} {1}".format(store, serial) return __salt__['cmd.run'](cmd)
saltstack/salt
salt/modules/win_certutil.py
del_store
python
def del_store(source, store, saltenv='base'): ''' Delete the given cert into the given Certificate Store source The source certificate file this can be in the form salt://path/to/file store The certificate store to delete the certificate from saltenv The salt environment to use this is ignored if the path is local CLI Example: .. code-block:: bash salt '*' certutil.del_store salt://cert.cer TrustedPublisher ''' cert_file = __salt__['cp.cache_file'](source, saltenv) serial = get_cert_serial(cert_file) cmd = "certutil.exe -delstore {0} {1}".format(store, serial) return __salt__['cmd.run'](cmd)
Delete the given cert into the given Certificate Store source The source certificate file this can be in the form salt://path/to/file store The certificate store to delete the certificate from saltenv The salt environment to use this is ignored if the path is local CLI Example: .. code-block:: bash salt '*' certutil.del_store salt://cert.cer TrustedPublisher
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_certutil.py#L101-L125
[ "def get_cert_serial(cert_file):\n '''\n Get the serial number of a certificate file\n\n cert_file\n The certificate file to find the serial for\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' certutil.get_cert_serial <certificate name>\n '''\n cmd = \"certutil.exe -silent -verify {0}\".format(cert_file)\n out = __salt__['cmd.run'](cmd)\n # match serial number by paragraph to work with multiple languages\n matches = re.search(r\":\\s*(\\w*)\\r\\n\\r\\n\", out)\n if matches is not None:\n return matches.groups()[0].strip()\n else:\n return None\n" ]
# -*- coding: utf-8 -*- ''' This module allows you to install certificates into the windows certificate manager. .. code-block:: bash salt '*' certutil.add_store salt://cert.cer "TrustedPublisher" ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import re import logging # Import Salt Libs import salt.utils.platform log = logging.getLogger(__name__) __virtualname__ = "certutil" def __virtual__(): ''' Only work on Windows ''' if salt.utils.platform.is_windows(): return __virtualname__ return False def get_cert_serial(cert_file): ''' Get the serial number of a certificate file cert_file The certificate file to find the serial for CLI Example: .. code-block:: bash salt '*' certutil.get_cert_serial <certificate name> ''' cmd = "certutil.exe -silent -verify {0}".format(cert_file) out = __salt__['cmd.run'](cmd) # match serial number by paragraph to work with multiple languages matches = re.search(r":\s*(\w*)\r\n\r\n", out) if matches is not None: return matches.groups()[0].strip() else: return None def get_stored_cert_serials(store): ''' Get all of the certificate serials in the specified store store The store to get all the certificate serials from CLI Example: .. code-block:: bash salt '*' certutil.get_stored_cert_serials <store> ''' cmd = "certutil.exe -store {0}".format(store) out = __salt__['cmd.run'](cmd) # match serial numbers by header position to work with multiple languages matches = re.findall(r"={16}\r\n.*:\s*(\w*)\r\n", out) return matches def add_store(source, store, saltenv='base'): ''' Add the given cert into the given Certificate Store source The source certificate file this can be in the form salt://path/to/file store The certificate store to add the certificate to saltenv The salt environment to use this is ignored if the path is local CLI Example: .. code-block:: bash salt '*' certutil.add_store salt://cert.cer TrustedPublisher ''' cert_file = __salt__['cp.cache_file'](source, saltenv) cmd = "certutil.exe -addstore {0} {1}".format(store, cert_file) return __salt__['cmd.run'](cmd)
saltstack/salt
salt/states/ddns.py
present
python
def present(name, zone, ttl, data, rdtype='A', **kwargs): ''' Ensures that the named DNS record is present with the given ttl. name The host portion of the DNS record, e.g., 'webserver'. Name and zone are concatenated when the entry is created unless name includes a trailing dot, so make sure that information is not duplicated in these two arguments. zone The zone to check/update ttl TTL for the record data Data for the DNS record. E.g., the IP address for an A record. rdtype DNS resource type. Default 'A'. ``**kwargs`` Additional arguments the ddns.update function may need (e.g. nameserver, keyfile, keyname). Note that the nsupdate key file can’t be reused by this function, the keyfile and other arguments must follow the `dnspython <http://www.dnspython.org/>`_ spec. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if __opts__['test']: ret['result'] = None ret['comment'] = '{0} record "{1}" will be updated'.format(rdtype, name) return ret status = __salt__['ddns.update'](zone, name, ttl, rdtype, data, **kwargs) if status is None: ret['result'] = True ret['comment'] = '{0} record "{1}" already present with ttl of {2}'.format( rdtype, name, ttl) elif status: ret['result'] = True ret['comment'] = 'Updated {0} record for "{1}"'.format(rdtype, name) ret['changes'] = {'name': name, 'zone': zone, 'ttl': ttl, 'rdtype': rdtype, 'data': data } else: ret['result'] = False ret['comment'] = 'Failed to create or update {0} record for "{1}"'.format(rdtype, name) return ret
Ensures that the named DNS record is present with the given ttl. name The host portion of the DNS record, e.g., 'webserver'. Name and zone are concatenated when the entry is created unless name includes a trailing dot, so make sure that information is not duplicated in these two arguments. zone The zone to check/update ttl TTL for the record data Data for the DNS record. E.g., the IP address for an A record. rdtype DNS resource type. Default 'A'. ``**kwargs`` Additional arguments the ddns.update function may need (e.g. nameserver, keyfile, keyname). Note that the nsupdate key file can’t be reused by this function, the keyfile and other arguments must follow the `dnspython <http://www.dnspython.org/>`_ spec.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ddns.py#L35-L91
null
# -*- coding: utf-8 -*- ''' Dynamic DNS updates =================== Ensure a DNS record is present or absent utilizing RFC 2136 type dynamic updates. :depends: - `dnspython <http://www.dnspython.org/>`_ .. note:: The ``dnspython`` module is required when managing DDNS using a TSIG key. If you are not using a TSIG key, DDNS is allowed by ACLs based on IP address and the ``dnspython`` module is not required. Example: .. code-block:: yaml webserver: ddns.present: - zone: example.com - ttl: 60 - data: 111.222.333.444 - nameserver: 123.234.345.456 - keyfile: /srv/salt/dnspy_tsig_key.txt ''' from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): return 'ddns' if 'ddns.update' in __salt__ else False def absent(name, zone, data=None, rdtype=None, **kwargs): ''' Ensures that the named DNS record is absent. name The host portion of the DNS record, e.g., 'webserver'. Name and zone are concatenated when the entry is created unless name includes a trailing dot, so make sure that information is not duplicated in these two arguments. zone The zone to check data Data for the DNS record. E.g., the IP address for an A record. If omitted, all records matching name (and rdtype, if provided) will be purged. rdtype DNS resource type. If omitted, all types will be purged. ``**kwargs`` Additional arguments the ddns.update function may need (e.g. nameserver, keyfile, keyname). Note that the nsupdate key file can’t be reused by this function, the keyfile and other arguments must follow the `dnspython <http://www.dnspython.org/>`_ spec. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if __opts__['test']: ret['result'] = None ret['comment'] = '{0} record "{1}" will be deleted'.format(rdtype, name) return ret status = __salt__['ddns.delete'](zone, name, rdtype, data, **kwargs) if status is None: ret['result'] = True ret['comment'] = 'No matching DNS record(s) present' elif status: ret['result'] = True ret['comment'] = 'Deleted DNS record(s)' ret['changes'] = {'Deleted': {'name': name, 'zone': zone } } else: ret['result'] = False ret['comment'] = 'Failed to delete DNS record(s)' return ret
saltstack/salt
salt/states/ddns.py
absent
python
def absent(name, zone, data=None, rdtype=None, **kwargs): ''' Ensures that the named DNS record is absent. name The host portion of the DNS record, e.g., 'webserver'. Name and zone are concatenated when the entry is created unless name includes a trailing dot, so make sure that information is not duplicated in these two arguments. zone The zone to check data Data for the DNS record. E.g., the IP address for an A record. If omitted, all records matching name (and rdtype, if provided) will be purged. rdtype DNS resource type. If omitted, all types will be purged. ``**kwargs`` Additional arguments the ddns.update function may need (e.g. nameserver, keyfile, keyname). Note that the nsupdate key file can’t be reused by this function, the keyfile and other arguments must follow the `dnspython <http://www.dnspython.org/>`_ spec. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if __opts__['test']: ret['result'] = None ret['comment'] = '{0} record "{1}" will be deleted'.format(rdtype, name) return ret status = __salt__['ddns.delete'](zone, name, rdtype, data, **kwargs) if status is None: ret['result'] = True ret['comment'] = 'No matching DNS record(s) present' elif status: ret['result'] = True ret['comment'] = 'Deleted DNS record(s)' ret['changes'] = {'Deleted': {'name': name, 'zone': zone } } else: ret['result'] = False ret['comment'] = 'Failed to delete DNS record(s)' return ret
Ensures that the named DNS record is absent. name The host portion of the DNS record, e.g., 'webserver'. Name and zone are concatenated when the entry is created unless name includes a trailing dot, so make sure that information is not duplicated in these two arguments. zone The zone to check data Data for the DNS record. E.g., the IP address for an A record. If omitted, all records matching name (and rdtype, if provided) will be purged. rdtype DNS resource type. If omitted, all types will be purged. ``**kwargs`` Additional arguments the ddns.update function may need (e.g. nameserver, keyfile, keyname). Note that the nsupdate key file can’t be reused by this function, the keyfile and other arguments must follow the `dnspython <http://www.dnspython.org/>`_ spec.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ddns.py#L94-L145
null
# -*- coding: utf-8 -*- ''' Dynamic DNS updates =================== Ensure a DNS record is present or absent utilizing RFC 2136 type dynamic updates. :depends: - `dnspython <http://www.dnspython.org/>`_ .. note:: The ``dnspython`` module is required when managing DDNS using a TSIG key. If you are not using a TSIG key, DDNS is allowed by ACLs based on IP address and the ``dnspython`` module is not required. Example: .. code-block:: yaml webserver: ddns.present: - zone: example.com - ttl: 60 - data: 111.222.333.444 - nameserver: 123.234.345.456 - keyfile: /srv/salt/dnspy_tsig_key.txt ''' from __future__ import absolute_import, print_function, unicode_literals def __virtual__(): return 'ddns' if 'ddns.update' in __salt__ else False def present(name, zone, ttl, data, rdtype='A', **kwargs): ''' Ensures that the named DNS record is present with the given ttl. name The host portion of the DNS record, e.g., 'webserver'. Name and zone are concatenated when the entry is created unless name includes a trailing dot, so make sure that information is not duplicated in these two arguments. zone The zone to check/update ttl TTL for the record data Data for the DNS record. E.g., the IP address for an A record. rdtype DNS resource type. Default 'A'. ``**kwargs`` Additional arguments the ddns.update function may need (e.g. nameserver, keyfile, keyname). Note that the nsupdate key file can’t be reused by this function, the keyfile and other arguments must follow the `dnspython <http://www.dnspython.org/>`_ spec. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if __opts__['test']: ret['result'] = None ret['comment'] = '{0} record "{1}" will be updated'.format(rdtype, name) return ret status = __salt__['ddns.update'](zone, name, ttl, rdtype, data, **kwargs) if status is None: ret['result'] = True ret['comment'] = '{0} record "{1}" already present with ttl of {2}'.format( rdtype, name, ttl) elif status: ret['result'] = True ret['comment'] = 'Updated {0} record for "{1}"'.format(rdtype, name) ret['changes'] = {'name': name, 'zone': zone, 'ttl': ttl, 'rdtype': rdtype, 'data': data } else: ret['result'] = False ret['comment'] = 'Failed to create or update {0} record for "{1}"'.format(rdtype, name) return ret
saltstack/salt
salt/renderers/json.py
render
python
def render(json_data, saltenv='base', sls='', **kws): ''' Accepts JSON as a string or as a file object and runs it through the JSON parser. :rtype: A Python data structure ''' if not isinstance(json_data, six.string_types): json_data = json_data.read() if json_data.startswith('#!'): json_data = json_data[(json_data.find('\n') + 1):] if not json_data.strip(): return {} return json.loads(json_data)
Accepts JSON as a string or as a file object and runs it through the JSON parser. :rtype: A Python data structure
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/json.py#L16-L30
null
# -*- coding: utf-8 -*- ''' JSON Renderer for Salt ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import salt.utils.json json = salt.utils.json.import_json() # Import salt libs from salt.ext import six
saltstack/salt
salt/modules/at.py
_cmd
python
def _cmd(binary, *args): ''' Wrapper to run at(1) or return None. ''' binary = salt.utils.path.which(binary) if not binary: raise CommandNotFoundError('{0}: command not found'.format(binary)) cmd = [binary] + list(args) return __salt__['cmd.run_stdout']([binary] + list(args), python_shell=False)
Wrapper to run at(1) or return None.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at.py#L51-L60
null
# -*- coding: utf-8 -*- ''' Wrapper module for at(1) Also, a 'tag' feature has been added to more easily tag jobs. :platform: linux,openbsd,freebsd .. versionchanged:: 2017.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import re import time import datetime # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import map # pylint: enable=import-error,redefined-builtin from salt.exceptions import CommandNotFoundError from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.path import salt.utils.platform # OS Families that should work (Ubuntu and Debian are the default) # TODO: Refactor some of this module to remove the checks for binaries # Tested on OpenBSD 5.0 BSD = ('OpenBSD', 'FreeBSD') __virtualname__ = 'at' def __virtual__(): ''' Most everything has the ability to support at(1) ''' if salt.utils.platform.is_windows() or salt.utils.platform.is_sunos(): return (False, 'The at module could not be loaded: unsupported platform') if salt.utils.path.which('at') is None: return (False, 'The at module could not be loaded: at command not found') return __virtualname__ def atq(tag=None): ''' List all queued and running jobs or only those with an optional 'tag'. CLI Example: .. code-block:: bash salt '*' at.atq salt '*' at.atq [tag] salt '*' at.atq [job number] ''' jobs = [] # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() # Tested on CentOS 5.8 if __grains__['os_family'] == 'RedHat': output = _cmd('at', '-l') else: output = _cmd('atq') if output is None: return '\'at.atq\' is not available.' # No jobs so return if output == '': return {'jobs': jobs} # Jobs created with at.at() will use the following # comment to denote a tagged job. job_kw_regex = re.compile(r'^### SALT: (\w+)') # Split each job into a dictionary and handle # pulling out tags or only listing jobs with a certain # tag for line in output.splitlines(): job_tag = '' # Redhat/CentOS if __grains__['os_family'] == 'RedHat': job, spec = line.split('\t') specs = spec.split() elif __grains__['os'] == 'OpenBSD': if line.startswith(' Rank'): continue else: tmp = line.split() timestr = ' '.join(tmp[1:5]) job = tmp[6] specs = datetime.datetime(*(time.strptime(timestr, '%b %d, %Y ' '%H:%M')[0:5])).isoformat().split('T') specs.append(tmp[7]) specs.append(tmp[5]) elif __grains__['os'] == 'FreeBSD': if line.startswith('Date'): continue else: tmp = line.split() timestr = ' '.join(tmp[1:6]) job = tmp[8] specs = datetime.datetime(*(time.strptime(timestr, '%b %d %H:%M:%S %Z %Y')[0:5])).isoformat().split('T') specs.append(tmp[7]) specs.append(tmp[6]) else: job, spec = line.split('\t') tmp = spec.split() timestr = ' '.join(tmp[0:5]) specs = datetime.datetime(*(time.strptime(timestr) [0:5])).isoformat().split('T') specs.append(tmp[5]) specs.append(tmp[6]) # Search for any tags atc_out = _cmd('at', '-c', job) for line in atc_out.splitlines(): tmp = job_kw_regex.match(line) if tmp: job_tag = tmp.groups()[0] if __grains__['os'] in BSD: job = six.text_type(job) else: job = int(job) # If a tag is supplied, only list jobs with that tag if tag: # TODO: Looks like there is a difference between salt and salt-call # If I don't wrap job in an int(), it fails on salt but works on # salt-call. With the int(), it fails with salt-call but not salt. if tag == job_tag or tag == job: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) else: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) return {'jobs': jobs} def atrm(*args): ''' Remove jobs from the queue. CLI Example: .. code-block:: bash salt '*' at.atrm <jobid> <jobid> .. <jobid> salt '*' at.atrm all salt '*' at.atrm all [tag] ''' # Need to do this here also since we use atq() if not salt.utils.path.which('at'): return '\'at.atrm\' is not available.' if not args: return {'jobs': {'removed': [], 'tag': None}} # Convert all to strings args = salt.utils.data.stringify(args) if args[0] == 'all': if len(args) > 1: opts = list(list(map(str, [j['job'] for j in atq(args[1])['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': args[1]}} else: opts = list(list(map(str, [j['job'] for j in atq()['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': None}} else: opts = list(list(map(str, [i['job'] for i in atq()['jobs'] if six.text_type(i['job']) in args]))) ret = {'jobs': {'removed': opts, 'tag': None}} # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() output = _cmd('at', '-d', ' '.join(opts)) if output is None: return '\'at.atrm\' is not available.' return ret def at(*args, **kwargs): # pylint: disable=C0103 ''' Add a job to the queue. The 'timespec' follows the format documented in the at(1) manpage. CLI Example: .. code-block:: bash salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>] salt '*' at.at 12:05am '/sbin/reboot' tag=reboot salt '*' at.at '3:05am +3 days' 'bin/myscript' tag=nightly runas=jim ''' if len(args) < 2: return {'jobs': []} # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() binary = salt.utils.path.which('at') if not binary: return '\'at.at\' is not available.' if 'tag' in kwargs: stdin = '### SALT: {0}\n{1}'.format(kwargs['tag'], ' '.join(args[1:])) else: stdin = ' '.join(args[1:]) cmd = [binary, args[0]] cmd_kwargs = {'stdin': stdin, 'python_shell': False} if 'runas' in kwargs: cmd_kwargs['runas'] = kwargs['runas'] output = __salt__['cmd.run'](cmd, **cmd_kwargs) if output is None: return '\'at.at\' is not available.' if output.endswith('Garbled time'): return {'jobs': [], 'error': 'invalid timespec'} if output.startswith('warning: commands'): output = output.splitlines()[1] if output.startswith('commands will be executed'): output = output.splitlines()[1] output = output.split()[1] if __grains__['os'] in BSD: return atq(six.text_type(output)) else: return atq(int(output)) def atc(jobid): ''' Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid> ''' # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() output = _cmd('at', '-c', six.text_type(jobid)) if output is None: return '\'at.atc\' is not available.' elif output == '': return {'error': 'invalid job id \'{0}\''.format(jobid)} return output def _atq(**kwargs): ''' Return match jobs list ''' jobs = [] runas = kwargs.get('runas', None) tag = kwargs.get('tag', None) hour = kwargs.get('hour', None) minute = kwargs.get('minute', None) day = kwargs.get('day', None) month = kwargs.get('month', None) year = kwargs.get('year', None) if year and len(six.text_type(year)) == 2: year = '20{0}'.format(year) jobinfo = atq()['jobs'] if not jobinfo: return {'jobs': jobs} for job in jobinfo: if not runas: pass elif runas == job['user']: pass else: continue if not tag: pass elif tag == job['tag']: pass else: continue if not hour: pass elif '{0:02d}'.format(int(hour)) == job['time'].split(':')[0]: pass else: continue if not minute: pass elif '{0:02d}'.format(int(minute)) == job['time'].split(':')[1]: pass else: continue if not day: pass elif '{0:02d}'.format(int(day)) == job['date'].split('-')[2]: pass else: continue if not month: pass elif '{0:02d}'.format(int(month)) == job['date'].split('-')[1]: pass else: continue if not year: pass elif year == job['date'].split('-')[0]: pass else: continue jobs.append(job) if not jobs: note = 'No match jobs or time format error' return {'jobs': jobs, 'note': note} return {'jobs': jobs} def jobcheck(**kwargs): ''' Check the job from queue. The kwargs dict include 'hour minute day month year tag runas' Other parameters will be ignored. CLI Example: .. code-block:: bash salt '*' at.jobcheck runas=jam day=13 salt '*' at.jobcheck day=13 month=12 year=13 tag=rose ''' if not kwargs: return {'error': 'You have given a condition'} return _atq(**kwargs)
saltstack/salt
salt/modules/at.py
atq
python
def atq(tag=None): ''' List all queued and running jobs or only those with an optional 'tag'. CLI Example: .. code-block:: bash salt '*' at.atq salt '*' at.atq [tag] salt '*' at.atq [job number] ''' jobs = [] # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() # Tested on CentOS 5.8 if __grains__['os_family'] == 'RedHat': output = _cmd('at', '-l') else: output = _cmd('atq') if output is None: return '\'at.atq\' is not available.' # No jobs so return if output == '': return {'jobs': jobs} # Jobs created with at.at() will use the following # comment to denote a tagged job. job_kw_regex = re.compile(r'^### SALT: (\w+)') # Split each job into a dictionary and handle # pulling out tags or only listing jobs with a certain # tag for line in output.splitlines(): job_tag = '' # Redhat/CentOS if __grains__['os_family'] == 'RedHat': job, spec = line.split('\t') specs = spec.split() elif __grains__['os'] == 'OpenBSD': if line.startswith(' Rank'): continue else: tmp = line.split() timestr = ' '.join(tmp[1:5]) job = tmp[6] specs = datetime.datetime(*(time.strptime(timestr, '%b %d, %Y ' '%H:%M')[0:5])).isoformat().split('T') specs.append(tmp[7]) specs.append(tmp[5]) elif __grains__['os'] == 'FreeBSD': if line.startswith('Date'): continue else: tmp = line.split() timestr = ' '.join(tmp[1:6]) job = tmp[8] specs = datetime.datetime(*(time.strptime(timestr, '%b %d %H:%M:%S %Z %Y')[0:5])).isoformat().split('T') specs.append(tmp[7]) specs.append(tmp[6]) else: job, spec = line.split('\t') tmp = spec.split() timestr = ' '.join(tmp[0:5]) specs = datetime.datetime(*(time.strptime(timestr) [0:5])).isoformat().split('T') specs.append(tmp[5]) specs.append(tmp[6]) # Search for any tags atc_out = _cmd('at', '-c', job) for line in atc_out.splitlines(): tmp = job_kw_regex.match(line) if tmp: job_tag = tmp.groups()[0] if __grains__['os'] in BSD: job = six.text_type(job) else: job = int(job) # If a tag is supplied, only list jobs with that tag if tag: # TODO: Looks like there is a difference between salt and salt-call # If I don't wrap job in an int(), it fails on salt but works on # salt-call. With the int(), it fails with salt-call but not salt. if tag == job_tag or tag == job: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) else: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) return {'jobs': jobs}
List all queued and running jobs or only those with an optional 'tag'. CLI Example: .. code-block:: bash salt '*' at.atq salt '*' at.atq [tag] salt '*' at.atq [job number]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at.py#L63-L163
[ "def _cmd(binary, *args):\n '''\n Wrapper to run at(1) or return None.\n '''\n binary = salt.utils.path.which(binary)\n if not binary:\n raise CommandNotFoundError('{0}: command not found'.format(binary))\n cmd = [binary] + list(args)\n return __salt__['cmd.run_stdout']([binary] + list(args),\n python_shell=False)\n" ]
# -*- coding: utf-8 -*- ''' Wrapper module for at(1) Also, a 'tag' feature has been added to more easily tag jobs. :platform: linux,openbsd,freebsd .. versionchanged:: 2017.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import re import time import datetime # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import map # pylint: enable=import-error,redefined-builtin from salt.exceptions import CommandNotFoundError from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.path import salt.utils.platform # OS Families that should work (Ubuntu and Debian are the default) # TODO: Refactor some of this module to remove the checks for binaries # Tested on OpenBSD 5.0 BSD = ('OpenBSD', 'FreeBSD') __virtualname__ = 'at' def __virtual__(): ''' Most everything has the ability to support at(1) ''' if salt.utils.platform.is_windows() or salt.utils.platform.is_sunos(): return (False, 'The at module could not be loaded: unsupported platform') if salt.utils.path.which('at') is None: return (False, 'The at module could not be loaded: at command not found') return __virtualname__ def _cmd(binary, *args): ''' Wrapper to run at(1) or return None. ''' binary = salt.utils.path.which(binary) if not binary: raise CommandNotFoundError('{0}: command not found'.format(binary)) cmd = [binary] + list(args) return __salt__['cmd.run_stdout']([binary] + list(args), python_shell=False) def atrm(*args): ''' Remove jobs from the queue. CLI Example: .. code-block:: bash salt '*' at.atrm <jobid> <jobid> .. <jobid> salt '*' at.atrm all salt '*' at.atrm all [tag] ''' # Need to do this here also since we use atq() if not salt.utils.path.which('at'): return '\'at.atrm\' is not available.' if not args: return {'jobs': {'removed': [], 'tag': None}} # Convert all to strings args = salt.utils.data.stringify(args) if args[0] == 'all': if len(args) > 1: opts = list(list(map(str, [j['job'] for j in atq(args[1])['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': args[1]}} else: opts = list(list(map(str, [j['job'] for j in atq()['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': None}} else: opts = list(list(map(str, [i['job'] for i in atq()['jobs'] if six.text_type(i['job']) in args]))) ret = {'jobs': {'removed': opts, 'tag': None}} # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() output = _cmd('at', '-d', ' '.join(opts)) if output is None: return '\'at.atrm\' is not available.' return ret def at(*args, **kwargs): # pylint: disable=C0103 ''' Add a job to the queue. The 'timespec' follows the format documented in the at(1) manpage. CLI Example: .. code-block:: bash salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>] salt '*' at.at 12:05am '/sbin/reboot' tag=reboot salt '*' at.at '3:05am +3 days' 'bin/myscript' tag=nightly runas=jim ''' if len(args) < 2: return {'jobs': []} # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() binary = salt.utils.path.which('at') if not binary: return '\'at.at\' is not available.' if 'tag' in kwargs: stdin = '### SALT: {0}\n{1}'.format(kwargs['tag'], ' '.join(args[1:])) else: stdin = ' '.join(args[1:]) cmd = [binary, args[0]] cmd_kwargs = {'stdin': stdin, 'python_shell': False} if 'runas' in kwargs: cmd_kwargs['runas'] = kwargs['runas'] output = __salt__['cmd.run'](cmd, **cmd_kwargs) if output is None: return '\'at.at\' is not available.' if output.endswith('Garbled time'): return {'jobs': [], 'error': 'invalid timespec'} if output.startswith('warning: commands'): output = output.splitlines()[1] if output.startswith('commands will be executed'): output = output.splitlines()[1] output = output.split()[1] if __grains__['os'] in BSD: return atq(six.text_type(output)) else: return atq(int(output)) def atc(jobid): ''' Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid> ''' # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() output = _cmd('at', '-c', six.text_type(jobid)) if output is None: return '\'at.atc\' is not available.' elif output == '': return {'error': 'invalid job id \'{0}\''.format(jobid)} return output def _atq(**kwargs): ''' Return match jobs list ''' jobs = [] runas = kwargs.get('runas', None) tag = kwargs.get('tag', None) hour = kwargs.get('hour', None) minute = kwargs.get('minute', None) day = kwargs.get('day', None) month = kwargs.get('month', None) year = kwargs.get('year', None) if year and len(six.text_type(year)) == 2: year = '20{0}'.format(year) jobinfo = atq()['jobs'] if not jobinfo: return {'jobs': jobs} for job in jobinfo: if not runas: pass elif runas == job['user']: pass else: continue if not tag: pass elif tag == job['tag']: pass else: continue if not hour: pass elif '{0:02d}'.format(int(hour)) == job['time'].split(':')[0]: pass else: continue if not minute: pass elif '{0:02d}'.format(int(minute)) == job['time'].split(':')[1]: pass else: continue if not day: pass elif '{0:02d}'.format(int(day)) == job['date'].split('-')[2]: pass else: continue if not month: pass elif '{0:02d}'.format(int(month)) == job['date'].split('-')[1]: pass else: continue if not year: pass elif year == job['date'].split('-')[0]: pass else: continue jobs.append(job) if not jobs: note = 'No match jobs or time format error' return {'jobs': jobs, 'note': note} return {'jobs': jobs} def jobcheck(**kwargs): ''' Check the job from queue. The kwargs dict include 'hour minute day month year tag runas' Other parameters will be ignored. CLI Example: .. code-block:: bash salt '*' at.jobcheck runas=jam day=13 salt '*' at.jobcheck day=13 month=12 year=13 tag=rose ''' if not kwargs: return {'error': 'You have given a condition'} return _atq(**kwargs)
saltstack/salt
salt/modules/at.py
atrm
python
def atrm(*args): ''' Remove jobs from the queue. CLI Example: .. code-block:: bash salt '*' at.atrm <jobid> <jobid> .. <jobid> salt '*' at.atrm all salt '*' at.atrm all [tag] ''' # Need to do this here also since we use atq() if not salt.utils.path.which('at'): return '\'at.atrm\' is not available.' if not args: return {'jobs': {'removed': [], 'tag': None}} # Convert all to strings args = salt.utils.data.stringify(args) if args[0] == 'all': if len(args) > 1: opts = list(list(map(str, [j['job'] for j in atq(args[1])['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': args[1]}} else: opts = list(list(map(str, [j['job'] for j in atq()['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': None}} else: opts = list(list(map(str, [i['job'] for i in atq()['jobs'] if six.text_type(i['job']) in args]))) ret = {'jobs': {'removed': opts, 'tag': None}} # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() output = _cmd('at', '-d', ' '.join(opts)) if output is None: return '\'at.atrm\' is not available.' return ret
Remove jobs from the queue. CLI Example: .. code-block:: bash salt '*' at.atrm <jobid> <jobid> .. <jobid> salt '*' at.atrm all salt '*' at.atrm all [tag]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at.py#L166-L207
[ "def _cmd(binary, *args):\n '''\n Wrapper to run at(1) or return None.\n '''\n binary = salt.utils.path.which(binary)\n if not binary:\n raise CommandNotFoundError('{0}: command not found'.format(binary))\n cmd = [binary] + list(args)\n return __salt__['cmd.run_stdout']([binary] + list(args),\n python_shell=False)\n" ]
# -*- coding: utf-8 -*- ''' Wrapper module for at(1) Also, a 'tag' feature has been added to more easily tag jobs. :platform: linux,openbsd,freebsd .. versionchanged:: 2017.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import re import time import datetime # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import map # pylint: enable=import-error,redefined-builtin from salt.exceptions import CommandNotFoundError from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.path import salt.utils.platform # OS Families that should work (Ubuntu and Debian are the default) # TODO: Refactor some of this module to remove the checks for binaries # Tested on OpenBSD 5.0 BSD = ('OpenBSD', 'FreeBSD') __virtualname__ = 'at' def __virtual__(): ''' Most everything has the ability to support at(1) ''' if salt.utils.platform.is_windows() or salt.utils.platform.is_sunos(): return (False, 'The at module could not be loaded: unsupported platform') if salt.utils.path.which('at') is None: return (False, 'The at module could not be loaded: at command not found') return __virtualname__ def _cmd(binary, *args): ''' Wrapper to run at(1) or return None. ''' binary = salt.utils.path.which(binary) if not binary: raise CommandNotFoundError('{0}: command not found'.format(binary)) cmd = [binary] + list(args) return __salt__['cmd.run_stdout']([binary] + list(args), python_shell=False) def atq(tag=None): ''' List all queued and running jobs or only those with an optional 'tag'. CLI Example: .. code-block:: bash salt '*' at.atq salt '*' at.atq [tag] salt '*' at.atq [job number] ''' jobs = [] # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() # Tested on CentOS 5.8 if __grains__['os_family'] == 'RedHat': output = _cmd('at', '-l') else: output = _cmd('atq') if output is None: return '\'at.atq\' is not available.' # No jobs so return if output == '': return {'jobs': jobs} # Jobs created with at.at() will use the following # comment to denote a tagged job. job_kw_regex = re.compile(r'^### SALT: (\w+)') # Split each job into a dictionary and handle # pulling out tags or only listing jobs with a certain # tag for line in output.splitlines(): job_tag = '' # Redhat/CentOS if __grains__['os_family'] == 'RedHat': job, spec = line.split('\t') specs = spec.split() elif __grains__['os'] == 'OpenBSD': if line.startswith(' Rank'): continue else: tmp = line.split() timestr = ' '.join(tmp[1:5]) job = tmp[6] specs = datetime.datetime(*(time.strptime(timestr, '%b %d, %Y ' '%H:%M')[0:5])).isoformat().split('T') specs.append(tmp[7]) specs.append(tmp[5]) elif __grains__['os'] == 'FreeBSD': if line.startswith('Date'): continue else: tmp = line.split() timestr = ' '.join(tmp[1:6]) job = tmp[8] specs = datetime.datetime(*(time.strptime(timestr, '%b %d %H:%M:%S %Z %Y')[0:5])).isoformat().split('T') specs.append(tmp[7]) specs.append(tmp[6]) else: job, spec = line.split('\t') tmp = spec.split() timestr = ' '.join(tmp[0:5]) specs = datetime.datetime(*(time.strptime(timestr) [0:5])).isoformat().split('T') specs.append(tmp[5]) specs.append(tmp[6]) # Search for any tags atc_out = _cmd('at', '-c', job) for line in atc_out.splitlines(): tmp = job_kw_regex.match(line) if tmp: job_tag = tmp.groups()[0] if __grains__['os'] in BSD: job = six.text_type(job) else: job = int(job) # If a tag is supplied, only list jobs with that tag if tag: # TODO: Looks like there is a difference between salt and salt-call # If I don't wrap job in an int(), it fails on salt but works on # salt-call. With the int(), it fails with salt-call but not salt. if tag == job_tag or tag == job: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) else: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) return {'jobs': jobs} def at(*args, **kwargs): # pylint: disable=C0103 ''' Add a job to the queue. The 'timespec' follows the format documented in the at(1) manpage. CLI Example: .. code-block:: bash salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>] salt '*' at.at 12:05am '/sbin/reboot' tag=reboot salt '*' at.at '3:05am +3 days' 'bin/myscript' tag=nightly runas=jim ''' if len(args) < 2: return {'jobs': []} # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() binary = salt.utils.path.which('at') if not binary: return '\'at.at\' is not available.' if 'tag' in kwargs: stdin = '### SALT: {0}\n{1}'.format(kwargs['tag'], ' '.join(args[1:])) else: stdin = ' '.join(args[1:]) cmd = [binary, args[0]] cmd_kwargs = {'stdin': stdin, 'python_shell': False} if 'runas' in kwargs: cmd_kwargs['runas'] = kwargs['runas'] output = __salt__['cmd.run'](cmd, **cmd_kwargs) if output is None: return '\'at.at\' is not available.' if output.endswith('Garbled time'): return {'jobs': [], 'error': 'invalid timespec'} if output.startswith('warning: commands'): output = output.splitlines()[1] if output.startswith('commands will be executed'): output = output.splitlines()[1] output = output.split()[1] if __grains__['os'] in BSD: return atq(six.text_type(output)) else: return atq(int(output)) def atc(jobid): ''' Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid> ''' # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() output = _cmd('at', '-c', six.text_type(jobid)) if output is None: return '\'at.atc\' is not available.' elif output == '': return {'error': 'invalid job id \'{0}\''.format(jobid)} return output def _atq(**kwargs): ''' Return match jobs list ''' jobs = [] runas = kwargs.get('runas', None) tag = kwargs.get('tag', None) hour = kwargs.get('hour', None) minute = kwargs.get('minute', None) day = kwargs.get('day', None) month = kwargs.get('month', None) year = kwargs.get('year', None) if year and len(six.text_type(year)) == 2: year = '20{0}'.format(year) jobinfo = atq()['jobs'] if not jobinfo: return {'jobs': jobs} for job in jobinfo: if not runas: pass elif runas == job['user']: pass else: continue if not tag: pass elif tag == job['tag']: pass else: continue if not hour: pass elif '{0:02d}'.format(int(hour)) == job['time'].split(':')[0]: pass else: continue if not minute: pass elif '{0:02d}'.format(int(minute)) == job['time'].split(':')[1]: pass else: continue if not day: pass elif '{0:02d}'.format(int(day)) == job['date'].split('-')[2]: pass else: continue if not month: pass elif '{0:02d}'.format(int(month)) == job['date'].split('-')[1]: pass else: continue if not year: pass elif year == job['date'].split('-')[0]: pass else: continue jobs.append(job) if not jobs: note = 'No match jobs or time format error' return {'jobs': jobs, 'note': note} return {'jobs': jobs} def jobcheck(**kwargs): ''' Check the job from queue. The kwargs dict include 'hour minute day month year tag runas' Other parameters will be ignored. CLI Example: .. code-block:: bash salt '*' at.jobcheck runas=jam day=13 salt '*' at.jobcheck day=13 month=12 year=13 tag=rose ''' if not kwargs: return {'error': 'You have given a condition'} return _atq(**kwargs)
saltstack/salt
salt/modules/at.py
at
python
def at(*args, **kwargs): # pylint: disable=C0103 ''' Add a job to the queue. The 'timespec' follows the format documented in the at(1) manpage. CLI Example: .. code-block:: bash salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>] salt '*' at.at 12:05am '/sbin/reboot' tag=reboot salt '*' at.at '3:05am +3 days' 'bin/myscript' tag=nightly runas=jim ''' if len(args) < 2: return {'jobs': []} # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() binary = salt.utils.path.which('at') if not binary: return '\'at.at\' is not available.' if 'tag' in kwargs: stdin = '### SALT: {0}\n{1}'.format(kwargs['tag'], ' '.join(args[1:])) else: stdin = ' '.join(args[1:]) cmd = [binary, args[0]] cmd_kwargs = {'stdin': stdin, 'python_shell': False} if 'runas' in kwargs: cmd_kwargs['runas'] = kwargs['runas'] output = __salt__['cmd.run'](cmd, **cmd_kwargs) if output is None: return '\'at.at\' is not available.' if output.endswith('Garbled time'): return {'jobs': [], 'error': 'invalid timespec'} if output.startswith('warning: commands'): output = output.splitlines()[1] if output.startswith('commands will be executed'): output = output.splitlines()[1] output = output.split()[1] if __grains__['os'] in BSD: return atq(six.text_type(output)) else: return atq(int(output))
Add a job to the queue. The 'timespec' follows the format documented in the at(1) manpage. CLI Example: .. code-block:: bash salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>] salt '*' at.at 12:05am '/sbin/reboot' tag=reboot salt '*' at.at '3:05am +3 days' 'bin/myscript' tag=nightly runas=jim
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at.py#L210-L263
[ "def atq(tag=None):\n '''\n List all queued and running jobs or only those with\n an optional 'tag'.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' at.atq\n salt '*' at.atq [tag]\n salt '*' at.atq [job number]\n '''\n jobs = []\n\n # Shim to produce output similar to what __virtual__() should do\n # but __salt__ isn't available in __virtual__()\n # Tested on CentOS 5.8\n if __grains__['os_family'] == 'RedHat':\n output = _cmd('at', '-l')\n else:\n output = _cmd('atq')\n\n if output is None:\n return '\\'at.atq\\' is not available.'\n\n # No jobs so return\n if output == '':\n return {'jobs': jobs}\n\n # Jobs created with at.at() will use the following\n # comment to denote a tagged job.\n job_kw_regex = re.compile(r'^### SALT: (\\w+)')\n\n # Split each job into a dictionary and handle\n # pulling out tags or only listing jobs with a certain\n # tag\n for line in output.splitlines():\n job_tag = ''\n\n # Redhat/CentOS\n if __grains__['os_family'] == 'RedHat':\n job, spec = line.split('\\t')\n specs = spec.split()\n elif __grains__['os'] == 'OpenBSD':\n if line.startswith(' Rank'):\n continue\n else:\n tmp = line.split()\n timestr = ' '.join(tmp[1:5])\n job = tmp[6]\n specs = datetime.datetime(*(time.strptime(timestr, '%b %d, %Y '\n '%H:%M')[0:5])).isoformat().split('T')\n specs.append(tmp[7])\n specs.append(tmp[5])\n elif __grains__['os'] == 'FreeBSD':\n if line.startswith('Date'):\n continue\n else:\n tmp = line.split()\n timestr = ' '.join(tmp[1:6])\n job = tmp[8]\n specs = datetime.datetime(*(time.strptime(timestr,\n '%b %d %H:%M:%S %Z %Y')[0:5])).isoformat().split('T')\n specs.append(tmp[7])\n specs.append(tmp[6])\n\n else:\n job, spec = line.split('\\t')\n tmp = spec.split()\n timestr = ' '.join(tmp[0:5])\n specs = datetime.datetime(*(time.strptime(timestr)\n [0:5])).isoformat().split('T')\n specs.append(tmp[5])\n specs.append(tmp[6])\n\n # Search for any tags\n atc_out = _cmd('at', '-c', job)\n for line in atc_out.splitlines():\n tmp = job_kw_regex.match(line)\n if tmp:\n job_tag = tmp.groups()[0]\n\n if __grains__['os'] in BSD:\n job = six.text_type(job)\n else:\n job = int(job)\n\n # If a tag is supplied, only list jobs with that tag\n if tag:\n # TODO: Looks like there is a difference between salt and salt-call\n # If I don't wrap job in an int(), it fails on salt but works on\n # salt-call. With the int(), it fails with salt-call but not salt.\n if tag == job_tag or tag == job:\n jobs.append({'job': job, 'date': specs[0], 'time': specs[1],\n 'queue': specs[2], 'user': specs[3], 'tag': job_tag})\n else:\n jobs.append({'job': job, 'date': specs[0], 'time': specs[1],\n 'queue': specs[2], 'user': specs[3], 'tag': job_tag})\n\n return {'jobs': jobs}\n" ]
# -*- coding: utf-8 -*- ''' Wrapper module for at(1) Also, a 'tag' feature has been added to more easily tag jobs. :platform: linux,openbsd,freebsd .. versionchanged:: 2017.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import re import time import datetime # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import map # pylint: enable=import-error,redefined-builtin from salt.exceptions import CommandNotFoundError from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.path import salt.utils.platform # OS Families that should work (Ubuntu and Debian are the default) # TODO: Refactor some of this module to remove the checks for binaries # Tested on OpenBSD 5.0 BSD = ('OpenBSD', 'FreeBSD') __virtualname__ = 'at' def __virtual__(): ''' Most everything has the ability to support at(1) ''' if salt.utils.platform.is_windows() or salt.utils.platform.is_sunos(): return (False, 'The at module could not be loaded: unsupported platform') if salt.utils.path.which('at') is None: return (False, 'The at module could not be loaded: at command not found') return __virtualname__ def _cmd(binary, *args): ''' Wrapper to run at(1) or return None. ''' binary = salt.utils.path.which(binary) if not binary: raise CommandNotFoundError('{0}: command not found'.format(binary)) cmd = [binary] + list(args) return __salt__['cmd.run_stdout']([binary] + list(args), python_shell=False) def atq(tag=None): ''' List all queued and running jobs or only those with an optional 'tag'. CLI Example: .. code-block:: bash salt '*' at.atq salt '*' at.atq [tag] salt '*' at.atq [job number] ''' jobs = [] # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() # Tested on CentOS 5.8 if __grains__['os_family'] == 'RedHat': output = _cmd('at', '-l') else: output = _cmd('atq') if output is None: return '\'at.atq\' is not available.' # No jobs so return if output == '': return {'jobs': jobs} # Jobs created with at.at() will use the following # comment to denote a tagged job. job_kw_regex = re.compile(r'^### SALT: (\w+)') # Split each job into a dictionary and handle # pulling out tags or only listing jobs with a certain # tag for line in output.splitlines(): job_tag = '' # Redhat/CentOS if __grains__['os_family'] == 'RedHat': job, spec = line.split('\t') specs = spec.split() elif __grains__['os'] == 'OpenBSD': if line.startswith(' Rank'): continue else: tmp = line.split() timestr = ' '.join(tmp[1:5]) job = tmp[6] specs = datetime.datetime(*(time.strptime(timestr, '%b %d, %Y ' '%H:%M')[0:5])).isoformat().split('T') specs.append(tmp[7]) specs.append(tmp[5]) elif __grains__['os'] == 'FreeBSD': if line.startswith('Date'): continue else: tmp = line.split() timestr = ' '.join(tmp[1:6]) job = tmp[8] specs = datetime.datetime(*(time.strptime(timestr, '%b %d %H:%M:%S %Z %Y')[0:5])).isoformat().split('T') specs.append(tmp[7]) specs.append(tmp[6]) else: job, spec = line.split('\t') tmp = spec.split() timestr = ' '.join(tmp[0:5]) specs = datetime.datetime(*(time.strptime(timestr) [0:5])).isoformat().split('T') specs.append(tmp[5]) specs.append(tmp[6]) # Search for any tags atc_out = _cmd('at', '-c', job) for line in atc_out.splitlines(): tmp = job_kw_regex.match(line) if tmp: job_tag = tmp.groups()[0] if __grains__['os'] in BSD: job = six.text_type(job) else: job = int(job) # If a tag is supplied, only list jobs with that tag if tag: # TODO: Looks like there is a difference between salt and salt-call # If I don't wrap job in an int(), it fails on salt but works on # salt-call. With the int(), it fails with salt-call but not salt. if tag == job_tag or tag == job: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) else: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) return {'jobs': jobs} def atrm(*args): ''' Remove jobs from the queue. CLI Example: .. code-block:: bash salt '*' at.atrm <jobid> <jobid> .. <jobid> salt '*' at.atrm all salt '*' at.atrm all [tag] ''' # Need to do this here also since we use atq() if not salt.utils.path.which('at'): return '\'at.atrm\' is not available.' if not args: return {'jobs': {'removed': [], 'tag': None}} # Convert all to strings args = salt.utils.data.stringify(args) if args[0] == 'all': if len(args) > 1: opts = list(list(map(str, [j['job'] for j in atq(args[1])['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': args[1]}} else: opts = list(list(map(str, [j['job'] for j in atq()['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': None}} else: opts = list(list(map(str, [i['job'] for i in atq()['jobs'] if six.text_type(i['job']) in args]))) ret = {'jobs': {'removed': opts, 'tag': None}} # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() output = _cmd('at', '-d', ' '.join(opts)) if output is None: return '\'at.atrm\' is not available.' return ret def atc(jobid): ''' Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid> ''' # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() output = _cmd('at', '-c', six.text_type(jobid)) if output is None: return '\'at.atc\' is not available.' elif output == '': return {'error': 'invalid job id \'{0}\''.format(jobid)} return output def _atq(**kwargs): ''' Return match jobs list ''' jobs = [] runas = kwargs.get('runas', None) tag = kwargs.get('tag', None) hour = kwargs.get('hour', None) minute = kwargs.get('minute', None) day = kwargs.get('day', None) month = kwargs.get('month', None) year = kwargs.get('year', None) if year and len(six.text_type(year)) == 2: year = '20{0}'.format(year) jobinfo = atq()['jobs'] if not jobinfo: return {'jobs': jobs} for job in jobinfo: if not runas: pass elif runas == job['user']: pass else: continue if not tag: pass elif tag == job['tag']: pass else: continue if not hour: pass elif '{0:02d}'.format(int(hour)) == job['time'].split(':')[0]: pass else: continue if not minute: pass elif '{0:02d}'.format(int(minute)) == job['time'].split(':')[1]: pass else: continue if not day: pass elif '{0:02d}'.format(int(day)) == job['date'].split('-')[2]: pass else: continue if not month: pass elif '{0:02d}'.format(int(month)) == job['date'].split('-')[1]: pass else: continue if not year: pass elif year == job['date'].split('-')[0]: pass else: continue jobs.append(job) if not jobs: note = 'No match jobs or time format error' return {'jobs': jobs, 'note': note} return {'jobs': jobs} def jobcheck(**kwargs): ''' Check the job from queue. The kwargs dict include 'hour minute day month year tag runas' Other parameters will be ignored. CLI Example: .. code-block:: bash salt '*' at.jobcheck runas=jam day=13 salt '*' at.jobcheck day=13 month=12 year=13 tag=rose ''' if not kwargs: return {'error': 'You have given a condition'} return _atq(**kwargs)
saltstack/salt
salt/modules/at.py
atc
python
def atc(jobid): ''' Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid> ''' # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() output = _cmd('at', '-c', six.text_type(jobid)) if output is None: return '\'at.atc\' is not available.' elif output == '': return {'error': 'invalid job id \'{0}\''.format(jobid)} return output
Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at.py#L266-L287
[ "def _cmd(binary, *args):\n '''\n Wrapper to run at(1) or return None.\n '''\n binary = salt.utils.path.which(binary)\n if not binary:\n raise CommandNotFoundError('{0}: command not found'.format(binary))\n cmd = [binary] + list(args)\n return __salt__['cmd.run_stdout']([binary] + list(args),\n python_shell=False)\n" ]
# -*- coding: utf-8 -*- ''' Wrapper module for at(1) Also, a 'tag' feature has been added to more easily tag jobs. :platform: linux,openbsd,freebsd .. versionchanged:: 2017.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import re import time import datetime # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import map # pylint: enable=import-error,redefined-builtin from salt.exceptions import CommandNotFoundError from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.path import salt.utils.platform # OS Families that should work (Ubuntu and Debian are the default) # TODO: Refactor some of this module to remove the checks for binaries # Tested on OpenBSD 5.0 BSD = ('OpenBSD', 'FreeBSD') __virtualname__ = 'at' def __virtual__(): ''' Most everything has the ability to support at(1) ''' if salt.utils.platform.is_windows() or salt.utils.platform.is_sunos(): return (False, 'The at module could not be loaded: unsupported platform') if salt.utils.path.which('at') is None: return (False, 'The at module could not be loaded: at command not found') return __virtualname__ def _cmd(binary, *args): ''' Wrapper to run at(1) or return None. ''' binary = salt.utils.path.which(binary) if not binary: raise CommandNotFoundError('{0}: command not found'.format(binary)) cmd = [binary] + list(args) return __salt__['cmd.run_stdout']([binary] + list(args), python_shell=False) def atq(tag=None): ''' List all queued and running jobs or only those with an optional 'tag'. CLI Example: .. code-block:: bash salt '*' at.atq salt '*' at.atq [tag] salt '*' at.atq [job number] ''' jobs = [] # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() # Tested on CentOS 5.8 if __grains__['os_family'] == 'RedHat': output = _cmd('at', '-l') else: output = _cmd('atq') if output is None: return '\'at.atq\' is not available.' # No jobs so return if output == '': return {'jobs': jobs} # Jobs created with at.at() will use the following # comment to denote a tagged job. job_kw_regex = re.compile(r'^### SALT: (\w+)') # Split each job into a dictionary and handle # pulling out tags or only listing jobs with a certain # tag for line in output.splitlines(): job_tag = '' # Redhat/CentOS if __grains__['os_family'] == 'RedHat': job, spec = line.split('\t') specs = spec.split() elif __grains__['os'] == 'OpenBSD': if line.startswith(' Rank'): continue else: tmp = line.split() timestr = ' '.join(tmp[1:5]) job = tmp[6] specs = datetime.datetime(*(time.strptime(timestr, '%b %d, %Y ' '%H:%M')[0:5])).isoformat().split('T') specs.append(tmp[7]) specs.append(tmp[5]) elif __grains__['os'] == 'FreeBSD': if line.startswith('Date'): continue else: tmp = line.split() timestr = ' '.join(tmp[1:6]) job = tmp[8] specs = datetime.datetime(*(time.strptime(timestr, '%b %d %H:%M:%S %Z %Y')[0:5])).isoformat().split('T') specs.append(tmp[7]) specs.append(tmp[6]) else: job, spec = line.split('\t') tmp = spec.split() timestr = ' '.join(tmp[0:5]) specs = datetime.datetime(*(time.strptime(timestr) [0:5])).isoformat().split('T') specs.append(tmp[5]) specs.append(tmp[6]) # Search for any tags atc_out = _cmd('at', '-c', job) for line in atc_out.splitlines(): tmp = job_kw_regex.match(line) if tmp: job_tag = tmp.groups()[0] if __grains__['os'] in BSD: job = six.text_type(job) else: job = int(job) # If a tag is supplied, only list jobs with that tag if tag: # TODO: Looks like there is a difference between salt and salt-call # If I don't wrap job in an int(), it fails on salt but works on # salt-call. With the int(), it fails with salt-call but not salt. if tag == job_tag or tag == job: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) else: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) return {'jobs': jobs} def atrm(*args): ''' Remove jobs from the queue. CLI Example: .. code-block:: bash salt '*' at.atrm <jobid> <jobid> .. <jobid> salt '*' at.atrm all salt '*' at.atrm all [tag] ''' # Need to do this here also since we use atq() if not salt.utils.path.which('at'): return '\'at.atrm\' is not available.' if not args: return {'jobs': {'removed': [], 'tag': None}} # Convert all to strings args = salt.utils.data.stringify(args) if args[0] == 'all': if len(args) > 1: opts = list(list(map(str, [j['job'] for j in atq(args[1])['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': args[1]}} else: opts = list(list(map(str, [j['job'] for j in atq()['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': None}} else: opts = list(list(map(str, [i['job'] for i in atq()['jobs'] if six.text_type(i['job']) in args]))) ret = {'jobs': {'removed': opts, 'tag': None}} # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() output = _cmd('at', '-d', ' '.join(opts)) if output is None: return '\'at.atrm\' is not available.' return ret def at(*args, **kwargs): # pylint: disable=C0103 ''' Add a job to the queue. The 'timespec' follows the format documented in the at(1) manpage. CLI Example: .. code-block:: bash salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>] salt '*' at.at 12:05am '/sbin/reboot' tag=reboot salt '*' at.at '3:05am +3 days' 'bin/myscript' tag=nightly runas=jim ''' if len(args) < 2: return {'jobs': []} # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() binary = salt.utils.path.which('at') if not binary: return '\'at.at\' is not available.' if 'tag' in kwargs: stdin = '### SALT: {0}\n{1}'.format(kwargs['tag'], ' '.join(args[1:])) else: stdin = ' '.join(args[1:]) cmd = [binary, args[0]] cmd_kwargs = {'stdin': stdin, 'python_shell': False} if 'runas' in kwargs: cmd_kwargs['runas'] = kwargs['runas'] output = __salt__['cmd.run'](cmd, **cmd_kwargs) if output is None: return '\'at.at\' is not available.' if output.endswith('Garbled time'): return {'jobs': [], 'error': 'invalid timespec'} if output.startswith('warning: commands'): output = output.splitlines()[1] if output.startswith('commands will be executed'): output = output.splitlines()[1] output = output.split()[1] if __grains__['os'] in BSD: return atq(six.text_type(output)) else: return atq(int(output)) def _atq(**kwargs): ''' Return match jobs list ''' jobs = [] runas = kwargs.get('runas', None) tag = kwargs.get('tag', None) hour = kwargs.get('hour', None) minute = kwargs.get('minute', None) day = kwargs.get('day', None) month = kwargs.get('month', None) year = kwargs.get('year', None) if year and len(six.text_type(year)) == 2: year = '20{0}'.format(year) jobinfo = atq()['jobs'] if not jobinfo: return {'jobs': jobs} for job in jobinfo: if not runas: pass elif runas == job['user']: pass else: continue if not tag: pass elif tag == job['tag']: pass else: continue if not hour: pass elif '{0:02d}'.format(int(hour)) == job['time'].split(':')[0]: pass else: continue if not minute: pass elif '{0:02d}'.format(int(minute)) == job['time'].split(':')[1]: pass else: continue if not day: pass elif '{0:02d}'.format(int(day)) == job['date'].split('-')[2]: pass else: continue if not month: pass elif '{0:02d}'.format(int(month)) == job['date'].split('-')[1]: pass else: continue if not year: pass elif year == job['date'].split('-')[0]: pass else: continue jobs.append(job) if not jobs: note = 'No match jobs or time format error' return {'jobs': jobs, 'note': note} return {'jobs': jobs} def jobcheck(**kwargs): ''' Check the job from queue. The kwargs dict include 'hour minute day month year tag runas' Other parameters will be ignored. CLI Example: .. code-block:: bash salt '*' at.jobcheck runas=jam day=13 salt '*' at.jobcheck day=13 month=12 year=13 tag=rose ''' if not kwargs: return {'error': 'You have given a condition'} return _atq(**kwargs)
saltstack/salt
salt/modules/at.py
_atq
python
def _atq(**kwargs): ''' Return match jobs list ''' jobs = [] runas = kwargs.get('runas', None) tag = kwargs.get('tag', None) hour = kwargs.get('hour', None) minute = kwargs.get('minute', None) day = kwargs.get('day', None) month = kwargs.get('month', None) year = kwargs.get('year', None) if year and len(six.text_type(year)) == 2: year = '20{0}'.format(year) jobinfo = atq()['jobs'] if not jobinfo: return {'jobs': jobs} for job in jobinfo: if not runas: pass elif runas == job['user']: pass else: continue if not tag: pass elif tag == job['tag']: pass else: continue if not hour: pass elif '{0:02d}'.format(int(hour)) == job['time'].split(':')[0]: pass else: continue if not minute: pass elif '{0:02d}'.format(int(minute)) == job['time'].split(':')[1]: pass else: continue if not day: pass elif '{0:02d}'.format(int(day)) == job['date'].split('-')[2]: pass else: continue if not month: pass elif '{0:02d}'.format(int(month)) == job['date'].split('-')[1]: pass else: continue if not year: pass elif year == job['date'].split('-')[0]: pass else: continue jobs.append(job) if not jobs: note = 'No match jobs or time format error' return {'jobs': jobs, 'note': note} return {'jobs': jobs}
Return match jobs list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/at.py#L290-L368
[ "def atq(tag=None):\n '''\n List all queued and running jobs or only those with\n an optional 'tag'.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' at.atq\n salt '*' at.atq [tag]\n salt '*' at.atq [job number]\n '''\n jobs = []\n\n # Shim to produce output similar to what __virtual__() should do\n # but __salt__ isn't available in __virtual__()\n # Tested on CentOS 5.8\n if __grains__['os_family'] == 'RedHat':\n output = _cmd('at', '-l')\n else:\n output = _cmd('atq')\n\n if output is None:\n return '\\'at.atq\\' is not available.'\n\n # No jobs so return\n if output == '':\n return {'jobs': jobs}\n\n # Jobs created with at.at() will use the following\n # comment to denote a tagged job.\n job_kw_regex = re.compile(r'^### SALT: (\\w+)')\n\n # Split each job into a dictionary and handle\n # pulling out tags or only listing jobs with a certain\n # tag\n for line in output.splitlines():\n job_tag = ''\n\n # Redhat/CentOS\n if __grains__['os_family'] == 'RedHat':\n job, spec = line.split('\\t')\n specs = spec.split()\n elif __grains__['os'] == 'OpenBSD':\n if line.startswith(' Rank'):\n continue\n else:\n tmp = line.split()\n timestr = ' '.join(tmp[1:5])\n job = tmp[6]\n specs = datetime.datetime(*(time.strptime(timestr, '%b %d, %Y '\n '%H:%M')[0:5])).isoformat().split('T')\n specs.append(tmp[7])\n specs.append(tmp[5])\n elif __grains__['os'] == 'FreeBSD':\n if line.startswith('Date'):\n continue\n else:\n tmp = line.split()\n timestr = ' '.join(tmp[1:6])\n job = tmp[8]\n specs = datetime.datetime(*(time.strptime(timestr,\n '%b %d %H:%M:%S %Z %Y')[0:5])).isoformat().split('T')\n specs.append(tmp[7])\n specs.append(tmp[6])\n\n else:\n job, spec = line.split('\\t')\n tmp = spec.split()\n timestr = ' '.join(tmp[0:5])\n specs = datetime.datetime(*(time.strptime(timestr)\n [0:5])).isoformat().split('T')\n specs.append(tmp[5])\n specs.append(tmp[6])\n\n # Search for any tags\n atc_out = _cmd('at', '-c', job)\n for line in atc_out.splitlines():\n tmp = job_kw_regex.match(line)\n if tmp:\n job_tag = tmp.groups()[0]\n\n if __grains__['os'] in BSD:\n job = six.text_type(job)\n else:\n job = int(job)\n\n # If a tag is supplied, only list jobs with that tag\n if tag:\n # TODO: Looks like there is a difference between salt and salt-call\n # If I don't wrap job in an int(), it fails on salt but works on\n # salt-call. With the int(), it fails with salt-call but not salt.\n if tag == job_tag or tag == job:\n jobs.append({'job': job, 'date': specs[0], 'time': specs[1],\n 'queue': specs[2], 'user': specs[3], 'tag': job_tag})\n else:\n jobs.append({'job': job, 'date': specs[0], 'time': specs[1],\n 'queue': specs[2], 'user': specs[3], 'tag': job_tag})\n\n return {'jobs': jobs}\n" ]
# -*- coding: utf-8 -*- ''' Wrapper module for at(1) Also, a 'tag' feature has been added to more easily tag jobs. :platform: linux,openbsd,freebsd .. versionchanged:: 2017.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import re import time import datetime # Import 3rd-party libs # pylint: disable=import-error,redefined-builtin from salt.ext.six.moves import map # pylint: enable=import-error,redefined-builtin from salt.exceptions import CommandNotFoundError from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.path import salt.utils.platform # OS Families that should work (Ubuntu and Debian are the default) # TODO: Refactor some of this module to remove the checks for binaries # Tested on OpenBSD 5.0 BSD = ('OpenBSD', 'FreeBSD') __virtualname__ = 'at' def __virtual__(): ''' Most everything has the ability to support at(1) ''' if salt.utils.platform.is_windows() or salt.utils.platform.is_sunos(): return (False, 'The at module could not be loaded: unsupported platform') if salt.utils.path.which('at') is None: return (False, 'The at module could not be loaded: at command not found') return __virtualname__ def _cmd(binary, *args): ''' Wrapper to run at(1) or return None. ''' binary = salt.utils.path.which(binary) if not binary: raise CommandNotFoundError('{0}: command not found'.format(binary)) cmd = [binary] + list(args) return __salt__['cmd.run_stdout']([binary] + list(args), python_shell=False) def atq(tag=None): ''' List all queued and running jobs or only those with an optional 'tag'. CLI Example: .. code-block:: bash salt '*' at.atq salt '*' at.atq [tag] salt '*' at.atq [job number] ''' jobs = [] # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() # Tested on CentOS 5.8 if __grains__['os_family'] == 'RedHat': output = _cmd('at', '-l') else: output = _cmd('atq') if output is None: return '\'at.atq\' is not available.' # No jobs so return if output == '': return {'jobs': jobs} # Jobs created with at.at() will use the following # comment to denote a tagged job. job_kw_regex = re.compile(r'^### SALT: (\w+)') # Split each job into a dictionary and handle # pulling out tags or only listing jobs with a certain # tag for line in output.splitlines(): job_tag = '' # Redhat/CentOS if __grains__['os_family'] == 'RedHat': job, spec = line.split('\t') specs = spec.split() elif __grains__['os'] == 'OpenBSD': if line.startswith(' Rank'): continue else: tmp = line.split() timestr = ' '.join(tmp[1:5]) job = tmp[6] specs = datetime.datetime(*(time.strptime(timestr, '%b %d, %Y ' '%H:%M')[0:5])).isoformat().split('T') specs.append(tmp[7]) specs.append(tmp[5]) elif __grains__['os'] == 'FreeBSD': if line.startswith('Date'): continue else: tmp = line.split() timestr = ' '.join(tmp[1:6]) job = tmp[8] specs = datetime.datetime(*(time.strptime(timestr, '%b %d %H:%M:%S %Z %Y')[0:5])).isoformat().split('T') specs.append(tmp[7]) specs.append(tmp[6]) else: job, spec = line.split('\t') tmp = spec.split() timestr = ' '.join(tmp[0:5]) specs = datetime.datetime(*(time.strptime(timestr) [0:5])).isoformat().split('T') specs.append(tmp[5]) specs.append(tmp[6]) # Search for any tags atc_out = _cmd('at', '-c', job) for line in atc_out.splitlines(): tmp = job_kw_regex.match(line) if tmp: job_tag = tmp.groups()[0] if __grains__['os'] in BSD: job = six.text_type(job) else: job = int(job) # If a tag is supplied, only list jobs with that tag if tag: # TODO: Looks like there is a difference between salt and salt-call # If I don't wrap job in an int(), it fails on salt but works on # salt-call. With the int(), it fails with salt-call but not salt. if tag == job_tag or tag == job: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) else: jobs.append({'job': job, 'date': specs[0], 'time': specs[1], 'queue': specs[2], 'user': specs[3], 'tag': job_tag}) return {'jobs': jobs} def atrm(*args): ''' Remove jobs from the queue. CLI Example: .. code-block:: bash salt '*' at.atrm <jobid> <jobid> .. <jobid> salt '*' at.atrm all salt '*' at.atrm all [tag] ''' # Need to do this here also since we use atq() if not salt.utils.path.which('at'): return '\'at.atrm\' is not available.' if not args: return {'jobs': {'removed': [], 'tag': None}} # Convert all to strings args = salt.utils.data.stringify(args) if args[0] == 'all': if len(args) > 1: opts = list(list(map(str, [j['job'] for j in atq(args[1])['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': args[1]}} else: opts = list(list(map(str, [j['job'] for j in atq()['jobs']]))) ret = {'jobs': {'removed': opts, 'tag': None}} else: opts = list(list(map(str, [i['job'] for i in atq()['jobs'] if six.text_type(i['job']) in args]))) ret = {'jobs': {'removed': opts, 'tag': None}} # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() output = _cmd('at', '-d', ' '.join(opts)) if output is None: return '\'at.atrm\' is not available.' return ret def at(*args, **kwargs): # pylint: disable=C0103 ''' Add a job to the queue. The 'timespec' follows the format documented in the at(1) manpage. CLI Example: .. code-block:: bash salt '*' at.at <timespec> <cmd> [tag=<tag>] [runas=<user>] salt '*' at.at 12:05am '/sbin/reboot' tag=reboot salt '*' at.at '3:05am +3 days' 'bin/myscript' tag=nightly runas=jim ''' if len(args) < 2: return {'jobs': []} # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() binary = salt.utils.path.which('at') if not binary: return '\'at.at\' is not available.' if 'tag' in kwargs: stdin = '### SALT: {0}\n{1}'.format(kwargs['tag'], ' '.join(args[1:])) else: stdin = ' '.join(args[1:]) cmd = [binary, args[0]] cmd_kwargs = {'stdin': stdin, 'python_shell': False} if 'runas' in kwargs: cmd_kwargs['runas'] = kwargs['runas'] output = __salt__['cmd.run'](cmd, **cmd_kwargs) if output is None: return '\'at.at\' is not available.' if output.endswith('Garbled time'): return {'jobs': [], 'error': 'invalid timespec'} if output.startswith('warning: commands'): output = output.splitlines()[1] if output.startswith('commands will be executed'): output = output.splitlines()[1] output = output.split()[1] if __grains__['os'] in BSD: return atq(six.text_type(output)) else: return atq(int(output)) def atc(jobid): ''' Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid> ''' # Shim to produce output similar to what __virtual__() should do # but __salt__ isn't available in __virtual__() output = _cmd('at', '-c', six.text_type(jobid)) if output is None: return '\'at.atc\' is not available.' elif output == '': return {'error': 'invalid job id \'{0}\''.format(jobid)} return output def jobcheck(**kwargs): ''' Check the job from queue. The kwargs dict include 'hour minute day month year tag runas' Other parameters will be ignored. CLI Example: .. code-block:: bash salt '*' at.jobcheck runas=jam day=13 salt '*' at.jobcheck day=13 month=12 year=13 tag=rose ''' if not kwargs: return {'error': 'You have given a condition'} return _atq(**kwargs)
saltstack/salt
salt/cli/support/__init__.py
_render_profile
python
def _render_profile(path, caller, runner): ''' Render profile as Jinja2. :param path: :return: ''' env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(path)), trim_blocks=False) return env.get_template(os.path.basename(path)).render(salt=caller, runners=runner).strip()
Render profile as Jinja2. :param path: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/__init__.py#L15-L22
null
# coding=utf-8 ''' Get default scenario of the support. ''' from __future__ import print_function, unicode_literals, absolute_import import yaml import os import salt.exceptions import jinja2 import logging log = logging.getLogger(__name__) def get_profile(profile, caller, runner): ''' Get profile. :param profile: :return: ''' profiles = profile.split(',') data = {} for profile in profiles: if os.path.basename(profile) == profile: profile = profile.split('.')[0] # Trim extension if someone added it profile_path = os.path.join(os.path.dirname(__file__), 'profiles', profile + '.yml') else: profile_path = profile if os.path.exists(profile_path): try: rendered_template = _render_profile(profile_path, caller, runner) line = '-' * 80 log.debug('\n%s\n%s\n%s\n', line, rendered_template, line) data.update(yaml.load(rendered_template)) except Exception as ex: log.debug(ex, exc_info=True) raise salt.exceptions.SaltException('Rendering profile failed: {}'.format(ex)) else: raise salt.exceptions.SaltException('Profile "{}" is not found.'.format(profile)) return data def get_profiles(config): ''' Get available profiles. :return: ''' profiles = [] for profile_name in os.listdir(os.path.join(os.path.dirname(__file__), 'profiles')): if profile_name.endswith('.yml'): profiles.append(profile_name.split('.')[0]) return sorted(profiles)
saltstack/salt
salt/cli/support/__init__.py
get_profile
python
def get_profile(profile, caller, runner): ''' Get profile. :param profile: :return: ''' profiles = profile.split(',') data = {} for profile in profiles: if os.path.basename(profile) == profile: profile = profile.split('.')[0] # Trim extension if someone added it profile_path = os.path.join(os.path.dirname(__file__), 'profiles', profile + '.yml') else: profile_path = profile if os.path.exists(profile_path): try: rendered_template = _render_profile(profile_path, caller, runner) line = '-' * 80 log.debug('\n%s\n%s\n%s\n', line, rendered_template, line) data.update(yaml.load(rendered_template)) except Exception as ex: log.debug(ex, exc_info=True) raise salt.exceptions.SaltException('Rendering profile failed: {}'.format(ex)) else: raise salt.exceptions.SaltException('Profile "{}" is not found.'.format(profile)) return data
Get profile. :param profile: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/__init__.py#L25-L52
[ "def _render_profile(path, caller, runner):\n '''\n Render profile as Jinja2.\n :param path:\n :return:\n '''\n env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(path)), trim_blocks=False)\n return env.get_template(os.path.basename(path)).render(salt=caller, runners=runner).strip()\n" ]
# coding=utf-8 ''' Get default scenario of the support. ''' from __future__ import print_function, unicode_literals, absolute_import import yaml import os import salt.exceptions import jinja2 import logging log = logging.getLogger(__name__) def _render_profile(path, caller, runner): ''' Render profile as Jinja2. :param path: :return: ''' env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(path)), trim_blocks=False) return env.get_template(os.path.basename(path)).render(salt=caller, runners=runner).strip() def get_profiles(config): ''' Get available profiles. :return: ''' profiles = [] for profile_name in os.listdir(os.path.join(os.path.dirname(__file__), 'profiles')): if profile_name.endswith('.yml'): profiles.append(profile_name.split('.')[0]) return sorted(profiles)
saltstack/salt
salt/cli/support/__init__.py
get_profiles
python
def get_profiles(config): ''' Get available profiles. :return: ''' profiles = [] for profile_name in os.listdir(os.path.join(os.path.dirname(__file__), 'profiles')): if profile_name.endswith('.yml'): profiles.append(profile_name.split('.')[0]) return sorted(profiles)
Get available profiles. :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/support/__init__.py#L55-L66
null
# coding=utf-8 ''' Get default scenario of the support. ''' from __future__ import print_function, unicode_literals, absolute_import import yaml import os import salt.exceptions import jinja2 import logging log = logging.getLogger(__name__) def _render_profile(path, caller, runner): ''' Render profile as Jinja2. :param path: :return: ''' env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(path)), trim_blocks=False) return env.get_template(os.path.basename(path)).render(salt=caller, runners=runner).strip() def get_profile(profile, caller, runner): ''' Get profile. :param profile: :return: ''' profiles = profile.split(',') data = {} for profile in profiles: if os.path.basename(profile) == profile: profile = profile.split('.')[0] # Trim extension if someone added it profile_path = os.path.join(os.path.dirname(__file__), 'profiles', profile + '.yml') else: profile_path = profile if os.path.exists(profile_path): try: rendered_template = _render_profile(profile_path, caller, runner) line = '-' * 80 log.debug('\n%s\n%s\n%s\n', line, rendered_template, line) data.update(yaml.load(rendered_template)) except Exception as ex: log.debug(ex, exc_info=True) raise salt.exceptions.SaltException('Rendering profile failed: {}'.format(ex)) else: raise salt.exceptions.SaltException('Profile "{}" is not found.'.format(profile)) return data
saltstack/salt
salt/utils/user.py
get_user
python
def get_user(): ''' Get the current user ''' if HAS_PWD: ret = pwd.getpwuid(os.geteuid()).pw_name elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32: ret = salt.utils.win_functions.get_current_user() else: raise CommandExecutionError( 'Required external library (pwd or win32api) not installed') return salt.utils.stringutils.to_unicode(ret)
Get the current user
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L54-L65
[ "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def get_current_user(with_domain=True):\n '''\n Gets the user executing the process\n\n Args:\n\n with_domain (bool):\n ``True`` will prepend the user name with the machine name or domain\n separated by a backslash\n\n Returns:\n str: The user name\n '''\n try:\n user_name = win32api.GetUserNameEx(win32api.NameSamCompatible)\n if user_name[-1] == '$':\n # Make the system account easier to identify.\n # Fetch sid so as to handle other language than english\n test_user = win32api.GetUserName()\n if test_user == 'SYSTEM':\n user_name = 'SYSTEM'\n elif get_sid_from_name(test_user) == 'S-1-5-18':\n user_name = 'SYSTEM'\n elif not with_domain:\n user_name = win32api.GetUserName()\n except pywintypes.error as exc:\n raise CommandExecutionError(\n 'Failed to get current user: {0}'.format(exc))\n\n if not user_name:\n return False\n\n return user_name\n" ]
# -*- coding: utf-8 -*- ''' Functions for querying and modifying a user account and the groups to which it belongs. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import ctypes import getpass import logging import os import sys # Import Salt libs import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.decorators.jinja import jinja_filter # Import 3rd-party libs from salt.ext import six # Conditional imports try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False try: import grp HAS_GRP = True except ImportError: HAS_GRP = False try: import pysss HAS_PYSSS = True except ImportError: HAS_PYSSS = False try: import salt.utils.win_functions HAS_WIN_FUNCTIONS = True except ImportError: HAS_WIN_FUNCTIONS = False log = logging.getLogger(__name__) @jinja_filter('get_uid') def get_uid(user=None): ''' Get the uid for a given user name. If no user given, the current euid will be returned. If the user does not exist, None will be returned. On systems which do not support pwd or os.geteuid, None will be returned. ''' if not HAS_PWD: return None elif user is None: try: return os.geteuid() except AttributeError: return None else: try: return pwd.getpwnam(user).pw_uid except KeyError: return None def _win_user_token_is_admin(user_token): ''' Using the win32 api, determine if the user with token 'user_token' has administrator rights. See MSDN entry here: http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx ''' class SID_IDENTIFIER_AUTHORITY(ctypes.Structure): _fields_ = [ ("byte0", ctypes.c_byte), ("byte1", ctypes.c_byte), ("byte2", ctypes.c_byte), ("byte3", ctypes.c_byte), ("byte4", ctypes.c_byte), ("byte5", ctypes.c_byte), ] nt_authority = SID_IDENTIFIER_AUTHORITY() nt_authority.byte5 = 5 SECURITY_BUILTIN_DOMAIN_RID = 0x20 DOMAIN_ALIAS_RID_ADMINS = 0x220 administrators_group = ctypes.c_void_p() if ctypes.windll.advapi32.AllocateAndInitializeSid( ctypes.byref(nt_authority), 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ctypes.byref(administrators_group)) == 0: raise Exception("AllocateAndInitializeSid failed") try: is_admin = ctypes.wintypes.BOOL() if ctypes.windll.advapi32.CheckTokenMembership( user_token, administrators_group, ctypes.byref(is_admin)) == 0: raise Exception("CheckTokenMembership failed") return is_admin.value != 0 finally: ctypes.windll.advapi32.FreeSid(administrators_group) def _win_current_user_is_admin(): ''' ctypes.windll.shell32.IsUserAnAdmin() is intentionally avoided due to this function being deprecated. ''' return _win_user_token_is_admin(0) def get_specific_user(): ''' Get a user name for publishing. If you find the user is "root" attempt to be more specific ''' user = get_user() if salt.utils.platform.is_windows(): if _win_current_user_is_admin(): return 'sudo_{0}'.format(user) else: env_vars = ('SUDO_USER',) if user == 'root': for evar in env_vars: if evar in os.environ: return 'sudo_{0}'.format(os.environ[evar]) return user def chugid(runas, group=None): ''' Change the current process to belong to the specified user (and the groups to which it belongs) ''' uinfo = pwd.getpwnam(runas) supgroups = [] supgroups_seen = set() if group: try: target_pw_gid = grp.getgrnam(group).gr_gid except KeyError as err: raise CommandExecutionError( 'Failed to fetch the GID for {0}. Error: {1}'.format( group, err ) ) else: target_pw_gid = uinfo.pw_gid # The line below used to exclude the current user's primary gid. # However, when root belongs to more than one group # this causes root's primary group of '0' to be dropped from # his grouplist. On FreeBSD, at least, this makes some # command executions fail with 'access denied'. # # The Python documentation says that os.setgroups sets only # the supplemental groups for a running process. On FreeBSD # this does not appear to be strictly true. group_list = get_group_dict(runas, include_default=True) if sys.platform == 'darwin': group_list = dict((k, v) for k, v in six.iteritems(group_list) if not k.startswith('_')) for group_name in group_list: gid = group_list[group_name] if (gid not in supgroups_seen and not supgroups_seen.add(gid)): supgroups.append(gid) if os.getgid() != target_pw_gid: try: os.setgid(target_pw_gid) except OSError as err: raise CommandExecutionError( 'Failed to change from gid {0} to {1}. Error: {2}'.format( os.getgid(), target_pw_gid, err ) ) # Set supplemental groups if sorted(os.getgroups()) != sorted(supgroups): try: os.setgroups(supgroups) except OSError as err: raise CommandExecutionError( 'Failed to set supplemental groups to {0}. Error: {1}'.format( supgroups, err ) ) if os.getuid() != uinfo.pw_uid: try: os.setuid(uinfo.pw_uid) except OSError as err: raise CommandExecutionError( 'Failed to change from uid {0} to {1}. Error: {2}'.format( os.getuid(), uinfo.pw_uid, err ) ) def chugid_and_umask(runas, umask, group=None): ''' Helper method for for subprocess.Popen to initialise uid/gid and umask for the new process. ''' set_runas = False set_grp = False current_user = getpass.getuser() if runas and runas != current_user: set_runas = True runas_user = runas else: runas_user = current_user current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name if group and group != current_grp: set_grp = True runas_grp = group else: runas_grp = current_grp if set_runas or set_grp: chugid(runas_user, runas_grp) if umask is not None: os.umask(umask) # pylint: disable=blacklisted-function def get_default_group(user): ''' Returns the specified user's default group. If the user doesn't exist, a KeyError will be raised. ''' return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \ if HAS_GRP and HAS_PWD \ else None def get_group_list(user, include_default=True): ''' Returns a list of all of the system group names of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] group_names = None ugroups = set() if hasattr(os, 'getgrouplist'): # Try os.getgrouplist, available in python >= 3.3 log.trace('Trying os.getgrouplist for \'%s\'', user) try: group_names = [ grp.getgrgid(grpid).gr_name for grpid in os.getgrouplist(user, pwd.getpwnam(user).pw_gid) ] except Exception: pass elif HAS_PYSSS: # Try pysss.getgrouplist log.trace('Trying pysss.getgrouplist for \'%s\'', user) try: group_names = list(pysss.getgrouplist(user)) except Exception: pass if group_names is None: # Fall back to generic code # Include the user's default group to match behavior of # os.getgrouplist() and pysss.getgrouplist() log.trace('Trying generic group list for \'%s\'', user) group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] try: default_group = get_default_group(user) if default_group not in group_names: group_names.append(default_group) except KeyError: # If for some reason the user does not have a default group pass if group_names is not None: ugroups.update(group_names) if include_default is False: # Historically, saltstack code for getting group lists did not # include the default group. Some things may only want # supplemental groups, so include_default=False omits the users # default group. try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name ugroups.remove(default_group) except KeyError: # If for some reason the user does not have a default group pass log.trace('Group list for user \'%s\': %s', user, sorted(ugroups)) return sorted(ugroups) def get_group_dict(user=None, include_default=True): ''' Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27} ''' if HAS_GRP is False or HAS_PWD is False: return {} group_dict = {} group_names = get_group_list(user, include_default=include_default) for group in group_names: group_dict.update({group: grp.getgrnam(group).gr_gid}) return group_dict def get_gid_list(user, include_default=True): ''' Returns a list of all of the system group IDs of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] gid_list = list( six.itervalues( get_group_dict(user, include_default=include_default) ) ) return sorted(set(gid_list)) def get_gid(group=None): ''' Get the gid for a given group name. If no group given, the current egid will be returned. If the group does not exist, None will be returned. On systems which do not support grp or os.getegid it will return None. ''' if not HAS_GRP: return None if group is None: try: return os.getegid() except AttributeError: return None else: try: return grp.getgrnam(group).gr_gid except KeyError: return None
saltstack/salt
salt/utils/user.py
get_uid
python
def get_uid(user=None): ''' Get the uid for a given user name. If no user given, the current euid will be returned. If the user does not exist, None will be returned. On systems which do not support pwd or os.geteuid, None will be returned. ''' if not HAS_PWD: return None elif user is None: try: return os.geteuid() except AttributeError: return None else: try: return pwd.getpwnam(user).pw_uid except KeyError: return None
Get the uid for a given user name. If no user given, the current euid will be returned. If the user does not exist, None will be returned. On systems which do not support pwd or os.geteuid, None will be returned.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L69-L86
null
# -*- coding: utf-8 -*- ''' Functions for querying and modifying a user account and the groups to which it belongs. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import ctypes import getpass import logging import os import sys # Import Salt libs import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.decorators.jinja import jinja_filter # Import 3rd-party libs from salt.ext import six # Conditional imports try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False try: import grp HAS_GRP = True except ImportError: HAS_GRP = False try: import pysss HAS_PYSSS = True except ImportError: HAS_PYSSS = False try: import salt.utils.win_functions HAS_WIN_FUNCTIONS = True except ImportError: HAS_WIN_FUNCTIONS = False log = logging.getLogger(__name__) def get_user(): ''' Get the current user ''' if HAS_PWD: ret = pwd.getpwuid(os.geteuid()).pw_name elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32: ret = salt.utils.win_functions.get_current_user() else: raise CommandExecutionError( 'Required external library (pwd or win32api) not installed') return salt.utils.stringutils.to_unicode(ret) @jinja_filter('get_uid') def _win_user_token_is_admin(user_token): ''' Using the win32 api, determine if the user with token 'user_token' has administrator rights. See MSDN entry here: http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx ''' class SID_IDENTIFIER_AUTHORITY(ctypes.Structure): _fields_ = [ ("byte0", ctypes.c_byte), ("byte1", ctypes.c_byte), ("byte2", ctypes.c_byte), ("byte3", ctypes.c_byte), ("byte4", ctypes.c_byte), ("byte5", ctypes.c_byte), ] nt_authority = SID_IDENTIFIER_AUTHORITY() nt_authority.byte5 = 5 SECURITY_BUILTIN_DOMAIN_RID = 0x20 DOMAIN_ALIAS_RID_ADMINS = 0x220 administrators_group = ctypes.c_void_p() if ctypes.windll.advapi32.AllocateAndInitializeSid( ctypes.byref(nt_authority), 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ctypes.byref(administrators_group)) == 0: raise Exception("AllocateAndInitializeSid failed") try: is_admin = ctypes.wintypes.BOOL() if ctypes.windll.advapi32.CheckTokenMembership( user_token, administrators_group, ctypes.byref(is_admin)) == 0: raise Exception("CheckTokenMembership failed") return is_admin.value != 0 finally: ctypes.windll.advapi32.FreeSid(administrators_group) def _win_current_user_is_admin(): ''' ctypes.windll.shell32.IsUserAnAdmin() is intentionally avoided due to this function being deprecated. ''' return _win_user_token_is_admin(0) def get_specific_user(): ''' Get a user name for publishing. If you find the user is "root" attempt to be more specific ''' user = get_user() if salt.utils.platform.is_windows(): if _win_current_user_is_admin(): return 'sudo_{0}'.format(user) else: env_vars = ('SUDO_USER',) if user == 'root': for evar in env_vars: if evar in os.environ: return 'sudo_{0}'.format(os.environ[evar]) return user def chugid(runas, group=None): ''' Change the current process to belong to the specified user (and the groups to which it belongs) ''' uinfo = pwd.getpwnam(runas) supgroups = [] supgroups_seen = set() if group: try: target_pw_gid = grp.getgrnam(group).gr_gid except KeyError as err: raise CommandExecutionError( 'Failed to fetch the GID for {0}. Error: {1}'.format( group, err ) ) else: target_pw_gid = uinfo.pw_gid # The line below used to exclude the current user's primary gid. # However, when root belongs to more than one group # this causes root's primary group of '0' to be dropped from # his grouplist. On FreeBSD, at least, this makes some # command executions fail with 'access denied'. # # The Python documentation says that os.setgroups sets only # the supplemental groups for a running process. On FreeBSD # this does not appear to be strictly true. group_list = get_group_dict(runas, include_default=True) if sys.platform == 'darwin': group_list = dict((k, v) for k, v in six.iteritems(group_list) if not k.startswith('_')) for group_name in group_list: gid = group_list[group_name] if (gid not in supgroups_seen and not supgroups_seen.add(gid)): supgroups.append(gid) if os.getgid() != target_pw_gid: try: os.setgid(target_pw_gid) except OSError as err: raise CommandExecutionError( 'Failed to change from gid {0} to {1}. Error: {2}'.format( os.getgid(), target_pw_gid, err ) ) # Set supplemental groups if sorted(os.getgroups()) != sorted(supgroups): try: os.setgroups(supgroups) except OSError as err: raise CommandExecutionError( 'Failed to set supplemental groups to {0}. Error: {1}'.format( supgroups, err ) ) if os.getuid() != uinfo.pw_uid: try: os.setuid(uinfo.pw_uid) except OSError as err: raise CommandExecutionError( 'Failed to change from uid {0} to {1}. Error: {2}'.format( os.getuid(), uinfo.pw_uid, err ) ) def chugid_and_umask(runas, umask, group=None): ''' Helper method for for subprocess.Popen to initialise uid/gid and umask for the new process. ''' set_runas = False set_grp = False current_user = getpass.getuser() if runas and runas != current_user: set_runas = True runas_user = runas else: runas_user = current_user current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name if group and group != current_grp: set_grp = True runas_grp = group else: runas_grp = current_grp if set_runas or set_grp: chugid(runas_user, runas_grp) if umask is not None: os.umask(umask) # pylint: disable=blacklisted-function def get_default_group(user): ''' Returns the specified user's default group. If the user doesn't exist, a KeyError will be raised. ''' return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \ if HAS_GRP and HAS_PWD \ else None def get_group_list(user, include_default=True): ''' Returns a list of all of the system group names of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] group_names = None ugroups = set() if hasattr(os, 'getgrouplist'): # Try os.getgrouplist, available in python >= 3.3 log.trace('Trying os.getgrouplist for \'%s\'', user) try: group_names = [ grp.getgrgid(grpid).gr_name for grpid in os.getgrouplist(user, pwd.getpwnam(user).pw_gid) ] except Exception: pass elif HAS_PYSSS: # Try pysss.getgrouplist log.trace('Trying pysss.getgrouplist for \'%s\'', user) try: group_names = list(pysss.getgrouplist(user)) except Exception: pass if group_names is None: # Fall back to generic code # Include the user's default group to match behavior of # os.getgrouplist() and pysss.getgrouplist() log.trace('Trying generic group list for \'%s\'', user) group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] try: default_group = get_default_group(user) if default_group not in group_names: group_names.append(default_group) except KeyError: # If for some reason the user does not have a default group pass if group_names is not None: ugroups.update(group_names) if include_default is False: # Historically, saltstack code for getting group lists did not # include the default group. Some things may only want # supplemental groups, so include_default=False omits the users # default group. try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name ugroups.remove(default_group) except KeyError: # If for some reason the user does not have a default group pass log.trace('Group list for user \'%s\': %s', user, sorted(ugroups)) return sorted(ugroups) def get_group_dict(user=None, include_default=True): ''' Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27} ''' if HAS_GRP is False or HAS_PWD is False: return {} group_dict = {} group_names = get_group_list(user, include_default=include_default) for group in group_names: group_dict.update({group: grp.getgrnam(group).gr_gid}) return group_dict def get_gid_list(user, include_default=True): ''' Returns a list of all of the system group IDs of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] gid_list = list( six.itervalues( get_group_dict(user, include_default=include_default) ) ) return sorted(set(gid_list)) def get_gid(group=None): ''' Get the gid for a given group name. If no group given, the current egid will be returned. If the group does not exist, None will be returned. On systems which do not support grp or os.getegid it will return None. ''' if not HAS_GRP: return None if group is None: try: return os.getegid() except AttributeError: return None else: try: return grp.getgrnam(group).gr_gid except KeyError: return None
saltstack/salt
salt/utils/user.py
_win_user_token_is_admin
python
def _win_user_token_is_admin(user_token): ''' Using the win32 api, determine if the user with token 'user_token' has administrator rights. See MSDN entry here: http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx ''' class SID_IDENTIFIER_AUTHORITY(ctypes.Structure): _fields_ = [ ("byte0", ctypes.c_byte), ("byte1", ctypes.c_byte), ("byte2", ctypes.c_byte), ("byte3", ctypes.c_byte), ("byte4", ctypes.c_byte), ("byte5", ctypes.c_byte), ] nt_authority = SID_IDENTIFIER_AUTHORITY() nt_authority.byte5 = 5 SECURITY_BUILTIN_DOMAIN_RID = 0x20 DOMAIN_ALIAS_RID_ADMINS = 0x220 administrators_group = ctypes.c_void_p() if ctypes.windll.advapi32.AllocateAndInitializeSid( ctypes.byref(nt_authority), 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ctypes.byref(administrators_group)) == 0: raise Exception("AllocateAndInitializeSid failed") try: is_admin = ctypes.wintypes.BOOL() if ctypes.windll.advapi32.CheckTokenMembership( user_token, administrators_group, ctypes.byref(is_admin)) == 0: raise Exception("CheckTokenMembership failed") return is_admin.value != 0 finally: ctypes.windll.advapi32.FreeSid(administrators_group)
Using the win32 api, determine if the user with token 'user_token' has administrator rights. See MSDN entry here: http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L89-L131
null
# -*- coding: utf-8 -*- ''' Functions for querying and modifying a user account and the groups to which it belongs. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import ctypes import getpass import logging import os import sys # Import Salt libs import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.decorators.jinja import jinja_filter # Import 3rd-party libs from salt.ext import six # Conditional imports try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False try: import grp HAS_GRP = True except ImportError: HAS_GRP = False try: import pysss HAS_PYSSS = True except ImportError: HAS_PYSSS = False try: import salt.utils.win_functions HAS_WIN_FUNCTIONS = True except ImportError: HAS_WIN_FUNCTIONS = False log = logging.getLogger(__name__) def get_user(): ''' Get the current user ''' if HAS_PWD: ret = pwd.getpwuid(os.geteuid()).pw_name elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32: ret = salt.utils.win_functions.get_current_user() else: raise CommandExecutionError( 'Required external library (pwd or win32api) not installed') return salt.utils.stringutils.to_unicode(ret) @jinja_filter('get_uid') def get_uid(user=None): ''' Get the uid for a given user name. If no user given, the current euid will be returned. If the user does not exist, None will be returned. On systems which do not support pwd or os.geteuid, None will be returned. ''' if not HAS_PWD: return None elif user is None: try: return os.geteuid() except AttributeError: return None else: try: return pwd.getpwnam(user).pw_uid except KeyError: return None def _win_current_user_is_admin(): ''' ctypes.windll.shell32.IsUserAnAdmin() is intentionally avoided due to this function being deprecated. ''' return _win_user_token_is_admin(0) def get_specific_user(): ''' Get a user name for publishing. If you find the user is "root" attempt to be more specific ''' user = get_user() if salt.utils.platform.is_windows(): if _win_current_user_is_admin(): return 'sudo_{0}'.format(user) else: env_vars = ('SUDO_USER',) if user == 'root': for evar in env_vars: if evar in os.environ: return 'sudo_{0}'.format(os.environ[evar]) return user def chugid(runas, group=None): ''' Change the current process to belong to the specified user (and the groups to which it belongs) ''' uinfo = pwd.getpwnam(runas) supgroups = [] supgroups_seen = set() if group: try: target_pw_gid = grp.getgrnam(group).gr_gid except KeyError as err: raise CommandExecutionError( 'Failed to fetch the GID for {0}. Error: {1}'.format( group, err ) ) else: target_pw_gid = uinfo.pw_gid # The line below used to exclude the current user's primary gid. # However, when root belongs to more than one group # this causes root's primary group of '0' to be dropped from # his grouplist. On FreeBSD, at least, this makes some # command executions fail with 'access denied'. # # The Python documentation says that os.setgroups sets only # the supplemental groups for a running process. On FreeBSD # this does not appear to be strictly true. group_list = get_group_dict(runas, include_default=True) if sys.platform == 'darwin': group_list = dict((k, v) for k, v in six.iteritems(group_list) if not k.startswith('_')) for group_name in group_list: gid = group_list[group_name] if (gid not in supgroups_seen and not supgroups_seen.add(gid)): supgroups.append(gid) if os.getgid() != target_pw_gid: try: os.setgid(target_pw_gid) except OSError as err: raise CommandExecutionError( 'Failed to change from gid {0} to {1}. Error: {2}'.format( os.getgid(), target_pw_gid, err ) ) # Set supplemental groups if sorted(os.getgroups()) != sorted(supgroups): try: os.setgroups(supgroups) except OSError as err: raise CommandExecutionError( 'Failed to set supplemental groups to {0}. Error: {1}'.format( supgroups, err ) ) if os.getuid() != uinfo.pw_uid: try: os.setuid(uinfo.pw_uid) except OSError as err: raise CommandExecutionError( 'Failed to change from uid {0} to {1}. Error: {2}'.format( os.getuid(), uinfo.pw_uid, err ) ) def chugid_and_umask(runas, umask, group=None): ''' Helper method for for subprocess.Popen to initialise uid/gid and umask for the new process. ''' set_runas = False set_grp = False current_user = getpass.getuser() if runas and runas != current_user: set_runas = True runas_user = runas else: runas_user = current_user current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name if group and group != current_grp: set_grp = True runas_grp = group else: runas_grp = current_grp if set_runas or set_grp: chugid(runas_user, runas_grp) if umask is not None: os.umask(umask) # pylint: disable=blacklisted-function def get_default_group(user): ''' Returns the specified user's default group. If the user doesn't exist, a KeyError will be raised. ''' return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \ if HAS_GRP and HAS_PWD \ else None def get_group_list(user, include_default=True): ''' Returns a list of all of the system group names of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] group_names = None ugroups = set() if hasattr(os, 'getgrouplist'): # Try os.getgrouplist, available in python >= 3.3 log.trace('Trying os.getgrouplist for \'%s\'', user) try: group_names = [ grp.getgrgid(grpid).gr_name for grpid in os.getgrouplist(user, pwd.getpwnam(user).pw_gid) ] except Exception: pass elif HAS_PYSSS: # Try pysss.getgrouplist log.trace('Trying pysss.getgrouplist for \'%s\'', user) try: group_names = list(pysss.getgrouplist(user)) except Exception: pass if group_names is None: # Fall back to generic code # Include the user's default group to match behavior of # os.getgrouplist() and pysss.getgrouplist() log.trace('Trying generic group list for \'%s\'', user) group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] try: default_group = get_default_group(user) if default_group not in group_names: group_names.append(default_group) except KeyError: # If for some reason the user does not have a default group pass if group_names is not None: ugroups.update(group_names) if include_default is False: # Historically, saltstack code for getting group lists did not # include the default group. Some things may only want # supplemental groups, so include_default=False omits the users # default group. try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name ugroups.remove(default_group) except KeyError: # If for some reason the user does not have a default group pass log.trace('Group list for user \'%s\': %s', user, sorted(ugroups)) return sorted(ugroups) def get_group_dict(user=None, include_default=True): ''' Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27} ''' if HAS_GRP is False or HAS_PWD is False: return {} group_dict = {} group_names = get_group_list(user, include_default=include_default) for group in group_names: group_dict.update({group: grp.getgrnam(group).gr_gid}) return group_dict def get_gid_list(user, include_default=True): ''' Returns a list of all of the system group IDs of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] gid_list = list( six.itervalues( get_group_dict(user, include_default=include_default) ) ) return sorted(set(gid_list)) def get_gid(group=None): ''' Get the gid for a given group name. If no group given, the current egid will be returned. If the group does not exist, None will be returned. On systems which do not support grp or os.getegid it will return None. ''' if not HAS_GRP: return None if group is None: try: return os.getegid() except AttributeError: return None else: try: return grp.getgrnam(group).gr_gid except KeyError: return None
saltstack/salt
salt/utils/user.py
get_specific_user
python
def get_specific_user(): ''' Get a user name for publishing. If you find the user is "root" attempt to be more specific ''' user = get_user() if salt.utils.platform.is_windows(): if _win_current_user_is_admin(): return 'sudo_{0}'.format(user) else: env_vars = ('SUDO_USER',) if user == 'root': for evar in env_vars: if evar in os.environ: return 'sudo_{0}'.format(os.environ[evar]) return user
Get a user name for publishing. If you find the user is "root" attempt to be more specific
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L142-L157
[ "def get_user():\n '''\n Get the current user\n '''\n if HAS_PWD:\n ret = pwd.getpwuid(os.geteuid()).pw_name\n elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32:\n ret = salt.utils.win_functions.get_current_user()\n else:\n raise CommandExecutionError(\n 'Required external library (pwd or win32api) not installed')\n return salt.utils.stringutils.to_unicode(ret)\n", "def _win_current_user_is_admin():\n '''\n ctypes.windll.shell32.IsUserAnAdmin() is intentionally avoided due to this\n function being deprecated.\n '''\n return _win_user_token_is_admin(0)\n" ]
# -*- coding: utf-8 -*- ''' Functions for querying and modifying a user account and the groups to which it belongs. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import ctypes import getpass import logging import os import sys # Import Salt libs import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.decorators.jinja import jinja_filter # Import 3rd-party libs from salt.ext import six # Conditional imports try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False try: import grp HAS_GRP = True except ImportError: HAS_GRP = False try: import pysss HAS_PYSSS = True except ImportError: HAS_PYSSS = False try: import salt.utils.win_functions HAS_WIN_FUNCTIONS = True except ImportError: HAS_WIN_FUNCTIONS = False log = logging.getLogger(__name__) def get_user(): ''' Get the current user ''' if HAS_PWD: ret = pwd.getpwuid(os.geteuid()).pw_name elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32: ret = salt.utils.win_functions.get_current_user() else: raise CommandExecutionError( 'Required external library (pwd or win32api) not installed') return salt.utils.stringutils.to_unicode(ret) @jinja_filter('get_uid') def get_uid(user=None): ''' Get the uid for a given user name. If no user given, the current euid will be returned. If the user does not exist, None will be returned. On systems which do not support pwd or os.geteuid, None will be returned. ''' if not HAS_PWD: return None elif user is None: try: return os.geteuid() except AttributeError: return None else: try: return pwd.getpwnam(user).pw_uid except KeyError: return None def _win_user_token_is_admin(user_token): ''' Using the win32 api, determine if the user with token 'user_token' has administrator rights. See MSDN entry here: http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx ''' class SID_IDENTIFIER_AUTHORITY(ctypes.Structure): _fields_ = [ ("byte0", ctypes.c_byte), ("byte1", ctypes.c_byte), ("byte2", ctypes.c_byte), ("byte3", ctypes.c_byte), ("byte4", ctypes.c_byte), ("byte5", ctypes.c_byte), ] nt_authority = SID_IDENTIFIER_AUTHORITY() nt_authority.byte5 = 5 SECURITY_BUILTIN_DOMAIN_RID = 0x20 DOMAIN_ALIAS_RID_ADMINS = 0x220 administrators_group = ctypes.c_void_p() if ctypes.windll.advapi32.AllocateAndInitializeSid( ctypes.byref(nt_authority), 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ctypes.byref(administrators_group)) == 0: raise Exception("AllocateAndInitializeSid failed") try: is_admin = ctypes.wintypes.BOOL() if ctypes.windll.advapi32.CheckTokenMembership( user_token, administrators_group, ctypes.byref(is_admin)) == 0: raise Exception("CheckTokenMembership failed") return is_admin.value != 0 finally: ctypes.windll.advapi32.FreeSid(administrators_group) def _win_current_user_is_admin(): ''' ctypes.windll.shell32.IsUserAnAdmin() is intentionally avoided due to this function being deprecated. ''' return _win_user_token_is_admin(0) def chugid(runas, group=None): ''' Change the current process to belong to the specified user (and the groups to which it belongs) ''' uinfo = pwd.getpwnam(runas) supgroups = [] supgroups_seen = set() if group: try: target_pw_gid = grp.getgrnam(group).gr_gid except KeyError as err: raise CommandExecutionError( 'Failed to fetch the GID for {0}. Error: {1}'.format( group, err ) ) else: target_pw_gid = uinfo.pw_gid # The line below used to exclude the current user's primary gid. # However, when root belongs to more than one group # this causes root's primary group of '0' to be dropped from # his grouplist. On FreeBSD, at least, this makes some # command executions fail with 'access denied'. # # The Python documentation says that os.setgroups sets only # the supplemental groups for a running process. On FreeBSD # this does not appear to be strictly true. group_list = get_group_dict(runas, include_default=True) if sys.platform == 'darwin': group_list = dict((k, v) for k, v in six.iteritems(group_list) if not k.startswith('_')) for group_name in group_list: gid = group_list[group_name] if (gid not in supgroups_seen and not supgroups_seen.add(gid)): supgroups.append(gid) if os.getgid() != target_pw_gid: try: os.setgid(target_pw_gid) except OSError as err: raise CommandExecutionError( 'Failed to change from gid {0} to {1}. Error: {2}'.format( os.getgid(), target_pw_gid, err ) ) # Set supplemental groups if sorted(os.getgroups()) != sorted(supgroups): try: os.setgroups(supgroups) except OSError as err: raise CommandExecutionError( 'Failed to set supplemental groups to {0}. Error: {1}'.format( supgroups, err ) ) if os.getuid() != uinfo.pw_uid: try: os.setuid(uinfo.pw_uid) except OSError as err: raise CommandExecutionError( 'Failed to change from uid {0} to {1}. Error: {2}'.format( os.getuid(), uinfo.pw_uid, err ) ) def chugid_and_umask(runas, umask, group=None): ''' Helper method for for subprocess.Popen to initialise uid/gid and umask for the new process. ''' set_runas = False set_grp = False current_user = getpass.getuser() if runas and runas != current_user: set_runas = True runas_user = runas else: runas_user = current_user current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name if group and group != current_grp: set_grp = True runas_grp = group else: runas_grp = current_grp if set_runas or set_grp: chugid(runas_user, runas_grp) if umask is not None: os.umask(umask) # pylint: disable=blacklisted-function def get_default_group(user): ''' Returns the specified user's default group. If the user doesn't exist, a KeyError will be raised. ''' return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \ if HAS_GRP and HAS_PWD \ else None def get_group_list(user, include_default=True): ''' Returns a list of all of the system group names of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] group_names = None ugroups = set() if hasattr(os, 'getgrouplist'): # Try os.getgrouplist, available in python >= 3.3 log.trace('Trying os.getgrouplist for \'%s\'', user) try: group_names = [ grp.getgrgid(grpid).gr_name for grpid in os.getgrouplist(user, pwd.getpwnam(user).pw_gid) ] except Exception: pass elif HAS_PYSSS: # Try pysss.getgrouplist log.trace('Trying pysss.getgrouplist for \'%s\'', user) try: group_names = list(pysss.getgrouplist(user)) except Exception: pass if group_names is None: # Fall back to generic code # Include the user's default group to match behavior of # os.getgrouplist() and pysss.getgrouplist() log.trace('Trying generic group list for \'%s\'', user) group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] try: default_group = get_default_group(user) if default_group not in group_names: group_names.append(default_group) except KeyError: # If for some reason the user does not have a default group pass if group_names is not None: ugroups.update(group_names) if include_default is False: # Historically, saltstack code for getting group lists did not # include the default group. Some things may only want # supplemental groups, so include_default=False omits the users # default group. try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name ugroups.remove(default_group) except KeyError: # If for some reason the user does not have a default group pass log.trace('Group list for user \'%s\': %s', user, sorted(ugroups)) return sorted(ugroups) def get_group_dict(user=None, include_default=True): ''' Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27} ''' if HAS_GRP is False or HAS_PWD is False: return {} group_dict = {} group_names = get_group_list(user, include_default=include_default) for group in group_names: group_dict.update({group: grp.getgrnam(group).gr_gid}) return group_dict def get_gid_list(user, include_default=True): ''' Returns a list of all of the system group IDs of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] gid_list = list( six.itervalues( get_group_dict(user, include_default=include_default) ) ) return sorted(set(gid_list)) def get_gid(group=None): ''' Get the gid for a given group name. If no group given, the current egid will be returned. If the group does not exist, None will be returned. On systems which do not support grp or os.getegid it will return None. ''' if not HAS_GRP: return None if group is None: try: return os.getegid() except AttributeError: return None else: try: return grp.getgrnam(group).gr_gid except KeyError: return None
saltstack/salt
salt/utils/user.py
chugid
python
def chugid(runas, group=None): ''' Change the current process to belong to the specified user (and the groups to which it belongs) ''' uinfo = pwd.getpwnam(runas) supgroups = [] supgroups_seen = set() if group: try: target_pw_gid = grp.getgrnam(group).gr_gid except KeyError as err: raise CommandExecutionError( 'Failed to fetch the GID for {0}. Error: {1}'.format( group, err ) ) else: target_pw_gid = uinfo.pw_gid # The line below used to exclude the current user's primary gid. # However, when root belongs to more than one group # this causes root's primary group of '0' to be dropped from # his grouplist. On FreeBSD, at least, this makes some # command executions fail with 'access denied'. # # The Python documentation says that os.setgroups sets only # the supplemental groups for a running process. On FreeBSD # this does not appear to be strictly true. group_list = get_group_dict(runas, include_default=True) if sys.platform == 'darwin': group_list = dict((k, v) for k, v in six.iteritems(group_list) if not k.startswith('_')) for group_name in group_list: gid = group_list[group_name] if (gid not in supgroups_seen and not supgroups_seen.add(gid)): supgroups.append(gid) if os.getgid() != target_pw_gid: try: os.setgid(target_pw_gid) except OSError as err: raise CommandExecutionError( 'Failed to change from gid {0} to {1}. Error: {2}'.format( os.getgid(), target_pw_gid, err ) ) # Set supplemental groups if sorted(os.getgroups()) != sorted(supgroups): try: os.setgroups(supgroups) except OSError as err: raise CommandExecutionError( 'Failed to set supplemental groups to {0}. Error: {1}'.format( supgroups, err ) ) if os.getuid() != uinfo.pw_uid: try: os.setuid(uinfo.pw_uid) except OSError as err: raise CommandExecutionError( 'Failed to change from uid {0} to {1}. Error: {2}'.format( os.getuid(), uinfo.pw_uid, err ) )
Change the current process to belong to the specified user (and the groups to which it belongs)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L160-L229
[ "def get_group_dict(user=None, include_default=True):\n '''\n Returns a dict of all of the system groups as keys, and group ids\n as values, of which the user is a member.\n E.g.: {'staff': 501, 'sudo': 27}\n '''\n if HAS_GRP is False or HAS_PWD is False:\n return {}\n group_dict = {}\n group_names = get_group_list(user, include_default=include_default)\n for group in group_names:\n group_dict.update({group: grp.getgrnam(group).gr_gid})\n return group_dict\n" ]
# -*- coding: utf-8 -*- ''' Functions for querying and modifying a user account and the groups to which it belongs. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import ctypes import getpass import logging import os import sys # Import Salt libs import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.decorators.jinja import jinja_filter # Import 3rd-party libs from salt.ext import six # Conditional imports try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False try: import grp HAS_GRP = True except ImportError: HAS_GRP = False try: import pysss HAS_PYSSS = True except ImportError: HAS_PYSSS = False try: import salt.utils.win_functions HAS_WIN_FUNCTIONS = True except ImportError: HAS_WIN_FUNCTIONS = False log = logging.getLogger(__name__) def get_user(): ''' Get the current user ''' if HAS_PWD: ret = pwd.getpwuid(os.geteuid()).pw_name elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32: ret = salt.utils.win_functions.get_current_user() else: raise CommandExecutionError( 'Required external library (pwd or win32api) not installed') return salt.utils.stringutils.to_unicode(ret) @jinja_filter('get_uid') def get_uid(user=None): ''' Get the uid for a given user name. If no user given, the current euid will be returned. If the user does not exist, None will be returned. On systems which do not support pwd or os.geteuid, None will be returned. ''' if not HAS_PWD: return None elif user is None: try: return os.geteuid() except AttributeError: return None else: try: return pwd.getpwnam(user).pw_uid except KeyError: return None def _win_user_token_is_admin(user_token): ''' Using the win32 api, determine if the user with token 'user_token' has administrator rights. See MSDN entry here: http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx ''' class SID_IDENTIFIER_AUTHORITY(ctypes.Structure): _fields_ = [ ("byte0", ctypes.c_byte), ("byte1", ctypes.c_byte), ("byte2", ctypes.c_byte), ("byte3", ctypes.c_byte), ("byte4", ctypes.c_byte), ("byte5", ctypes.c_byte), ] nt_authority = SID_IDENTIFIER_AUTHORITY() nt_authority.byte5 = 5 SECURITY_BUILTIN_DOMAIN_RID = 0x20 DOMAIN_ALIAS_RID_ADMINS = 0x220 administrators_group = ctypes.c_void_p() if ctypes.windll.advapi32.AllocateAndInitializeSid( ctypes.byref(nt_authority), 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ctypes.byref(administrators_group)) == 0: raise Exception("AllocateAndInitializeSid failed") try: is_admin = ctypes.wintypes.BOOL() if ctypes.windll.advapi32.CheckTokenMembership( user_token, administrators_group, ctypes.byref(is_admin)) == 0: raise Exception("CheckTokenMembership failed") return is_admin.value != 0 finally: ctypes.windll.advapi32.FreeSid(administrators_group) def _win_current_user_is_admin(): ''' ctypes.windll.shell32.IsUserAnAdmin() is intentionally avoided due to this function being deprecated. ''' return _win_user_token_is_admin(0) def get_specific_user(): ''' Get a user name for publishing. If you find the user is "root" attempt to be more specific ''' user = get_user() if salt.utils.platform.is_windows(): if _win_current_user_is_admin(): return 'sudo_{0}'.format(user) else: env_vars = ('SUDO_USER',) if user == 'root': for evar in env_vars: if evar in os.environ: return 'sudo_{0}'.format(os.environ[evar]) return user def chugid_and_umask(runas, umask, group=None): ''' Helper method for for subprocess.Popen to initialise uid/gid and umask for the new process. ''' set_runas = False set_grp = False current_user = getpass.getuser() if runas and runas != current_user: set_runas = True runas_user = runas else: runas_user = current_user current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name if group and group != current_grp: set_grp = True runas_grp = group else: runas_grp = current_grp if set_runas or set_grp: chugid(runas_user, runas_grp) if umask is not None: os.umask(umask) # pylint: disable=blacklisted-function def get_default_group(user): ''' Returns the specified user's default group. If the user doesn't exist, a KeyError will be raised. ''' return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \ if HAS_GRP and HAS_PWD \ else None def get_group_list(user, include_default=True): ''' Returns a list of all of the system group names of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] group_names = None ugroups = set() if hasattr(os, 'getgrouplist'): # Try os.getgrouplist, available in python >= 3.3 log.trace('Trying os.getgrouplist for \'%s\'', user) try: group_names = [ grp.getgrgid(grpid).gr_name for grpid in os.getgrouplist(user, pwd.getpwnam(user).pw_gid) ] except Exception: pass elif HAS_PYSSS: # Try pysss.getgrouplist log.trace('Trying pysss.getgrouplist for \'%s\'', user) try: group_names = list(pysss.getgrouplist(user)) except Exception: pass if group_names is None: # Fall back to generic code # Include the user's default group to match behavior of # os.getgrouplist() and pysss.getgrouplist() log.trace('Trying generic group list for \'%s\'', user) group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] try: default_group = get_default_group(user) if default_group not in group_names: group_names.append(default_group) except KeyError: # If for some reason the user does not have a default group pass if group_names is not None: ugroups.update(group_names) if include_default is False: # Historically, saltstack code for getting group lists did not # include the default group. Some things may only want # supplemental groups, so include_default=False omits the users # default group. try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name ugroups.remove(default_group) except KeyError: # If for some reason the user does not have a default group pass log.trace('Group list for user \'%s\': %s', user, sorted(ugroups)) return sorted(ugroups) def get_group_dict(user=None, include_default=True): ''' Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27} ''' if HAS_GRP is False or HAS_PWD is False: return {} group_dict = {} group_names = get_group_list(user, include_default=include_default) for group in group_names: group_dict.update({group: grp.getgrnam(group).gr_gid}) return group_dict def get_gid_list(user, include_default=True): ''' Returns a list of all of the system group IDs of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] gid_list = list( six.itervalues( get_group_dict(user, include_default=include_default) ) ) return sorted(set(gid_list)) def get_gid(group=None): ''' Get the gid for a given group name. If no group given, the current egid will be returned. If the group does not exist, None will be returned. On systems which do not support grp or os.getegid it will return None. ''' if not HAS_GRP: return None if group is None: try: return os.getegid() except AttributeError: return None else: try: return grp.getgrnam(group).gr_gid except KeyError: return None
saltstack/salt
salt/utils/user.py
chugid_and_umask
python
def chugid_and_umask(runas, umask, group=None): ''' Helper method for for subprocess.Popen to initialise uid/gid and umask for the new process. ''' set_runas = False set_grp = False current_user = getpass.getuser() if runas and runas != current_user: set_runas = True runas_user = runas else: runas_user = current_user current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name if group and group != current_grp: set_grp = True runas_grp = group else: runas_grp = current_grp if set_runas or set_grp: chugid(runas_user, runas_grp) if umask is not None: os.umask(umask)
Helper method for for subprocess.Popen to initialise uid/gid and umask for the new process.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L232-L257
[ "def chugid(runas, group=None):\n '''\n Change the current process to belong to the specified user (and the groups\n to which it belongs)\n '''\n uinfo = pwd.getpwnam(runas)\n supgroups = []\n supgroups_seen = set()\n\n if group:\n try:\n target_pw_gid = grp.getgrnam(group).gr_gid\n except KeyError as err:\n raise CommandExecutionError(\n 'Failed to fetch the GID for {0}. Error: {1}'.format(\n group, err\n )\n )\n else:\n target_pw_gid = uinfo.pw_gid\n\n # The line below used to exclude the current user's primary gid.\n # However, when root belongs to more than one group\n # this causes root's primary group of '0' to be dropped from\n # his grouplist. On FreeBSD, at least, this makes some\n # command executions fail with 'access denied'.\n #\n # The Python documentation says that os.setgroups sets only\n # the supplemental groups for a running process. On FreeBSD\n # this does not appear to be strictly true.\n group_list = get_group_dict(runas, include_default=True)\n if sys.platform == 'darwin':\n group_list = dict((k, v) for k, v in six.iteritems(group_list)\n if not k.startswith('_'))\n for group_name in group_list:\n gid = group_list[group_name]\n if (gid not in supgroups_seen\n and not supgroups_seen.add(gid)):\n supgroups.append(gid)\n\n if os.getgid() != target_pw_gid:\n try:\n os.setgid(target_pw_gid)\n except OSError as err:\n raise CommandExecutionError(\n 'Failed to change from gid {0} to {1}. Error: {2}'.format(\n os.getgid(), target_pw_gid, err\n )\n )\n\n # Set supplemental groups\n if sorted(os.getgroups()) != sorted(supgroups):\n try:\n os.setgroups(supgroups)\n except OSError as err:\n raise CommandExecutionError(\n 'Failed to set supplemental groups to {0}. Error: {1}'.format(\n supgroups, err\n )\n )\n\n if os.getuid() != uinfo.pw_uid:\n try:\n os.setuid(uinfo.pw_uid)\n except OSError as err:\n raise CommandExecutionError(\n 'Failed to change from uid {0} to {1}. Error: {2}'.format(\n os.getuid(), uinfo.pw_uid, err\n )\n )\n" ]
# -*- coding: utf-8 -*- ''' Functions for querying and modifying a user account and the groups to which it belongs. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import ctypes import getpass import logging import os import sys # Import Salt libs import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.decorators.jinja import jinja_filter # Import 3rd-party libs from salt.ext import six # Conditional imports try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False try: import grp HAS_GRP = True except ImportError: HAS_GRP = False try: import pysss HAS_PYSSS = True except ImportError: HAS_PYSSS = False try: import salt.utils.win_functions HAS_WIN_FUNCTIONS = True except ImportError: HAS_WIN_FUNCTIONS = False log = logging.getLogger(__name__) def get_user(): ''' Get the current user ''' if HAS_PWD: ret = pwd.getpwuid(os.geteuid()).pw_name elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32: ret = salt.utils.win_functions.get_current_user() else: raise CommandExecutionError( 'Required external library (pwd or win32api) not installed') return salt.utils.stringutils.to_unicode(ret) @jinja_filter('get_uid') def get_uid(user=None): ''' Get the uid for a given user name. If no user given, the current euid will be returned. If the user does not exist, None will be returned. On systems which do not support pwd or os.geteuid, None will be returned. ''' if not HAS_PWD: return None elif user is None: try: return os.geteuid() except AttributeError: return None else: try: return pwd.getpwnam(user).pw_uid except KeyError: return None def _win_user_token_is_admin(user_token): ''' Using the win32 api, determine if the user with token 'user_token' has administrator rights. See MSDN entry here: http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx ''' class SID_IDENTIFIER_AUTHORITY(ctypes.Structure): _fields_ = [ ("byte0", ctypes.c_byte), ("byte1", ctypes.c_byte), ("byte2", ctypes.c_byte), ("byte3", ctypes.c_byte), ("byte4", ctypes.c_byte), ("byte5", ctypes.c_byte), ] nt_authority = SID_IDENTIFIER_AUTHORITY() nt_authority.byte5 = 5 SECURITY_BUILTIN_DOMAIN_RID = 0x20 DOMAIN_ALIAS_RID_ADMINS = 0x220 administrators_group = ctypes.c_void_p() if ctypes.windll.advapi32.AllocateAndInitializeSid( ctypes.byref(nt_authority), 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ctypes.byref(administrators_group)) == 0: raise Exception("AllocateAndInitializeSid failed") try: is_admin = ctypes.wintypes.BOOL() if ctypes.windll.advapi32.CheckTokenMembership( user_token, administrators_group, ctypes.byref(is_admin)) == 0: raise Exception("CheckTokenMembership failed") return is_admin.value != 0 finally: ctypes.windll.advapi32.FreeSid(administrators_group) def _win_current_user_is_admin(): ''' ctypes.windll.shell32.IsUserAnAdmin() is intentionally avoided due to this function being deprecated. ''' return _win_user_token_is_admin(0) def get_specific_user(): ''' Get a user name for publishing. If you find the user is "root" attempt to be more specific ''' user = get_user() if salt.utils.platform.is_windows(): if _win_current_user_is_admin(): return 'sudo_{0}'.format(user) else: env_vars = ('SUDO_USER',) if user == 'root': for evar in env_vars: if evar in os.environ: return 'sudo_{0}'.format(os.environ[evar]) return user def chugid(runas, group=None): ''' Change the current process to belong to the specified user (and the groups to which it belongs) ''' uinfo = pwd.getpwnam(runas) supgroups = [] supgroups_seen = set() if group: try: target_pw_gid = grp.getgrnam(group).gr_gid except KeyError as err: raise CommandExecutionError( 'Failed to fetch the GID for {0}. Error: {1}'.format( group, err ) ) else: target_pw_gid = uinfo.pw_gid # The line below used to exclude the current user's primary gid. # However, when root belongs to more than one group # this causes root's primary group of '0' to be dropped from # his grouplist. On FreeBSD, at least, this makes some # command executions fail with 'access denied'. # # The Python documentation says that os.setgroups sets only # the supplemental groups for a running process. On FreeBSD # this does not appear to be strictly true. group_list = get_group_dict(runas, include_default=True) if sys.platform == 'darwin': group_list = dict((k, v) for k, v in six.iteritems(group_list) if not k.startswith('_')) for group_name in group_list: gid = group_list[group_name] if (gid not in supgroups_seen and not supgroups_seen.add(gid)): supgroups.append(gid) if os.getgid() != target_pw_gid: try: os.setgid(target_pw_gid) except OSError as err: raise CommandExecutionError( 'Failed to change from gid {0} to {1}. Error: {2}'.format( os.getgid(), target_pw_gid, err ) ) # Set supplemental groups if sorted(os.getgroups()) != sorted(supgroups): try: os.setgroups(supgroups) except OSError as err: raise CommandExecutionError( 'Failed to set supplemental groups to {0}. Error: {1}'.format( supgroups, err ) ) if os.getuid() != uinfo.pw_uid: try: os.setuid(uinfo.pw_uid) except OSError as err: raise CommandExecutionError( 'Failed to change from uid {0} to {1}. Error: {2}'.format( os.getuid(), uinfo.pw_uid, err ) ) # pylint: disable=blacklisted-function def get_default_group(user): ''' Returns the specified user's default group. If the user doesn't exist, a KeyError will be raised. ''' return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \ if HAS_GRP and HAS_PWD \ else None def get_group_list(user, include_default=True): ''' Returns a list of all of the system group names of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] group_names = None ugroups = set() if hasattr(os, 'getgrouplist'): # Try os.getgrouplist, available in python >= 3.3 log.trace('Trying os.getgrouplist for \'%s\'', user) try: group_names = [ grp.getgrgid(grpid).gr_name for grpid in os.getgrouplist(user, pwd.getpwnam(user).pw_gid) ] except Exception: pass elif HAS_PYSSS: # Try pysss.getgrouplist log.trace('Trying pysss.getgrouplist for \'%s\'', user) try: group_names = list(pysss.getgrouplist(user)) except Exception: pass if group_names is None: # Fall back to generic code # Include the user's default group to match behavior of # os.getgrouplist() and pysss.getgrouplist() log.trace('Trying generic group list for \'%s\'', user) group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] try: default_group = get_default_group(user) if default_group not in group_names: group_names.append(default_group) except KeyError: # If for some reason the user does not have a default group pass if group_names is not None: ugroups.update(group_names) if include_default is False: # Historically, saltstack code for getting group lists did not # include the default group. Some things may only want # supplemental groups, so include_default=False omits the users # default group. try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name ugroups.remove(default_group) except KeyError: # If for some reason the user does not have a default group pass log.trace('Group list for user \'%s\': %s', user, sorted(ugroups)) return sorted(ugroups) def get_group_dict(user=None, include_default=True): ''' Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27} ''' if HAS_GRP is False or HAS_PWD is False: return {} group_dict = {} group_names = get_group_list(user, include_default=include_default) for group in group_names: group_dict.update({group: grp.getgrnam(group).gr_gid}) return group_dict def get_gid_list(user, include_default=True): ''' Returns a list of all of the system group IDs of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] gid_list = list( six.itervalues( get_group_dict(user, include_default=include_default) ) ) return sorted(set(gid_list)) def get_gid(group=None): ''' Get the gid for a given group name. If no group given, the current egid will be returned. If the group does not exist, None will be returned. On systems which do not support grp or os.getegid it will return None. ''' if not HAS_GRP: return None if group is None: try: return os.getegid() except AttributeError: return None else: try: return grp.getgrnam(group).gr_gid except KeyError: return None
saltstack/salt
salt/utils/user.py
get_default_group
python
def get_default_group(user): ''' Returns the specified user's default group. If the user doesn't exist, a KeyError will be raised. ''' return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \ if HAS_GRP and HAS_PWD \ else None
Returns the specified user's default group. If the user doesn't exist, a KeyError will be raised.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L260-L267
null
# -*- coding: utf-8 -*- ''' Functions for querying and modifying a user account and the groups to which it belongs. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import ctypes import getpass import logging import os import sys # Import Salt libs import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.decorators.jinja import jinja_filter # Import 3rd-party libs from salt.ext import six # Conditional imports try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False try: import grp HAS_GRP = True except ImportError: HAS_GRP = False try: import pysss HAS_PYSSS = True except ImportError: HAS_PYSSS = False try: import salt.utils.win_functions HAS_WIN_FUNCTIONS = True except ImportError: HAS_WIN_FUNCTIONS = False log = logging.getLogger(__name__) def get_user(): ''' Get the current user ''' if HAS_PWD: ret = pwd.getpwuid(os.geteuid()).pw_name elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32: ret = salt.utils.win_functions.get_current_user() else: raise CommandExecutionError( 'Required external library (pwd or win32api) not installed') return salt.utils.stringutils.to_unicode(ret) @jinja_filter('get_uid') def get_uid(user=None): ''' Get the uid for a given user name. If no user given, the current euid will be returned. If the user does not exist, None will be returned. On systems which do not support pwd or os.geteuid, None will be returned. ''' if not HAS_PWD: return None elif user is None: try: return os.geteuid() except AttributeError: return None else: try: return pwd.getpwnam(user).pw_uid except KeyError: return None def _win_user_token_is_admin(user_token): ''' Using the win32 api, determine if the user with token 'user_token' has administrator rights. See MSDN entry here: http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx ''' class SID_IDENTIFIER_AUTHORITY(ctypes.Structure): _fields_ = [ ("byte0", ctypes.c_byte), ("byte1", ctypes.c_byte), ("byte2", ctypes.c_byte), ("byte3", ctypes.c_byte), ("byte4", ctypes.c_byte), ("byte5", ctypes.c_byte), ] nt_authority = SID_IDENTIFIER_AUTHORITY() nt_authority.byte5 = 5 SECURITY_BUILTIN_DOMAIN_RID = 0x20 DOMAIN_ALIAS_RID_ADMINS = 0x220 administrators_group = ctypes.c_void_p() if ctypes.windll.advapi32.AllocateAndInitializeSid( ctypes.byref(nt_authority), 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ctypes.byref(administrators_group)) == 0: raise Exception("AllocateAndInitializeSid failed") try: is_admin = ctypes.wintypes.BOOL() if ctypes.windll.advapi32.CheckTokenMembership( user_token, administrators_group, ctypes.byref(is_admin)) == 0: raise Exception("CheckTokenMembership failed") return is_admin.value != 0 finally: ctypes.windll.advapi32.FreeSid(administrators_group) def _win_current_user_is_admin(): ''' ctypes.windll.shell32.IsUserAnAdmin() is intentionally avoided due to this function being deprecated. ''' return _win_user_token_is_admin(0) def get_specific_user(): ''' Get a user name for publishing. If you find the user is "root" attempt to be more specific ''' user = get_user() if salt.utils.platform.is_windows(): if _win_current_user_is_admin(): return 'sudo_{0}'.format(user) else: env_vars = ('SUDO_USER',) if user == 'root': for evar in env_vars: if evar in os.environ: return 'sudo_{0}'.format(os.environ[evar]) return user def chugid(runas, group=None): ''' Change the current process to belong to the specified user (and the groups to which it belongs) ''' uinfo = pwd.getpwnam(runas) supgroups = [] supgroups_seen = set() if group: try: target_pw_gid = grp.getgrnam(group).gr_gid except KeyError as err: raise CommandExecutionError( 'Failed to fetch the GID for {0}. Error: {1}'.format( group, err ) ) else: target_pw_gid = uinfo.pw_gid # The line below used to exclude the current user's primary gid. # However, when root belongs to more than one group # this causes root's primary group of '0' to be dropped from # his grouplist. On FreeBSD, at least, this makes some # command executions fail with 'access denied'. # # The Python documentation says that os.setgroups sets only # the supplemental groups for a running process. On FreeBSD # this does not appear to be strictly true. group_list = get_group_dict(runas, include_default=True) if sys.platform == 'darwin': group_list = dict((k, v) for k, v in six.iteritems(group_list) if not k.startswith('_')) for group_name in group_list: gid = group_list[group_name] if (gid not in supgroups_seen and not supgroups_seen.add(gid)): supgroups.append(gid) if os.getgid() != target_pw_gid: try: os.setgid(target_pw_gid) except OSError as err: raise CommandExecutionError( 'Failed to change from gid {0} to {1}. Error: {2}'.format( os.getgid(), target_pw_gid, err ) ) # Set supplemental groups if sorted(os.getgroups()) != sorted(supgroups): try: os.setgroups(supgroups) except OSError as err: raise CommandExecutionError( 'Failed to set supplemental groups to {0}. Error: {1}'.format( supgroups, err ) ) if os.getuid() != uinfo.pw_uid: try: os.setuid(uinfo.pw_uid) except OSError as err: raise CommandExecutionError( 'Failed to change from uid {0} to {1}. Error: {2}'.format( os.getuid(), uinfo.pw_uid, err ) ) def chugid_and_umask(runas, umask, group=None): ''' Helper method for for subprocess.Popen to initialise uid/gid and umask for the new process. ''' set_runas = False set_grp = False current_user = getpass.getuser() if runas and runas != current_user: set_runas = True runas_user = runas else: runas_user = current_user current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name if group and group != current_grp: set_grp = True runas_grp = group else: runas_grp = current_grp if set_runas or set_grp: chugid(runas_user, runas_grp) if umask is not None: os.umask(umask) # pylint: disable=blacklisted-function def get_group_list(user, include_default=True): ''' Returns a list of all of the system group names of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] group_names = None ugroups = set() if hasattr(os, 'getgrouplist'): # Try os.getgrouplist, available in python >= 3.3 log.trace('Trying os.getgrouplist for \'%s\'', user) try: group_names = [ grp.getgrgid(grpid).gr_name for grpid in os.getgrouplist(user, pwd.getpwnam(user).pw_gid) ] except Exception: pass elif HAS_PYSSS: # Try pysss.getgrouplist log.trace('Trying pysss.getgrouplist for \'%s\'', user) try: group_names = list(pysss.getgrouplist(user)) except Exception: pass if group_names is None: # Fall back to generic code # Include the user's default group to match behavior of # os.getgrouplist() and pysss.getgrouplist() log.trace('Trying generic group list for \'%s\'', user) group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] try: default_group = get_default_group(user) if default_group not in group_names: group_names.append(default_group) except KeyError: # If for some reason the user does not have a default group pass if group_names is not None: ugroups.update(group_names) if include_default is False: # Historically, saltstack code for getting group lists did not # include the default group. Some things may only want # supplemental groups, so include_default=False omits the users # default group. try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name ugroups.remove(default_group) except KeyError: # If for some reason the user does not have a default group pass log.trace('Group list for user \'%s\': %s', user, sorted(ugroups)) return sorted(ugroups) def get_group_dict(user=None, include_default=True): ''' Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27} ''' if HAS_GRP is False or HAS_PWD is False: return {} group_dict = {} group_names = get_group_list(user, include_default=include_default) for group in group_names: group_dict.update({group: grp.getgrnam(group).gr_gid}) return group_dict def get_gid_list(user, include_default=True): ''' Returns a list of all of the system group IDs of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] gid_list = list( six.itervalues( get_group_dict(user, include_default=include_default) ) ) return sorted(set(gid_list)) def get_gid(group=None): ''' Get the gid for a given group name. If no group given, the current egid will be returned. If the group does not exist, None will be returned. On systems which do not support grp or os.getegid it will return None. ''' if not HAS_GRP: return None if group is None: try: return os.getegid() except AttributeError: return None else: try: return grp.getgrnam(group).gr_gid except KeyError: return None
saltstack/salt
salt/utils/user.py
get_group_list
python
def get_group_list(user, include_default=True): ''' Returns a list of all of the system group names of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] group_names = None ugroups = set() if hasattr(os, 'getgrouplist'): # Try os.getgrouplist, available in python >= 3.3 log.trace('Trying os.getgrouplist for \'%s\'', user) try: group_names = [ grp.getgrgid(grpid).gr_name for grpid in os.getgrouplist(user, pwd.getpwnam(user).pw_gid) ] except Exception: pass elif HAS_PYSSS: # Try pysss.getgrouplist log.trace('Trying pysss.getgrouplist for \'%s\'', user) try: group_names = list(pysss.getgrouplist(user)) except Exception: pass if group_names is None: # Fall back to generic code # Include the user's default group to match behavior of # os.getgrouplist() and pysss.getgrouplist() log.trace('Trying generic group list for \'%s\'', user) group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] try: default_group = get_default_group(user) if default_group not in group_names: group_names.append(default_group) except KeyError: # If for some reason the user does not have a default group pass if group_names is not None: ugroups.update(group_names) if include_default is False: # Historically, saltstack code for getting group lists did not # include the default group. Some things may only want # supplemental groups, so include_default=False omits the users # default group. try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name ugroups.remove(default_group) except KeyError: # If for some reason the user does not have a default group pass log.trace('Group list for user \'%s\': %s', user, sorted(ugroups)) return sorted(ugroups)
Returns a list of all of the system group names of which the user is a member.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L270-L326
[ "def get_default_group(user):\n '''\n Returns the specified user's default group. If the user doesn't exist, a\n KeyError will be raised.\n '''\n return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \\\n if HAS_GRP and HAS_PWD \\\n else None\n" ]
# -*- coding: utf-8 -*- ''' Functions for querying and modifying a user account and the groups to which it belongs. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import ctypes import getpass import logging import os import sys # Import Salt libs import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.decorators.jinja import jinja_filter # Import 3rd-party libs from salt.ext import six # Conditional imports try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False try: import grp HAS_GRP = True except ImportError: HAS_GRP = False try: import pysss HAS_PYSSS = True except ImportError: HAS_PYSSS = False try: import salt.utils.win_functions HAS_WIN_FUNCTIONS = True except ImportError: HAS_WIN_FUNCTIONS = False log = logging.getLogger(__name__) def get_user(): ''' Get the current user ''' if HAS_PWD: ret = pwd.getpwuid(os.geteuid()).pw_name elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32: ret = salt.utils.win_functions.get_current_user() else: raise CommandExecutionError( 'Required external library (pwd or win32api) not installed') return salt.utils.stringutils.to_unicode(ret) @jinja_filter('get_uid') def get_uid(user=None): ''' Get the uid for a given user name. If no user given, the current euid will be returned. If the user does not exist, None will be returned. On systems which do not support pwd or os.geteuid, None will be returned. ''' if not HAS_PWD: return None elif user is None: try: return os.geteuid() except AttributeError: return None else: try: return pwd.getpwnam(user).pw_uid except KeyError: return None def _win_user_token_is_admin(user_token): ''' Using the win32 api, determine if the user with token 'user_token' has administrator rights. See MSDN entry here: http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx ''' class SID_IDENTIFIER_AUTHORITY(ctypes.Structure): _fields_ = [ ("byte0", ctypes.c_byte), ("byte1", ctypes.c_byte), ("byte2", ctypes.c_byte), ("byte3", ctypes.c_byte), ("byte4", ctypes.c_byte), ("byte5", ctypes.c_byte), ] nt_authority = SID_IDENTIFIER_AUTHORITY() nt_authority.byte5 = 5 SECURITY_BUILTIN_DOMAIN_RID = 0x20 DOMAIN_ALIAS_RID_ADMINS = 0x220 administrators_group = ctypes.c_void_p() if ctypes.windll.advapi32.AllocateAndInitializeSid( ctypes.byref(nt_authority), 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ctypes.byref(administrators_group)) == 0: raise Exception("AllocateAndInitializeSid failed") try: is_admin = ctypes.wintypes.BOOL() if ctypes.windll.advapi32.CheckTokenMembership( user_token, administrators_group, ctypes.byref(is_admin)) == 0: raise Exception("CheckTokenMembership failed") return is_admin.value != 0 finally: ctypes.windll.advapi32.FreeSid(administrators_group) def _win_current_user_is_admin(): ''' ctypes.windll.shell32.IsUserAnAdmin() is intentionally avoided due to this function being deprecated. ''' return _win_user_token_is_admin(0) def get_specific_user(): ''' Get a user name for publishing. If you find the user is "root" attempt to be more specific ''' user = get_user() if salt.utils.platform.is_windows(): if _win_current_user_is_admin(): return 'sudo_{0}'.format(user) else: env_vars = ('SUDO_USER',) if user == 'root': for evar in env_vars: if evar in os.environ: return 'sudo_{0}'.format(os.environ[evar]) return user def chugid(runas, group=None): ''' Change the current process to belong to the specified user (and the groups to which it belongs) ''' uinfo = pwd.getpwnam(runas) supgroups = [] supgroups_seen = set() if group: try: target_pw_gid = grp.getgrnam(group).gr_gid except KeyError as err: raise CommandExecutionError( 'Failed to fetch the GID for {0}. Error: {1}'.format( group, err ) ) else: target_pw_gid = uinfo.pw_gid # The line below used to exclude the current user's primary gid. # However, when root belongs to more than one group # this causes root's primary group of '0' to be dropped from # his grouplist. On FreeBSD, at least, this makes some # command executions fail with 'access denied'. # # The Python documentation says that os.setgroups sets only # the supplemental groups for a running process. On FreeBSD # this does not appear to be strictly true. group_list = get_group_dict(runas, include_default=True) if sys.platform == 'darwin': group_list = dict((k, v) for k, v in six.iteritems(group_list) if not k.startswith('_')) for group_name in group_list: gid = group_list[group_name] if (gid not in supgroups_seen and not supgroups_seen.add(gid)): supgroups.append(gid) if os.getgid() != target_pw_gid: try: os.setgid(target_pw_gid) except OSError as err: raise CommandExecutionError( 'Failed to change from gid {0} to {1}. Error: {2}'.format( os.getgid(), target_pw_gid, err ) ) # Set supplemental groups if sorted(os.getgroups()) != sorted(supgroups): try: os.setgroups(supgroups) except OSError as err: raise CommandExecutionError( 'Failed to set supplemental groups to {0}. Error: {1}'.format( supgroups, err ) ) if os.getuid() != uinfo.pw_uid: try: os.setuid(uinfo.pw_uid) except OSError as err: raise CommandExecutionError( 'Failed to change from uid {0} to {1}. Error: {2}'.format( os.getuid(), uinfo.pw_uid, err ) ) def chugid_and_umask(runas, umask, group=None): ''' Helper method for for subprocess.Popen to initialise uid/gid and umask for the new process. ''' set_runas = False set_grp = False current_user = getpass.getuser() if runas and runas != current_user: set_runas = True runas_user = runas else: runas_user = current_user current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name if group and group != current_grp: set_grp = True runas_grp = group else: runas_grp = current_grp if set_runas or set_grp: chugid(runas_user, runas_grp) if umask is not None: os.umask(umask) # pylint: disable=blacklisted-function def get_default_group(user): ''' Returns the specified user's default group. If the user doesn't exist, a KeyError will be raised. ''' return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \ if HAS_GRP and HAS_PWD \ else None def get_group_dict(user=None, include_default=True): ''' Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27} ''' if HAS_GRP is False or HAS_PWD is False: return {} group_dict = {} group_names = get_group_list(user, include_default=include_default) for group in group_names: group_dict.update({group: grp.getgrnam(group).gr_gid}) return group_dict def get_gid_list(user, include_default=True): ''' Returns a list of all of the system group IDs of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] gid_list = list( six.itervalues( get_group_dict(user, include_default=include_default) ) ) return sorted(set(gid_list)) def get_gid(group=None): ''' Get the gid for a given group name. If no group given, the current egid will be returned. If the group does not exist, None will be returned. On systems which do not support grp or os.getegid it will return None. ''' if not HAS_GRP: return None if group is None: try: return os.getegid() except AttributeError: return None else: try: return grp.getgrnam(group).gr_gid except KeyError: return None
saltstack/salt
salt/utils/user.py
get_group_dict
python
def get_group_dict(user=None, include_default=True): ''' Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27} ''' if HAS_GRP is False or HAS_PWD is False: return {} group_dict = {} group_names = get_group_list(user, include_default=include_default) for group in group_names: group_dict.update({group: grp.getgrnam(group).gr_gid}) return group_dict
Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L329-L341
[ "def get_group_list(user, include_default=True):\n '''\n Returns a list of all of the system group names of which the user\n is a member.\n '''\n if HAS_GRP is False or HAS_PWD is False:\n return []\n group_names = None\n ugroups = set()\n if hasattr(os, 'getgrouplist'):\n # Try os.getgrouplist, available in python >= 3.3\n log.trace('Trying os.getgrouplist for \\'%s\\'', user)\n try:\n group_names = [\n grp.getgrgid(grpid).gr_name for grpid in\n os.getgrouplist(user, pwd.getpwnam(user).pw_gid)\n ]\n except Exception:\n pass\n elif HAS_PYSSS:\n # Try pysss.getgrouplist\n log.trace('Trying pysss.getgrouplist for \\'%s\\'', user)\n try:\n group_names = list(pysss.getgrouplist(user))\n except Exception:\n pass\n\n if group_names is None:\n # Fall back to generic code\n # Include the user's default group to match behavior of\n # os.getgrouplist() and pysss.getgrouplist()\n log.trace('Trying generic group list for \\'%s\\'', user)\n group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem]\n try:\n default_group = get_default_group(user)\n if default_group not in group_names:\n group_names.append(default_group)\n except KeyError:\n # If for some reason the user does not have a default group\n pass\n\n if group_names is not None:\n ugroups.update(group_names)\n\n if include_default is False:\n # Historically, saltstack code for getting group lists did not\n # include the default group. Some things may only want\n # supplemental groups, so include_default=False omits the users\n # default group.\n try:\n default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name\n ugroups.remove(default_group)\n except KeyError:\n # If for some reason the user does not have a default group\n pass\n log.trace('Group list for user \\'%s\\': %s', user, sorted(ugroups))\n return sorted(ugroups)\n" ]
# -*- coding: utf-8 -*- ''' Functions for querying and modifying a user account and the groups to which it belongs. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import ctypes import getpass import logging import os import sys # Import Salt libs import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.decorators.jinja import jinja_filter # Import 3rd-party libs from salt.ext import six # Conditional imports try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False try: import grp HAS_GRP = True except ImportError: HAS_GRP = False try: import pysss HAS_PYSSS = True except ImportError: HAS_PYSSS = False try: import salt.utils.win_functions HAS_WIN_FUNCTIONS = True except ImportError: HAS_WIN_FUNCTIONS = False log = logging.getLogger(__name__) def get_user(): ''' Get the current user ''' if HAS_PWD: ret = pwd.getpwuid(os.geteuid()).pw_name elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32: ret = salt.utils.win_functions.get_current_user() else: raise CommandExecutionError( 'Required external library (pwd or win32api) not installed') return salt.utils.stringutils.to_unicode(ret) @jinja_filter('get_uid') def get_uid(user=None): ''' Get the uid for a given user name. If no user given, the current euid will be returned. If the user does not exist, None will be returned. On systems which do not support pwd or os.geteuid, None will be returned. ''' if not HAS_PWD: return None elif user is None: try: return os.geteuid() except AttributeError: return None else: try: return pwd.getpwnam(user).pw_uid except KeyError: return None def _win_user_token_is_admin(user_token): ''' Using the win32 api, determine if the user with token 'user_token' has administrator rights. See MSDN entry here: http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx ''' class SID_IDENTIFIER_AUTHORITY(ctypes.Structure): _fields_ = [ ("byte0", ctypes.c_byte), ("byte1", ctypes.c_byte), ("byte2", ctypes.c_byte), ("byte3", ctypes.c_byte), ("byte4", ctypes.c_byte), ("byte5", ctypes.c_byte), ] nt_authority = SID_IDENTIFIER_AUTHORITY() nt_authority.byte5 = 5 SECURITY_BUILTIN_DOMAIN_RID = 0x20 DOMAIN_ALIAS_RID_ADMINS = 0x220 administrators_group = ctypes.c_void_p() if ctypes.windll.advapi32.AllocateAndInitializeSid( ctypes.byref(nt_authority), 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ctypes.byref(administrators_group)) == 0: raise Exception("AllocateAndInitializeSid failed") try: is_admin = ctypes.wintypes.BOOL() if ctypes.windll.advapi32.CheckTokenMembership( user_token, administrators_group, ctypes.byref(is_admin)) == 0: raise Exception("CheckTokenMembership failed") return is_admin.value != 0 finally: ctypes.windll.advapi32.FreeSid(administrators_group) def _win_current_user_is_admin(): ''' ctypes.windll.shell32.IsUserAnAdmin() is intentionally avoided due to this function being deprecated. ''' return _win_user_token_is_admin(0) def get_specific_user(): ''' Get a user name for publishing. If you find the user is "root" attempt to be more specific ''' user = get_user() if salt.utils.platform.is_windows(): if _win_current_user_is_admin(): return 'sudo_{0}'.format(user) else: env_vars = ('SUDO_USER',) if user == 'root': for evar in env_vars: if evar in os.environ: return 'sudo_{0}'.format(os.environ[evar]) return user def chugid(runas, group=None): ''' Change the current process to belong to the specified user (and the groups to which it belongs) ''' uinfo = pwd.getpwnam(runas) supgroups = [] supgroups_seen = set() if group: try: target_pw_gid = grp.getgrnam(group).gr_gid except KeyError as err: raise CommandExecutionError( 'Failed to fetch the GID for {0}. Error: {1}'.format( group, err ) ) else: target_pw_gid = uinfo.pw_gid # The line below used to exclude the current user's primary gid. # However, when root belongs to more than one group # this causes root's primary group of '0' to be dropped from # his grouplist. On FreeBSD, at least, this makes some # command executions fail with 'access denied'. # # The Python documentation says that os.setgroups sets only # the supplemental groups for a running process. On FreeBSD # this does not appear to be strictly true. group_list = get_group_dict(runas, include_default=True) if sys.platform == 'darwin': group_list = dict((k, v) for k, v in six.iteritems(group_list) if not k.startswith('_')) for group_name in group_list: gid = group_list[group_name] if (gid not in supgroups_seen and not supgroups_seen.add(gid)): supgroups.append(gid) if os.getgid() != target_pw_gid: try: os.setgid(target_pw_gid) except OSError as err: raise CommandExecutionError( 'Failed to change from gid {0} to {1}. Error: {2}'.format( os.getgid(), target_pw_gid, err ) ) # Set supplemental groups if sorted(os.getgroups()) != sorted(supgroups): try: os.setgroups(supgroups) except OSError as err: raise CommandExecutionError( 'Failed to set supplemental groups to {0}. Error: {1}'.format( supgroups, err ) ) if os.getuid() != uinfo.pw_uid: try: os.setuid(uinfo.pw_uid) except OSError as err: raise CommandExecutionError( 'Failed to change from uid {0} to {1}. Error: {2}'.format( os.getuid(), uinfo.pw_uid, err ) ) def chugid_and_umask(runas, umask, group=None): ''' Helper method for for subprocess.Popen to initialise uid/gid and umask for the new process. ''' set_runas = False set_grp = False current_user = getpass.getuser() if runas and runas != current_user: set_runas = True runas_user = runas else: runas_user = current_user current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name if group and group != current_grp: set_grp = True runas_grp = group else: runas_grp = current_grp if set_runas or set_grp: chugid(runas_user, runas_grp) if umask is not None: os.umask(umask) # pylint: disable=blacklisted-function def get_default_group(user): ''' Returns the specified user's default group. If the user doesn't exist, a KeyError will be raised. ''' return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \ if HAS_GRP and HAS_PWD \ else None def get_group_list(user, include_default=True): ''' Returns a list of all of the system group names of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] group_names = None ugroups = set() if hasattr(os, 'getgrouplist'): # Try os.getgrouplist, available in python >= 3.3 log.trace('Trying os.getgrouplist for \'%s\'', user) try: group_names = [ grp.getgrgid(grpid).gr_name for grpid in os.getgrouplist(user, pwd.getpwnam(user).pw_gid) ] except Exception: pass elif HAS_PYSSS: # Try pysss.getgrouplist log.trace('Trying pysss.getgrouplist for \'%s\'', user) try: group_names = list(pysss.getgrouplist(user)) except Exception: pass if group_names is None: # Fall back to generic code # Include the user's default group to match behavior of # os.getgrouplist() and pysss.getgrouplist() log.trace('Trying generic group list for \'%s\'', user) group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] try: default_group = get_default_group(user) if default_group not in group_names: group_names.append(default_group) except KeyError: # If for some reason the user does not have a default group pass if group_names is not None: ugroups.update(group_names) if include_default is False: # Historically, saltstack code for getting group lists did not # include the default group. Some things may only want # supplemental groups, so include_default=False omits the users # default group. try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name ugroups.remove(default_group) except KeyError: # If for some reason the user does not have a default group pass log.trace('Group list for user \'%s\': %s', user, sorted(ugroups)) return sorted(ugroups) def get_gid_list(user, include_default=True): ''' Returns a list of all of the system group IDs of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] gid_list = list( six.itervalues( get_group_dict(user, include_default=include_default) ) ) return sorted(set(gid_list)) def get_gid(group=None): ''' Get the gid for a given group name. If no group given, the current egid will be returned. If the group does not exist, None will be returned. On systems which do not support grp or os.getegid it will return None. ''' if not HAS_GRP: return None if group is None: try: return os.getegid() except AttributeError: return None else: try: return grp.getgrnam(group).gr_gid except KeyError: return None
saltstack/salt
salt/utils/user.py
get_gid_list
python
def get_gid_list(user, include_default=True): ''' Returns a list of all of the system group IDs of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] gid_list = list( six.itervalues( get_group_dict(user, include_default=include_default) ) ) return sorted(set(gid_list))
Returns a list of all of the system group IDs of which the user is a member.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L344-L356
[ "def itervalues(d, **kw):\n return d.itervalues(**kw)\n", "def get_group_dict(user=None, include_default=True):\n '''\n Returns a dict of all of the system groups as keys, and group ids\n as values, of which the user is a member.\n E.g.: {'staff': 501, 'sudo': 27}\n '''\n if HAS_GRP is False or HAS_PWD is False:\n return {}\n group_dict = {}\n group_names = get_group_list(user, include_default=include_default)\n for group in group_names:\n group_dict.update({group: grp.getgrnam(group).gr_gid})\n return group_dict\n" ]
# -*- coding: utf-8 -*- ''' Functions for querying and modifying a user account and the groups to which it belongs. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import ctypes import getpass import logging import os import sys # Import Salt libs import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.decorators.jinja import jinja_filter # Import 3rd-party libs from salt.ext import six # Conditional imports try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False try: import grp HAS_GRP = True except ImportError: HAS_GRP = False try: import pysss HAS_PYSSS = True except ImportError: HAS_PYSSS = False try: import salt.utils.win_functions HAS_WIN_FUNCTIONS = True except ImportError: HAS_WIN_FUNCTIONS = False log = logging.getLogger(__name__) def get_user(): ''' Get the current user ''' if HAS_PWD: ret = pwd.getpwuid(os.geteuid()).pw_name elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32: ret = salt.utils.win_functions.get_current_user() else: raise CommandExecutionError( 'Required external library (pwd or win32api) not installed') return salt.utils.stringutils.to_unicode(ret) @jinja_filter('get_uid') def get_uid(user=None): ''' Get the uid for a given user name. If no user given, the current euid will be returned. If the user does not exist, None will be returned. On systems which do not support pwd or os.geteuid, None will be returned. ''' if not HAS_PWD: return None elif user is None: try: return os.geteuid() except AttributeError: return None else: try: return pwd.getpwnam(user).pw_uid except KeyError: return None def _win_user_token_is_admin(user_token): ''' Using the win32 api, determine if the user with token 'user_token' has administrator rights. See MSDN entry here: http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx ''' class SID_IDENTIFIER_AUTHORITY(ctypes.Structure): _fields_ = [ ("byte0", ctypes.c_byte), ("byte1", ctypes.c_byte), ("byte2", ctypes.c_byte), ("byte3", ctypes.c_byte), ("byte4", ctypes.c_byte), ("byte5", ctypes.c_byte), ] nt_authority = SID_IDENTIFIER_AUTHORITY() nt_authority.byte5 = 5 SECURITY_BUILTIN_DOMAIN_RID = 0x20 DOMAIN_ALIAS_RID_ADMINS = 0x220 administrators_group = ctypes.c_void_p() if ctypes.windll.advapi32.AllocateAndInitializeSid( ctypes.byref(nt_authority), 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ctypes.byref(administrators_group)) == 0: raise Exception("AllocateAndInitializeSid failed") try: is_admin = ctypes.wintypes.BOOL() if ctypes.windll.advapi32.CheckTokenMembership( user_token, administrators_group, ctypes.byref(is_admin)) == 0: raise Exception("CheckTokenMembership failed") return is_admin.value != 0 finally: ctypes.windll.advapi32.FreeSid(administrators_group) def _win_current_user_is_admin(): ''' ctypes.windll.shell32.IsUserAnAdmin() is intentionally avoided due to this function being deprecated. ''' return _win_user_token_is_admin(0) def get_specific_user(): ''' Get a user name for publishing. If you find the user is "root" attempt to be more specific ''' user = get_user() if salt.utils.platform.is_windows(): if _win_current_user_is_admin(): return 'sudo_{0}'.format(user) else: env_vars = ('SUDO_USER',) if user == 'root': for evar in env_vars: if evar in os.environ: return 'sudo_{0}'.format(os.environ[evar]) return user def chugid(runas, group=None): ''' Change the current process to belong to the specified user (and the groups to which it belongs) ''' uinfo = pwd.getpwnam(runas) supgroups = [] supgroups_seen = set() if group: try: target_pw_gid = grp.getgrnam(group).gr_gid except KeyError as err: raise CommandExecutionError( 'Failed to fetch the GID for {0}. Error: {1}'.format( group, err ) ) else: target_pw_gid = uinfo.pw_gid # The line below used to exclude the current user's primary gid. # However, when root belongs to more than one group # this causes root's primary group of '0' to be dropped from # his grouplist. On FreeBSD, at least, this makes some # command executions fail with 'access denied'. # # The Python documentation says that os.setgroups sets only # the supplemental groups for a running process. On FreeBSD # this does not appear to be strictly true. group_list = get_group_dict(runas, include_default=True) if sys.platform == 'darwin': group_list = dict((k, v) for k, v in six.iteritems(group_list) if not k.startswith('_')) for group_name in group_list: gid = group_list[group_name] if (gid not in supgroups_seen and not supgroups_seen.add(gid)): supgroups.append(gid) if os.getgid() != target_pw_gid: try: os.setgid(target_pw_gid) except OSError as err: raise CommandExecutionError( 'Failed to change from gid {0} to {1}. Error: {2}'.format( os.getgid(), target_pw_gid, err ) ) # Set supplemental groups if sorted(os.getgroups()) != sorted(supgroups): try: os.setgroups(supgroups) except OSError as err: raise CommandExecutionError( 'Failed to set supplemental groups to {0}. Error: {1}'.format( supgroups, err ) ) if os.getuid() != uinfo.pw_uid: try: os.setuid(uinfo.pw_uid) except OSError as err: raise CommandExecutionError( 'Failed to change from uid {0} to {1}. Error: {2}'.format( os.getuid(), uinfo.pw_uid, err ) ) def chugid_and_umask(runas, umask, group=None): ''' Helper method for for subprocess.Popen to initialise uid/gid and umask for the new process. ''' set_runas = False set_grp = False current_user = getpass.getuser() if runas and runas != current_user: set_runas = True runas_user = runas else: runas_user = current_user current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name if group and group != current_grp: set_grp = True runas_grp = group else: runas_grp = current_grp if set_runas or set_grp: chugid(runas_user, runas_grp) if umask is not None: os.umask(umask) # pylint: disable=blacklisted-function def get_default_group(user): ''' Returns the specified user's default group. If the user doesn't exist, a KeyError will be raised. ''' return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \ if HAS_GRP and HAS_PWD \ else None def get_group_list(user, include_default=True): ''' Returns a list of all of the system group names of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] group_names = None ugroups = set() if hasattr(os, 'getgrouplist'): # Try os.getgrouplist, available in python >= 3.3 log.trace('Trying os.getgrouplist for \'%s\'', user) try: group_names = [ grp.getgrgid(grpid).gr_name for grpid in os.getgrouplist(user, pwd.getpwnam(user).pw_gid) ] except Exception: pass elif HAS_PYSSS: # Try pysss.getgrouplist log.trace('Trying pysss.getgrouplist for \'%s\'', user) try: group_names = list(pysss.getgrouplist(user)) except Exception: pass if group_names is None: # Fall back to generic code # Include the user's default group to match behavior of # os.getgrouplist() and pysss.getgrouplist() log.trace('Trying generic group list for \'%s\'', user) group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] try: default_group = get_default_group(user) if default_group not in group_names: group_names.append(default_group) except KeyError: # If for some reason the user does not have a default group pass if group_names is not None: ugroups.update(group_names) if include_default is False: # Historically, saltstack code for getting group lists did not # include the default group. Some things may only want # supplemental groups, so include_default=False omits the users # default group. try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name ugroups.remove(default_group) except KeyError: # If for some reason the user does not have a default group pass log.trace('Group list for user \'%s\': %s', user, sorted(ugroups)) return sorted(ugroups) def get_group_dict(user=None, include_default=True): ''' Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27} ''' if HAS_GRP is False or HAS_PWD is False: return {} group_dict = {} group_names = get_group_list(user, include_default=include_default) for group in group_names: group_dict.update({group: grp.getgrnam(group).gr_gid}) return group_dict def get_gid(group=None): ''' Get the gid for a given group name. If no group given, the current egid will be returned. If the group does not exist, None will be returned. On systems which do not support grp or os.getegid it will return None. ''' if not HAS_GRP: return None if group is None: try: return os.getegid() except AttributeError: return None else: try: return grp.getgrnam(group).gr_gid except KeyError: return None
saltstack/salt
salt/utils/user.py
get_gid
python
def get_gid(group=None): ''' Get the gid for a given group name. If no group given, the current egid will be returned. If the group does not exist, None will be returned. On systems which do not support grp or os.getegid it will return None. ''' if not HAS_GRP: return None if group is None: try: return os.getegid() except AttributeError: return None else: try: return grp.getgrnam(group).gr_gid except KeyError: return None
Get the gid for a given group name. If no group given, the current egid will be returned. If the group does not exist, None will be returned. On systems which do not support grp or os.getegid it will return None.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/user.py#L359-L376
null
# -*- coding: utf-8 -*- ''' Functions for querying and modifying a user account and the groups to which it belongs. ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import ctypes import getpass import logging import os import sys # Import Salt libs import salt.utils.path import salt.utils.platform import salt.utils.stringutils from salt.exceptions import CommandExecutionError from salt.utils.decorators.jinja import jinja_filter # Import 3rd-party libs from salt.ext import six # Conditional imports try: import pwd HAS_PWD = True except ImportError: HAS_PWD = False try: import grp HAS_GRP = True except ImportError: HAS_GRP = False try: import pysss HAS_PYSSS = True except ImportError: HAS_PYSSS = False try: import salt.utils.win_functions HAS_WIN_FUNCTIONS = True except ImportError: HAS_WIN_FUNCTIONS = False log = logging.getLogger(__name__) def get_user(): ''' Get the current user ''' if HAS_PWD: ret = pwd.getpwuid(os.geteuid()).pw_name elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32: ret = salt.utils.win_functions.get_current_user() else: raise CommandExecutionError( 'Required external library (pwd or win32api) not installed') return salt.utils.stringutils.to_unicode(ret) @jinja_filter('get_uid') def get_uid(user=None): ''' Get the uid for a given user name. If no user given, the current euid will be returned. If the user does not exist, None will be returned. On systems which do not support pwd or os.geteuid, None will be returned. ''' if not HAS_PWD: return None elif user is None: try: return os.geteuid() except AttributeError: return None else: try: return pwd.getpwnam(user).pw_uid except KeyError: return None def _win_user_token_is_admin(user_token): ''' Using the win32 api, determine if the user with token 'user_token' has administrator rights. See MSDN entry here: http://msdn.microsoft.com/en-us/library/aa376389(VS.85).aspx ''' class SID_IDENTIFIER_AUTHORITY(ctypes.Structure): _fields_ = [ ("byte0", ctypes.c_byte), ("byte1", ctypes.c_byte), ("byte2", ctypes.c_byte), ("byte3", ctypes.c_byte), ("byte4", ctypes.c_byte), ("byte5", ctypes.c_byte), ] nt_authority = SID_IDENTIFIER_AUTHORITY() nt_authority.byte5 = 5 SECURITY_BUILTIN_DOMAIN_RID = 0x20 DOMAIN_ALIAS_RID_ADMINS = 0x220 administrators_group = ctypes.c_void_p() if ctypes.windll.advapi32.AllocateAndInitializeSid( ctypes.byref(nt_authority), 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, ctypes.byref(administrators_group)) == 0: raise Exception("AllocateAndInitializeSid failed") try: is_admin = ctypes.wintypes.BOOL() if ctypes.windll.advapi32.CheckTokenMembership( user_token, administrators_group, ctypes.byref(is_admin)) == 0: raise Exception("CheckTokenMembership failed") return is_admin.value != 0 finally: ctypes.windll.advapi32.FreeSid(administrators_group) def _win_current_user_is_admin(): ''' ctypes.windll.shell32.IsUserAnAdmin() is intentionally avoided due to this function being deprecated. ''' return _win_user_token_is_admin(0) def get_specific_user(): ''' Get a user name for publishing. If you find the user is "root" attempt to be more specific ''' user = get_user() if salt.utils.platform.is_windows(): if _win_current_user_is_admin(): return 'sudo_{0}'.format(user) else: env_vars = ('SUDO_USER',) if user == 'root': for evar in env_vars: if evar in os.environ: return 'sudo_{0}'.format(os.environ[evar]) return user def chugid(runas, group=None): ''' Change the current process to belong to the specified user (and the groups to which it belongs) ''' uinfo = pwd.getpwnam(runas) supgroups = [] supgroups_seen = set() if group: try: target_pw_gid = grp.getgrnam(group).gr_gid except KeyError as err: raise CommandExecutionError( 'Failed to fetch the GID for {0}. Error: {1}'.format( group, err ) ) else: target_pw_gid = uinfo.pw_gid # The line below used to exclude the current user's primary gid. # However, when root belongs to more than one group # this causes root's primary group of '0' to be dropped from # his grouplist. On FreeBSD, at least, this makes some # command executions fail with 'access denied'. # # The Python documentation says that os.setgroups sets only # the supplemental groups for a running process. On FreeBSD # this does not appear to be strictly true. group_list = get_group_dict(runas, include_default=True) if sys.platform == 'darwin': group_list = dict((k, v) for k, v in six.iteritems(group_list) if not k.startswith('_')) for group_name in group_list: gid = group_list[group_name] if (gid not in supgroups_seen and not supgroups_seen.add(gid)): supgroups.append(gid) if os.getgid() != target_pw_gid: try: os.setgid(target_pw_gid) except OSError as err: raise CommandExecutionError( 'Failed to change from gid {0} to {1}. Error: {2}'.format( os.getgid(), target_pw_gid, err ) ) # Set supplemental groups if sorted(os.getgroups()) != sorted(supgroups): try: os.setgroups(supgroups) except OSError as err: raise CommandExecutionError( 'Failed to set supplemental groups to {0}. Error: {1}'.format( supgroups, err ) ) if os.getuid() != uinfo.pw_uid: try: os.setuid(uinfo.pw_uid) except OSError as err: raise CommandExecutionError( 'Failed to change from uid {0} to {1}. Error: {2}'.format( os.getuid(), uinfo.pw_uid, err ) ) def chugid_and_umask(runas, umask, group=None): ''' Helper method for for subprocess.Popen to initialise uid/gid and umask for the new process. ''' set_runas = False set_grp = False current_user = getpass.getuser() if runas and runas != current_user: set_runas = True runas_user = runas else: runas_user = current_user current_grp = grp.getgrgid(pwd.getpwnam(getpass.getuser()).pw_gid).gr_name if group and group != current_grp: set_grp = True runas_grp = group else: runas_grp = current_grp if set_runas or set_grp: chugid(runas_user, runas_grp) if umask is not None: os.umask(umask) # pylint: disable=blacklisted-function def get_default_group(user): ''' Returns the specified user's default group. If the user doesn't exist, a KeyError will be raised. ''' return grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name \ if HAS_GRP and HAS_PWD \ else None def get_group_list(user, include_default=True): ''' Returns a list of all of the system group names of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] group_names = None ugroups = set() if hasattr(os, 'getgrouplist'): # Try os.getgrouplist, available in python >= 3.3 log.trace('Trying os.getgrouplist for \'%s\'', user) try: group_names = [ grp.getgrgid(grpid).gr_name for grpid in os.getgrouplist(user, pwd.getpwnam(user).pw_gid) ] except Exception: pass elif HAS_PYSSS: # Try pysss.getgrouplist log.trace('Trying pysss.getgrouplist for \'%s\'', user) try: group_names = list(pysss.getgrouplist(user)) except Exception: pass if group_names is None: # Fall back to generic code # Include the user's default group to match behavior of # os.getgrouplist() and pysss.getgrouplist() log.trace('Trying generic group list for \'%s\'', user) group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] try: default_group = get_default_group(user) if default_group not in group_names: group_names.append(default_group) except KeyError: # If for some reason the user does not have a default group pass if group_names is not None: ugroups.update(group_names) if include_default is False: # Historically, saltstack code for getting group lists did not # include the default group. Some things may only want # supplemental groups, so include_default=False omits the users # default group. try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name ugroups.remove(default_group) except KeyError: # If for some reason the user does not have a default group pass log.trace('Group list for user \'%s\': %s', user, sorted(ugroups)) return sorted(ugroups) def get_group_dict(user=None, include_default=True): ''' Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27} ''' if HAS_GRP is False or HAS_PWD is False: return {} group_dict = {} group_names = get_group_list(user, include_default=include_default) for group in group_names: group_dict.update({group: grp.getgrnam(group).gr_gid}) return group_dict def get_gid_list(user, include_default=True): ''' Returns a list of all of the system group IDs of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] gid_list = list( six.itervalues( get_group_dict(user, include_default=include_default) ) ) return sorted(set(gid_list))
saltstack/salt
salt/netapi/rest_cherrypy/app.py
html_override_tool
python
def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app'))
Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L649-L681
null
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms, and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: True) :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log.access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log.error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " "user %s from IP %s") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False else: logger.info(failure_str, username, ip) return False else: logger.info(pass_str, username, ip) return True def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug('Found IP list: %s', auth_ip_list) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug('Request from IP: %s', rem_ip) if rem_ip not in auth_ip_list: logger.error('Blocked IP: %s', rem_ip) raise cherrypy.HTTPError(403, 'Bad IP') def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # CORS requests should short-circuit the other tools. cherrypy.response.body = '' cherrypy.response.status = 200 cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg) def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = '' @process_request_body def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body @process_request_body def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
saltstack/salt
salt/netapi/rest_cherrypy/app.py
salt_token_tool
python
def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth
If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L684-L693
null
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms, and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: True) :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log.access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log.error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " "user %s from IP %s") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False else: logger.info(failure_str, username, ip) return False else: logger.info(pass_str, username, ip) return True def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug('Found IP list: %s', auth_ip_list) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug('Request from IP: %s', rem_ip) if rem_ip not in auth_ip_list: logger.error('Blocked IP: %s', rem_ip) raise cherrypy.HTTPError(403, 'Bad IP') def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # CORS requests should short-circuit the other tools. cherrypy.response.body = '' cherrypy.response.status = 200 cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg) def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = '' @process_request_body def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body @process_request_body def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
saltstack/salt
salt/netapi/rest_cherrypy/app.py
salt_api_acl_tool
python
def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " "user %s from IP %s") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False else: logger.info(failure_str, username, ip) return False else: logger.info(pass_str, username, ip) return True
..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L696-L762
null
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms, and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: True) :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log.access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log.error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug('Found IP list: %s', auth_ip_list) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug('Request from IP: %s', rem_ip) if rem_ip not in auth_ip_list: logger.error('Blocked IP: %s', rem_ip) raise cherrypy.HTTPError(403, 'Bad IP') def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # CORS requests should short-circuit the other tools. cherrypy.response.body = '' cherrypy.response.status = 200 cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg) def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = '' @process_request_body def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body @process_request_body def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
saltstack/salt
salt/netapi/rest_cherrypy/app.py
salt_ip_verify_tool
python
def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug('Found IP list: %s', auth_ip_list) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug('Request from IP: %s', rem_ip) if rem_ip not in auth_ip_list: logger.error('Blocked IP: %s', rem_ip) raise cherrypy.HTTPError(403, 'Bad IP')
If there is a list of restricted IPs, verify current client is coming from one of those IPs.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L765-L783
null
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms, and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: True) :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log.access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log.error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " "user %s from IP %s") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False else: logger.info(failure_str, username, ip) return False else: logger.info(pass_str, username, ip) return True def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # CORS requests should short-circuit the other tools. cherrypy.response.body = '' cherrypy.response.status = 200 cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg) def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = '' @process_request_body def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body @process_request_body def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
saltstack/salt
salt/netapi/rest_cherrypy/app.py
cors_tool
python
def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # CORS requests should short-circuit the other tools. cherrypy.response.body = '' cherrypy.response.status = 200 cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True
Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L798-L840
null
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms, and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: True) :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log.access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log.error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " "user %s from IP %s") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False else: logger.info(failure_str, username, ip) return False else: logger.info(pass_str, username, ip) return True def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug('Found IP list: %s', auth_ip_list) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug('Request from IP: %s', rem_ip) if rem_ip not in auth_ip_list: logger.error('Blocked IP: %s', rem_ip) raise cherrypy.HTTPError(403, 'Bad IP') def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg) def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = '' @process_request_body def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body @process_request_body def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
saltstack/salt
salt/netapi/rest_cherrypy/app.py
hypermedia_handler
python
def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg)
Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L853-L918
null
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms, and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: True) :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log.access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log.error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " "user %s from IP %s") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False else: logger.info(failure_str, username, ip) return False else: logger.info(pass_str, username, ip) return True def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug('Found IP list: %s', auth_ip_list) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug('Request from IP: %s', rem_ip) if rem_ip not in auth_ip_list: logger.error('Blocked IP: %s', rem_ip) raise cherrypy.HTTPError(403, 'Bad IP') def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # CORS requests should short-circuit the other tools. cherrypy.response.body = '' cherrypy.response.status = 200 cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = '' @process_request_body def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body @process_request_body def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
saltstack/salt
salt/netapi/rest_cherrypy/app.py
hypermedia_out
python
def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler
Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L921-L933
null
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms, and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: True) :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log.access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log.error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " "user %s from IP %s") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False else: logger.info(failure_str, username, ip) return False else: logger.info(pass_str, username, ip) return True def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug('Found IP list: %s', auth_ip_list) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug('Request from IP: %s', rem_ip) if rem_ip not in auth_ip_list: logger.error('Blocked IP: %s', rem_ip) raise cherrypy.HTTPError(403, 'Bad IP') def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # CORS requests should short-circuit the other tools. cherrypy.response.body = '' cherrypy.response.status = 200 cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg) def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = '' @process_request_body def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body @process_request_body def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
saltstack/salt
salt/netapi/rest_cherrypy/app.py
process_request_body
python
def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped
A decorator to skip a processor function if process_request_body is False
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L936-L944
null
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms, and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: True) :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log.access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log.error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " "user %s from IP %s") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False else: logger.info(failure_str, username, ip) return False else: logger.info(pass_str, username, ip) return True def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug('Found IP list: %s', auth_ip_list) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug('Request from IP: %s', rem_ip) if rem_ip not in auth_ip_list: logger.error('Blocked IP: %s', rem_ip) raise cherrypy.HTTPError(403, 'Bad IP') def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # CORS requests should short-circuit the other tools. cherrypy.response.body = '' cherrypy.response.status = 200 cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg) def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = '' @process_request_body def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body @process_request_body def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
saltstack/salt
salt/netapi/rest_cherrypy/app.py
urlencoded_processor
python
def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = ''
Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L947-L969
null
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms, and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: True) :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log.access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log.error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " "user %s from IP %s") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False else: logger.info(failure_str, username, ip) return False else: logger.info(pass_str, username, ip) return True def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug('Found IP list: %s', auth_ip_list) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug('Request from IP: %s', rem_ip) if rem_ip not in auth_ip_list: logger.error('Blocked IP: %s', rem_ip) raise cherrypy.HTTPError(403, 'Bad IP') def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # CORS requests should short-circuit the other tools. cherrypy.response.body = '' cherrypy.response.status = 200 cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg) def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped @process_request_body def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body @process_request_body def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
saltstack/salt
salt/netapi/rest_cherrypy/app.py
json_processor
python
def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body
Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L973-L993
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms, and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: True) :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log.access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log.error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " "user %s from IP %s") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False else: logger.info(failure_str, username, ip) return False else: logger.info(pass_str, username, ip) return True def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug('Found IP list: %s', auth_ip_list) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug('Request from IP: %s', rem_ip) if rem_ip not in auth_ip_list: logger.error('Blocked IP: %s', rem_ip) raise cherrypy.HTTPError(403, 'Bad IP') def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # CORS requests should short-circuit the other tools. cherrypy.response.body = '' cherrypy.response.status = 200 cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg) def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = '' @process_request_body @process_request_body def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
saltstack/salt
salt/netapi/rest_cherrypy/app.py
yaml_processor
python
def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body
Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L997-L1016
[ "def safe_load(stream, Loader=SaltYamlSafeLoader):\n '''\n .. versionadded:: 2018.3.0\n\n Helper function which automagically uses our custom loader.\n '''\n return yaml.load(stream, Loader=Loader)\n" ]
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms, and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: True) :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log.access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log.error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " "user %s from IP %s") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False else: logger.info(failure_str, username, ip) return False else: logger.info(pass_str, username, ip) return True def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug('Found IP list: %s', auth_ip_list) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug('Request from IP: %s', rem_ip) if rem_ip not in auth_ip_list: logger.error('Blocked IP: %s', rem_ip) raise cherrypy.HTTPError(403, 'Bad IP') def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # CORS requests should short-circuit the other tools. cherrypy.response.body = '' cherrypy.response.status = 200 cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg) def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = '' @process_request_body def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body @process_request_body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
saltstack/salt
salt/netapi/rest_cherrypy/app.py
hypermedia_in
python
def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map
Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1045-L1074
null
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms, and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: True) :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log.access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log.error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " "user %s from IP %s") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False else: logger.info(failure_str, username, ip) return False else: logger.info(pass_str, username, ip) return True def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug('Found IP list: %s', auth_ip_list) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug('Request from IP: %s', rem_ip) if rem_ip not in auth_ip_list: logger.error('Blocked IP: %s', rem_ip) raise cherrypy.HTTPError(403, 'Bad IP') def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # CORS requests should short-circuit the other tools. cherrypy.response.body = '' cherrypy.response.status = 200 cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg) def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = '' @process_request_body def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body @process_request_body def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
saltstack/salt
salt/netapi/rest_cherrypy/app.py
lowdata_fmt
python
def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data
Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1077-L1100
null
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms, and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: True) :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log.access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log.error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " "user %s from IP %s") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False else: logger.info(failure_str, username, ip) return False else: logger.info(pass_str, username, ip) return True def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug('Found IP list: %s', auth_ip_list) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug('Request from IP: %s', rem_ip) if rem_ip not in auth_ip_list: logger.error('Blocked IP: %s', rem_ip) raise cherrypy.HTTPError(403, 'Bad IP') def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # CORS requests should short-circuit the other tools. cherrypy.response.body = '' cherrypy.response.status = 200 cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg) def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = '' @process_request_body def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body @process_request_body def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
saltstack/salt
salt/netapi/rest_cherrypy/app.py
get_app
python
def get_app(opts): ''' Returns a WSGI app and a configuration dictionary ''' apiopts = opts.get(__name__.rsplit('.', 2)[-2], {}) # rest_cherrypy opts # Add Salt and salt-api config options to the main CherryPy config dict cherrypy.config['saltopts'] = opts cherrypy.config['apiopts'] = apiopts root = API() # cherrypy app cpyopts = root.get_conf() # cherrypy app opts return root, apiopts, cpyopts
Returns a WSGI app and a configuration dictionary
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2927-L2940
[ "def get_conf(self):\n '''\n Combine the CherryPy configuration with the rest_cherrypy config values\n pulled from the master config and return the CherryPy configuration\n '''\n conf = {\n 'global': {\n 'server.socket_host': self.apiopts.get('host', '0.0.0.0'),\n 'server.socket_port': self.apiopts.get('port', 8000),\n 'server.thread_pool': self.apiopts.get('thread_pool', 100),\n 'server.socket_queue_size': self.apiopts.get('queue_size', 30),\n 'max_request_body_size': self.apiopts.get(\n 'max_request_body_size', 1048576),\n 'debug': self.apiopts.get('debug', False),\n 'log.access_file': self.apiopts.get('log_access_file', ''),\n 'log.error_file': self.apiopts.get('log_error_file', ''),\n },\n '/': {\n 'request.dispatch': cherrypy.dispatch.MethodDispatcher(),\n\n 'tools.trailing_slash.on': True,\n 'tools.gzip.on': True,\n\n 'tools.html_override.on': True,\n 'tools.cors_tool.on': True,\n },\n }\n\n if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0:\n # CherryPy >= 12.0 no longer supports \"timeout_monitor\", only set\n # this config option when using an older version of CherryPy.\n # See Issue #44601 for more information.\n conf['global']['engine.timeout_monitor.on'] = self.apiopts.get(\n 'expire_responses', True\n )\n\n if cpstats and self.apiopts.get('collect_stats', False):\n conf['/']['tools.cpstats.on'] = True\n\n if 'favicon' in self.apiopts:\n conf['/favicon.ico'] = {\n 'tools.staticfile.on': True,\n 'tools.staticfile.filename': self.apiopts['favicon'],\n }\n\n if self.apiopts.get('debug', False) is False:\n conf['global']['environment'] = 'production'\n\n # Serve static media if the directory has been set in the configuration\n if 'static' in self.apiopts:\n conf[self.apiopts.get('static_path', '/static')] = {\n 'tools.staticdir.on': True,\n 'tools.staticdir.dir': self.apiopts['static'],\n }\n\n # Add to global config\n cherrypy.config.update(conf['global'])\n\n return conf\n" ]
# encoding: utf-8 ''' A REST API for Salt =================== .. py:currentmodule:: salt.netapi.rest_cherrypy.app .. note:: This module is Experimental on Windows platforms, and supports limited configurations: - doesn't support PAM authentication (i.e. external_auth: auto) - doesn't support SSL (i.e. disable_ssl: True) :depends: - CherryPy Python module. Note: there is a `known SSL traceback for CherryPy versions 3.2.5 through 3.7.x <https://github.com/cherrypy/cherrypy/issues/1298>`_. Please use version 3.2.3 or the latest 10.x version instead. :optdepends: - ws4py Python module for websockets support. :client_libraries: - Java: https://github.com/SUSE/salt-netapi-client - Python: https://github.com/saltstack/pepper :setup: All steps below are performed on the machine running the Salt Master daemon. Configuration goes into the Master configuration file. 1. Install ``salt-api``. (This step varies between OS and Linux distros. Some package systems have a split package, others include salt-api in the main Salt package. Ensure the ``salt-api --version`` output matches the ``salt --version`` output.) 2. Install CherryPy. (Read the version caveat in the section above.) 3. Optional: generate self-signed SSL certificates. Using a secure HTTPS connection is strongly recommended since Salt eauth authentication credentials will be sent over the wire. 1. Install the PyOpenSSL package. 2. Generate a self-signed certificate using the :py:func:`~salt.modules.tls.create_self_signed_cert` execution function. .. code-block:: bash salt-call --local tls.create_self_signed_cert 4. Edit the master config to create at least one external auth user or group following the :ref:`full external auth instructions <acl-eauth>`. 5. Edit the master config with the following production-ready example to enable the ``rest_cherrypy`` module. (Adjust cert paths as needed, or disable SSL (not recommended!).) .. code-block:: yaml rest_cherrypy: port: 8000 ssl_crt: /etc/pki/tls/certs/localhost.crt ssl_key: /etc/pki/tls/certs/localhost.key 6. Restart the ``salt-master`` daemon. 7. Start the ``salt-api`` daemon. :configuration: All available configuration options are detailed below. These settings configure the CherryPy HTTP server and do not apply when using an external server such as Apache or Nginx. port **Required** The port for the webserver to listen on. host : ``0.0.0.0`` The socket interface for the HTTP server to listen on. debug : ``False`` Starts the web server in development mode. It will reload itself when the underlying code is changed and will output more debugging info. log.access_file Path to a file to write HTTP access logs. .. versionadded:: 2016.11.0 log.error_file Path to a file to write HTTP error logs. .. versionadded:: 2016.11.0 ssl_crt The path to a SSL certificate. (See below) ssl_key The path to the private key for your SSL certificate. (See below) ssl_chain (Optional when using PyOpenSSL) the certificate chain to pass to ``Context.load_verify_locations``. disable_ssl A flag to disable SSL. Warning: your Salt authentication credentials will be sent in the clear! webhook_disable_auth : False The :py:class:`Webhook` URL requires authentication by default but external services cannot always be configured to send authentication. See the Webhook documentation for suggestions on securing this interface. webhook_url : /hook Configure the URL endpoint for the :py:class:`Webhook` entry point. thread_pool : ``100`` The number of worker threads to start up in the pool. socket_queue_size : ``30`` Specify the maximum number of HTTP connections to queue. expire_responses : True Whether to check for and kill HTTP responses that have exceeded the default timeout. .. deprecated:: 2016.11.9,2017.7.3,2018.3.0 The "expire_responses" configuration setting, which corresponds to the ``timeout_monitor`` setting in CherryPy, is no longer supported in CherryPy versions >= 12.0.0. max_request_body_size : ``1048576`` Maximum size for the HTTP request body. collect_stats : False Collect and report statistics about the CherryPy server Reports are available via the :py:class:`Stats` URL. stats_disable_auth : False Do not require authentication to access the ``/stats`` endpoint. .. versionadded:: 2018.3.0 static A filesystem path to static HTML/JavaScript/CSS/image assets. static_path : ``/static`` The URL prefix to use when serving static assets out of the directory specified in the ``static`` setting. enable_sessions : ``True`` Enable or disable all endpoints that rely on session cookies. This can be useful to enforce only header-based authentication. .. versionadded:: 2017.7.0 app : ``index.html`` A filesystem path to an HTML file that will be served as a static file. This is useful for bootstrapping a single-page JavaScript app. Warning! If you set this option to a custom web application, anything that uses cookie-based authentication is vulnerable to XSRF attacks. Send the custom ``X-Auth-Token`` header instead and consider disabling the ``enable_sessions`` setting. .. versionchanged:: 2017.7.0 Add a proof-of-concept JavaScript single-page app. app_path : ``/app`` The URL prefix to use for serving the HTML file specified in the ``app`` setting. This should be a simple name containing no slashes. Any path information after the specified path is ignored; this is useful for apps that utilize the HTML5 history API. root_prefix : ``/`` A URL path to the main entry point for the application. This is useful for serving multiple applications from the same URL. .. _rest_cherrypy-auth: Authentication -------------- Authentication is performed by passing a session token with each request. Tokens are generated via the :py:class:`Login` URL. The token may be sent in one of two ways: as a custom header or as a session cookie. The latter is far more convenient for clients that support cookies. * Include a custom header named :mailheader:`X-Auth-Token`. For example, using curl: .. code-block:: bash curl -sSk https://localhost:8000/login \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=pam Copy the ``token`` value from the output and include it in subsequent requests: .. code-block:: bash curl -sSk https://localhost:8000 \\ -H 'Accept: application/x-yaml' \\ -H 'X-Auth-Token: 697adbdc8fe971d09ae4c2a3add7248859c87079'\\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping * Sent via a cookie. This option is a convenience for HTTP clients that automatically handle cookie support (such as browsers). For example, using curl: .. code-block:: bash # Write the cookie file: curl -sSk https://localhost:8000/login \\ -c ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d username=saltdev \\ -d password=saltdev \\ -d eauth=auto # Read the cookie file: curl -sSk https://localhost:8000 \\ -b ~/cookies.txt \\ -H 'Accept: application/x-yaml' \\ -d client=local \\ -d tgt='*' \\ -d fun=test.ping Another example using the :program:`requests` library in Python: .. code-block:: python >>> import requests >>> session = requests.Session() >>> session.post('http://localhost:8000/login', json={ 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'auto', }) <Response [200]> >>> resp = session.post('http://localhost:8000', json=[{ 'client': 'local', 'tgt': '*', 'fun': 'test.arg', 'arg': ['foo', 'bar'], 'kwarg': {'baz': 'Baz!'}, }]) >>> resp.json() {u'return': [{ ...snip... }]} .. seealso:: You can bypass the session handling via the :py:class:`Run` URL. Usage ----- This interface directly exposes Salt's :ref:`Python API <python-api>`. Everything possible at the CLI is possible through the Python API. Commands are executed on the Salt Master. The root URL (``/``) is RPC-like in that it accepts instructions in the request body for what Salt functions to execute, and the response contains the result of those function calls. For example: .. code-block:: text % curl -sSi https://localhost:8000 \ -H 'Content-type: application/json' \ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping" }]' HTTP/1.1 200 OK Content-Type: application/json [...snip...] {"return": [{"jerry": true}]} The request body must be an array of commands. Use this workflow to build a command: 1. Choose a client interface. 2. Choose a function. 3. Fill out the remaining parameters needed for the chosen client. The ``client`` field is a reference to the main Python classes used in Salt's Python API. Read the full :ref:`Client APIs <client-apis>` documentation, but in short: * "local" uses :py:class:`LocalClient <salt.client.LocalClient>` which sends commands to Minions. Equivalent to the ``salt`` CLI command. * "runner" uses :py:class:`RunnerClient <salt.runner.RunnerClient>` which invokes runner modules on the Master. Equivalent to the ``salt-run`` CLI command. * "wheel" uses :py:class:`WheelClient <salt.wheel.WheelClient>` which invokes wheel modules on the Master. Wheel modules do not have a direct CLI equivalent but they typically manage Master-side resources such as state files, pillar files, the Salt config files, and the :py:mod:`key wheel module <salt.wheel.key>` exposes similar functionality as the ``salt-key`` CLI command. Most clients have variants like synchronous or asynchronous execution as well as others like batch execution. See the :ref:`full list of client interfaces <client-interfaces>`. Each client requires different arguments and sometimes has different syntax. For example, ``LocalClient`` requires the ``tgt`` argument because it forwards the command to Minions and the other client interfaces do not. ``LocalClient`` also takes ``arg`` (array) and ``kwarg`` (dictionary) arguments because these values are sent to the Minions and used to execute the requested function there. ``RunnerClient`` and ``WheelClient`` are executed directly on the Master and thus do not need or accept those arguments. Read the method signatures in the client documentation linked above, but hopefully an example will help illustrate the concept. This example causes Salt to execute two functions -- the :py:func:`test.arg execution function <salt.modules.test.arg>` using ``LocalClient`` and the :py:func:`test.arg runner function <salt.runners.test.arg>` using ``RunnerClient``; note the different structure for each command. The results for both are combined and returned as one response. .. code-block:: text % curl -b ~/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.arg", "arg": ["positional arg one", "positional arg two"], "kwarg": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion" } }, { "client": "runner", "fun": "test.arg", "keyword arg one": "Hello from a master", "keyword arg two": "Runners do not support positional args" } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "args": [ "positional arg one", "positional arg two" ], "kwargs": { "keyword arg one": "Hello from a minion", "keyword arg two": "Hello again from a minion", [...snip...] } }, [...snip; other minion returns here...] }, { "args": [], "kwargs": { "keyword arg two": "Runners do not support positional args", "keyword arg one": "Hello from a master" } } ] } One more example, this time with more commonly used functions: .. code-block:: text curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "state.sls", "kwarg": { "mods": "apache", "pillar": { "lookup": { "wwwdir": "/srv/httpd/htdocs" } } } }, { "client": "runner", "fun": "cloud.create", "provider": "my-ec2-provider", "instances": "my-centos-6", "image": "ami-1624987f", "delvol_on_destroy", true } ] ' HTTP/1.1 200 OK [...snip...] { "return": [ { "jerry": { "pkg_|-install_apache_|-httpd_|-installed": { [...snip full state return here...] } } [...snip other minion returns here...] }, { [...snip full salt-cloud output here...] } ] } Content negotiation ------------------- This REST interface is flexible in what data formats it will accept as well as what formats it will return (e.g., JSON, YAML, urlencoded). * Specify the format of data in the request body by including the :mailheader:`Content-Type` header. * Specify the desired data format for the response body with the :mailheader:`Accept` header. We recommend the JSON format for most HTTP requests. urlencoded data is simple and cannot express complex data structures -- and that is often required for some Salt commands, such as starting a state run that uses Pillar data. Salt's CLI tool can reformat strings passed in at the CLI into complex data structures, and that behavior also works via salt-api, but that can be brittle and since salt-api can accept JSON it is best just to send JSON. Here is an example of sending urlencoded data: .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -d client=runner \\ -d fun='jobs.lookup_jid' \\ -d jid='20150129182456704682' .. admonition:: urlencoded data caveats * Only a single command may be sent per HTTP request. * Repeating the ``arg`` parameter multiple times will cause those parameters to be combined into a single list. Note, some popular frameworks and languages (notably jQuery, PHP, and Ruby on Rails) will automatically append empty brackets onto repeated query string parameters. E.g., ``?foo[]=fooone&foo[]=footwo``. This is **not** supported; send ``?foo=fooone&foo=footwo`` instead, or send JSON or YAML. A note about ``curl`` The ``-d`` flag to curl does *not* automatically urlencode data which can affect passwords and other data that contains characters that must be encoded. Use the ``--data-urlencode`` flag instead. E.g.: .. code-block:: bash curl -ksi http://localhost:8000/login \\ -H "Accept: application/json" \\ -d username='myapiuser' \\ --data-urlencode password='1234+' \\ -d eauth='pam' Performance Expectations and Recommended Usage ============================================== This module provides a thin wrapper around :ref:`Salt's Python API <python-api>`. Executing a Salt command via rest_cherrypy is directly analogous to executing a Salt command via Salt's CLI (which also uses the Python API) -- they share the same semantics, performance characteristics, and 98% of the same code. As a rule-of-thumb: if you wouldn't do it at the CLI don't do it via this API. Long-Running HTTP Connections ----------------------------- The CherryPy server is a production-ready, threading HTTP server written in Python. Because it makes use of a thread pool to process HTTP requests it is not ideally suited to maintaining large numbers of concurrent, synchronous connections. On moderate hardware with default settings it should top-out at around 30 to 50 concurrent connections. That number of long-running, synchronous Salt processes is also not ideal. Like at the CLI, each Salt command run will start a process that instantiates its own ``LocalClient``, which instantiates its own listener to the Salt event bus, and sends out its own periodic ``saltutil.find_job`` queries to determine if a Minion is still running the command. Not exactly a lightweight operation. Timeouts -------- In addition to the above resource overhead for long-running connections, there are the usual HTTP timeout semantics for the CherryPy server, any HTTP client being used, as well as any hardware in between such as proxies, gateways, or load balancers. rest_cherrypy can be configured not to time-out long responses via the ``expire_responses`` setting, and both :py:class:`LocalClient <salt.client.LocalClient>` and :py:class:`RunnerClient <salt.runner.RunnerClient>` have their own timeout parameters that may be passed as top-level keywords: .. code-block:: bash curl -b /tmp/cookies.txt -sSi localhost:8000 \ -H 'Content-type: application/json' \ -d ' [ { "client": "local", "tgt": "*", "fun": "test.sleep", "kwarg": {"length": 30}, "timeout": 60 }, { "client": "runner", "fun": "test.sleep", "kwarg": {"s_time": 30}, "timeout": 60 } ] ' Best Practices -------------- Given the performance overhead and HTTP timeouts for long-running operations described above, the most effective and most scalable way to use both Salt and salt-api is to run commands asynchronously using the ``local_async``, ``runner_async``, and ``wheel_async`` clients. Running asynchronous jobs results in being able to process 3x more commands per second for ``LocalClient`` and 17x more commands per second for ``RunnerClient``, in addition to much less network traffic and memory requirements. Job returns can be fetched from Salt's job cache via the ``/jobs/<jid>`` endpoint, or they can be collected into a data store using Salt's :ref:`Returner system <returners>`. The ``/events`` endpoint is specifically designed to handle long-running HTTP connections and it exposes Salt's event bus which includes job returns. Watching this endpoint first, then executing asynchronous Salt commands second, is the most lightweight and scalable way to use ``rest_cherrypy`` while still receiving job returns in real-time. But this requires clients that can properly handle the inherent asynchronicity of that workflow. Performance Tuning ------------------ The ``thread_pool`` and ``socket_queue_size`` settings can be used to increase the capacity of rest_cherrypy to handle incoming requests. Keep an eye on RAM usage as well as available file handles while testing changes to these settings. As salt-api is a thin wrapper around Salt's Python API, also keep an eye on the performance of Salt when testing. Future Plans ------------ Now that Salt uses the Tornado concurrency library internally, we plan to improve performance in the API by taking advantage of existing processes and event listeners and to use lightweight coroutines to facilitate more simultaneous HTTP connections and better support for synchronous operations. That effort can be tracked in `issue 26505`__, but until that issue is closed rest_cherrypy will remain the officially recommended REST API. .. __: https://github.com/saltstack/salt/issues/26505 .. |req_token| replace:: a session token from :py:class:`~Login`. .. |req_accept| replace:: the desired response format. .. |req_ct| replace:: the format of the request body. .. |res_ct| replace:: the format of the response body; depends on the :mailheader:`Accept` request header. .. |200| replace:: success .. |400| replace:: bad or malformed request .. |401| replace:: authentication required .. |406| replace:: requested Content-Type not available ''' # We need a custom pylintrc here... # pylint: disable=W0212,E1101,C0103,R0201,W0221,W0613 # Import Python libs from __future__ import absolute_import import collections import itertools import functools import logging import os import signal import tarfile from multiprocessing import Process, Pipe logger = logging.getLogger(__name__) # Import third-party libs # pylint: disable=import-error, 3rd-party-module-not-gated import cherrypy try: from cherrypy.lib import cpstats except AttributeError: cpstats = None logger.warn('Import of cherrypy.cpstats failed. ' 'Possible upstream bug: ' 'https://github.com/cherrypy/cherrypy/issues/1444') except ImportError: cpstats = None logger.warn('Import of cherrypy.cpstats failed.') # pylint: enable=import-error, 3rd-party-module-not-gated # Import Salt libs import salt import salt.auth import salt.exceptions import salt.utils.event import salt.utils.json import salt.utils.stringutils import salt.utils.versions import salt.utils.yaml from salt.ext import six from salt.ext.six import BytesIO # Import salt-api libs import salt.netapi # Imports related to websocket try: from .tools import websockets from . import event_processor HAS_WEBSOCKETS = True except ImportError: websockets = type('websockets', (object,), { 'SynchronizingWebsocket': None, }) HAS_WEBSOCKETS = False def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( apiopts.get('app_path', '/app'), apiopts.get('static_path', '/static'), ) if 'app' not in cherrypy.config['apiopts']: return if request.path_info.startswith(url_blacklist): return if request.headers.get('Accept') == '*/*': return try: wants_html = cherrypy.lib.cptools.accept('text/html') except cherrypy.HTTPError: return else: if wants_html != 'text/html': return raise cherrypy.InternalRedirect(apiopts.get('app_path', '/app')) def salt_token_tool(): ''' If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended ''' x_auth = cherrypy.request.headers.get('X-Auth-Token', None) # X-Auth-Token header trumps session cookie if x_auth: cherrypy.request.cookie['session_id'] = x_auth def salt_api_acl_tool(username, request): ''' ..versionadded:: 2016.3.0 Verifies user requests against the API whitelist. (User/IP pair) in order to provide whitelisting for the API similar to the master, but over the API. ..code-block:: yaml rest_cherrypy: api_acl: users: '*': - 1.1.1.1 - 1.1.1.2 foo: - 8.8.4.4 bar: - '*' :param username: Username to check against the API. :type username: str :param request: Cherrypy request to check against the API. :type request: cherrypy.request ''' failure_str = ("[api_acl] Authentication failed for " "user %s from IP %s") success_str = ("[api_acl] Authentication sucessful for " "user %s from IP %s") pass_str = ("[api_acl] Authentication not checked for " "user %s from IP %s") acl = None # Salt Configuration salt_config = cherrypy.config.get('saltopts', None) if salt_config: # Cherrypy Config. cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: # ACL Config. acl = cherrypy_conf.get('api_acl', None) ip = request.remote.ip if acl: users = acl.get('users', {}) if users: if username in users: if ip in users[username] or '*' in users[username]: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False elif username not in users and '*' in users: if ip in users['*'] or '*' in users['*']: logger.info(success_str, username, ip) return True else: logger.info(failure_str, username, ip) return False else: logger.info(failure_str, username, ip) return False else: logger.info(pass_str, username, ip) return True def salt_ip_verify_tool(): ''' If there is a list of restricted IPs, verify current client is coming from one of those IPs. ''' # This is overly cumbersome and crude, # But, it's also safe... ish... salt_config = cherrypy.config.get('saltopts', None) if salt_config: cherrypy_conf = salt_config.get('rest_cherrypy', None) if cherrypy_conf: auth_ip_list = cherrypy_conf.get('authorized_ips', None) if auth_ip_list: logger.debug('Found IP list: %s', auth_ip_list) rem_ip = cherrypy.request.headers.get('Remote-Addr', None) logger.debug('Request from IP: %s', rem_ip) if rem_ip not in auth_ip_list: logger.error('Blocked IP: %s', rem_ip) raise cherrypy.HTTPError(403, 'Bad IP') def salt_auth_tool(): ''' Redirect all unauthenticated requests to the login page ''' # Redirect to the login page if the session hasn't been authed if 'token' not in cherrypy.session: # pylint: disable=W8601 raise cherrypy.HTTPError(401) # Session is authenticated; inform caches cherrypy.response.headers['Cache-Control'] = 'private' def cors_tool(): ''' Handle both simple and complex CORS requests Add CORS headers to each response. If the request is a CORS preflight request swap out the default handler with a simple, single-purpose handler that verifies the request and provides a valid CORS response. ''' req_head = cherrypy.request.headers resp_head = cherrypy.response.headers # Always set response headers necessary for 'simple' CORS. resp_head['Access-Control-Allow-Origin'] = req_head.get('Origin', '*') resp_head['Access-Control-Expose-Headers'] = 'GET, POST' resp_head['Access-Control-Allow-Credentials'] = 'true' # Non-simple CORS preflight request; short-circuit the normal handler. if cherrypy.request.method == 'OPTIONS': ac_method = req_head.get('Access-Control-Request-Method', None) allowed_methods = ['GET', 'POST'] allowed_headers = [ 'Content-Type', 'X-Auth-Token', 'X-Requested-With', ] if ac_method and ac_method in allowed_methods: resp_head['Access-Control-Allow-Methods'] = ', '.join(allowed_methods) resp_head['Access-Control-Allow-Headers'] = ', '.join(allowed_headers) resp_head['Connection'] = 'keep-alive' resp_head['Access-Control-Max-Age'] = '1400' # CORS requests should short-circuit the other tools. cherrypy.response.body = '' cherrypy.response.status = 200 cherrypy.serving.request.handler = None # Needed to avoid the auth_tool check. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session['token'] = True return True # Be conservative in what you send # Maps Content-Type to serialization functions; this is a tuple of tuples to # preserve order of preference. ct_out_map = ( ('application/json', salt.utils.json.dumps), ('application/x-yaml', functools.partial( salt.utils.yaml.safe_dump, default_flow_style=False)), ) def hypermedia_handler(*args, **kwargs): ''' Determine the best output format based on the Accept header, execute the regular handler, and transform the output to the request content type (even if it's an error). :param args: Pass args through to the main handler :param kwargs: Pass kwargs through to the main handler ''' # Execute the real handler. Handle or pass-through any errors we know how # to handle (auth & HTTP errors). Reformat any errors we don't know how to # handle as a data structure. try: cherrypy.response.processors = dict(ct_out_map) ret = cherrypy.serving.request._hypermedia_inner_handler(*args, **kwargs) except (salt.exceptions.AuthenticationError, salt.exceptions.AuthorizationError, salt.exceptions.EauthAuthenticationError, salt.exceptions.TokenAuthenticationError): raise cherrypy.HTTPError(401) except salt.exceptions.SaltInvocationError: raise cherrypy.HTTPError(400) except (salt.exceptions.SaltDaemonNotRunning, salt.exceptions.SaltReqTimeoutError) as exc: raise cherrypy.HTTPError(503, exc.strerror) except salt.exceptions.SaltClientTimeout: raise cherrypy.HTTPError(504) except cherrypy.CherryPyException: raise except Exception as exc: # The TimeoutError exception class was removed in CherryPy in 12.0.0, but # Still check existence of TimeoutError and handle in CherryPy < 12. # The check was moved down from the SaltClientTimeout error line because # A one-line if statement throws a BaseException inheritance TypeError. if hasattr(cherrypy, 'TimeoutError') and isinstance(exc, cherrypy.TimeoutError): raise cherrypy.HTTPError(504) import traceback logger.debug("Error while processing request for: %s", cherrypy.request.path_info, exc_info=True) cherrypy.response.status = 500 ret = { 'status': cherrypy.response.status, 'return': '{0}'.format(traceback.format_exc(exc)) if cherrypy.config['debug'] else "An unexpected error occurred"} # Raises 406 if requested content-type is not supported best = cherrypy.lib.cptools.accept([i for (i, _) in ct_out_map]) # Transform the output from the handler into the requested output format cherrypy.response.headers['Content-Type'] = best out = cherrypy.response.processors[best] try: response = out(ret) if six.PY3: response = salt.utils.stringutils.to_bytes(response) return response except Exception: msg = 'Could not serialize the return data from Salt.' logger.debug(msg, exc_info=True) raise cherrypy.HTTPError(500, msg) def hypermedia_out(): ''' Determine the best handler for the requested content type Wrap the normal handler and transform the output from that handler into the requested content type ''' request = cherrypy.serving.request request._hypermedia_inner_handler = request.handler # If handler has been explicitly set to None, don't override. if request.handler is not None: request.handler = hypermedia_handler def process_request_body(fn): ''' A decorator to skip a processor function if process_request_body is False ''' @functools.wraps(fn) def wrapped(*args, **kwargs): # pylint: disable=C0111 if cherrypy.request.process_request_body is not False: fn(*args, **kwargs) return wrapped def urlencoded_processor(entity): ''' Accept x-www-form-urlencoded data (run through CherryPy's formatter) and reformat it into a Low State data structure. Since we can't easily represent complicated data structures with key-value pairs, any more complicated requirements (e.g. compound commands) must instead be delivered via JSON or YAML. For example:: .. code-block:: bash curl -si localhost:8000 -d client=local -d tgt='*' \\ -d fun='test.kwarg' -d arg='one=1' -d arg='two=2' :param entity: raw POST data ''' # First call out to CherryPy's default processor cherrypy._cpreqbody.process_urlencoded(entity) cherrypy._cpreqbody.process_urlencoded(entity) cherrypy.serving.request.unserialized_data = entity.params cherrypy.serving.request.raw_body = '' @process_request_body def json_processor(entity): ''' Unserialize raw POST data in JSON format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) del contents try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document') cherrypy.serving.request.raw_body = body @process_request_body def yaml_processor(entity): ''' Unserialize raw POST data in YAML format to a Python data structure. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.yaml.safe_load(body) except ValueError: raise cherrypy.HTTPError(400, 'Invalid YAML document') cherrypy.serving.request.raw_body = body @process_request_body def text_processor(entity): ''' Attempt to unserialize plain text as JSON Some large services still send JSON with a text/plain Content-Type. Those services are bad and should feel bad. :param entity: raw POST data ''' if six.PY2: body = entity.fp.read() else: # https://github.com/cherrypy/cherrypy/pull/1572 contents = BytesIO() body = entity.fp.read(fp_out=contents) contents.seek(0) body = salt.utils.stringutils.to_unicode(contents.read()) try: cherrypy.serving.request.unserialized_data = salt.utils.json.loads(body) except ValueError: cherrypy.serving.request.unserialized_data = body cherrypy.serving.request.raw_body = body def hypermedia_in(): ''' Unserialize POST/PUT data of a specified Content-Type. The following custom processors all are intended to format Low State data and will place that data structure into the request object. :raises HTTPError: if the request contains a Content-Type that we do not have a processor for ''' # Be liberal in what you accept ct_in_map = { 'application/x-www-form-urlencoded': urlencoded_processor, 'application/json': json_processor, 'application/x-yaml': yaml_processor, 'text/yaml': yaml_processor, 'text/plain': text_processor, } # Do not process the body for POST requests that have specified no content # or have not specified Content-Length if (cherrypy.request.method.upper() == 'POST' and cherrypy.request.headers.get('Content-Length', '0') == '0'): cherrypy.request.process_request_body = False cherrypy.request.unserialized_data = None cherrypy.request.body.processors.clear() cherrypy.request.body.default_proc = cherrypy.HTTPError( 406, 'Content type not supported') cherrypy.request.body.processors = ct_in_map def lowdata_fmt(): ''' Validate and format lowdata from incoming unserialized request data This tool requires that the hypermedia_in tool has already been run. ''' if cherrypy.request.method.upper() != 'POST': return data = cherrypy.request.unserialized_data # if the data was sent as urlencoded, we need to make it a list. # this is a very forgiving implementation as different clients set different # headers for form encoded data (including charset or something similar) if data and isinstance(data, collections.Mapping): # Make the 'arg' param a list if not already if 'arg' in data and not isinstance(data['arg'], list): data['arg'] = [data['arg']] # Finally, make a Low State and put it in request cherrypy.request.lowstate = [data] else: cherrypy.serving.request.lowstate = data tools_config = { 'on_start_resource': [ ('html_override', html_override_tool), ('salt_token', salt_token_tool), ], 'before_request_body': [ ('cors_tool', cors_tool), ('salt_auth', salt_auth_tool), ('hypermedia_in', hypermedia_in), ], 'before_handler': [ ('lowdata_fmt', lowdata_fmt), ('hypermedia_out', hypermedia_out), ('salt_ip_verify', salt_ip_verify_tool), ], } for hook, tool_list in tools_config.items(): for idx, tool_config in enumerate(tool_list): tool_name, tool_fn = tool_config setattr(cherrypy.tools, tool_name, cherrypy.Tool( hook, tool_fn, priority=(50 + idx))) ############################################################################### class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) } class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), } def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, } class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", } def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]} class Logout(LowDataAdapter): ''' Class to remove or invalidate sessions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, 'tools.lowdata_fmt.on': False, }) def POST(self): ''' Destroy the currently active session and expire the session cookie ''' cherrypy.lib.sessions.expire() # set client-side to expire cherrypy.session.regenerate() # replace server-side with new return {'return': "Your token has been cleared"} class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate()) class Run(LowDataAdapter): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` salt-api does not enforce authorization, Salt's eauth system does that. Local/Runner/WheelClient all accept ``username``/``password``/``eauth`` **or** ``token`` kwargs that are then checked by the eauth system. The session mechanism in ``rest_cherrypy`` simply pairs a session with a Salt eauth token and then passes the ``token`` kwarg in automatically. If you already have a Salt eauth token, perhaps generated by the :py:func:`mk_token <salt.runners.auth.mk_token>` function in the Auth Runner module, then there is no reason to use sessions. This endpoint accepts either a ``username``, ``password``, ``eauth`` trio, **or** a ``token`` kwarg and does not make use of sessions at all. ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.sessions.on': False, }) def POST(self, **kwargs): ''' Run commands bypassing the :ref:`normal session handling <rest_cherrypy-auth>` Other than that this URL is identical to the :py:meth:`root URL (/) <LowDataAdapter.POST>`. .. http:post:: /run An array of lowstate data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto" }]' **Or** using a Salt Eauth token: .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -H 'Content-type: application/json' \\ -d '[{ "client": "local", "tgt": "*", "fun": "test.ping", "token": "<salt eauth token here>" }]' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping", "username": "saltdev", "password": "saltdev", "eauth": "auto"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true The /run enpoint can also be used to issue commands using the salt-ssh subsystem. When using salt-ssh, eauth credentials should not be supplied. Instead, authentication should be handled by the SSH layer itself. The use of the salt-ssh client does not require a salt master to be running. Instead, only a roster file must be present in the salt configuration directory. All SSH client requests are synchronous. **Example SSH client request:** .. code-block:: bash curl -sS localhost:8000/run \\ -H 'Accept: application/x-yaml' \\ -d client='ssh' \\ -d tgt='*' \\ -d fun='test.ping' .. code-block:: text POST /run HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Length: 75 Content-Type: application/x-www-form-urlencoded client=ssh&tgt=*&fun=test.ping **Example SSH response:** .. code-block:: text return: - silver: fun: test.ping fun_args: [] id: silver jid: '20141203103525666185' retcode: 0 return: true success: true ''' return { 'return': list(self.exec_lowstate()), } class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen() class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts) def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start() class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret} class Stats(object): ''' Expose statistics on the running CherryPy server ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def __init__(self): if cherrypy.config['apiopts'].get('stats_disable_auth'): self._cp_config['tools.salt_auth.on'] = False def GET(self): ''' Return a dump of statistics collected from the CherryPy server .. http:get:: /stats :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :resheader Content-Type: |res_ct| :status 200: |200| :status 401: |401| :status 406: |406| ''' if hasattr(logging, 'statistics'): return cpstats.extrapolate_statistics(logging.statistics) return {} class App(object): ''' Class to serve HTML5 apps ''' exposed = True def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index)) class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf
saltstack/salt
salt/netapi/rest_cherrypy/app.py
LowDataAdapter.exec_lowstate
python
def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret
Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1155-L1208
null
class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) }
saltstack/salt
salt/netapi/rest_cherrypy/app.py
LowDataAdapter.POST
python
def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true ''' return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))) }
Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| :term:`lowstate` data describing Salt commands must be sent in the request body. **Example request:** .. code-block:: bash curl -sSik https://localhost:8000 \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -H "Content-type: application/json" \\ -d '[{"client": "local", "tgt": "*", "fun": "test.ping"}]' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml X-Auth-Token: d40d1e1e Content-Type: application/json [{"client": "local", "tgt": "*", "fun": "test.ping"}] **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 200 Allow: GET, HEAD, POST Content-Type: application/x-yaml return: - ms-0: true ms-1: true ms-2: true ms-3: true ms-4: true
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1251-L1310
[ "def exec_lowstate(self, client=None, token=None):\n '''\n Pull a Low State data structure from request and execute the low-data\n chunks through Salt. The low-data chunks will be updated to include the\n authorization token for the current session.\n '''\n lowstate = cherrypy.request.lowstate\n\n # Release the session lock before executing any potentially\n # long-running Salt commands. This allows different threads to execute\n # Salt commands concurrently without blocking.\n if cherrypy.request.config.get('tools.sessions.on', False):\n cherrypy.session.release_lock()\n\n # if the lowstate loaded isn't a list, lets notify the client\n if not isinstance(lowstate, list):\n raise cherrypy.HTTPError(400, 'Lowstates must be a list')\n\n # Make any requested additions or modifications to each lowstate, then\n # execute each one and yield the result.\n for chunk in lowstate:\n if token:\n chunk['token'] = token\n\n if 'token' in chunk:\n # Make sure that auth token is hex\n try:\n int(chunk['token'], 16)\n except (TypeError, ValueError):\n raise cherrypy.HTTPError(401, 'Invalid token')\n\n if 'token' in chunk:\n # Make sure that auth token is hex\n try:\n int(chunk['token'], 16)\n except (TypeError, ValueError):\n raise cherrypy.HTTPError(401, 'Invalid token')\n\n if client:\n chunk['client'] = client\n\n # Make any 'arg' params a list if not already.\n # This is largely to fix a deficiency in the urlencoded format.\n if 'arg' in chunk and not isinstance(chunk['arg'], list):\n chunk['arg'] = [chunk['arg']]\n\n ret = self.api.run(chunk)\n\n # Sometimes Salt gives us a return and sometimes an iterator\n if isinstance(ret, collections.Iterator):\n for i in ret:\n yield i\n else:\n yield ret\n" ]
class LowDataAdapter(object): ''' The primary entry point to Salt's REST API ''' exposed = True _cp_config = { 'tools.salt_token.on': True, 'tools.sessions.on': True, 'tools.sessions.timeout': 60 * 10, # 10 hours # 'tools.autovary.on': True, 'tools.hypermedia_out.on': True, 'tools.hypermedia_in.on': True, 'tools.lowdata_fmt.on': True, 'tools.salt_ip_verify.on': True, } def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self.api = salt.netapi.NetapiClient(self.opts) def exec_lowstate(self, client=None, token=None): ''' Pull a Low State data structure from request and execute the low-data chunks through Salt. The low-data chunks will be updated to include the authorization token for the current session. ''' lowstate = cherrypy.request.lowstate # Release the session lock before executing any potentially # long-running Salt commands. This allows different threads to execute # Salt commands concurrently without blocking. if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() # if the lowstate loaded isn't a list, lets notify the client if not isinstance(lowstate, list): raise cherrypy.HTTPError(400, 'Lowstates must be a list') # Make any requested additions or modifications to each lowstate, then # execute each one and yield the result. for chunk in lowstate: if token: chunk['token'] = token if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if 'token' in chunk: # Make sure that auth token is hex try: int(chunk['token'], 16) except (TypeError, ValueError): raise cherrypy.HTTPError(401, 'Invalid token') if client: chunk['client'] = client # Make any 'arg' params a list if not already. # This is largely to fix a deficiency in the urlencoded format. if 'arg' in chunk and not isinstance(chunk['arg'], list): chunk['arg'] = [chunk['arg']] ret = self.api.run(chunk) # Sometimes Salt gives us a return and sometimes an iterator if isinstance(ret, collections.Iterator): for i in ret: yield i else: yield ret @cherrypy.config(**{'tools.sessions.on': False}) def GET(self): ''' An explanation of the API with links of where to go next .. http:get:: / :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000 .. code-block:: text GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json ''' import inspect # pylint: disable=unused-import return { 'return': "Welcome", 'clients': salt.netapi.CLIENTS, } @cherrypy.tools.salt_token() @cherrypy.tools.salt_auth()
saltstack/salt
salt/netapi/rest_cherrypy/app.py
Minions.GET
python
def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), }
A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ...
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1321-L1366
[ "def exec_lowstate(self, client=None, token=None):\n '''\n Pull a Low State data structure from request and execute the low-data\n chunks through Salt. The low-data chunks will be updated to include the\n authorization token for the current session.\n '''\n lowstate = cherrypy.request.lowstate\n\n # Release the session lock before executing any potentially\n # long-running Salt commands. This allows different threads to execute\n # Salt commands concurrently without blocking.\n if cherrypy.request.config.get('tools.sessions.on', False):\n cherrypy.session.release_lock()\n\n # if the lowstate loaded isn't a list, lets notify the client\n if not isinstance(lowstate, list):\n raise cherrypy.HTTPError(400, 'Lowstates must be a list')\n\n # Make any requested additions or modifications to each lowstate, then\n # execute each one and yield the result.\n for chunk in lowstate:\n if token:\n chunk['token'] = token\n\n if 'token' in chunk:\n # Make sure that auth token is hex\n try:\n int(chunk['token'], 16)\n except (TypeError, ValueError):\n raise cherrypy.HTTPError(401, 'Invalid token')\n\n if 'token' in chunk:\n # Make sure that auth token is hex\n try:\n int(chunk['token'], 16)\n except (TypeError, ValueError):\n raise cherrypy.HTTPError(401, 'Invalid token')\n\n if client:\n chunk['client'] = client\n\n # Make any 'arg' params a list if not already.\n # This is largely to fix a deficiency in the urlencoded format.\n if 'arg' in chunk and not isinstance(chunk['arg'], list):\n chunk['arg'] = [chunk['arg']]\n\n ret = self.api.run(chunk)\n\n # Sometimes Salt gives us a return and sometimes an iterator\n if isinstance(ret, collections.Iterator):\n for i in ret:\n yield i\n else:\n yield ret\n" ]
class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, }
saltstack/salt
salt/netapi/rest_cherrypy/app.py
Minions.POST
python
def POST(self, **kwargs): ''' Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265 ''' job_data = list(self.exec_lowstate(client='local_async', token=cherrypy.session.get('token'))) cherrypy.response.status = 202 return { 'return': job_data, '_links': { 'jobs': [{'href': '/jobs/{0}'.format(i['jid'])} for i in job_data if i], }, }
Start an execution command and immediately return the job id .. http:post:: /minions :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| :status 200: |200| :status 400: |400| :status 401: |401| :status 406: |406| Lowstate data describing Salt commands must be sent in the request body. The ``client`` option will be set to :py:meth:`~salt.client.LocalClient.local_async`. **Example request:** .. code-block:: bash curl -sSi localhost:8000/minions \\ -b ~/cookies.txt \\ -H "Accept: application/x-yaml" \\ -d '[{"tgt": "*", "fun": "status.diskusage"}]' .. code-block:: text POST /minions HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml Content-Type: application/json tgt=*&fun=status.diskusage **Example response:** .. code-block:: text HTTP/1.1 202 Accepted Content-Length: 86 Content-Type: application/x-yaml return: - jid: '20130603122505459265' minions: [ms-4, ms-3, ms-2, ms-1, ms-0] _links: jobs: - href: /jobs/20130603122505459265
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1368-L1432
[ "def exec_lowstate(self, client=None, token=None):\n '''\n Pull a Low State data structure from request and execute the low-data\n chunks through Salt. The low-data chunks will be updated to include the\n authorization token for the current session.\n '''\n lowstate = cherrypy.request.lowstate\n\n # Release the session lock before executing any potentially\n # long-running Salt commands. This allows different threads to execute\n # Salt commands concurrently without blocking.\n if cherrypy.request.config.get('tools.sessions.on', False):\n cherrypy.session.release_lock()\n\n # if the lowstate loaded isn't a list, lets notify the client\n if not isinstance(lowstate, list):\n raise cherrypy.HTTPError(400, 'Lowstates must be a list')\n\n # Make any requested additions or modifications to each lowstate, then\n # execute each one and yield the result.\n for chunk in lowstate:\n if token:\n chunk['token'] = token\n\n if 'token' in chunk:\n # Make sure that auth token is hex\n try:\n int(chunk['token'], 16)\n except (TypeError, ValueError):\n raise cherrypy.HTTPError(401, 'Invalid token')\n\n if 'token' in chunk:\n # Make sure that auth token is hex\n try:\n int(chunk['token'], 16)\n except (TypeError, ValueError):\n raise cherrypy.HTTPError(401, 'Invalid token')\n\n if client:\n chunk['client'] = client\n\n # Make any 'arg' params a list if not already.\n # This is largely to fix a deficiency in the urlencoded format.\n if 'arg' in chunk and not isinstance(chunk['arg'], list):\n chunk['arg'] = [chunk['arg']]\n\n ret = self.api.run(chunk)\n\n # Sometimes Salt gives us a return and sometimes an iterator\n if isinstance(ret, collections.Iterator):\n for i in ret:\n yield i\n else:\n yield ret\n" ]
class Minions(LowDataAdapter): ''' Convenience URLs for working with minions ''' _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, }) def GET(self, mid=None): ''' A convenience URL for getting lists of minions or getting minion details .. http:get:: /minions/(mid) :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/minions/ms-3 .. code-block:: text GET /minions/ms-3 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 129005 Content-Type: application/x-yaml return: - ms-3: grains.items: ... ''' cherrypy.request.lowstate = [{ 'client': 'local', 'tgt': mid or '*', 'fun': 'grains.items', }] return { 'return': list(self.exec_lowstate( token=cherrypy.session.get('token'))), }
saltstack/salt
salt/netapi/rest_cherrypy/app.py
Jobs.GET
python
def GET(self, jid=None, timeout=''): ''' A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06 ''' lowstate = {'client': 'runner'} if jid: lowstate.update({'fun': 'jobs.list_job', 'jid': jid}) else: lowstate.update({'fun': 'jobs.list_jobs'}) cherrypy.request.lowstate = [lowstate] job_ret_info = list(self.exec_lowstate( token=cherrypy.session.get('token'))) ret = {} if jid: ret['info'] = [job_ret_info[0]] minion_ret = {} returns = job_ret_info[0].get('Result') for minion in returns: if u'return' in returns[minion]: minion_ret[minion] = returns[minion].get(u'return') else: minion_ret[minion] = returns[minion].get('return') ret['return'] = [minion_ret] else: ret['return'] = [job_ret_info[0]] return ret
A convenience URL for getting lists of previously run jobs or getting the return from a single job .. http:get:: /jobs/(jid) List jobs or show a single job from the job cache. :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/jobs .. code-block:: text GET /jobs HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: - '20121130104633606931': Arguments: - '3' Function: test.fib Start Time: 2012, Nov 30 10:46:33.606931 Target: jerry Target-type: glob **Example request:** .. code-block:: bash curl -i localhost:8000/jobs/20121130104633606931 .. code-block:: text GET /jobs/20121130104633606931 HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml info: - Arguments: - '3' Function: test.fib Minions: - jerry Start Time: 2012, Nov 30 10:46:33.606931 Target: '*' Target-type: glob User: saltdev jid: '20121130104633606931' return: - jerry: - - 0 - 1 - 1 - 2 - 6.9141387939453125e-06
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1440-L1548
[ "def exec_lowstate(self, client=None, token=None):\n '''\n Pull a Low State data structure from request and execute the low-data\n chunks through Salt. The low-data chunks will be updated to include the\n authorization token for the current session.\n '''\n lowstate = cherrypy.request.lowstate\n\n # Release the session lock before executing any potentially\n # long-running Salt commands. This allows different threads to execute\n # Salt commands concurrently without blocking.\n if cherrypy.request.config.get('tools.sessions.on', False):\n cherrypy.session.release_lock()\n\n # if the lowstate loaded isn't a list, lets notify the client\n if not isinstance(lowstate, list):\n raise cherrypy.HTTPError(400, 'Lowstates must be a list')\n\n # Make any requested additions or modifications to each lowstate, then\n # execute each one and yield the result.\n for chunk in lowstate:\n if token:\n chunk['token'] = token\n\n if 'token' in chunk:\n # Make sure that auth token is hex\n try:\n int(chunk['token'], 16)\n except (TypeError, ValueError):\n raise cherrypy.HTTPError(401, 'Invalid token')\n\n if 'token' in chunk:\n # Make sure that auth token is hex\n try:\n int(chunk['token'], 16)\n except (TypeError, ValueError):\n raise cherrypy.HTTPError(401, 'Invalid token')\n\n if client:\n chunk['client'] = client\n\n # Make any 'arg' params a list if not already.\n # This is largely to fix a deficiency in the urlencoded format.\n if 'arg' in chunk and not isinstance(chunk['arg'], list):\n chunk['arg'] = [chunk['arg']]\n\n ret = self.api.run(chunk)\n\n # Sometimes Salt gives us a return and sometimes an iterator\n if isinstance(ret, collections.Iterator):\n for i in ret:\n yield i\n else:\n yield ret\n" ]
class Jobs(LowDataAdapter): _cp_config = dict(LowDataAdapter._cp_config, **{ 'tools.salt_auth.on': True, })
saltstack/salt
salt/netapi/rest_cherrypy/app.py
Keys.GET
python
def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})}
Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1561-L1646
[ "def exec_lowstate(self, client=None, token=None):\n '''\n Pull a Low State data structure from request and execute the low-data\n chunks through Salt. The low-data chunks will be updated to include the\n authorization token for the current session.\n '''\n lowstate = cherrypy.request.lowstate\n\n # Release the session lock before executing any potentially\n # long-running Salt commands. This allows different threads to execute\n # Salt commands concurrently without blocking.\n if cherrypy.request.config.get('tools.sessions.on', False):\n cherrypy.session.release_lock()\n\n # if the lowstate loaded isn't a list, lets notify the client\n if not isinstance(lowstate, list):\n raise cherrypy.HTTPError(400, 'Lowstates must be a list')\n\n # Make any requested additions or modifications to each lowstate, then\n # execute each one and yield the result.\n for chunk in lowstate:\n if token:\n chunk['token'] = token\n\n if 'token' in chunk:\n # Make sure that auth token is hex\n try:\n int(chunk['token'], 16)\n except (TypeError, ValueError):\n raise cherrypy.HTTPError(401, 'Invalid token')\n\n if 'token' in chunk:\n # Make sure that auth token is hex\n try:\n int(chunk['token'], 16)\n except (TypeError, ValueError):\n raise cherrypy.HTTPError(401, 'Invalid token')\n\n if client:\n chunk['client'] = client\n\n # Make any 'arg' params a list if not already.\n # This is largely to fix a deficiency in the urlencoded format.\n if 'arg' in chunk and not isinstance(chunk['arg'], list):\n chunk['arg'] = [chunk['arg']]\n\n ret = self.api.run(chunk)\n\n # Sometimes Salt gives us a return and sometimes an iterator\n if isinstance(ret, collections.Iterator):\n for i in ret:\n yield i\n else:\n yield ret\n" ]
class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj
saltstack/salt
salt/netapi/rest_cherrypy/app.py
Keys.POST
python
def POST(self, **kwargs): r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000 ''' lowstate = cherrypy.request.lowstate lowstate[0].update({ 'client': 'wheel', 'fun': 'key.gen_accept', }) if 'mid' in lowstate[0]: lowstate[0]['id_'] = lowstate[0].pop('mid') result = self.exec_lowstate() ret = next(result, {}).get('data', {}).get('return', {}) pub_key = ret.get('pub', '') pub_key_file = tarfile.TarInfo('minion.pub') pub_key_file.size = len(pub_key) priv_key = ret.get('priv', '') priv_key_file = tarfile.TarInfo('minion.pem') priv_key_file.size = len(priv_key) fileobj = BytesIO() tarball = tarfile.open(fileobj=fileobj, mode='w') if six.PY3: pub_key = pub_key.encode(__salt_system_encoding__) priv_key = priv_key.encode(__salt_system_encoding__) tarball.addfile(pub_key_file, BytesIO(pub_key)) tarball.addfile(priv_key_file, BytesIO(priv_key)) tarball.close() headers = cherrypy.response.headers headers['Content-Disposition'] = 'attachment; filename="saltkeys-{0}.tar"'.format(lowstate[0]['id_']) headers['Content-Type'] = 'application/x-tar' headers['Content-Length'] = len(fileobj.getvalue()) headers['Cache-Control'] = 'no-cache' fileobj.seek(0) return fileobj
r''' Easily generate keys for a minion and auto-accept the new key Accepts all the same parameters as the :py:func:`key.gen_accept <salt.wheel.key.gen_accept>`. .. note:: A note about ``curl`` Avoid using the ``-i`` flag or HTTP headers will be written and produce an invalid tar file. Example partial kickstart script to bootstrap a new minion: .. code-block:: text %post mkdir -p /etc/salt/pki/minion curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ | tar -C /etc/salt/pki/minion -xf - mkdir -p /etc/salt/minion.d printf 'master: 10.0.0.5\nid: jerry' > /etc/salt/minion.d/id.conf %end .. http:post:: /keys Generate a public and private key and return both as a tarball Authentication credentials must be passed in the request. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/keys \ -d mid=jerry \ -d username=kickstart \ -d password=kickstart \ -d eauth=pam \ -o jerry-salt-keys.tar .. code-block:: text POST /keys HTTP/1.1 Host: localhost:8000 **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 10240 Content-Disposition: attachment; filename="saltkeys-jerry.tar" Content-Type: application/x-tar jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1649-L1752
[ "def exec_lowstate(self, client=None, token=None):\n '''\n Pull a Low State data structure from request and execute the low-data\n chunks through Salt. The low-data chunks will be updated to include the\n authorization token for the current session.\n '''\n lowstate = cherrypy.request.lowstate\n\n # Release the session lock before executing any potentially\n # long-running Salt commands. This allows different threads to execute\n # Salt commands concurrently without blocking.\n if cherrypy.request.config.get('tools.sessions.on', False):\n cherrypy.session.release_lock()\n\n # if the lowstate loaded isn't a list, lets notify the client\n if not isinstance(lowstate, list):\n raise cherrypy.HTTPError(400, 'Lowstates must be a list')\n\n # Make any requested additions or modifications to each lowstate, then\n # execute each one and yield the result.\n for chunk in lowstate:\n if token:\n chunk['token'] = token\n\n if 'token' in chunk:\n # Make sure that auth token is hex\n try:\n int(chunk['token'], 16)\n except (TypeError, ValueError):\n raise cherrypy.HTTPError(401, 'Invalid token')\n\n if 'token' in chunk:\n # Make sure that auth token is hex\n try:\n int(chunk['token'], 16)\n except (TypeError, ValueError):\n raise cherrypy.HTTPError(401, 'Invalid token')\n\n if client:\n chunk['client'] = client\n\n # Make any 'arg' params a list if not already.\n # This is largely to fix a deficiency in the urlencoded format.\n if 'arg' in chunk and not isinstance(chunk['arg'], list):\n chunk['arg'] = [chunk['arg']]\n\n ret = self.api.run(chunk)\n\n # Sometimes Salt gives us a return and sometimes an iterator\n if isinstance(ret, collections.Iterator):\n for i in ret:\n yield i\n else:\n yield ret\n" ]
class Keys(LowDataAdapter): ''' Convenience URLs for working with minion keys .. versionadded:: 2014.7.0 These URLs wrap the functionality provided by the :py:mod:`key wheel module <salt.wheel.key>` functions. ''' def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/keys .. code-block:: text GET /keys HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 165 Content-Type: application/x-yaml return: local: - master.pem - master.pub minions: - jerry minions_pre: [] minions_rejected: [] **Example request:** .. code-block:: bash curl -i localhost:8000/keys/jerry .. code-block:: text GET /keys/jerry HTTP/1.1 Host: localhost:8000 Accept: application/x-yaml **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Length: 73 Content-Type: application/x-yaml return: minions: jerry: 51:93:b3:d0:9f:3a:6d:e5:28:67:c2:4b:27:d6:cd:2b ''' if mid: lowstate = [{ 'client': 'wheel', 'fun': 'key.finger', 'match': mid, }] else: lowstate = [{ 'client': 'wheel', 'fun': 'key.list_all', }] cherrypy.request.lowstate = lowstate result = self.exec_lowstate(token=cherrypy.session.get('token')) return {'return': next(result, {}).get('data', {}).get('return', {})} @cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False})
saltstack/salt
salt/netapi/rest_cherrypy/app.py
Login.POST
python
def POST(self, **kwargs): ''' :ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }} ''' if not self.api._is_master_running(): raise salt.exceptions.SaltDaemonNotRunning( 'Salt Master is not available.') # the urlencoded_processor will wrap this in a list if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate username = creds.get('username', None) # Validate against the whitelist. if not salt_api_acl_tool(username, cherrypy.request): raise cherrypy.HTTPError(401) # Mint token. token = self.auth.mk_token(creds) if 'token' not in token: raise cherrypy.HTTPError(401, 'Could not authenticate using provided credentials') cherrypy.response.headers['X-Auth-Token'] = cherrypy.session.id cherrypy.session['token'] = token['token'] cherrypy.session['timeout'] = (token['expire'] - token['start']) / 60 # Grab eauth config for the current backend for the current user try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) if token['eauth'] == 'django' and '^model' in eauth: perms = token['auth_list'] else: # Get sum of '*' perms, user-specific perms, and group-specific perms perms = eauth.get(token['name'], []) perms.extend(eauth.get('*', [])) if 'groups' in token and token['groups']: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) if not perms: logger.debug("Eauth permission list not found.") except Exception: logger.debug( "Configuration for external_auth malformed for eauth '%s', " "and user '%s'.", token.get('eauth'), token.get('name'), exc_info=True ) perms = None return {'return': [{ 'token': cherrypy.session.id, 'expire': token['expire'], 'start': token['start'], 'user': token['name'], 'eauth': token['eauth'], 'perms': perms or {}, }]}
:ref:`Authenticate <rest_cherrypy-auth>` against Salt's eauth system .. http:post:: /login :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :form eauth: the eauth backend configured for the user :form username: username :form password: password :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -si localhost:8000/login \\ -c ~/cookies.txt \\ -H "Accept: application/json" \\ -H "Content-type: application/json" \\ -d '{ "username": "saltuser", "password": "saltuser", "eauth": "auto" }' .. code-block:: text POST / HTTP/1.1 Host: localhost:8000 Content-Length: 42 Content-Type: application/json Accept: application/json {"username": "saltuser", "password": "saltuser", "eauth": "auto"} **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json Content-Length: 206 X-Auth-Token: 6d1b722e Set-Cookie: session_id=6d1b722e; expires=Sat, 17 Nov 2012 03:23:52 GMT; Path=/ {"return": { "token": "6d1b722e", "start": 1363805943.776223, "expire": 1363849143.776224, "user": "saltuser", "eauth": "pam", "perms": [ "grains.*", "status.*", "sys.*", "test.*" ] }}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1805-L1932
[ "def salt_api_acl_tool(username, request):\n '''\n ..versionadded:: 2016.3.0\n\n Verifies user requests against the API whitelist. (User/IP pair)\n in order to provide whitelisting for the API similar to the\n master, but over the API.\n\n ..code-block:: yaml\n\n rest_cherrypy:\n api_acl:\n users:\n '*':\n - 1.1.1.1\n - 1.1.1.2\n foo:\n - 8.8.4.4\n bar:\n - '*'\n\n :param username: Username to check against the API.\n :type username: str\n :param request: Cherrypy request to check against the API.\n :type request: cherrypy.request\n '''\n failure_str = (\"[api_acl] Authentication failed for \"\n \"user %s from IP %s\")\n success_str = (\"[api_acl] Authentication sucessful for \"\n \"user %s from IP %s\")\n pass_str = (\"[api_acl] Authentication not checked for \"\n \"user %s from IP %s\")\n\n acl = None\n # Salt Configuration\n salt_config = cherrypy.config.get('saltopts', None)\n if salt_config:\n # Cherrypy Config.\n cherrypy_conf = salt_config.get('rest_cherrypy', None)\n if cherrypy_conf:\n # ACL Config.\n acl = cherrypy_conf.get('api_acl', None)\n\n ip = request.remote.ip\n if acl:\n users = acl.get('users', {})\n if users:\n if username in users:\n if ip in users[username] or '*' in users[username]:\n logger.info(success_str, username, ip)\n return True\n else:\n logger.info(failure_str, username, ip)\n return False\n elif username not in users and '*' in users:\n if ip in users['*'] or '*' in users['*']:\n logger.info(success_str, username, ip)\n return True\n else:\n logger.info(failure_str, username, ip)\n return False\n else:\n logger.info(failure_str, username, ip)\n return False\n else:\n logger.info(pass_str, username, ip)\n return True\n" ]
class Login(LowDataAdapter): ''' Log in to receive a session token :ref:`Authentication information <rest_cherrypy-auth>`. ''' def __init__(self, *args, **kwargs): super(Login, self).__init__(*args, **kwargs) self.auth = salt.auth.Resolver(self.opts) def GET(self): ''' Present the login interface .. http:get:: /login An explanation of how to log in. :status 200: |200| :status 401: |401| :status 406: |406| **Example request:** .. code-block:: bash curl -i localhost:8000/login .. code-block:: text GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: text/html ''' cherrypy.response.headers['WWW-Authenticate'] = 'Session' return { 'status': cherrypy.response.status, 'return': "Please log in", }
saltstack/salt
salt/netapi/rest_cherrypy/app.py
Token.POST
python
def POST(self, **kwargs): r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }] ''' for creds in cherrypy.request.lowstate: try: creds.update({ 'client': 'runner', 'fun': 'auth.mk_token', 'kwarg': { 'username': creds['username'], 'password': creds['password'], 'eauth': creds['eauth'], }, }) except KeyError: raise cherrypy.HTTPError(400, 'Require "username", "password", and "eauth" params') return list(self.exec_lowstate())
r''' .. http:post:: /token Generate a Salt eauth token :status 200: |200| :status 400: |400| :status 401: |401| **Example request:** .. code-block:: bash curl -sSk https://localhost:8000/token \ -H 'Content-type: application/json' \ -d '{ "username": "saltdev", "password": "saltdev", "eauth": "auto" }' **Example response:** .. code-block:: text HTTP/1.1 200 OK Content-Type: application/json [{ "start": 1494987445.528182, "token": "e72ca1655d05...", "expire": 1495030645.528183, "name": "saltdev", "eauth": "auto" }]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1964-L2016
[ "def exec_lowstate(self, client=None, token=None):\n '''\n Pull a Low State data structure from request and execute the low-data\n chunks through Salt. The low-data chunks will be updated to include the\n authorization token for the current session.\n '''\n lowstate = cherrypy.request.lowstate\n\n # Release the session lock before executing any potentially\n # long-running Salt commands. This allows different threads to execute\n # Salt commands concurrently without blocking.\n if cherrypy.request.config.get('tools.sessions.on', False):\n cherrypy.session.release_lock()\n\n # if the lowstate loaded isn't a list, lets notify the client\n if not isinstance(lowstate, list):\n raise cherrypy.HTTPError(400, 'Lowstates must be a list')\n\n # Make any requested additions or modifications to each lowstate, then\n # execute each one and yield the result.\n for chunk in lowstate:\n if token:\n chunk['token'] = token\n\n if 'token' in chunk:\n # Make sure that auth token is hex\n try:\n int(chunk['token'], 16)\n except (TypeError, ValueError):\n raise cherrypy.HTTPError(401, 'Invalid token')\n\n if 'token' in chunk:\n # Make sure that auth token is hex\n try:\n int(chunk['token'], 16)\n except (TypeError, ValueError):\n raise cherrypy.HTTPError(401, 'Invalid token')\n\n if client:\n chunk['client'] = client\n\n # Make any 'arg' params a list if not already.\n # This is largely to fix a deficiency in the urlencoded format.\n if 'arg' in chunk and not isinstance(chunk['arg'], list):\n chunk['arg'] = [chunk['arg']]\n\n ret = self.api.run(chunk)\n\n # Sometimes Salt gives us a return and sometimes an iterator\n if isinstance(ret, collections.Iterator):\n for i in ret:\n yield i\n else:\n yield ret\n" ]
class Token(LowDataAdapter): ''' Generate a Salt token from eauth credentials Wraps functionality in the :py:mod:`auth Runner <salt.runners.auth>`. .. versionadded:: 2017.7.0 ''' @cherrypy.config(**{'tools.sessions.on': False})
saltstack/salt
salt/netapi/rest_cherrypy/app.py
Events._is_valid_token
python
def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False
Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2191-L2219
null
class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen()
saltstack/salt
salt/netapi/rest_cherrypy/app.py
Events.GET
python
def GET(self, token=None, salt_token=None): r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}} ''' cookies = cherrypy.request.cookie auth_token = token or salt_token or ( cookies['session_id'].value if 'session_id' in cookies else None) if not self._is_valid_token(auth_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 'text/event-stream' cherrypy.response.headers['Cache-Control'] = 'no-cache' cherrypy.response.headers['Connection'] = 'keep-alive' def listen(): ''' An iterator to yield Salt events ''' event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) yield str('retry: 400\n') # future lint: disable=blacklisted-function while True: data = next(stream) yield str('tag: {0}\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function yield str('data: {0}\n\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function return listen()
r''' An HTTP stream of the Salt master event bus This stream is formatted per the Server Sent Events (SSE) spec. Each event is formatted as JSON. .. http:get:: /events :status 200: |200| :status 401: |401| :status 406: |406| :query token: **optional** parameter containing the token ordinarily supplied via the X-Auth-Token header in order to allow cross-domain requests in browsers that do not include CORS support in the EventSource API. E.g., ``curl -NsS localhost:8000/events?token=308650d`` :query salt_token: **optional** parameter containing a raw Salt *eauth token* (not to be confused with the token returned from the /login URL). E.g., ``curl -NsS localhost:8000/events?salt_token=30742765`` **Example request:** .. code-block:: bash curl -NsS localhost:8000/events .. code-block:: text GET /events HTTP/1.1 Host: localhost:8000 **Example response:** Note, the ``tag`` field is not part of the spec. SSE compliant clients should ignore unknown fields. This addition allows non-compliant clients to only watch for certain tags without having to deserialze the JSON object each time. .. code-block:: text HTTP/1.1 200 OK Connection: keep-alive Cache-Control: no-cache Content-Type: text/event-stream;charset=utf-8 retry: 400 tag: salt/job/20130802115730568475/new data: {'tag': 'salt/job/20130802115730568475/new', 'data': {'minions': ['ms-4', 'ms-3', 'ms-2', 'ms-1', 'ms-0']}} tag: salt/job/20130802115730568475/ret/jerry data: {'tag': 'salt/job/20130802115730568475/ret/jerry', 'data': {'jid': '20130802115730568475', 'return': True, 'retcode': 0, 'success': True, 'cmd': '_return', 'fun': 'test.ping', 'id': 'ms-1'}} The event stream can be easily consumed via JavaScript: .. code-block:: javascript var source = new EventSource('/events'); source.onopen = function() { console.info('Listening ...') }; source.onerror = function(err) { console.error(err) }; source.onmessage = function(message) { var saltEvent = JSON.parse(message.data); console.log(saltEvent.tag, saltEvent.data); }; Note, the SSE stream is fast and completely asynchronous and Salt is very fast. If a job is created using a regular POST request, it is possible that the job return will be available on the SSE stream before the response for the POST request arrives. It is important to take that asynchronicity into account when designing an application. Below are some general guidelines. * Subscribe to the SSE stream _before_ creating any events. * Process SSE events directly as they arrive and don't wait for any other process to "complete" first (like an ajax request). * Keep a buffer of events if the event stream must be used for synchronous lookups. * Be cautious in writing Salt's event stream directly to the DOM. It is very busy and can quickly overwhelm the memory allocated to a browser tab. A full, working proof-of-concept JavaScript application is available :blob:`adjacent to this file <salt/netapi/rest_cherrypy/index.html>`. It can be viewed by pointing a browser at the ``/app`` endpoint in a running ``rest_cherrypy`` instance. Or using CORS: .. code-block:: javascript var source = new EventSource('/events?token=ecd589e4e01912cf3c4035afad73426dbb8dba75', {withCredentials: true}); It is also possible to consume the stream via the shell. Records are separated by blank lines; the ``data:`` and ``tag:`` prefixes will need to be removed manually before attempting to unserialize the JSON. curl's ``-N`` flag turns off input buffering which is required to process the stream incrementally. Here is a basic example of printing each event as it comes in: .. code-block:: bash curl -NsS localhost:8000/events |\ while IFS= read -r line ; do echo $line done Here is an example of using awk to filter events based on tag: .. code-block:: bash curl -NsS localhost:8000/events |\ awk ' BEGIN { RS=""; FS="\\n" } $1 ~ /^tag: salt\/job\/[0-9]+\/new$/ { print $0 } ' tag: salt/job/20140112010149808995/new data: {"tag": "salt/job/20140112010149808995/new", "data": {"tgt_type": "glob", "jid": "20140112010149808995", "tgt": "jerry", "_stamp": "2014-01-12_01:01:49.809617", "user": "shouse", "arg": [], "fun": "test.ping", "minions": ["jerry"]}} tag: 20140112010149808995 data: {"tag": "20140112010149808995", "data": {"fun_args": [], "jid": "20140112010149808995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2221-L2380
[ "def _is_valid_token(self, auth_token):\n '''\n Check if this is a valid salt-api token or valid Salt token\n\n salt-api tokens are regular session tokens that tie back to a real Salt\n token. Salt tokens are tokens generated by Salt's eauth system.\n\n :return bool: True if valid, False if not valid.\n '''\n # Make sure that auth token is hex. If it's None, or something other\n # than hex, this will raise a ValueError.\n try:\n int(auth_token, 16)\n except (TypeError, ValueError):\n return False\n\n # First check if the given token is in our session table; if so it's a\n # salt-api token and we need to get the Salt token from there.\n orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None))\n # If it's not in the session table, assume it's a regular Salt token.\n salt_token = orig_session.get('token', auth_token)\n\n # The eauth system does not currently support perms for the event\n # stream, so we're just checking if the token exists not if the token\n # allows access.\n if salt_token and self.resolver.get_token(salt_token):\n return True\n\n return False\n", "def listen():\n '''\n An iterator to yield Salt events\n '''\n event = salt.utils.event.get_event(\n 'master',\n sock_dir=self.opts['sock_dir'],\n transport=self.opts['transport'],\n opts=self.opts,\n listen=True)\n stream = event.iter_events(full=True, auto_reconnect=True)\n\n yield str('retry: 400\\n') # future lint: disable=blacklisted-function\n\n while True:\n data = next(stream)\n yield str('tag: {0}\\n').format(data.get('tag', '')) # future lint: disable=blacklisted-function\n yield str('data: {0}\\n\\n').format(salt.utils.json.dumps(data)) # future lint: disable=blacklisted-function\n" ]
class Events(object): ''' Expose the Salt event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.resolver = salt.auth.Resolver(self.opts) def _is_valid_token(self, auth_token): ''' Check if this is a valid salt-api token or valid Salt token salt-api tokens are regular session tokens that tie back to a real Salt token. Salt tokens are tokens generated by Salt's eauth system. :return bool: True if valid, False if not valid. ''' # Make sure that auth token is hex. If it's None, or something other # than hex, this will raise a ValueError. try: int(auth_token, 16) except (TypeError, ValueError): return False # First check if the given token is in our session table; if so it's a # salt-api token and we need to get the Salt token from there. orig_session, _ = cherrypy.session.cache.get(auth_token, ({}, None)) # If it's not in the session table, assume it's a regular Salt token. salt_token = orig_session.get('token', auth_token) # The eauth system does not currently support perms for the event # stream, so we're just checking if the token exists not if the token # allows access. if salt_token and self.resolver.get_token(salt_token): return True return False
saltstack/salt
salt/netapi/rest_cherrypy/app.py
WebsocketEndpoint.GET
python
def GET(self, token=None, **kwargs): ''' Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``. ''' # Pulling the session token from an URL param is a workaround for # browsers not supporting CORS in the EventSource API. if token: orig_session, _ = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') # Manually verify the token if not salt_token or not self.auth.get_tok(salt_token): raise cherrypy.HTTPError(401) # Release the session lock before starting the long-running response cherrypy.session.release_lock() # A handler is the server side end of the websocket connection. Each # request spawns a new instance of this handler handler = cherrypy.request.ws_handler def event_stream(handler, pipe): ''' An iterator to return Salt events (and optionally format them) ''' # blocks until send is called on the parent end of this pipe. pipe.recv() event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=True) stream = event.iter_events(full=True, auto_reconnect=True) SaltInfo = event_processor.SaltInfo(handler) def signal_handler(signal, frame): os._exit(0) signal.signal(signal.SIGTERM, signal_handler) while True: data = next(stream) if data: try: # work around try to decode catch unicode errors if 'format_events' in kwargs: SaltInfo.process(data, salt_token, self.opts) else: handler.send( str('data: {0}\n\n').format(salt.utils.json.dumps(data)), # future lint: disable=blacklisted-function False ) except UnicodeDecodeError: logger.error( "Error: Salt event has non UTF-8 data:\n%s", data) parent_pipe, child_pipe = Pipe() handler.pipe = parent_pipe handler.opts = self.opts # Process to handle asynchronous push to a client. # Each GET request causes a process to be kicked off. proc = Process(target=event_stream, args=(handler, child_pipe)) proc.start()
Return a websocket connection of Salt's event stream .. http:get:: /ws/(token) :query format_events: The event stream will undergo server-side formatting if the ``format_events`` URL parameter is included in the request. This can be useful to avoid formatting on the client-side: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws?format_events :reqheader X-Auth-Token: an authentication token from :py:class:`~Login`. :status 101: switching to the websockets protocol :status 401: |401| :status 406: |406| **Example request:** :: curl -NsSk \\ -H 'X-Auth-Token: ffedf49d' \\ -H 'Host: localhost:8000' \\ -H 'Connection: Upgrade' \\ -H 'Upgrade: websocket' \\ -H 'Origin: https://localhost:8000' \\ -H 'Sec-WebSocket-Version: 13' \\ -H 'Sec-WebSocket-Key: '"$(echo -n $RANDOM | base64)" \\ localhost:8000/ws .. code-block:: text GET /ws HTTP/1.1 Connection: Upgrade Upgrade: websocket Host: localhost:8000 Origin: https://localhost:8000 Sec-WebSocket-Version: 13 Sec-WebSocket-Key: s65VsgHigh7v/Jcf4nXHnA== X-Auth-Token: ffedf49d **Example response**: .. code-block:: text HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: mWZjBV9FCglzn1rIKJAxrTFlnJE= Sec-WebSocket-Version: 13 An authentication token **may optionally** be passed as part of the URL for browsers that cannot be configured to send the authentication header or cookie: .. code-block:: bash curl -NsS <...snip...> localhost:8000/ws/ffedf49d The event stream can be easily consumed via JavaScript: .. code-block:: javascript // Note, you must be authenticated! var source = new Websocket('ws://localhost:8000/ws/d0ce6c1a'); source.onerror = function(e) { console.debug('error!', e); }; source.onmessage = function(e) { console.debug(e.data); }; source.send('websocket client ready') source.close(); Or via Python, using the Python module `websocket-client <https://pypi.python.org/pypi/websocket-client/>`_ for example. .. code-block:: python # Note, you must be authenticated! from websocket import create_connection ws = create_connection('ws://localhost:8000/ws/d0ce6c1a') ws.send('websocket client ready') # Look at https://pypi.python.org/pypi/websocket-client/ for more # examples. while listening_to_events: print ws.recv() ws.close() Above examples show how to establish a websocket connection to Salt and activating real time updates from Salt's event stream by signaling ``websocket client ready``.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2413-L2573
null
class WebsocketEndpoint(object): ''' Open a WebSocket connection to Salt's event bus The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure. Uses websocket as the transport mechanism. .. seealso:: :ref:`events` ''' exposed = True _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', # Auth handled manually below 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, 'tools.websocket.on': True, 'tools.websocket.handler_cls': websockets.SynchronizingWebsocket, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.auth = salt.auth.LoadAuth(self.opts)
saltstack/salt
salt/netapi/rest_cherrypy/app.py
Webhook.POST
python
def POST(self, *args, **kwargs): ''' Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %} ''' tag = '/'.join(itertools.chain(self.tag_base, args)) data = cherrypy.serving.request.unserialized_data if not data: data = {} raw_body = getattr(cherrypy.serving.request, 'raw_body', '') headers = dict(cherrypy.request.headers) ret = self.event.fire_event({ 'body': raw_body, 'post': data, 'headers': headers, }, tag) return {'success': ret}
Fire an event in Salt with a custom event tag and data .. http:post:: /hook :status 200: |200| :status 401: |401| :status 406: |406| :status 413: request body is too large **Example request:** .. code-block:: bash curl -sS localhost:8000/hook \\ -H 'Content-type: application/json' \\ -d '{"foo": "Foo!", "bar": "Bar!"}' .. code-block:: text POST /hook HTTP/1.1 Host: localhost:8000 Content-Length: 16 Content-Type: application/json {"foo": "Foo!", "bar": "Bar!"} **Example response**: .. code-block:: text HTTP/1.1 200 OK Content-Length: 14 Content-Type: application/json {"success": true} As a practical example, an internal continuous-integration build server could send an HTTP POST request to the URL ``https://localhost:8000/hook/mycompany/build/success`` which contains the result of a build and the SHA of the version that was built as JSON. That would then produce the following event in Salt that could be used to kick off a deployment via Salt's Reactor:: Event fired at Fri Feb 14 17:40:11 2014 ************************* Tag: salt/netapi/hook/mycompany/build/success Data: {'_stamp': '2014-02-14_17:40:11.440996', 'headers': { 'X-My-Secret-Key': 'F0fAgoQjIT@W', 'Content-Length': '37', 'Content-Type': 'application/json', 'Host': 'localhost:8000', 'Remote-Addr': '127.0.0.1'}, 'post': {'revision': 'aa22a3c4b2e7', 'result': True}} Salt's Reactor could listen for the event: .. code-block:: yaml reactor: - 'salt/netapi/hook/mycompany/build/*': - /srv/reactor/react_ci_builds.sls And finally deploy the new build: .. code-block:: jinja {% set secret_key = data.get('headers', {}).get('X-My-Secret-Key') %} {% set build = data.get('post', {}) %} {% if secret_key == 'F0fAgoQjIT@W' and build.result == True %} deploy_my_app: cmd.state.sls: - tgt: 'application*' - arg: - myapp.deploy - kwarg: pillar: revision: {{ revision }} {% endif %}
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2643-L2739
null
class Webhook(object): ''' A generic web hook entry point that fires an event on Salt's event bus External services can POST data to this URL to trigger an event in Salt. For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks. .. note:: Be mindful of security Salt's Reactor can run any code. A Reactor SLS that responds to a hook event is responsible for validating that the event came from a trusted source and contains valid data. **This is a generic interface and securing it is up to you!** This URL requires authentication however not all external services can be configured to authenticate. For this reason authentication can be selectively disabled for this URL. Follow best practices -- always use SSL, pass a secret key, configure the firewall to only allow traffic from a known source, etc. The event data is taken from the request body. The :mailheader:`Content-Type` header is respected for the payload. The event tag is prefixed with ``salt/netapi/hook`` and the URL path is appended to the end. For example, a ``POST`` request sent to ``/hook/mycompany/myapp/mydata`` will produce a Salt event with the tag ``salt/netapi/hook/mycompany/myapp/mydata``. The following is an example ``.travis.yml`` file to send notifications to Salt of successful test runs: .. code-block:: yaml language: python script: python -m unittest tests after_success: - | curl -sSk https://saltapi-url.example.com:8000/hook/travis/build/success \ -d branch="${TRAVIS_BRANCH}" \ -d commit="${TRAVIS_COMMIT}" .. seealso:: :ref:`events`, :ref:`reactor <reactor>` ''' exposed = True tag_base = ['salt', 'netapi', 'hook'] _cp_config = dict(LowDataAdapter._cp_config, **{ # Don't do any lowdata processing on the POST data 'tools.lowdata_fmt.on': True, # Auth can be overridden in __init__(). 'tools.salt_auth.on': True, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.event = salt.utils.event.get_event( 'master', sock_dir=self.opts['sock_dir'], transport=self.opts['transport'], opts=self.opts, listen=False) if cherrypy.config['apiopts'].get('webhook_disable_auth'): self._cp_config['tools.salt_auth.on'] = False
saltstack/salt
salt/netapi/rest_cherrypy/app.py
App.GET
python
def GET(self, *args): ''' Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401| ''' apiopts = cherrypy.config['apiopts'] default_index = os.path.abspath(os.path.join( os.path.dirname(__file__), 'index.html')) return cherrypy.lib.static.serve_file( apiopts.get('app', default_index))
Serve a single static file ignoring the remaining path This is useful in combination with a browser-based app using the HTML5 history API. .. http::get:: /app :reqheader X-Auth-Token: |req_token| :status 200: |200| :status 401: |401|
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2783-L2803
null
class App(object): ''' Class to serve HTML5 apps ''' exposed = True
saltstack/salt
salt/netapi/rest_cherrypy/app.py
API._setattr_url_map
python
def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls())
Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2823-L2838
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf
saltstack/salt
salt/netapi/rest_cherrypy/app.py
API._update_url_map
python
def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, })
Assemble any dynamic or configurable URLs
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2840-L2857
null
class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map() def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf
saltstack/salt
salt/netapi/rest_cherrypy/app.py
API.get_conf
python
def get_conf(self): ''' Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration ''' conf = { 'global': { 'server.socket_host': self.apiopts.get('host', '0.0.0.0'), 'server.socket_port': self.apiopts.get('port', 8000), 'server.thread_pool': self.apiopts.get('thread_pool', 100), 'server.socket_queue_size': self.apiopts.get('queue_size', 30), 'max_request_body_size': self.apiopts.get( 'max_request_body_size', 1048576), 'debug': self.apiopts.get('debug', False), 'log.access_file': self.apiopts.get('log_access_file', ''), 'log.error_file': self.apiopts.get('log_error_file', ''), }, '/': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.trailing_slash.on': True, 'tools.gzip.on': True, 'tools.html_override.on': True, 'tools.cors_tool.on': True, }, } if salt.utils.versions.version_cmp(cherrypy.__version__, '12.0.0') < 0: # CherryPy >= 12.0 no longer supports "timeout_monitor", only set # this config option when using an older version of CherryPy. # See Issue #44601 for more information. conf['global']['engine.timeout_monitor.on'] = self.apiopts.get( 'expire_responses', True ) if cpstats and self.apiopts.get('collect_stats', False): conf['/']['tools.cpstats.on'] = True if 'favicon' in self.apiopts: conf['/favicon.ico'] = { 'tools.staticfile.on': True, 'tools.staticfile.filename': self.apiopts['favicon'], } if self.apiopts.get('debug', False) is False: conf['global']['environment'] = 'production' # Serve static media if the directory has been set in the configuration if 'static' in self.apiopts: conf[self.apiopts.get('static_path', '/static')] = { 'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static'], } # Add to global config cherrypy.config.update(conf['global']) return conf
Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L2866-L2924
[ "def version_cmp(pkg1, pkg2, ignore_epoch=False):\n '''\n Compares two version strings using salt.utils.versions.LooseVersion. This\n is a fallback for providers which don't have a version comparison utility\n built into them. Return -1 if version1 < version2, 0 if version1 ==\n version2, and 1 if version1 > version2. Return None if there was a problem\n making the comparison.\n '''\n normalize = lambda x: six.text_type(x).split(':', 1)[-1] \\\n if ignore_epoch else six.text_type(x)\n pkg1 = normalize(pkg1)\n pkg2 = normalize(pkg2)\n\n try:\n # pylint: disable=no-member\n if LooseVersion(pkg1) < LooseVersion(pkg2):\n return -1\n elif LooseVersion(pkg1) == LooseVersion(pkg2):\n return 0\n elif LooseVersion(pkg1) > LooseVersion(pkg2):\n return 1\n except Exception as exc:\n log.exception(exc)\n return None\n" ]
class API(object): ''' Collect configuration and URL map for building the CherryPy app ''' url_map = { 'index': LowDataAdapter, 'login': Login, 'logout': Logout, 'token': Token, 'minions': Minions, 'run': Run, 'jobs': Jobs, 'keys': Keys, 'events': Events, 'stats': Stats, } def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] else: url_blacklist = [] urls = ((url, cls) for url, cls in six.iteritems(self.url_map) if url not in url_blacklist) for url, cls in urls: setattr(self, url, cls()) def _update_url_map(self): ''' Assemble any dynamic or configurable URLs ''' if HAS_WEBSOCKETS: self.url_map.update({ 'ws': WebsocketEndpoint, }) # Allow the Webhook URL to be overridden from the conf. self.url_map.update({ self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook, }) # Enable the single-page JS app URL. self.url_map.update({ self.apiopts.get('app_path', 'app').lstrip('/'): App, }) def __init__(self): self.opts = cherrypy.config['saltopts'] self.apiopts = cherrypy.config['apiopts'] self._update_url_map() self._setattr_url_map()
saltstack/salt
salt/modules/gentoo_service.py
get_disabled
python
def get_disabled(): ''' Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=False, include_disabled=True) return sorted(disabled_services)
Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoo_service.py#L107-L119
[ "def _get_service_list(include_enabled=True, include_disabled=False):\n enabled_services = dict()\n disabled_services = set()\n lines = _list_services()\n for line in lines:\n if '|' not in line:\n continue\n service = [l.strip() for l in line.split('|')]\n # enabled service should have runlevels\n if service[1]:\n if include_enabled:\n enabled_services.update({service[0]: sorted(service[1].split())})\n continue\n # in any other case service is disabled\n if include_disabled:\n disabled_services.update({service[0]: []})\n return enabled_services, disabled_services\n" ]
# -*- coding: utf-8 -*- ''' Top level package command wrapper, used to translate the os detected by grains to the correct service manager .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import fnmatch import re # Import salt libs import salt.utils.systemd import salt.utils.odict as odict # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' def __virtual__(): ''' Only work on systems which default to OpenRC ''' if __grains__['os_family'] == 'Gentoo' and not salt.utils.systemd.booted(__context__): return __virtualname__ if __grains__['os'] == 'Alpine': return __virtualname__ return (False, 'The gentoo_service execution module cannot be loaded: ' 'only available on Gentoo/Open-RC systems.') def _ret_code(cmd, ignore_retcode=False): log.debug('executing [%s]', cmd) sts = __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=ignore_retcode) return sts def _list_services(): return __salt__['cmd.run']('rc-update -v show').splitlines() def _get_service_list(include_enabled=True, include_disabled=False): enabled_services = dict() disabled_services = set() lines = _list_services() for line in lines: if '|' not in line: continue service = [l.strip() for l in line.split('|')] # enabled service should have runlevels if service[1]: if include_enabled: enabled_services.update({service[0]: sorted(service[1].split())}) continue # in any other case service is disabled if include_disabled: disabled_services.update({service[0]: []}) return enabled_services, disabled_services def _enable_delta(name, requested_runlevels): all_enabled = get_enabled() current_levels = set(all_enabled[name] if name in all_enabled else []) enabled_levels = requested_runlevels - current_levels disabled_levels = current_levels - requested_runlevels return enabled_levels, disabled_levels def _disable_delta(name, requested_runlevels): all_enabled = get_enabled() current_levels = set(all_enabled[name] if name in all_enabled else []) return current_levels & requested_runlevels def _service_cmd(*args): return '/etc/init.d/{0} {1}'.format(args[0], ' '.join(args[1:])) def _enable_disable_cmd(name, command, runlevels=()): return 'rc-update {0} {1} {2}'.format(command, name, ' '.join(sorted(runlevels))).strip() def get_enabled(): ''' Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' (enabled_services, disabled_services) = _get_service_list() return odict.OrderedDict(enabled_services) def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, include_disabled=True) return name in enabled_services or name in disabled_services def missing(name): ''' The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) def get_all(): ''' Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, include_disabled=True) enabled_services.update(dict([(s, []) for s in disabled_services])) return odict.OrderedDict(enabled_services) def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' cmd = _service_cmd(name, 'start') return not _ret_code(cmd) def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' cmd = _service_cmd(name, 'stop') return not _ret_code(cmd) def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' cmd = _service_cmd(name, 'restart') return not _ret_code(cmd) def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' cmd = _service_cmd(name, 'reload') return not _ret_code(cmd) def zap(name): ''' Resets service state CLI Example: .. code-block:: bash salt '*' service.zap <service name> ''' cmd = _service_cmd(name, 'zap') return not _ret_code(cmd) def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' if sig: return bool(__salt__['status.pid'](sig)) contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: cmd = _service_cmd(service, 'status') results[service] = not _ret_code(cmd, ignore_retcode=True) if contains_globbing: return results return results[name] def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> <runlevels=single-runlevel> salt '*' service.enable <service name> <runlevels=[runlevel1,runlevel2]> ''' if 'runlevels' in kwargs: requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) enabled_levels, disabled_levels = _enable_delta(name, requested_levels) commands = [] if disabled_levels: commands.append(_enable_disable_cmd(name, 'delete', disabled_levels)) if enabled_levels: commands.append(_enable_disable_cmd(name, 'add', enabled_levels)) if not commands: return True else: commands = [_enable_disable_cmd(name, 'add')] for cmd in commands: if _ret_code(cmd): return False return True def disable(name, **kwargs): ''' Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> <runlevels=single-runlevel> salt '*' service.disable <service name> <runlevels=[runlevel1,runlevel2]> ''' levels = [] if 'runlevels' in kwargs: requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) levels = _disable_delta(name, requested_levels) if not levels: return True cmd = _enable_disable_cmd(name, 'delete', levels) return not _ret_code(cmd) def enabled(name, **kwargs): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.enabled <service name> <runlevels=single-runlevel> salt '*' service.enabled <service name> <runlevels=[runlevel1,runlevel2]> ''' enabled_services = get_enabled() if name not in enabled_services: return False if 'runlevels' not in kwargs: return True requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) return len(requested_levels - set(enabled_services[name])) == 0 def disabled(name): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.disabled <service name> <runlevels=[runlevel]> ''' return name in get_disabled()
saltstack/salt
salt/modules/gentoo_service.py
available
python
def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, include_disabled=True) return name in enabled_services or name in disabled_services
Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoo_service.py#L122-L135
[ "def _get_service_list(include_enabled=True, include_disabled=False):\n enabled_services = dict()\n disabled_services = set()\n lines = _list_services()\n for line in lines:\n if '|' not in line:\n continue\n service = [l.strip() for l in line.split('|')]\n # enabled service should have runlevels\n if service[1]:\n if include_enabled:\n enabled_services.update({service[0]: sorted(service[1].split())})\n continue\n # in any other case service is disabled\n if include_disabled:\n disabled_services.update({service[0]: []})\n return enabled_services, disabled_services\n" ]
# -*- coding: utf-8 -*- ''' Top level package command wrapper, used to translate the os detected by grains to the correct service manager .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import fnmatch import re # Import salt libs import salt.utils.systemd import salt.utils.odict as odict # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' def __virtual__(): ''' Only work on systems which default to OpenRC ''' if __grains__['os_family'] == 'Gentoo' and not salt.utils.systemd.booted(__context__): return __virtualname__ if __grains__['os'] == 'Alpine': return __virtualname__ return (False, 'The gentoo_service execution module cannot be loaded: ' 'only available on Gentoo/Open-RC systems.') def _ret_code(cmd, ignore_retcode=False): log.debug('executing [%s]', cmd) sts = __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=ignore_retcode) return sts def _list_services(): return __salt__['cmd.run']('rc-update -v show').splitlines() def _get_service_list(include_enabled=True, include_disabled=False): enabled_services = dict() disabled_services = set() lines = _list_services() for line in lines: if '|' not in line: continue service = [l.strip() for l in line.split('|')] # enabled service should have runlevels if service[1]: if include_enabled: enabled_services.update({service[0]: sorted(service[1].split())}) continue # in any other case service is disabled if include_disabled: disabled_services.update({service[0]: []}) return enabled_services, disabled_services def _enable_delta(name, requested_runlevels): all_enabled = get_enabled() current_levels = set(all_enabled[name] if name in all_enabled else []) enabled_levels = requested_runlevels - current_levels disabled_levels = current_levels - requested_runlevels return enabled_levels, disabled_levels def _disable_delta(name, requested_runlevels): all_enabled = get_enabled() current_levels = set(all_enabled[name] if name in all_enabled else []) return current_levels & requested_runlevels def _service_cmd(*args): return '/etc/init.d/{0} {1}'.format(args[0], ' '.join(args[1:])) def _enable_disable_cmd(name, command, runlevels=()): return 'rc-update {0} {1} {2}'.format(command, name, ' '.join(sorted(runlevels))).strip() def get_enabled(): ''' Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' (enabled_services, disabled_services) = _get_service_list() return odict.OrderedDict(enabled_services) def get_disabled(): ''' Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=False, include_disabled=True) return sorted(disabled_services) def missing(name): ''' The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) def get_all(): ''' Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, include_disabled=True) enabled_services.update(dict([(s, []) for s in disabled_services])) return odict.OrderedDict(enabled_services) def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' cmd = _service_cmd(name, 'start') return not _ret_code(cmd) def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' cmd = _service_cmd(name, 'stop') return not _ret_code(cmd) def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' cmd = _service_cmd(name, 'restart') return not _ret_code(cmd) def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' cmd = _service_cmd(name, 'reload') return not _ret_code(cmd) def zap(name): ''' Resets service state CLI Example: .. code-block:: bash salt '*' service.zap <service name> ''' cmd = _service_cmd(name, 'zap') return not _ret_code(cmd) def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' if sig: return bool(__salt__['status.pid'](sig)) contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: cmd = _service_cmd(service, 'status') results[service] = not _ret_code(cmd, ignore_retcode=True) if contains_globbing: return results return results[name] def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> <runlevels=single-runlevel> salt '*' service.enable <service name> <runlevels=[runlevel1,runlevel2]> ''' if 'runlevels' in kwargs: requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) enabled_levels, disabled_levels = _enable_delta(name, requested_levels) commands = [] if disabled_levels: commands.append(_enable_disable_cmd(name, 'delete', disabled_levels)) if enabled_levels: commands.append(_enable_disable_cmd(name, 'add', enabled_levels)) if not commands: return True else: commands = [_enable_disable_cmd(name, 'add')] for cmd in commands: if _ret_code(cmd): return False return True def disable(name, **kwargs): ''' Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> <runlevels=single-runlevel> salt '*' service.disable <service name> <runlevels=[runlevel1,runlevel2]> ''' levels = [] if 'runlevels' in kwargs: requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) levels = _disable_delta(name, requested_levels) if not levels: return True cmd = _enable_disable_cmd(name, 'delete', levels) return not _ret_code(cmd) def enabled(name, **kwargs): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.enabled <service name> <runlevels=single-runlevel> salt '*' service.enabled <service name> <runlevels=[runlevel1,runlevel2]> ''' enabled_services = get_enabled() if name not in enabled_services: return False if 'runlevels' not in kwargs: return True requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) return len(requested_levels - set(enabled_services[name])) == 0 def disabled(name): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.disabled <service name> <runlevels=[runlevel]> ''' return name in get_disabled()
saltstack/salt
salt/modules/gentoo_service.py
get_all
python
def get_all(): ''' Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, include_disabled=True) enabled_services.update(dict([(s, []) for s in disabled_services])) return odict.OrderedDict(enabled_services)
Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoo_service.py#L153-L166
[ "def _get_service_list(include_enabled=True, include_disabled=False):\n enabled_services = dict()\n disabled_services = set()\n lines = _list_services()\n for line in lines:\n if '|' not in line:\n continue\n service = [l.strip() for l in line.split('|')]\n # enabled service should have runlevels\n if service[1]:\n if include_enabled:\n enabled_services.update({service[0]: sorted(service[1].split())})\n continue\n # in any other case service is disabled\n if include_disabled:\n disabled_services.update({service[0]: []})\n return enabled_services, disabled_services\n" ]
# -*- coding: utf-8 -*- ''' Top level package command wrapper, used to translate the os detected by grains to the correct service manager .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import fnmatch import re # Import salt libs import salt.utils.systemd import salt.utils.odict as odict # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' def __virtual__(): ''' Only work on systems which default to OpenRC ''' if __grains__['os_family'] == 'Gentoo' and not salt.utils.systemd.booted(__context__): return __virtualname__ if __grains__['os'] == 'Alpine': return __virtualname__ return (False, 'The gentoo_service execution module cannot be loaded: ' 'only available on Gentoo/Open-RC systems.') def _ret_code(cmd, ignore_retcode=False): log.debug('executing [%s]', cmd) sts = __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=ignore_retcode) return sts def _list_services(): return __salt__['cmd.run']('rc-update -v show').splitlines() def _get_service_list(include_enabled=True, include_disabled=False): enabled_services = dict() disabled_services = set() lines = _list_services() for line in lines: if '|' not in line: continue service = [l.strip() for l in line.split('|')] # enabled service should have runlevels if service[1]: if include_enabled: enabled_services.update({service[0]: sorted(service[1].split())}) continue # in any other case service is disabled if include_disabled: disabled_services.update({service[0]: []}) return enabled_services, disabled_services def _enable_delta(name, requested_runlevels): all_enabled = get_enabled() current_levels = set(all_enabled[name] if name in all_enabled else []) enabled_levels = requested_runlevels - current_levels disabled_levels = current_levels - requested_runlevels return enabled_levels, disabled_levels def _disable_delta(name, requested_runlevels): all_enabled = get_enabled() current_levels = set(all_enabled[name] if name in all_enabled else []) return current_levels & requested_runlevels def _service_cmd(*args): return '/etc/init.d/{0} {1}'.format(args[0], ' '.join(args[1:])) def _enable_disable_cmd(name, command, runlevels=()): return 'rc-update {0} {1} {2}'.format(command, name, ' '.join(sorted(runlevels))).strip() def get_enabled(): ''' Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' (enabled_services, disabled_services) = _get_service_list() return odict.OrderedDict(enabled_services) def get_disabled(): ''' Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=False, include_disabled=True) return sorted(disabled_services) def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, include_disabled=True) return name in enabled_services or name in disabled_services def missing(name): ''' The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' cmd = _service_cmd(name, 'start') return not _ret_code(cmd) def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' cmd = _service_cmd(name, 'stop') return not _ret_code(cmd) def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' cmd = _service_cmd(name, 'restart') return not _ret_code(cmd) def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' cmd = _service_cmd(name, 'reload') return not _ret_code(cmd) def zap(name): ''' Resets service state CLI Example: .. code-block:: bash salt '*' service.zap <service name> ''' cmd = _service_cmd(name, 'zap') return not _ret_code(cmd) def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' if sig: return bool(__salt__['status.pid'](sig)) contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: cmd = _service_cmd(service, 'status') results[service] = not _ret_code(cmd, ignore_retcode=True) if contains_globbing: return results return results[name] def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> <runlevels=single-runlevel> salt '*' service.enable <service name> <runlevels=[runlevel1,runlevel2]> ''' if 'runlevels' in kwargs: requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) enabled_levels, disabled_levels = _enable_delta(name, requested_levels) commands = [] if disabled_levels: commands.append(_enable_disable_cmd(name, 'delete', disabled_levels)) if enabled_levels: commands.append(_enable_disable_cmd(name, 'add', enabled_levels)) if not commands: return True else: commands = [_enable_disable_cmd(name, 'add')] for cmd in commands: if _ret_code(cmd): return False return True def disable(name, **kwargs): ''' Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> <runlevels=single-runlevel> salt '*' service.disable <service name> <runlevels=[runlevel1,runlevel2]> ''' levels = [] if 'runlevels' in kwargs: requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) levels = _disable_delta(name, requested_levels) if not levels: return True cmd = _enable_disable_cmd(name, 'delete', levels) return not _ret_code(cmd) def enabled(name, **kwargs): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.enabled <service name> <runlevels=single-runlevel> salt '*' service.enabled <service name> <runlevels=[runlevel1,runlevel2]> ''' enabled_services = get_enabled() if name not in enabled_services: return False if 'runlevels' not in kwargs: return True requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) return len(requested_levels - set(enabled_services[name])) == 0 def disabled(name): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.disabled <service name> <runlevels=[runlevel]> ''' return name in get_disabled()
saltstack/salt
salt/modules/gentoo_service.py
status
python
def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' if sig: return bool(__salt__['status.pid'](sig)) contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: cmd = _service_cmd(service, 'status') results[service] = not _ret_code(cmd, ignore_retcode=True) if contains_globbing: return results return results[name]
Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoo_service.py#L239-L276
[ "def get_all():\n '''\n Return all available boot services\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.get_all\n '''\n (enabled_services, disabled_services) = _get_service_list(include_enabled=True,\n include_disabled=True)\n enabled_services.update(dict([(s, []) for s in disabled_services]))\n return odict.OrderedDict(enabled_services)\n", "def _service_cmd(*args):\n return '/etc/init.d/{0} {1}'.format(args[0], ' '.join(args[1:]))\n", "def _ret_code(cmd, ignore_retcode=False):\n log.debug('executing [%s]', cmd)\n sts = __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=ignore_retcode)\n return sts\n" ]
# -*- coding: utf-8 -*- ''' Top level package command wrapper, used to translate the os detected by grains to the correct service manager .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import fnmatch import re # Import salt libs import salt.utils.systemd import salt.utils.odict as odict # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' def __virtual__(): ''' Only work on systems which default to OpenRC ''' if __grains__['os_family'] == 'Gentoo' and not salt.utils.systemd.booted(__context__): return __virtualname__ if __grains__['os'] == 'Alpine': return __virtualname__ return (False, 'The gentoo_service execution module cannot be loaded: ' 'only available on Gentoo/Open-RC systems.') def _ret_code(cmd, ignore_retcode=False): log.debug('executing [%s]', cmd) sts = __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=ignore_retcode) return sts def _list_services(): return __salt__['cmd.run']('rc-update -v show').splitlines() def _get_service_list(include_enabled=True, include_disabled=False): enabled_services = dict() disabled_services = set() lines = _list_services() for line in lines: if '|' not in line: continue service = [l.strip() for l in line.split('|')] # enabled service should have runlevels if service[1]: if include_enabled: enabled_services.update({service[0]: sorted(service[1].split())}) continue # in any other case service is disabled if include_disabled: disabled_services.update({service[0]: []}) return enabled_services, disabled_services def _enable_delta(name, requested_runlevels): all_enabled = get_enabled() current_levels = set(all_enabled[name] if name in all_enabled else []) enabled_levels = requested_runlevels - current_levels disabled_levels = current_levels - requested_runlevels return enabled_levels, disabled_levels def _disable_delta(name, requested_runlevels): all_enabled = get_enabled() current_levels = set(all_enabled[name] if name in all_enabled else []) return current_levels & requested_runlevels def _service_cmd(*args): return '/etc/init.d/{0} {1}'.format(args[0], ' '.join(args[1:])) def _enable_disable_cmd(name, command, runlevels=()): return 'rc-update {0} {1} {2}'.format(command, name, ' '.join(sorted(runlevels))).strip() def get_enabled(): ''' Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' (enabled_services, disabled_services) = _get_service_list() return odict.OrderedDict(enabled_services) def get_disabled(): ''' Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=False, include_disabled=True) return sorted(disabled_services) def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, include_disabled=True) return name in enabled_services or name in disabled_services def missing(name): ''' The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) def get_all(): ''' Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, include_disabled=True) enabled_services.update(dict([(s, []) for s in disabled_services])) return odict.OrderedDict(enabled_services) def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' cmd = _service_cmd(name, 'start') return not _ret_code(cmd) def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' cmd = _service_cmd(name, 'stop') return not _ret_code(cmd) def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' cmd = _service_cmd(name, 'restart') return not _ret_code(cmd) def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' cmd = _service_cmd(name, 'reload') return not _ret_code(cmd) def zap(name): ''' Resets service state CLI Example: .. code-block:: bash salt '*' service.zap <service name> ''' cmd = _service_cmd(name, 'zap') return not _ret_code(cmd) def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> <runlevels=single-runlevel> salt '*' service.enable <service name> <runlevels=[runlevel1,runlevel2]> ''' if 'runlevels' in kwargs: requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) enabled_levels, disabled_levels = _enable_delta(name, requested_levels) commands = [] if disabled_levels: commands.append(_enable_disable_cmd(name, 'delete', disabled_levels)) if enabled_levels: commands.append(_enable_disable_cmd(name, 'add', enabled_levels)) if not commands: return True else: commands = [_enable_disable_cmd(name, 'add')] for cmd in commands: if _ret_code(cmd): return False return True def disable(name, **kwargs): ''' Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> <runlevels=single-runlevel> salt '*' service.disable <service name> <runlevels=[runlevel1,runlevel2]> ''' levels = [] if 'runlevels' in kwargs: requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) levels = _disable_delta(name, requested_levels) if not levels: return True cmd = _enable_disable_cmd(name, 'delete', levels) return not _ret_code(cmd) def enabled(name, **kwargs): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.enabled <service name> <runlevels=single-runlevel> salt '*' service.enabled <service name> <runlevels=[runlevel1,runlevel2]> ''' enabled_services = get_enabled() if name not in enabled_services: return False if 'runlevels' not in kwargs: return True requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) return len(requested_levels - set(enabled_services[name])) == 0 def disabled(name): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.disabled <service name> <runlevels=[runlevel]> ''' return name in get_disabled()
saltstack/salt
salt/modules/gentoo_service.py
enable
python
def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> <runlevels=single-runlevel> salt '*' service.enable <service name> <runlevels=[runlevel1,runlevel2]> ''' if 'runlevels' in kwargs: requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) enabled_levels, disabled_levels = _enable_delta(name, requested_levels) commands = [] if disabled_levels: commands.append(_enable_disable_cmd(name, 'delete', disabled_levels)) if enabled_levels: commands.append(_enable_disable_cmd(name, 'add', enabled_levels)) if not commands: return True else: commands = [_enable_disable_cmd(name, 'add')] for cmd in commands: if _ret_code(cmd): return False return True
Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> <runlevels=single-runlevel> salt '*' service.enable <service name> <runlevels=[runlevel1,runlevel2]>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoo_service.py#L279-L306
[ "def _ret_code(cmd, ignore_retcode=False):\n log.debug('executing [%s]', cmd)\n sts = __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=ignore_retcode)\n return sts\n", "def _enable_delta(name, requested_runlevels):\n all_enabled = get_enabled()\n current_levels = set(all_enabled[name] if name in all_enabled else [])\n enabled_levels = requested_runlevels - current_levels\n disabled_levels = current_levels - requested_runlevels\n return enabled_levels, disabled_levels\n", "def _enable_disable_cmd(name, command, runlevels=()):\n return 'rc-update {0} {1} {2}'.format(command, name, ' '.join(sorted(runlevels))).strip()\n" ]
# -*- coding: utf-8 -*- ''' Top level package command wrapper, used to translate the os detected by grains to the correct service manager .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import fnmatch import re # Import salt libs import salt.utils.systemd import salt.utils.odict as odict # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' def __virtual__(): ''' Only work on systems which default to OpenRC ''' if __grains__['os_family'] == 'Gentoo' and not salt.utils.systemd.booted(__context__): return __virtualname__ if __grains__['os'] == 'Alpine': return __virtualname__ return (False, 'The gentoo_service execution module cannot be loaded: ' 'only available on Gentoo/Open-RC systems.') def _ret_code(cmd, ignore_retcode=False): log.debug('executing [%s]', cmd) sts = __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=ignore_retcode) return sts def _list_services(): return __salt__['cmd.run']('rc-update -v show').splitlines() def _get_service_list(include_enabled=True, include_disabled=False): enabled_services = dict() disabled_services = set() lines = _list_services() for line in lines: if '|' not in line: continue service = [l.strip() for l in line.split('|')] # enabled service should have runlevels if service[1]: if include_enabled: enabled_services.update({service[0]: sorted(service[1].split())}) continue # in any other case service is disabled if include_disabled: disabled_services.update({service[0]: []}) return enabled_services, disabled_services def _enable_delta(name, requested_runlevels): all_enabled = get_enabled() current_levels = set(all_enabled[name] if name in all_enabled else []) enabled_levels = requested_runlevels - current_levels disabled_levels = current_levels - requested_runlevels return enabled_levels, disabled_levels def _disable_delta(name, requested_runlevels): all_enabled = get_enabled() current_levels = set(all_enabled[name] if name in all_enabled else []) return current_levels & requested_runlevels def _service_cmd(*args): return '/etc/init.d/{0} {1}'.format(args[0], ' '.join(args[1:])) def _enable_disable_cmd(name, command, runlevels=()): return 'rc-update {0} {1} {2}'.format(command, name, ' '.join(sorted(runlevels))).strip() def get_enabled(): ''' Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' (enabled_services, disabled_services) = _get_service_list() return odict.OrderedDict(enabled_services) def get_disabled(): ''' Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=False, include_disabled=True) return sorted(disabled_services) def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, include_disabled=True) return name in enabled_services or name in disabled_services def missing(name): ''' The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) def get_all(): ''' Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, include_disabled=True) enabled_services.update(dict([(s, []) for s in disabled_services])) return odict.OrderedDict(enabled_services) def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' cmd = _service_cmd(name, 'start') return not _ret_code(cmd) def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' cmd = _service_cmd(name, 'stop') return not _ret_code(cmd) def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' cmd = _service_cmd(name, 'restart') return not _ret_code(cmd) def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' cmd = _service_cmd(name, 'reload') return not _ret_code(cmd) def zap(name): ''' Resets service state CLI Example: .. code-block:: bash salt '*' service.zap <service name> ''' cmd = _service_cmd(name, 'zap') return not _ret_code(cmd) def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' if sig: return bool(__salt__['status.pid'](sig)) contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: cmd = _service_cmd(service, 'status') results[service] = not _ret_code(cmd, ignore_retcode=True) if contains_globbing: return results return results[name] def disable(name, **kwargs): ''' Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> <runlevels=single-runlevel> salt '*' service.disable <service name> <runlevels=[runlevel1,runlevel2]> ''' levels = [] if 'runlevels' in kwargs: requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) levels = _disable_delta(name, requested_levels) if not levels: return True cmd = _enable_disable_cmd(name, 'delete', levels) return not _ret_code(cmd) def enabled(name, **kwargs): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.enabled <service name> <runlevels=single-runlevel> salt '*' service.enabled <service name> <runlevels=[runlevel1,runlevel2]> ''' enabled_services = get_enabled() if name not in enabled_services: return False if 'runlevels' not in kwargs: return True requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) return len(requested_levels - set(enabled_services[name])) == 0 def disabled(name): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.disabled <service name> <runlevels=[runlevel]> ''' return name in get_disabled()
saltstack/salt
salt/modules/gentoo_service.py
disable
python
def disable(name, **kwargs): ''' Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> <runlevels=single-runlevel> salt '*' service.disable <service name> <runlevels=[runlevel1,runlevel2]> ''' levels = [] if 'runlevels' in kwargs: requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) levels = _disable_delta(name, requested_levels) if not levels: return True cmd = _enable_disable_cmd(name, 'delete', levels) return not _ret_code(cmd)
Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> <runlevels=single-runlevel> salt '*' service.disable <service name> <runlevels=[runlevel1,runlevel2]>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoo_service.py#L309-L328
[ "def _ret_code(cmd, ignore_retcode=False):\n log.debug('executing [%s]', cmd)\n sts = __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=ignore_retcode)\n return sts\n", "def _disable_delta(name, requested_runlevels):\n all_enabled = get_enabled()\n current_levels = set(all_enabled[name] if name in all_enabled else [])\n return current_levels & requested_runlevels\n", "def _enable_disable_cmd(name, command, runlevels=()):\n return 'rc-update {0} {1} {2}'.format(command, name, ' '.join(sorted(runlevels))).strip()\n" ]
# -*- coding: utf-8 -*- ''' Top level package command wrapper, used to translate the os detected by grains to the correct service manager .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import fnmatch import re # Import salt libs import salt.utils.systemd import salt.utils.odict as odict # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' def __virtual__(): ''' Only work on systems which default to OpenRC ''' if __grains__['os_family'] == 'Gentoo' and not salt.utils.systemd.booted(__context__): return __virtualname__ if __grains__['os'] == 'Alpine': return __virtualname__ return (False, 'The gentoo_service execution module cannot be loaded: ' 'only available on Gentoo/Open-RC systems.') def _ret_code(cmd, ignore_retcode=False): log.debug('executing [%s]', cmd) sts = __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=ignore_retcode) return sts def _list_services(): return __salt__['cmd.run']('rc-update -v show').splitlines() def _get_service_list(include_enabled=True, include_disabled=False): enabled_services = dict() disabled_services = set() lines = _list_services() for line in lines: if '|' not in line: continue service = [l.strip() for l in line.split('|')] # enabled service should have runlevels if service[1]: if include_enabled: enabled_services.update({service[0]: sorted(service[1].split())}) continue # in any other case service is disabled if include_disabled: disabled_services.update({service[0]: []}) return enabled_services, disabled_services def _enable_delta(name, requested_runlevels): all_enabled = get_enabled() current_levels = set(all_enabled[name] if name in all_enabled else []) enabled_levels = requested_runlevels - current_levels disabled_levels = current_levels - requested_runlevels return enabled_levels, disabled_levels def _disable_delta(name, requested_runlevels): all_enabled = get_enabled() current_levels = set(all_enabled[name] if name in all_enabled else []) return current_levels & requested_runlevels def _service_cmd(*args): return '/etc/init.d/{0} {1}'.format(args[0], ' '.join(args[1:])) def _enable_disable_cmd(name, command, runlevels=()): return 'rc-update {0} {1} {2}'.format(command, name, ' '.join(sorted(runlevels))).strip() def get_enabled(): ''' Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' (enabled_services, disabled_services) = _get_service_list() return odict.OrderedDict(enabled_services) def get_disabled(): ''' Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=False, include_disabled=True) return sorted(disabled_services) def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, include_disabled=True) return name in enabled_services or name in disabled_services def missing(name): ''' The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) def get_all(): ''' Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, include_disabled=True) enabled_services.update(dict([(s, []) for s in disabled_services])) return odict.OrderedDict(enabled_services) def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' cmd = _service_cmd(name, 'start') return not _ret_code(cmd) def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' cmd = _service_cmd(name, 'stop') return not _ret_code(cmd) def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' cmd = _service_cmd(name, 'restart') return not _ret_code(cmd) def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' cmd = _service_cmd(name, 'reload') return not _ret_code(cmd) def zap(name): ''' Resets service state CLI Example: .. code-block:: bash salt '*' service.zap <service name> ''' cmd = _service_cmd(name, 'zap') return not _ret_code(cmd) def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' if sig: return bool(__salt__['status.pid'](sig)) contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: cmd = _service_cmd(service, 'status') results[service] = not _ret_code(cmd, ignore_retcode=True) if contains_globbing: return results return results[name] def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> <runlevels=single-runlevel> salt '*' service.enable <service name> <runlevels=[runlevel1,runlevel2]> ''' if 'runlevels' in kwargs: requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) enabled_levels, disabled_levels = _enable_delta(name, requested_levels) commands = [] if disabled_levels: commands.append(_enable_disable_cmd(name, 'delete', disabled_levels)) if enabled_levels: commands.append(_enable_disable_cmd(name, 'add', enabled_levels)) if not commands: return True else: commands = [_enable_disable_cmd(name, 'add')] for cmd in commands: if _ret_code(cmd): return False return True def enabled(name, **kwargs): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.enabled <service name> <runlevels=single-runlevel> salt '*' service.enabled <service name> <runlevels=[runlevel1,runlevel2]> ''' enabled_services = get_enabled() if name not in enabled_services: return False if 'runlevels' not in kwargs: return True requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) return len(requested_levels - set(enabled_services[name])) == 0 def disabled(name): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.disabled <service name> <runlevels=[runlevel]> ''' return name in get_disabled()
saltstack/salt
salt/modules/gentoo_service.py
enabled
python
def enabled(name, **kwargs): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.enabled <service name> <runlevels=single-runlevel> salt '*' service.enabled <service name> <runlevels=[runlevel1,runlevel2]> ''' enabled_services = get_enabled() if name not in enabled_services: return False if 'runlevels' not in kwargs: return True requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) return len(requested_levels - set(enabled_services[name])) == 0
Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.enabled <service name> <runlevels=single-runlevel> salt '*' service.enabled <service name> <runlevels=[runlevel1,runlevel2]>
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/gentoo_service.py#L331-L349
[ "def get_enabled():\n '''\n Return a list of service that are enabled on boot\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' service.get_enabled\n '''\n (enabled_services, disabled_services) = _get_service_list()\n return odict.OrderedDict(enabled_services)\n" ]
# -*- coding: utf-8 -*- ''' Top level package command wrapper, used to translate the os detected by grains to the correct service manager .. important:: If you feel that Salt should be using this module to manage services on a minion, and it is using a different module (or gives an error similar to *'service.start' is not available*), see :ref:`here <module-provider-override>`. ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import fnmatch import re # Import salt libs import salt.utils.systemd import salt.utils.odict as odict # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'service' def __virtual__(): ''' Only work on systems which default to OpenRC ''' if __grains__['os_family'] == 'Gentoo' and not salt.utils.systemd.booted(__context__): return __virtualname__ if __grains__['os'] == 'Alpine': return __virtualname__ return (False, 'The gentoo_service execution module cannot be loaded: ' 'only available on Gentoo/Open-RC systems.') def _ret_code(cmd, ignore_retcode=False): log.debug('executing [%s]', cmd) sts = __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=ignore_retcode) return sts def _list_services(): return __salt__['cmd.run']('rc-update -v show').splitlines() def _get_service_list(include_enabled=True, include_disabled=False): enabled_services = dict() disabled_services = set() lines = _list_services() for line in lines: if '|' not in line: continue service = [l.strip() for l in line.split('|')] # enabled service should have runlevels if service[1]: if include_enabled: enabled_services.update({service[0]: sorted(service[1].split())}) continue # in any other case service is disabled if include_disabled: disabled_services.update({service[0]: []}) return enabled_services, disabled_services def _enable_delta(name, requested_runlevels): all_enabled = get_enabled() current_levels = set(all_enabled[name] if name in all_enabled else []) enabled_levels = requested_runlevels - current_levels disabled_levels = current_levels - requested_runlevels return enabled_levels, disabled_levels def _disable_delta(name, requested_runlevels): all_enabled = get_enabled() current_levels = set(all_enabled[name] if name in all_enabled else []) return current_levels & requested_runlevels def _service_cmd(*args): return '/etc/init.d/{0} {1}'.format(args[0], ' '.join(args[1:])) def _enable_disable_cmd(name, command, runlevels=()): return 'rc-update {0} {1} {2}'.format(command, name, ' '.join(sorted(runlevels))).strip() def get_enabled(): ''' Return a list of service that are enabled on boot CLI Example: .. code-block:: bash salt '*' service.get_enabled ''' (enabled_services, disabled_services) = _get_service_list() return odict.OrderedDict(enabled_services) def get_disabled(): ''' Return a set of services that are installed but disabled CLI Example: .. code-block:: bash salt '*' service.get_disabled ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=False, include_disabled=True) return sorted(disabled_services) def available(name): ''' Returns ``True`` if the specified service is available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, include_disabled=True) return name in enabled_services or name in disabled_services def missing(name): ''' The inverse of service.available. Returns ``True`` if the specified service is not available, otherwise returns ``False``. CLI Example: .. code-block:: bash salt '*' service.missing sshd ''' return not available(name) def get_all(): ''' Return all available boot services CLI Example: .. code-block:: bash salt '*' service.get_all ''' (enabled_services, disabled_services) = _get_service_list(include_enabled=True, include_disabled=True) enabled_services.update(dict([(s, []) for s in disabled_services])) return odict.OrderedDict(enabled_services) def start(name): ''' Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> ''' cmd = _service_cmd(name, 'start') return not _ret_code(cmd) def stop(name): ''' Stop the specified service CLI Example: .. code-block:: bash salt '*' service.stop <service name> ''' cmd = _service_cmd(name, 'stop') return not _ret_code(cmd) def restart(name): ''' Restart the named service CLI Example: .. code-block:: bash salt '*' service.restart <service name> ''' cmd = _service_cmd(name, 'restart') return not _ret_code(cmd) def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' cmd = _service_cmd(name, 'reload') return not _ret_code(cmd) def zap(name): ''' Resets service state CLI Example: .. code-block:: bash salt '*' service.zap <service name> ''' cmd = _service_cmd(name, 'zap') return not _ret_code(cmd) def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the service to check sig (str): Signature to use to find the service via ps Returns: bool: True if running, False otherwise dict: Maps service name to True if running, False otherwise CLI Example: .. code-block:: bash salt '*' service.status <service name> [service signature] ''' if sig: return bool(__salt__['status.pid'](sig)) contains_globbing = bool(re.search(r'\*|\?|\[.+\]', name)) if contains_globbing: services = fnmatch.filter(get_all(), name) else: services = [name] results = {} for service in services: cmd = _service_cmd(service, 'status') results[service] = not _ret_code(cmd, ignore_retcode=True) if contains_globbing: return results return results[name] def enable(name, **kwargs): ''' Enable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.enable <service name> <runlevels=single-runlevel> salt '*' service.enable <service name> <runlevels=[runlevel1,runlevel2]> ''' if 'runlevels' in kwargs: requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) enabled_levels, disabled_levels = _enable_delta(name, requested_levels) commands = [] if disabled_levels: commands.append(_enable_disable_cmd(name, 'delete', disabled_levels)) if enabled_levels: commands.append(_enable_disable_cmd(name, 'add', enabled_levels)) if not commands: return True else: commands = [_enable_disable_cmd(name, 'add')] for cmd in commands: if _ret_code(cmd): return False return True def disable(name, **kwargs): ''' Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> <runlevels=single-runlevel> salt '*' service.disable <service name> <runlevels=[runlevel1,runlevel2]> ''' levels = [] if 'runlevels' in kwargs: requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'], list) else [kwargs['runlevels']]) levels = _disable_delta(name, requested_levels) if not levels: return True cmd = _enable_disable_cmd(name, 'delete', levels) return not _ret_code(cmd) def disabled(name): ''' Return True if the named service is enabled, false otherwise CLI Example: .. code-block:: bash salt '*' service.disabled <service name> <runlevels=[runlevel]> ''' return name in get_disabled()
saltstack/salt
salt/states/virtualenv_mod.py
managed
python
def managed(name, venv_bin=None, requirements=None, system_site_packages=False, distribute=False, use_wheel=False, clear=False, python=None, extra_search_dir=None, never_download=None, prompt=None, user=None, cwd=None, index_url=None, extra_index_url=None, pre_releases=False, no_deps=False, pip_download=None, pip_download_cache=None, pip_exists_action=None, pip_ignore_installed=False, proxy=None, use_vt=False, env_vars=None, no_use_wheel=False, pip_upgrade=False, pip_pkgs=None, pip_no_cache_dir=False, pip_cache_dir=None, process_dependency_links=False, no_binary=None, **kwargs): ''' Create a virtualenv and optionally manage it with pip name Path to the virtualenv. venv_bin: virtualenv The name (and optionally path) of the virtualenv command. This can also be set globally in the minion config file as ``virtualenv.venv_bin``. requirements: None Path to a pip requirements file. If the path begins with ``salt://`` the file will be transferred from the master file server. use_wheel: False Prefer wheel archives (requires pip >= 1.4). python : None Python executable used to build the virtualenv user: None The user under which to run virtualenv and pip. cwd: None Path to the working directory where `pip install` is executed. no_deps: False Pass `--no-deps` to `pip install`. pip_exists_action: None Default action of pip when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup. proxy: None Proxy address which is passed to `pip install`. env_vars: None Set environment variables that some builds will depend on. For example, a Python C-module may have a Makefile that needs INCLUDE_PATH set to pick up a header file while compiling. no_use_wheel: False Force to not use wheel archives (requires pip>=1.4) no_binary Force to not use binary packages (requires pip >= 7.0.0) Accepts either :all: to disable all binary packages, :none: to empty the set, or a list of one or more packages pip_upgrade: False Pass `--upgrade` to `pip install`. pip_pkgs: None As an alternative to `requirements`, pass a list of pip packages that should be installed. process_dependency_links: False Run pip install with the --process_dependency_links flag. .. versionadded:: 2017.7.0 Also accepts any kwargs that the virtualenv module will. However, some kwargs, such as the ``pip`` option, require ``- distribute: True``. .. code-block:: yaml /var/www/myvirtualenv.com: virtualenv.managed: - system_site_packages: False - requirements: salt://REQUIREMENTS.txt - env_vars: PATH_VAR: '/usr/local/bin/' ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} if 'virtualenv.create' not in __salt__: ret['result'] = False ret['comment'] = 'Virtualenv was not detected on this system' return ret if salt.utils.platform.is_windows(): venv_py = os.path.join(name, 'Scripts', 'python.exe') else: venv_py = os.path.join(name, 'bin', 'python') venv_exists = os.path.exists(venv_py) # Bail out early if the specified requirements file can't be found if requirements and requirements.startswith('salt://'): cached_requirements = __salt__['cp.is_cached'](requirements, __env__) if not cached_requirements: # It's not cached, let's cache it. cached_requirements = __salt__['cp.cache_file']( requirements, __env__ ) # Check if the master version has changed. if cached_requirements and __salt__['cp.hash_file'](requirements, __env__) != \ __salt__['cp.hash_file'](cached_requirements, __env__): cached_requirements = __salt__['cp.cache_file']( requirements, __env__ ) if not cached_requirements: ret.update({ 'result': False, 'comment': 'pip requirements file \'{0}\' not found'.format( requirements ) }) return ret requirements = cached_requirements # If it already exists, grab the version for posterity if venv_exists and clear: ret['changes']['cleared_packages'] = \ __salt__['pip.freeze'](bin_env=name) ret['changes']['old'] = \ __salt__['cmd.run_stderr']('{0} -V'.format(venv_py)).strip('\n') # Create (or clear) the virtualenv if __opts__['test']: if venv_exists and clear: ret['result'] = None ret['comment'] = 'Virtualenv {0} is set to be cleared'.format(name) return ret if venv_exists and not clear: ret['comment'] = 'Virtualenv {0} is already created'.format(name) return ret ret['result'] = None ret['comment'] = 'Virtualenv {0} is set to be created'.format(name) return ret if not venv_exists or (venv_exists and clear): try: venv_ret = __salt__['virtualenv.create']( name, venv_bin=venv_bin, system_site_packages=system_site_packages, distribute=distribute, clear=clear, python=python, extra_search_dir=extra_search_dir, never_download=never_download, prompt=prompt, user=user, use_vt=use_vt, **kwargs ) except CommandNotFoundError as err: ret['result'] = False ret['comment'] = 'Failed to create virtualenv: {0}'.format(err) return ret if venv_ret['retcode'] != 0: ret['result'] = False ret['comment'] = venv_ret['stdout'] + venv_ret['stderr'] return ret ret['result'] = True ret['changes']['new'] = __salt__['cmd.run_stderr']( '{0} -V'.format(venv_py)).strip('\n') if clear: ret['comment'] = 'Cleared existing virtualenv' else: ret['comment'] = 'Created new virtualenv' elif venv_exists: ret['comment'] = 'virtualenv exists' # Check that the pip binary supports the 'use_wheel' option if use_wheel: min_version = '1.4' max_version = '9.0.3' cur_version = __salt__['pip.version'](bin_env=name) too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version) too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version) if too_low or too_high: ret['result'] = False ret['comment'] = ('The \'use_wheel\' option is only supported in ' 'pip between {0} and {1}. The version of pip detected ' 'was {2}.').format(min_version, max_version, cur_version) return ret # Check that the pip binary supports the 'no_use_wheel' option if no_use_wheel: min_version = '1.4' max_version = '9.0.3' cur_version = __salt__['pip.version'](bin_env=name) too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version) too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version) if too_low or too_high: ret['result'] = False ret['comment'] = ('The \'no_use_wheel\' option is only supported in ' 'pip between {0} and {1}. The version of pip detected ' 'was {2}.').format(min_version, max_version, cur_version) return ret # Check that the pip binary supports the 'no_binary' option if no_binary: min_version = '7.0.0' cur_version = __salt__['pip.version'](bin_env=name) too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version) if too_low: ret['result'] = False ret['comment'] = ('The \'no_binary\' option is only supported in ' 'pip {0} and newer. The version of pip detected ' 'was {1}.').format(min_version, cur_version) return ret # Populate the venv via a requirements file if requirements or pip_pkgs: try: before = set(__salt__['pip.freeze'](bin_env=name, user=user, use_vt=use_vt)) except CommandExecutionError as exc: ret['result'] = False ret['comment'] = exc.strerror return ret if requirements: if isinstance(requirements, six.string_types): req_canary = requirements.split(',')[0] elif isinstance(requirements, list): req_canary = requirements[0] else: raise TypeError( 'pip requirements must be either a string or a list' ) if req_canary != os.path.abspath(req_canary): cwd = os.path.dirname(os.path.abspath(req_canary)) pip_ret = __salt__['pip.install']( pkgs=pip_pkgs, requirements=requirements, process_dependency_links=process_dependency_links, bin_env=name, use_wheel=use_wheel, no_use_wheel=no_use_wheel, no_binary=no_binary, user=user, cwd=cwd, index_url=index_url, extra_index_url=extra_index_url, download=pip_download, download_cache=pip_download_cache, pre_releases=pre_releases, exists_action=pip_exists_action, ignore_installed=pip_ignore_installed, upgrade=pip_upgrade, no_deps=no_deps, proxy=proxy, use_vt=use_vt, env_vars=env_vars, no_cache_dir=pip_no_cache_dir, cache_dir=pip_cache_dir, **kwargs ) ret['result'] &= pip_ret['retcode'] == 0 if pip_ret['retcode'] > 0: ret['comment'] = '{0}\n{1}\n{2}'.format(ret['comment'], pip_ret['stdout'], pip_ret['stderr']) after = set(__salt__['pip.freeze'](bin_env=name)) new = list(after - before) old = list(before - after) if new or old: ret['changes']['packages'] = { 'new': new if new else '', 'old': old if old else ''} return ret
Create a virtualenv and optionally manage it with pip name Path to the virtualenv. venv_bin: virtualenv The name (and optionally path) of the virtualenv command. This can also be set globally in the minion config file as ``virtualenv.venv_bin``. requirements: None Path to a pip requirements file. If the path begins with ``salt://`` the file will be transferred from the master file server. use_wheel: False Prefer wheel archives (requires pip >= 1.4). python : None Python executable used to build the virtualenv user: None The user under which to run virtualenv and pip. cwd: None Path to the working directory where `pip install` is executed. no_deps: False Pass `--no-deps` to `pip install`. pip_exists_action: None Default action of pip when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup. proxy: None Proxy address which is passed to `pip install`. env_vars: None Set environment variables that some builds will depend on. For example, a Python C-module may have a Makefile that needs INCLUDE_PATH set to pick up a header file while compiling. no_use_wheel: False Force to not use wheel archives (requires pip>=1.4) no_binary Force to not use binary packages (requires pip >= 7.0.0) Accepts either :all: to disable all binary packages, :none: to empty the set, or a list of one or more packages pip_upgrade: False Pass `--upgrade` to `pip install`. pip_pkgs: None As an alternative to `requirements`, pass a list of pip packages that should be installed. process_dependency_links: False Run pip install with the --process_dependency_links flag. .. versionadded:: 2017.7.0 Also accepts any kwargs that the virtualenv module will. However, some kwargs, such as the ``pip`` option, require ``- distribute: True``. .. code-block:: yaml /var/www/myvirtualenv.com: virtualenv.managed: - system_site_packages: False - requirements: salt://REQUIREMENTS.txt - env_vars: PATH_VAR: '/usr/local/bin/'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/virtualenv_mod.py#L33-L337
[ "def compare(ver1='', oper='==', ver2='', cmp_func=None, ignore_epoch=False):\n '''\n Compares two version numbers. Accepts a custom function to perform the\n cmp-style version comparison, otherwise uses version_cmp().\n '''\n cmp_map = {'<': (-1,), '<=': (-1, 0), '==': (0,),\n '>=': (0, 1), '>': (1,)}\n if oper not in ('!=',) and oper not in cmp_map:\n log.error('Invalid operator \\'%s\\' for version comparison', oper)\n return False\n\n if cmp_func is None:\n cmp_func = version_cmp\n\n cmp_result = cmp_func(ver1, ver2, ignore_epoch=ignore_epoch)\n if cmp_result is None:\n return False\n\n # Check if integer/long\n if not isinstance(cmp_result, numbers.Integral):\n log.error('The version comparison function did not return an '\n 'integer/long.')\n return False\n\n if oper == '!=':\n return cmp_result not in cmp_map['==']\n else:\n # Gracefully handle cmp_result not in (-1, 0, 1).\n if cmp_result < -1:\n cmp_result = -1\n elif cmp_result > 1:\n cmp_result = 1\n\n return cmp_result in cmp_map[oper]\n" ]
# -*- coding: utf-8 -*- ''' Setup of Python virtualenv sandboxes. .. versionadded:: 0.17.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import Salt libs import salt.version import salt.utils.functools import salt.utils.platform import salt.utils.versions from salt.exceptions import CommandExecutionError, CommandNotFoundError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'virtualenv' def __virtual__(): return __virtualname__ manage = salt.utils.functools.alias_function(managed, 'manage')
saltstack/salt
salt/modules/rh_ip.py
_parse_settings_bond_1
python
def _parse_settings_bond_1(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond1. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '1'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'primary' in opts: bond.update({'primary': opts['primary']}) return bond
Filters given options and outputs valid settings for bond1. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L320-L356
null
# -*- coding: utf-8 -*- ''' The networking module for RHEL/Fedora based distros ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging import os.path import os # Import third party libs import jinja2 import jinja2.exceptions # Import salt libs import salt.utils.files import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net from salt.exceptions import CommandExecutionError from salt.ext import six # Set up logging log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'rh_ip') ) ) # Define the module's virtual name __virtualname__ = 'ip' def __virtual__(): ''' Confine this module to RHEL/Fedora based distros ''' if __grains__['os_family'] == 'RedHat': return __virtualname__ return (False, 'The rh_ip execution module cannot be loaded: this module is only available on RHEL/Fedora based distributions.') # Setup networking attributes _ETHTOOL_CONFIG_OPTS = [ 'autoneg', 'speed', 'duplex', 'rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro', 'advertise' ] _RH_CONFIG_OPTS = [ 'domain', 'peerdns', 'peerntp', 'defroute', 'mtu', 'static-routes', 'gateway', 'zone' ] _RH_CONFIG_BONDING_OPTS = [ 'mode', 'miimon', 'arp_interval', 'arp_ip_target', 'downdelay', 'updelay', 'use_carrier', 'lacp_rate', 'hashing-algorithm', 'max_bonds', 'tx_queues', 'num_grat_arp', 'num_unsol_na', 'primary', 'primary_reselect', 'ad_select', 'xmit_hash_policy', 'arp_validate', 'fail_over_mac', 'all_slaves_active', 'resend_igmp' ] _RH_NETWORK_SCRIPT_DIR = '/etc/sysconfig/network-scripts' _RH_NETWORK_FILE = '/etc/sysconfig/network' _RH_NETWORK_CONF_FILES = '/etc/modprobe.d' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] _CONFIG_FALSE = ['no', 'off', 'false', '0', False] _IFACE_TYPES = [ 'eth', 'bond', 'alias', 'clone', 'ipsec', 'dialup', 'bridge', 'slave', 'vlan', 'ipip', 'ib', ] def _error_msg_iface(iface, option, expected): ''' Build an appropriate error message from a given option and a list of expected values. ''' msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]' return msg.format(iface, option, '|'.join(str(e) for e in expected)) def _error_msg_routes(iface, option, expected): ''' Build an appropriate error message from a given option and a list of expected values. ''' msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]' return msg.format(iface, option, expected) def _log_default_iface(iface, opt, value): log.info('Using default option -- Interface: %s Option: %s Value: %s', iface, opt, value) def _error_msg_network(option, expected): ''' Build an appropriate error message from a given option and a list of expected values. ''' msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]' return msg.format(option, '|'.join(str(e) for e in expected)) def _log_default_network(opt, value): log.info('Using existing setting -- Setting: %s Value: %s', opt, value) def _parse_rh_config(path): rh_config = _read_file(path) cv_rh_config = {} if rh_config: for line in rh_config: line = line.strip() if not line or line.startswith('!') or line.startswith('#'): continue pair = [p.rstrip() for p in line.split('=', 1)] if len(pair) != 2: continue name, value = pair cv_rh_config[name.upper()] = value return cv_rh_config def _parse_ethtool_opts(opts, iface): ''' Filters given options and outputs valid settings for ETHTOOLS_OPTS If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' config = {} if 'autoneg' in opts: if opts['autoneg'] in _CONFIG_TRUE: config.update({'autoneg': 'on'}) elif opts['autoneg'] in _CONFIG_FALSE: config.update({'autoneg': 'off'}) else: _raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE) if 'duplex' in opts: valid = ['full', 'half'] if opts['duplex'] in valid: config.update({'duplex': opts['duplex']}) else: _raise_error_iface(iface, 'duplex', valid) if 'speed' in opts: valid = ['10', '100', '1000', '10000'] if six.text_type(opts['speed']) in valid: config.update({'speed': opts['speed']}) else: _raise_error_iface(iface, opts['speed'], valid) if 'advertise' in opts: valid = [ '0x001', '0x002', '0x004', '0x008', '0x010', '0x020', '0x20000', '0x8000', '0x1000', '0x40000', '0x80000', '0x200000', '0x400000', '0x800000', '0x1000000', '0x2000000', '0x4000000' ] if six.text_type(opts['advertise']) in valid: config.update({'advertise': opts['advertise']}) else: _raise_error_iface(iface, 'advertise', valid) valid = _CONFIG_TRUE + _CONFIG_FALSE for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'): if option in opts: if opts[option] in _CONFIG_TRUE: config.update({option: 'on'}) elif opts[option] in _CONFIG_FALSE: config.update({option: 'off'}) else: _raise_error_iface(iface, option, valid) return config def _parse_settings_bond(opts, iface): ''' Filters given options and outputs valid settings for requested operation. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond_def = { # 803.ad aggregation selection logic # 0 for stable (default) # 1 for bandwidth # 2 for count 'ad_select': '0', # Max number of transmit queues (default = 16) 'tx_queues': '16', # Link monitoring in milliseconds. Most NICs support this 'miimon': '100', # ARP interval in milliseconds 'arp_interval': '250', # Delay before considering link down in milliseconds (miimon * 2) 'downdelay': '200', # lacp_rate 0: Slow - every 30 seconds # lacp_rate 1: Fast - every 1 second 'lacp_rate': '0', # Max bonds for this driver 'max_bonds': '1', # Specifies the time, in milliseconds, to wait before # enabling a slave after a link recovery has been # detected. Only used with miimon. 'updelay': '0', # Used with miimon. # On: driver sends mii # Off: ethtool sends mii 'use_carrier': '0', # Default. Don't change unless you know what you are doing. 'xmit_hash_policy': 'layer2', } if opts['mode'] in ['balance-rr', '0']: log.info( 'Device: %s Bonding Mode: load balancing (round-robin)', iface ) return _parse_settings_bond_0(opts, iface, bond_def) elif opts['mode'] in ['active-backup', '1']: log.info( 'Device: %s Bonding Mode: fault-tolerance (active-backup)', iface ) return _parse_settings_bond_1(opts, iface, bond_def) elif opts['mode'] in ['balance-xor', '2']: log.info( 'Device: %s Bonding Mode: load balancing (xor)', iface ) return _parse_settings_bond_2(opts, iface, bond_def) elif opts['mode'] in ['broadcast', '3']: log.info( 'Device: %s Bonding Mode: fault-tolerance (broadcast)', iface ) return _parse_settings_bond_3(opts, iface, bond_def) elif opts['mode'] in ['802.3ad', '4']: log.info( 'Device: %s Bonding Mode: IEEE 802.3ad Dynamic link ' 'aggregation', iface ) return _parse_settings_bond_4(opts, iface, bond_def) elif opts['mode'] in ['balance-tlb', '5']: log.info( 'Device: %s Bonding Mode: transmit load balancing', iface ) return _parse_settings_bond_5(opts, iface, bond_def) elif opts['mode'] in ['balance-alb', '6']: log.info( 'Device: %s Bonding Mode: adaptive load balancing', iface ) return _parse_settings_bond_6(opts, iface, bond_def) else: valid = [ '0', '1', '2', '3', '4', '5', '6', 'balance-rr', 'active-backup', 'balance-xor', 'broadcast', '802.3ad', 'balance-tlb', 'balance-alb' ] _raise_error_iface(iface, 'mode', valid) def _parse_settings_bond_0(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond0. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' # balance-rr shares miimon settings with balance-xor bond = _parse_settings_bond_1(opts, iface, bond_def) bond.update({'mode': '0'}) # ARP targets in n.n.n.n form valid = ['list of ips (up to 16)'] if 'arp_ip_target' in opts: if isinstance(opts['arp_ip_target'], list): if 1 <= len(opts['arp_ip_target']) <= 16: bond.update({'arp_ip_target': ''}) for ip in opts['arp_ip_target']: # pylint: disable=C0103 if bond['arp_ip_target']: bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip else: bond['arp_ip_target'] = ip else: _raise_error_iface(iface, 'arp_ip_target', valid) else: _raise_error_iface(iface, 'arp_ip_target', valid) elif 'miimon' not in opts: _raise_error_iface(iface, 'arp_ip_target', valid) if 'arp_interval' in opts: try: int(opts['arp_interval']) bond.update({'arp_interval': opts['arp_interval']}) except Exception: _raise_error_iface(iface, 'arp_interval', ['integer']) else: _log_default_iface(iface, 'arp_interval', bond_def['arp_interval']) bond.update({'arp_interval': bond_def['arp_interval']}) return bond def _parse_settings_bond_2(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond2. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '2'} valid = ['list of ips (up to 16)'] if 'arp_ip_target' in opts: if isinstance(opts['arp_ip_target'], list): if 1 <= len(opts['arp_ip_target']) <= 16: bond.update({'arp_ip_target': ''}) for ip in opts['arp_ip_target']: # pylint: disable=C0103 if bond['arp_ip_target']: bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip else: bond['arp_ip_target'] = ip else: _raise_error_iface(iface, 'arp_ip_target', valid) else: _raise_error_iface(iface, 'arp_ip_target', valid) else: _raise_error_iface(iface, 'arp_ip_target', valid) if 'arp_interval' in opts: try: int(opts['arp_interval']) bond.update({'arp_interval': opts['arp_interval']}) except Exception: _raise_error_iface(iface, 'arp_interval', ['integer']) else: _log_default_iface(iface, 'arp_interval', bond_def['arp_interval']) bond.update({'arp_interval': bond_def['arp_interval']}) if 'hashing-algorithm' in opts: valid = ['layer2', 'layer2+3', 'layer3+4'] if opts['hashing-algorithm'] in valid: bond.update({'xmit_hash_policy': opts['hashing-algorithm']}) else: _raise_error_iface(iface, 'hashing-algorithm', valid) return bond def _parse_settings_bond_3(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond3. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '3'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) return bond def _parse_settings_bond_4(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond4. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '4'} for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']: if binding in opts: if binding == 'lacp_rate': if opts[binding] == 'fast': opts.update({binding: '1'}) if opts[binding] == 'slow': opts.update({binding: '0'}) valid = ['fast', '1', 'slow', '0'] else: valid = ['integer'] try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, valid) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'hashing-algorithm' in opts: valid = ['layer2', 'layer2+3', 'layer3+4'] if opts['hashing-algorithm'] in valid: bond.update({'xmit_hash_policy': opts['hashing-algorithm']}) else: _raise_error_iface(iface, 'hashing-algorithm', valid) return bond def _parse_settings_bond_5(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond5. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '5'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'primary' in opts: bond.update({'primary': opts['primary']}) return bond def _parse_settings_bond_6(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond6. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '6'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'primary' in opts: bond.update({'primary': opts['primary']}) return bond def _parse_settings_vlan(opts, iface): ''' Filters given options and outputs valid settings for a vlan ''' vlan = {} if 'reorder_hdr' in opts: if opts['reorder_hdr'] in _CONFIG_TRUE + _CONFIG_FALSE: vlan.update({'reorder_hdr': opts['reorder_hdr']}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'reorder_hdr', valid) if 'vlan_id' in opts: if opts['vlan_id'] > 0: vlan.update({'vlan_id': opts['vlan_id']}) else: _raise_error_iface(iface, 'vlan_id', 'Positive integer') if 'phys_dev' in opts: if opts['phys_dev']: vlan.update({'phys_dev': opts['phys_dev']}) else: _raise_error_iface(iface, 'phys_dev', 'Non-empty string') return vlan def _parse_settings_eth(opts, iface_type, enabled, iface): ''' Filters given options and outputs valid settings for a network interface. ''' result = {'name': iface} if 'proto' in opts: valid = ['none', 'bootp', 'dhcp'] if opts['proto'] in valid: result['proto'] = opts['proto'] else: _raise_error_iface(iface, opts['proto'], valid) if 'dns' in opts: result['dns'] = opts['dns'] result['peerdns'] = 'yes' if 'mtu' in opts: try: result['mtu'] = int(opts['mtu']) except ValueError: _raise_error_iface(iface, 'mtu', ['integer']) if iface_type not in ['bridge']: ethtool = _parse_ethtool_opts(opts, iface) if ethtool: result['ethtool'] = ethtool if iface_type == 'slave': result['proto'] = 'none' if iface_type == 'bond': bonding = _parse_settings_bond(opts, iface) if bonding: result['bonding'] = bonding result['devtype'] = "Bond" if iface_type == 'vlan': vlan = _parse_settings_vlan(opts, iface) if vlan: result['devtype'] = "Vlan" for opt in vlan: result[opt] = opts[opt] if iface_type not in ['bond', 'vlan', 'bridge', 'ipip']: auto_addr = False if 'addr' in opts: if salt.utils.validate.net.mac(opts['addr']): result['addr'] = opts['addr'] elif opts['addr'] == 'auto': auto_addr = True elif opts['addr'] != 'none': _raise_error_iface(iface, opts['addr'], ['AA:BB:CC:DD:EE:FF', 'auto', 'none']) else: auto_addr = True if auto_addr: # If interface type is slave for bond, not setting hwaddr if iface_type != 'slave': ifaces = __salt__['network.interfaces']() if iface in ifaces and 'hwaddr' in ifaces[iface]: result['addr'] = ifaces[iface]['hwaddr'] if iface_type == 'eth': result['devtype'] = 'Ethernet' if iface_type == 'bridge': result['devtype'] = 'Bridge' bypassfirewall = True valid = _CONFIG_TRUE + _CONFIG_FALSE for opt in ['bypassfirewall']: if opt in opts: if opts[opt] in _CONFIG_TRUE: bypassfirewall = True elif opts[opt] in _CONFIG_FALSE: bypassfirewall = False else: _raise_error_iface(iface, opts[opt], valid) bridgectls = [ 'net.bridge.bridge-nf-call-ip6tables', 'net.bridge.bridge-nf-call-iptables', 'net.bridge.bridge-nf-call-arptables', ] if bypassfirewall: sysctl_value = 0 else: sysctl_value = 1 for sysctl in bridgectls: try: __salt__['sysctl.persist'](sysctl, sysctl_value) except CommandExecutionError: log.warning('Failed to set sysctl: %s', sysctl) else: if 'bridge' in opts: result['bridge'] = opts['bridge'] if iface_type == 'ipip': result['devtype'] = 'IPIP' for opt in ['my_inner_ipaddr', 'my_outer_ipaddr']: if opt not in opts: _raise_error_iface(iface, opts[opt], ['1.2.3.4']) else: result[opt] = opts[opt] if iface_type == 'ib': result['devtype'] = 'InfiniBand' if 'prefix' in opts: if 'netmask' in opts: msg = 'Cannot use prefix and netmask together' log.error(msg) raise AttributeError(msg) result['prefix'] = opts['prefix'] elif 'netmask' in opts: result['netmask'] = opts['netmask'] for opt in ['ipaddr', 'master', 'srcaddr', 'delay', 'domain', 'gateway', 'uuid', 'nickname', 'zone']: if opt in opts: result[opt] = opts[opt] for opt in ['ipv6addr', 'ipv6gateway']: if opt in opts: result[opt] = opts[opt] if 'ipaddrs' in opts: result['ipaddrs'] = [] for opt in opts['ipaddrs']: if salt.utils.validate.net.ipv4_addr(opt): ip, prefix = [i.strip() for i in opt.split('/')] result['ipaddrs'].append({'ipaddr': ip, 'prefix': prefix}) else: msg = 'ipv4 CIDR is invalid' log.error(msg) raise AttributeError(msg) if 'ipv6addrs' in opts: for opt in opts['ipv6addrs']: if not salt.utils.validate.net.ipv6_addr(opt): msg = 'ipv6 CIDR is invalid' log.error(msg) raise AttributeError(msg) result['ipv6addrs'] = opts['ipv6addrs'] if 'enable_ipv6' in opts: result['enable_ipv6'] = opts['enable_ipv6'] valid = _CONFIG_TRUE + _CONFIG_FALSE for opt in ['onparent', 'peerdns', 'peerroutes', 'slave', 'vlan', 'defroute', 'stp', 'ipv6_peerdns', 'ipv6_defroute', 'ipv6_peerroutes', 'ipv6_autoconf', 'ipv4_failure_fatal', 'dhcpv6c']: if opt in opts: if opts[opt] in _CONFIG_TRUE: result[opt] = 'yes' elif opts[opt] in _CONFIG_FALSE: result[opt] = 'no' else: _raise_error_iface(iface, opts[opt], valid) if 'onboot' in opts: log.warning( 'The \'onboot\' option is controlled by the \'enabled\' option. ' 'Interface: %s Enabled: %s', iface, enabled ) if enabled: result['onboot'] = 'yes' else: result['onboot'] = 'no' # If the interface is defined then we want to always take # control away from non-root users; unless the administrator # wants to allow non-root users to control the device. if 'userctl' in opts: if opts['userctl'] in _CONFIG_TRUE: result['userctl'] = 'yes' elif opts['userctl'] in _CONFIG_FALSE: result['userctl'] = 'no' else: _raise_error_iface(iface, opts['userctl'], valid) else: result['userctl'] = 'no' # This vlan is in opts, and should be only used in range interface # will affect jinja template for interface generating if 'vlan' in opts: if opts['vlan'] in _CONFIG_TRUE: result['vlan'] = 'yes' elif opts['vlan'] in _CONFIG_FALSE: result['vlan'] = 'no' else: _raise_error_iface(iface, opts['vlan'], valid) if 'arpcheck' in opts: if opts['arpcheck'] in _CONFIG_FALSE: result['arpcheck'] = 'no' if 'ipaddr_start' in opts: result['ipaddr_start'] = opts['ipaddr_start'] if 'ipaddr_end' in opts: result['ipaddr_end'] = opts['ipaddr_end'] if 'clonenum_start' in opts: result['clonenum_start'] = opts['clonenum_start'] # If NetworkManager is available, we can control whether we use # it or not if 'nm_controlled' in opts: if opts['nm_controlled'] in _CONFIG_TRUE: result['nm_controlled'] = 'yes' elif opts['nm_controlled'] in _CONFIG_FALSE: result['nm_controlled'] = 'no' else: _raise_error_iface(iface, opts['nm_controlled'], valid) else: result['nm_controlled'] = 'no' return result def _parse_routes(iface, opts): ''' Filters given options and outputs valid settings for the route settings file. ''' # Normalize keys opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts)) result = {} if 'routes' not in opts: _raise_error_routes(iface, 'routes', 'List of routes') for opt in opts: result[opt] = opts[opt] return result def _parse_network_settings(opts, current): ''' Filters given options and outputs valid settings for the global network settings file. ''' # Normalize keys opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts)) current = dict((k.lower(), v) for (k, v) in six.iteritems(current)) # Check for supported parameters retain_settings = opts.get('retain_settings', False) result = current if retain_settings else {} # Default quote type is an empty string, which will not quote values quote_type = '' valid = _CONFIG_TRUE + _CONFIG_FALSE if 'enabled' not in opts: try: opts['networking'] = current['networking'] # If networking option is quoted, use its quote type quote_type = salt.utils.stringutils.is_quoted(opts['networking']) _log_default_network('networking', current['networking']) except ValueError: _raise_error_network('networking', valid) else: opts['networking'] = opts['enabled'] true_val = '{0}yes{0}'.format(quote_type) false_val = '{0}no{0}'.format(quote_type) networking = salt.utils.stringutils.dequote(opts['networking']) if networking in valid: if networking in _CONFIG_TRUE: result['networking'] = true_val elif networking in _CONFIG_FALSE: result['networking'] = false_val else: _raise_error_network('networking', valid) if 'hostname' not in opts: try: opts['hostname'] = current['hostname'] _log_default_network('hostname', current['hostname']) except Exception: _raise_error_network('hostname', ['server1.example.com']) if opts['hostname']: result['hostname'] = '{1}{0}{1}'.format( salt.utils.stringutils.dequote(opts['hostname']), quote_type) else: _raise_error_network('hostname', ['server1.example.com']) if 'nozeroconf' in opts: nozeroconf = salt.utils.stringutils.dequote(opts['nozeroconf']) if nozeroconf in valid: if nozeroconf in _CONFIG_TRUE: result['nozeroconf'] = true_val elif nozeroconf in _CONFIG_FALSE: result['nozeroconf'] = false_val else: _raise_error_network('nozeroconf', valid) for opt in opts: if opt not in ['networking', 'hostname', 'nozeroconf']: result[opt] = '{1}{0}{1}'.format( salt.utils.stringutils.dequote(opts[opt]), quote_type) return result def _raise_error_iface(iface, option, expected): ''' Log and raise an error with a logical formatted message. ''' msg = _error_msg_iface(iface, option, expected) log.error(msg) raise AttributeError(msg) def _raise_error_network(option, expected): ''' Log and raise an error with a logical formatted message. ''' msg = _error_msg_network(option, expected) log.error(msg) raise AttributeError(msg) def _raise_error_routes(iface, option, expected): ''' Log and raise an error with a logical formatted message. ''' msg = _error_msg_routes(iface, option, expected) log.error(msg) raise AttributeError(msg) def _read_file(path): ''' Reads and returns the contents of a file ''' try: with salt.utils.files.fopen(path, 'rb') as rfh: lines = salt.utils.stringutils.to_unicode(rfh.read()).splitlines() try: lines.remove('') except ValueError: pass return lines except Exception: return [] # Return empty list for type consistency def _write_file_iface(iface, data, folder, pattern): ''' Writes a file to disk ''' filename = os.path.join(folder, pattern.format(iface)) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist' msg = msg.format(filename, folder) log.error(msg) raise AttributeError(msg) with salt.utils.files.fopen(filename, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) def _write_file_network(data, filename): ''' Writes a file to disk ''' with salt.utils.files.fopen(filename, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) def _read_temp(data): lines = data.splitlines() try: # Discard newlines if they exist lines.remove('') except ValueError: pass return lines def build_bond(iface, **settings): ''' Create a bond script in /etc/modprobe.d with the passed settings and load the bonding kernel module. CLI Example: .. code-block:: bash salt '*' ip.build_bond bond0 mode=balance-alb ''' rh_major = __grains__['osrelease'][:1] opts = _parse_settings_bond(settings, iface) try: template = JINJA.get_template('conf.jinja') except jinja2.exceptions.TemplateNotFound: log.error('Could not load template conf.jinja') return '' data = template.render({'name': iface, 'bonding': opts}) _write_file_iface(iface, data, _RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface)) path = os.path.join(_RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface)) if rh_major == '5': __salt__['cmd.run']( 'sed -i -e "/^alias\\s{0}.*/d" /etc/modprobe.conf'.format(iface), python_shell=False ) __salt__['cmd.run']( 'sed -i -e "/^options\\s{0}.*/d" /etc/modprobe.conf'.format(iface), python_shell=False ) __salt__['file.append']('/etc/modprobe.conf', path) __salt__['kmod.load']('bonding') if settings['test']: return _read_temp(data) return _read_file(path) def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['os'] == 'Fedora': if __grains__['osmajorrelease'] >= 18: rh_major = '7' else: rh_major = '6' else: rh_major = __grains__['osrelease'][:1] iface_type = iface_type.lower() if iface_type not in _IFACE_TYPES: _raise_error_iface(iface, iface_type, _IFACE_TYPES) if iface_type == 'slave': settings['slave'] = 'yes' if 'master' not in settings: msg = 'master is a required setting for slave interfaces' log.error(msg) raise AttributeError(msg) if iface_type == 'vlan': settings['vlan'] = 'yes' if iface_type == 'bridge': __salt__['pkg.install']('bridge-utils') if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'ipip', 'ib', 'alias']: opts = _parse_settings_eth(settings, iface_type, enabled, iface) try: template = JINJA.get_template('rh{0}_eth.jinja'.format(rh_major)) except jinja2.exceptions.TemplateNotFound: log.error( 'Could not load template rh%s_eth.jinja', rh_major ) return '' ifcfg = template.render(opts) if 'test' in settings and settings['test']: return _read_temp(ifcfg) _write_file_iface(iface, ifcfg, _RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}') path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface)) return _read_file(path) def build_routes(iface, **settings): ''' Build a route script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_routes eth0 <settings> ''' template = 'rh6_route_eth.jinja' try: if int(__grains__['osrelease'][0]) < 6: template = 'route_eth.jinja' except ValueError: pass log.debug('Template name: %s', template) opts = _parse_routes(iface, settings) log.debug('Opts: \n %s', opts) try: template = JINJA.get_template(template) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', template) return '' opts6 = [] opts4 = [] for route in opts['routes']: ipaddr = route['ipaddr'] if salt.utils.validate.net.ipv6_addr(ipaddr): opts6.append(route) else: opts4.append(route) log.debug("IPv4 routes:\n%s", opts4) log.debug("IPv6 routes:\n%s", opts6) routecfg = template.render(routes=opts4, iface=iface) routecfg6 = template.render(routes=opts6, iface=iface) if settings['test']: routes = _read_temp(routecfg) routes.extend(_read_temp(routecfg6)) return routes _write_file_iface(iface, routecfg, _RH_NETWORK_SCRIPT_DIR, 'route-{0}') _write_file_iface(iface, routecfg6, _RH_NETWORK_SCRIPT_DIR, 'route6-{0}') path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route-{0}'.format(iface)) path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route6-{0}'.format(iface)) routes = _read_file(path) routes.extend(_read_file(path6)) return routes def down(iface, iface_type): ''' Shutdown a network interface CLI Example: .. code-block:: bash salt '*' ip.down eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ifdown {0}'.format(iface)) return None def get_bond(iface): ''' Return the content of a bond script CLI Example: .. code-block:: bash salt '*' ip.get_bond bond0 ''' path = os.path.join(_RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface)) return _read_file(path) def get_interface(iface): ''' Return the contents of an interface script CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface)) return _read_file(path) def up(iface, iface_type): # pylint: disable=C0103 ''' Start up a network interface CLI Example: .. code-block:: bash salt '*' ip.up eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ifup {0}'.format(iface)) return None def get_routes(iface): ''' Return the contents of the interface routes script. CLI Example: .. code-block:: bash salt '*' ip.get_routes eth0 ''' path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route-{0}'.format(iface)) path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route6-{0}'.format(iface)) routes = _read_file(path) routes.extend(_read_file(path6)) return routes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' return _read_file(_RH_NETWORK_FILE) def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: res = __salt__['service.restart']('network') return hostname_res and res def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' # Read current configuration and store default values current_network_settings = _parse_rh_config(_RH_NETWORK_FILE) # Build settings opts = _parse_network_settings(settings, current_network_settings) try: template = JINJA.get_template('network.jinja') except jinja2.exceptions.TemplateNotFound: log.error('Could not load template network.jinja') return '' network = template.render(opts) if settings['test']: return _read_temp(network) # Write settings _write_file_network(network, _RH_NETWORK_FILE) return _read_file(_RH_NETWORK_FILE)
saltstack/salt
salt/modules/rh_ip.py
_parse_settings_vlan
python
def _parse_settings_vlan(opts, iface): ''' Filters given options and outputs valid settings for a vlan ''' vlan = {} if 'reorder_hdr' in opts: if opts['reorder_hdr'] in _CONFIG_TRUE + _CONFIG_FALSE: vlan.update({'reorder_hdr': opts['reorder_hdr']}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'reorder_hdr', valid) if 'vlan_id' in opts: if opts['vlan_id'] > 0: vlan.update({'vlan_id': opts['vlan_id']}) else: _raise_error_iface(iface, 'vlan_id', 'Positive integer') if 'phys_dev' in opts: if opts['phys_dev']: vlan.update({'phys_dev': opts['phys_dev']}) else: _raise_error_iface(iface, 'phys_dev', 'Non-empty string') return vlan
Filters given options and outputs valid settings for a vlan
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L571-L596
null
# -*- coding: utf-8 -*- ''' The networking module for RHEL/Fedora based distros ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging import os.path import os # Import third party libs import jinja2 import jinja2.exceptions # Import salt libs import salt.utils.files import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net from salt.exceptions import CommandExecutionError from salt.ext import six # Set up logging log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'rh_ip') ) ) # Define the module's virtual name __virtualname__ = 'ip' def __virtual__(): ''' Confine this module to RHEL/Fedora based distros ''' if __grains__['os_family'] == 'RedHat': return __virtualname__ return (False, 'The rh_ip execution module cannot be loaded: this module is only available on RHEL/Fedora based distributions.') # Setup networking attributes _ETHTOOL_CONFIG_OPTS = [ 'autoneg', 'speed', 'duplex', 'rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro', 'advertise' ] _RH_CONFIG_OPTS = [ 'domain', 'peerdns', 'peerntp', 'defroute', 'mtu', 'static-routes', 'gateway', 'zone' ] _RH_CONFIG_BONDING_OPTS = [ 'mode', 'miimon', 'arp_interval', 'arp_ip_target', 'downdelay', 'updelay', 'use_carrier', 'lacp_rate', 'hashing-algorithm', 'max_bonds', 'tx_queues', 'num_grat_arp', 'num_unsol_na', 'primary', 'primary_reselect', 'ad_select', 'xmit_hash_policy', 'arp_validate', 'fail_over_mac', 'all_slaves_active', 'resend_igmp' ] _RH_NETWORK_SCRIPT_DIR = '/etc/sysconfig/network-scripts' _RH_NETWORK_FILE = '/etc/sysconfig/network' _RH_NETWORK_CONF_FILES = '/etc/modprobe.d' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] _CONFIG_FALSE = ['no', 'off', 'false', '0', False] _IFACE_TYPES = [ 'eth', 'bond', 'alias', 'clone', 'ipsec', 'dialup', 'bridge', 'slave', 'vlan', 'ipip', 'ib', ] def _error_msg_iface(iface, option, expected): ''' Build an appropriate error message from a given option and a list of expected values. ''' msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]' return msg.format(iface, option, '|'.join(str(e) for e in expected)) def _error_msg_routes(iface, option, expected): ''' Build an appropriate error message from a given option and a list of expected values. ''' msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]' return msg.format(iface, option, expected) def _log_default_iface(iface, opt, value): log.info('Using default option -- Interface: %s Option: %s Value: %s', iface, opt, value) def _error_msg_network(option, expected): ''' Build an appropriate error message from a given option and a list of expected values. ''' msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]' return msg.format(option, '|'.join(str(e) for e in expected)) def _log_default_network(opt, value): log.info('Using existing setting -- Setting: %s Value: %s', opt, value) def _parse_rh_config(path): rh_config = _read_file(path) cv_rh_config = {} if rh_config: for line in rh_config: line = line.strip() if not line or line.startswith('!') or line.startswith('#'): continue pair = [p.rstrip() for p in line.split('=', 1)] if len(pair) != 2: continue name, value = pair cv_rh_config[name.upper()] = value return cv_rh_config def _parse_ethtool_opts(opts, iface): ''' Filters given options and outputs valid settings for ETHTOOLS_OPTS If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' config = {} if 'autoneg' in opts: if opts['autoneg'] in _CONFIG_TRUE: config.update({'autoneg': 'on'}) elif opts['autoneg'] in _CONFIG_FALSE: config.update({'autoneg': 'off'}) else: _raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE) if 'duplex' in opts: valid = ['full', 'half'] if opts['duplex'] in valid: config.update({'duplex': opts['duplex']}) else: _raise_error_iface(iface, 'duplex', valid) if 'speed' in opts: valid = ['10', '100', '1000', '10000'] if six.text_type(opts['speed']) in valid: config.update({'speed': opts['speed']}) else: _raise_error_iface(iface, opts['speed'], valid) if 'advertise' in opts: valid = [ '0x001', '0x002', '0x004', '0x008', '0x010', '0x020', '0x20000', '0x8000', '0x1000', '0x40000', '0x80000', '0x200000', '0x400000', '0x800000', '0x1000000', '0x2000000', '0x4000000' ] if six.text_type(opts['advertise']) in valid: config.update({'advertise': opts['advertise']}) else: _raise_error_iface(iface, 'advertise', valid) valid = _CONFIG_TRUE + _CONFIG_FALSE for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'): if option in opts: if opts[option] in _CONFIG_TRUE: config.update({option: 'on'}) elif opts[option] in _CONFIG_FALSE: config.update({option: 'off'}) else: _raise_error_iface(iface, option, valid) return config def _parse_settings_bond(opts, iface): ''' Filters given options and outputs valid settings for requested operation. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond_def = { # 803.ad aggregation selection logic # 0 for stable (default) # 1 for bandwidth # 2 for count 'ad_select': '0', # Max number of transmit queues (default = 16) 'tx_queues': '16', # Link monitoring in milliseconds. Most NICs support this 'miimon': '100', # ARP interval in milliseconds 'arp_interval': '250', # Delay before considering link down in milliseconds (miimon * 2) 'downdelay': '200', # lacp_rate 0: Slow - every 30 seconds # lacp_rate 1: Fast - every 1 second 'lacp_rate': '0', # Max bonds for this driver 'max_bonds': '1', # Specifies the time, in milliseconds, to wait before # enabling a slave after a link recovery has been # detected. Only used with miimon. 'updelay': '0', # Used with miimon. # On: driver sends mii # Off: ethtool sends mii 'use_carrier': '0', # Default. Don't change unless you know what you are doing. 'xmit_hash_policy': 'layer2', } if opts['mode'] in ['balance-rr', '0']: log.info( 'Device: %s Bonding Mode: load balancing (round-robin)', iface ) return _parse_settings_bond_0(opts, iface, bond_def) elif opts['mode'] in ['active-backup', '1']: log.info( 'Device: %s Bonding Mode: fault-tolerance (active-backup)', iface ) return _parse_settings_bond_1(opts, iface, bond_def) elif opts['mode'] in ['balance-xor', '2']: log.info( 'Device: %s Bonding Mode: load balancing (xor)', iface ) return _parse_settings_bond_2(opts, iface, bond_def) elif opts['mode'] in ['broadcast', '3']: log.info( 'Device: %s Bonding Mode: fault-tolerance (broadcast)', iface ) return _parse_settings_bond_3(opts, iface, bond_def) elif opts['mode'] in ['802.3ad', '4']: log.info( 'Device: %s Bonding Mode: IEEE 802.3ad Dynamic link ' 'aggregation', iface ) return _parse_settings_bond_4(opts, iface, bond_def) elif opts['mode'] in ['balance-tlb', '5']: log.info( 'Device: %s Bonding Mode: transmit load balancing', iface ) return _parse_settings_bond_5(opts, iface, bond_def) elif opts['mode'] in ['balance-alb', '6']: log.info( 'Device: %s Bonding Mode: adaptive load balancing', iface ) return _parse_settings_bond_6(opts, iface, bond_def) else: valid = [ '0', '1', '2', '3', '4', '5', '6', 'balance-rr', 'active-backup', 'balance-xor', 'broadcast', '802.3ad', 'balance-tlb', 'balance-alb' ] _raise_error_iface(iface, 'mode', valid) def _parse_settings_bond_0(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond0. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' # balance-rr shares miimon settings with balance-xor bond = _parse_settings_bond_1(opts, iface, bond_def) bond.update({'mode': '0'}) # ARP targets in n.n.n.n form valid = ['list of ips (up to 16)'] if 'arp_ip_target' in opts: if isinstance(opts['arp_ip_target'], list): if 1 <= len(opts['arp_ip_target']) <= 16: bond.update({'arp_ip_target': ''}) for ip in opts['arp_ip_target']: # pylint: disable=C0103 if bond['arp_ip_target']: bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip else: bond['arp_ip_target'] = ip else: _raise_error_iface(iface, 'arp_ip_target', valid) else: _raise_error_iface(iface, 'arp_ip_target', valid) elif 'miimon' not in opts: _raise_error_iface(iface, 'arp_ip_target', valid) if 'arp_interval' in opts: try: int(opts['arp_interval']) bond.update({'arp_interval': opts['arp_interval']}) except Exception: _raise_error_iface(iface, 'arp_interval', ['integer']) else: _log_default_iface(iface, 'arp_interval', bond_def['arp_interval']) bond.update({'arp_interval': bond_def['arp_interval']}) return bond def _parse_settings_bond_1(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond1. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '1'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'primary' in opts: bond.update({'primary': opts['primary']}) return bond def _parse_settings_bond_2(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond2. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '2'} valid = ['list of ips (up to 16)'] if 'arp_ip_target' in opts: if isinstance(opts['arp_ip_target'], list): if 1 <= len(opts['arp_ip_target']) <= 16: bond.update({'arp_ip_target': ''}) for ip in opts['arp_ip_target']: # pylint: disable=C0103 if bond['arp_ip_target']: bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip else: bond['arp_ip_target'] = ip else: _raise_error_iface(iface, 'arp_ip_target', valid) else: _raise_error_iface(iface, 'arp_ip_target', valid) else: _raise_error_iface(iface, 'arp_ip_target', valid) if 'arp_interval' in opts: try: int(opts['arp_interval']) bond.update({'arp_interval': opts['arp_interval']}) except Exception: _raise_error_iface(iface, 'arp_interval', ['integer']) else: _log_default_iface(iface, 'arp_interval', bond_def['arp_interval']) bond.update({'arp_interval': bond_def['arp_interval']}) if 'hashing-algorithm' in opts: valid = ['layer2', 'layer2+3', 'layer3+4'] if opts['hashing-algorithm'] in valid: bond.update({'xmit_hash_policy': opts['hashing-algorithm']}) else: _raise_error_iface(iface, 'hashing-algorithm', valid) return bond def _parse_settings_bond_3(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond3. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '3'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) return bond def _parse_settings_bond_4(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond4. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '4'} for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']: if binding in opts: if binding == 'lacp_rate': if opts[binding] == 'fast': opts.update({binding: '1'}) if opts[binding] == 'slow': opts.update({binding: '0'}) valid = ['fast', '1', 'slow', '0'] else: valid = ['integer'] try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, valid) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'hashing-algorithm' in opts: valid = ['layer2', 'layer2+3', 'layer3+4'] if opts['hashing-algorithm'] in valid: bond.update({'xmit_hash_policy': opts['hashing-algorithm']}) else: _raise_error_iface(iface, 'hashing-algorithm', valid) return bond def _parse_settings_bond_5(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond5. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '5'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'primary' in opts: bond.update({'primary': opts['primary']}) return bond def _parse_settings_bond_6(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond6. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '6'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'primary' in opts: bond.update({'primary': opts['primary']}) return bond def _parse_settings_eth(opts, iface_type, enabled, iface): ''' Filters given options and outputs valid settings for a network interface. ''' result = {'name': iface} if 'proto' in opts: valid = ['none', 'bootp', 'dhcp'] if opts['proto'] in valid: result['proto'] = opts['proto'] else: _raise_error_iface(iface, opts['proto'], valid) if 'dns' in opts: result['dns'] = opts['dns'] result['peerdns'] = 'yes' if 'mtu' in opts: try: result['mtu'] = int(opts['mtu']) except ValueError: _raise_error_iface(iface, 'mtu', ['integer']) if iface_type not in ['bridge']: ethtool = _parse_ethtool_opts(opts, iface) if ethtool: result['ethtool'] = ethtool if iface_type == 'slave': result['proto'] = 'none' if iface_type == 'bond': bonding = _parse_settings_bond(opts, iface) if bonding: result['bonding'] = bonding result['devtype'] = "Bond" if iface_type == 'vlan': vlan = _parse_settings_vlan(opts, iface) if vlan: result['devtype'] = "Vlan" for opt in vlan: result[opt] = opts[opt] if iface_type not in ['bond', 'vlan', 'bridge', 'ipip']: auto_addr = False if 'addr' in opts: if salt.utils.validate.net.mac(opts['addr']): result['addr'] = opts['addr'] elif opts['addr'] == 'auto': auto_addr = True elif opts['addr'] != 'none': _raise_error_iface(iface, opts['addr'], ['AA:BB:CC:DD:EE:FF', 'auto', 'none']) else: auto_addr = True if auto_addr: # If interface type is slave for bond, not setting hwaddr if iface_type != 'slave': ifaces = __salt__['network.interfaces']() if iface in ifaces and 'hwaddr' in ifaces[iface]: result['addr'] = ifaces[iface]['hwaddr'] if iface_type == 'eth': result['devtype'] = 'Ethernet' if iface_type == 'bridge': result['devtype'] = 'Bridge' bypassfirewall = True valid = _CONFIG_TRUE + _CONFIG_FALSE for opt in ['bypassfirewall']: if opt in opts: if opts[opt] in _CONFIG_TRUE: bypassfirewall = True elif opts[opt] in _CONFIG_FALSE: bypassfirewall = False else: _raise_error_iface(iface, opts[opt], valid) bridgectls = [ 'net.bridge.bridge-nf-call-ip6tables', 'net.bridge.bridge-nf-call-iptables', 'net.bridge.bridge-nf-call-arptables', ] if bypassfirewall: sysctl_value = 0 else: sysctl_value = 1 for sysctl in bridgectls: try: __salt__['sysctl.persist'](sysctl, sysctl_value) except CommandExecutionError: log.warning('Failed to set sysctl: %s', sysctl) else: if 'bridge' in opts: result['bridge'] = opts['bridge'] if iface_type == 'ipip': result['devtype'] = 'IPIP' for opt in ['my_inner_ipaddr', 'my_outer_ipaddr']: if opt not in opts: _raise_error_iface(iface, opts[opt], ['1.2.3.4']) else: result[opt] = opts[opt] if iface_type == 'ib': result['devtype'] = 'InfiniBand' if 'prefix' in opts: if 'netmask' in opts: msg = 'Cannot use prefix and netmask together' log.error(msg) raise AttributeError(msg) result['prefix'] = opts['prefix'] elif 'netmask' in opts: result['netmask'] = opts['netmask'] for opt in ['ipaddr', 'master', 'srcaddr', 'delay', 'domain', 'gateway', 'uuid', 'nickname', 'zone']: if opt in opts: result[opt] = opts[opt] for opt in ['ipv6addr', 'ipv6gateway']: if opt in opts: result[opt] = opts[opt] if 'ipaddrs' in opts: result['ipaddrs'] = [] for opt in opts['ipaddrs']: if salt.utils.validate.net.ipv4_addr(opt): ip, prefix = [i.strip() for i in opt.split('/')] result['ipaddrs'].append({'ipaddr': ip, 'prefix': prefix}) else: msg = 'ipv4 CIDR is invalid' log.error(msg) raise AttributeError(msg) if 'ipv6addrs' in opts: for opt in opts['ipv6addrs']: if not salt.utils.validate.net.ipv6_addr(opt): msg = 'ipv6 CIDR is invalid' log.error(msg) raise AttributeError(msg) result['ipv6addrs'] = opts['ipv6addrs'] if 'enable_ipv6' in opts: result['enable_ipv6'] = opts['enable_ipv6'] valid = _CONFIG_TRUE + _CONFIG_FALSE for opt in ['onparent', 'peerdns', 'peerroutes', 'slave', 'vlan', 'defroute', 'stp', 'ipv6_peerdns', 'ipv6_defroute', 'ipv6_peerroutes', 'ipv6_autoconf', 'ipv4_failure_fatal', 'dhcpv6c']: if opt in opts: if opts[opt] in _CONFIG_TRUE: result[opt] = 'yes' elif opts[opt] in _CONFIG_FALSE: result[opt] = 'no' else: _raise_error_iface(iface, opts[opt], valid) if 'onboot' in opts: log.warning( 'The \'onboot\' option is controlled by the \'enabled\' option. ' 'Interface: %s Enabled: %s', iface, enabled ) if enabled: result['onboot'] = 'yes' else: result['onboot'] = 'no' # If the interface is defined then we want to always take # control away from non-root users; unless the administrator # wants to allow non-root users to control the device. if 'userctl' in opts: if opts['userctl'] in _CONFIG_TRUE: result['userctl'] = 'yes' elif opts['userctl'] in _CONFIG_FALSE: result['userctl'] = 'no' else: _raise_error_iface(iface, opts['userctl'], valid) else: result['userctl'] = 'no' # This vlan is in opts, and should be only used in range interface # will affect jinja template for interface generating if 'vlan' in opts: if opts['vlan'] in _CONFIG_TRUE: result['vlan'] = 'yes' elif opts['vlan'] in _CONFIG_FALSE: result['vlan'] = 'no' else: _raise_error_iface(iface, opts['vlan'], valid) if 'arpcheck' in opts: if opts['arpcheck'] in _CONFIG_FALSE: result['arpcheck'] = 'no' if 'ipaddr_start' in opts: result['ipaddr_start'] = opts['ipaddr_start'] if 'ipaddr_end' in opts: result['ipaddr_end'] = opts['ipaddr_end'] if 'clonenum_start' in opts: result['clonenum_start'] = opts['clonenum_start'] # If NetworkManager is available, we can control whether we use # it or not if 'nm_controlled' in opts: if opts['nm_controlled'] in _CONFIG_TRUE: result['nm_controlled'] = 'yes' elif opts['nm_controlled'] in _CONFIG_FALSE: result['nm_controlled'] = 'no' else: _raise_error_iface(iface, opts['nm_controlled'], valid) else: result['nm_controlled'] = 'no' return result def _parse_routes(iface, opts): ''' Filters given options and outputs valid settings for the route settings file. ''' # Normalize keys opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts)) result = {} if 'routes' not in opts: _raise_error_routes(iface, 'routes', 'List of routes') for opt in opts: result[opt] = opts[opt] return result def _parse_network_settings(opts, current): ''' Filters given options and outputs valid settings for the global network settings file. ''' # Normalize keys opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts)) current = dict((k.lower(), v) for (k, v) in six.iteritems(current)) # Check for supported parameters retain_settings = opts.get('retain_settings', False) result = current if retain_settings else {} # Default quote type is an empty string, which will not quote values quote_type = '' valid = _CONFIG_TRUE + _CONFIG_FALSE if 'enabled' not in opts: try: opts['networking'] = current['networking'] # If networking option is quoted, use its quote type quote_type = salt.utils.stringutils.is_quoted(opts['networking']) _log_default_network('networking', current['networking']) except ValueError: _raise_error_network('networking', valid) else: opts['networking'] = opts['enabled'] true_val = '{0}yes{0}'.format(quote_type) false_val = '{0}no{0}'.format(quote_type) networking = salt.utils.stringutils.dequote(opts['networking']) if networking in valid: if networking in _CONFIG_TRUE: result['networking'] = true_val elif networking in _CONFIG_FALSE: result['networking'] = false_val else: _raise_error_network('networking', valid) if 'hostname' not in opts: try: opts['hostname'] = current['hostname'] _log_default_network('hostname', current['hostname']) except Exception: _raise_error_network('hostname', ['server1.example.com']) if opts['hostname']: result['hostname'] = '{1}{0}{1}'.format( salt.utils.stringutils.dequote(opts['hostname']), quote_type) else: _raise_error_network('hostname', ['server1.example.com']) if 'nozeroconf' in opts: nozeroconf = salt.utils.stringutils.dequote(opts['nozeroconf']) if nozeroconf in valid: if nozeroconf in _CONFIG_TRUE: result['nozeroconf'] = true_val elif nozeroconf in _CONFIG_FALSE: result['nozeroconf'] = false_val else: _raise_error_network('nozeroconf', valid) for opt in opts: if opt not in ['networking', 'hostname', 'nozeroconf']: result[opt] = '{1}{0}{1}'.format( salt.utils.stringutils.dequote(opts[opt]), quote_type) return result def _raise_error_iface(iface, option, expected): ''' Log and raise an error with a logical formatted message. ''' msg = _error_msg_iface(iface, option, expected) log.error(msg) raise AttributeError(msg) def _raise_error_network(option, expected): ''' Log and raise an error with a logical formatted message. ''' msg = _error_msg_network(option, expected) log.error(msg) raise AttributeError(msg) def _raise_error_routes(iface, option, expected): ''' Log and raise an error with a logical formatted message. ''' msg = _error_msg_routes(iface, option, expected) log.error(msg) raise AttributeError(msg) def _read_file(path): ''' Reads and returns the contents of a file ''' try: with salt.utils.files.fopen(path, 'rb') as rfh: lines = salt.utils.stringutils.to_unicode(rfh.read()).splitlines() try: lines.remove('') except ValueError: pass return lines except Exception: return [] # Return empty list for type consistency def _write_file_iface(iface, data, folder, pattern): ''' Writes a file to disk ''' filename = os.path.join(folder, pattern.format(iface)) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist' msg = msg.format(filename, folder) log.error(msg) raise AttributeError(msg) with salt.utils.files.fopen(filename, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) def _write_file_network(data, filename): ''' Writes a file to disk ''' with salt.utils.files.fopen(filename, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) def _read_temp(data): lines = data.splitlines() try: # Discard newlines if they exist lines.remove('') except ValueError: pass return lines def build_bond(iface, **settings): ''' Create a bond script in /etc/modprobe.d with the passed settings and load the bonding kernel module. CLI Example: .. code-block:: bash salt '*' ip.build_bond bond0 mode=balance-alb ''' rh_major = __grains__['osrelease'][:1] opts = _parse_settings_bond(settings, iface) try: template = JINJA.get_template('conf.jinja') except jinja2.exceptions.TemplateNotFound: log.error('Could not load template conf.jinja') return '' data = template.render({'name': iface, 'bonding': opts}) _write_file_iface(iface, data, _RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface)) path = os.path.join(_RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface)) if rh_major == '5': __salt__['cmd.run']( 'sed -i -e "/^alias\\s{0}.*/d" /etc/modprobe.conf'.format(iface), python_shell=False ) __salt__['cmd.run']( 'sed -i -e "/^options\\s{0}.*/d" /etc/modprobe.conf'.format(iface), python_shell=False ) __salt__['file.append']('/etc/modprobe.conf', path) __salt__['kmod.load']('bonding') if settings['test']: return _read_temp(data) return _read_file(path) def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['os'] == 'Fedora': if __grains__['osmajorrelease'] >= 18: rh_major = '7' else: rh_major = '6' else: rh_major = __grains__['osrelease'][:1] iface_type = iface_type.lower() if iface_type not in _IFACE_TYPES: _raise_error_iface(iface, iface_type, _IFACE_TYPES) if iface_type == 'slave': settings['slave'] = 'yes' if 'master' not in settings: msg = 'master is a required setting for slave interfaces' log.error(msg) raise AttributeError(msg) if iface_type == 'vlan': settings['vlan'] = 'yes' if iface_type == 'bridge': __salt__['pkg.install']('bridge-utils') if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'ipip', 'ib', 'alias']: opts = _parse_settings_eth(settings, iface_type, enabled, iface) try: template = JINJA.get_template('rh{0}_eth.jinja'.format(rh_major)) except jinja2.exceptions.TemplateNotFound: log.error( 'Could not load template rh%s_eth.jinja', rh_major ) return '' ifcfg = template.render(opts) if 'test' in settings and settings['test']: return _read_temp(ifcfg) _write_file_iface(iface, ifcfg, _RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}') path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface)) return _read_file(path) def build_routes(iface, **settings): ''' Build a route script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_routes eth0 <settings> ''' template = 'rh6_route_eth.jinja' try: if int(__grains__['osrelease'][0]) < 6: template = 'route_eth.jinja' except ValueError: pass log.debug('Template name: %s', template) opts = _parse_routes(iface, settings) log.debug('Opts: \n %s', opts) try: template = JINJA.get_template(template) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', template) return '' opts6 = [] opts4 = [] for route in opts['routes']: ipaddr = route['ipaddr'] if salt.utils.validate.net.ipv6_addr(ipaddr): opts6.append(route) else: opts4.append(route) log.debug("IPv4 routes:\n%s", opts4) log.debug("IPv6 routes:\n%s", opts6) routecfg = template.render(routes=opts4, iface=iface) routecfg6 = template.render(routes=opts6, iface=iface) if settings['test']: routes = _read_temp(routecfg) routes.extend(_read_temp(routecfg6)) return routes _write_file_iface(iface, routecfg, _RH_NETWORK_SCRIPT_DIR, 'route-{0}') _write_file_iface(iface, routecfg6, _RH_NETWORK_SCRIPT_DIR, 'route6-{0}') path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route-{0}'.format(iface)) path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route6-{0}'.format(iface)) routes = _read_file(path) routes.extend(_read_file(path6)) return routes def down(iface, iface_type): ''' Shutdown a network interface CLI Example: .. code-block:: bash salt '*' ip.down eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ifdown {0}'.format(iface)) return None def get_bond(iface): ''' Return the content of a bond script CLI Example: .. code-block:: bash salt '*' ip.get_bond bond0 ''' path = os.path.join(_RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface)) return _read_file(path) def get_interface(iface): ''' Return the contents of an interface script CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface)) return _read_file(path) def up(iface, iface_type): # pylint: disable=C0103 ''' Start up a network interface CLI Example: .. code-block:: bash salt '*' ip.up eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ifup {0}'.format(iface)) return None def get_routes(iface): ''' Return the contents of the interface routes script. CLI Example: .. code-block:: bash salt '*' ip.get_routes eth0 ''' path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route-{0}'.format(iface)) path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route6-{0}'.format(iface)) routes = _read_file(path) routes.extend(_read_file(path6)) return routes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' return _read_file(_RH_NETWORK_FILE) def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: res = __salt__['service.restart']('network') return hostname_res and res def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' # Read current configuration and store default values current_network_settings = _parse_rh_config(_RH_NETWORK_FILE) # Build settings opts = _parse_network_settings(settings, current_network_settings) try: template = JINJA.get_template('network.jinja') except jinja2.exceptions.TemplateNotFound: log.error('Could not load template network.jinja') return '' network = template.render(opts) if settings['test']: return _read_temp(network) # Write settings _write_file_network(network, _RH_NETWORK_FILE) return _read_file(_RH_NETWORK_FILE)
saltstack/salt
salt/modules/rh_ip.py
_parse_settings_eth
python
def _parse_settings_eth(opts, iface_type, enabled, iface): ''' Filters given options and outputs valid settings for a network interface. ''' result = {'name': iface} if 'proto' in opts: valid = ['none', 'bootp', 'dhcp'] if opts['proto'] in valid: result['proto'] = opts['proto'] else: _raise_error_iface(iface, opts['proto'], valid) if 'dns' in opts: result['dns'] = opts['dns'] result['peerdns'] = 'yes' if 'mtu' in opts: try: result['mtu'] = int(opts['mtu']) except ValueError: _raise_error_iface(iface, 'mtu', ['integer']) if iface_type not in ['bridge']: ethtool = _parse_ethtool_opts(opts, iface) if ethtool: result['ethtool'] = ethtool if iface_type == 'slave': result['proto'] = 'none' if iface_type == 'bond': bonding = _parse_settings_bond(opts, iface) if bonding: result['bonding'] = bonding result['devtype'] = "Bond" if iface_type == 'vlan': vlan = _parse_settings_vlan(opts, iface) if vlan: result['devtype'] = "Vlan" for opt in vlan: result[opt] = opts[opt] if iface_type not in ['bond', 'vlan', 'bridge', 'ipip']: auto_addr = False if 'addr' in opts: if salt.utils.validate.net.mac(opts['addr']): result['addr'] = opts['addr'] elif opts['addr'] == 'auto': auto_addr = True elif opts['addr'] != 'none': _raise_error_iface(iface, opts['addr'], ['AA:BB:CC:DD:EE:FF', 'auto', 'none']) else: auto_addr = True if auto_addr: # If interface type is slave for bond, not setting hwaddr if iface_type != 'slave': ifaces = __salt__['network.interfaces']() if iface in ifaces and 'hwaddr' in ifaces[iface]: result['addr'] = ifaces[iface]['hwaddr'] if iface_type == 'eth': result['devtype'] = 'Ethernet' if iface_type == 'bridge': result['devtype'] = 'Bridge' bypassfirewall = True valid = _CONFIG_TRUE + _CONFIG_FALSE for opt in ['bypassfirewall']: if opt in opts: if opts[opt] in _CONFIG_TRUE: bypassfirewall = True elif opts[opt] in _CONFIG_FALSE: bypassfirewall = False else: _raise_error_iface(iface, opts[opt], valid) bridgectls = [ 'net.bridge.bridge-nf-call-ip6tables', 'net.bridge.bridge-nf-call-iptables', 'net.bridge.bridge-nf-call-arptables', ] if bypassfirewall: sysctl_value = 0 else: sysctl_value = 1 for sysctl in bridgectls: try: __salt__['sysctl.persist'](sysctl, sysctl_value) except CommandExecutionError: log.warning('Failed to set sysctl: %s', sysctl) else: if 'bridge' in opts: result['bridge'] = opts['bridge'] if iface_type == 'ipip': result['devtype'] = 'IPIP' for opt in ['my_inner_ipaddr', 'my_outer_ipaddr']: if opt not in opts: _raise_error_iface(iface, opts[opt], ['1.2.3.4']) else: result[opt] = opts[opt] if iface_type == 'ib': result['devtype'] = 'InfiniBand' if 'prefix' in opts: if 'netmask' in opts: msg = 'Cannot use prefix and netmask together' log.error(msg) raise AttributeError(msg) result['prefix'] = opts['prefix'] elif 'netmask' in opts: result['netmask'] = opts['netmask'] for opt in ['ipaddr', 'master', 'srcaddr', 'delay', 'domain', 'gateway', 'uuid', 'nickname', 'zone']: if opt in opts: result[opt] = opts[opt] for opt in ['ipv6addr', 'ipv6gateway']: if opt in opts: result[opt] = opts[opt] if 'ipaddrs' in opts: result['ipaddrs'] = [] for opt in opts['ipaddrs']: if salt.utils.validate.net.ipv4_addr(opt): ip, prefix = [i.strip() for i in opt.split('/')] result['ipaddrs'].append({'ipaddr': ip, 'prefix': prefix}) else: msg = 'ipv4 CIDR is invalid' log.error(msg) raise AttributeError(msg) if 'ipv6addrs' in opts: for opt in opts['ipv6addrs']: if not salt.utils.validate.net.ipv6_addr(opt): msg = 'ipv6 CIDR is invalid' log.error(msg) raise AttributeError(msg) result['ipv6addrs'] = opts['ipv6addrs'] if 'enable_ipv6' in opts: result['enable_ipv6'] = opts['enable_ipv6'] valid = _CONFIG_TRUE + _CONFIG_FALSE for opt in ['onparent', 'peerdns', 'peerroutes', 'slave', 'vlan', 'defroute', 'stp', 'ipv6_peerdns', 'ipv6_defroute', 'ipv6_peerroutes', 'ipv6_autoconf', 'ipv4_failure_fatal', 'dhcpv6c']: if opt in opts: if opts[opt] in _CONFIG_TRUE: result[opt] = 'yes' elif opts[opt] in _CONFIG_FALSE: result[opt] = 'no' else: _raise_error_iface(iface, opts[opt], valid) if 'onboot' in opts: log.warning( 'The \'onboot\' option is controlled by the \'enabled\' option. ' 'Interface: %s Enabled: %s', iface, enabled ) if enabled: result['onboot'] = 'yes' else: result['onboot'] = 'no' # If the interface is defined then we want to always take # control away from non-root users; unless the administrator # wants to allow non-root users to control the device. if 'userctl' in opts: if opts['userctl'] in _CONFIG_TRUE: result['userctl'] = 'yes' elif opts['userctl'] in _CONFIG_FALSE: result['userctl'] = 'no' else: _raise_error_iface(iface, opts['userctl'], valid) else: result['userctl'] = 'no' # This vlan is in opts, and should be only used in range interface # will affect jinja template for interface generating if 'vlan' in opts: if opts['vlan'] in _CONFIG_TRUE: result['vlan'] = 'yes' elif opts['vlan'] in _CONFIG_FALSE: result['vlan'] = 'no' else: _raise_error_iface(iface, opts['vlan'], valid) if 'arpcheck' in opts: if opts['arpcheck'] in _CONFIG_FALSE: result['arpcheck'] = 'no' if 'ipaddr_start' in opts: result['ipaddr_start'] = opts['ipaddr_start'] if 'ipaddr_end' in opts: result['ipaddr_end'] = opts['ipaddr_end'] if 'clonenum_start' in opts: result['clonenum_start'] = opts['clonenum_start'] # If NetworkManager is available, we can control whether we use # it or not if 'nm_controlled' in opts: if opts['nm_controlled'] in _CONFIG_TRUE: result['nm_controlled'] = 'yes' elif opts['nm_controlled'] in _CONFIG_FALSE: result['nm_controlled'] = 'no' else: _raise_error_iface(iface, opts['nm_controlled'], valid) else: result['nm_controlled'] = 'no' return result
Filters given options and outputs valid settings for a network interface.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L599-L816
null
# -*- coding: utf-8 -*- ''' The networking module for RHEL/Fedora based distros ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging import os.path import os # Import third party libs import jinja2 import jinja2.exceptions # Import salt libs import salt.utils.files import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net from salt.exceptions import CommandExecutionError from salt.ext import six # Set up logging log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'rh_ip') ) ) # Define the module's virtual name __virtualname__ = 'ip' def __virtual__(): ''' Confine this module to RHEL/Fedora based distros ''' if __grains__['os_family'] == 'RedHat': return __virtualname__ return (False, 'The rh_ip execution module cannot be loaded: this module is only available on RHEL/Fedora based distributions.') # Setup networking attributes _ETHTOOL_CONFIG_OPTS = [ 'autoneg', 'speed', 'duplex', 'rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro', 'advertise' ] _RH_CONFIG_OPTS = [ 'domain', 'peerdns', 'peerntp', 'defroute', 'mtu', 'static-routes', 'gateway', 'zone' ] _RH_CONFIG_BONDING_OPTS = [ 'mode', 'miimon', 'arp_interval', 'arp_ip_target', 'downdelay', 'updelay', 'use_carrier', 'lacp_rate', 'hashing-algorithm', 'max_bonds', 'tx_queues', 'num_grat_arp', 'num_unsol_na', 'primary', 'primary_reselect', 'ad_select', 'xmit_hash_policy', 'arp_validate', 'fail_over_mac', 'all_slaves_active', 'resend_igmp' ] _RH_NETWORK_SCRIPT_DIR = '/etc/sysconfig/network-scripts' _RH_NETWORK_FILE = '/etc/sysconfig/network' _RH_NETWORK_CONF_FILES = '/etc/modprobe.d' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] _CONFIG_FALSE = ['no', 'off', 'false', '0', False] _IFACE_TYPES = [ 'eth', 'bond', 'alias', 'clone', 'ipsec', 'dialup', 'bridge', 'slave', 'vlan', 'ipip', 'ib', ] def _error_msg_iface(iface, option, expected): ''' Build an appropriate error message from a given option and a list of expected values. ''' msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]' return msg.format(iface, option, '|'.join(str(e) for e in expected)) def _error_msg_routes(iface, option, expected): ''' Build an appropriate error message from a given option and a list of expected values. ''' msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]' return msg.format(iface, option, expected) def _log_default_iface(iface, opt, value): log.info('Using default option -- Interface: %s Option: %s Value: %s', iface, opt, value) def _error_msg_network(option, expected): ''' Build an appropriate error message from a given option and a list of expected values. ''' msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]' return msg.format(option, '|'.join(str(e) for e in expected)) def _log_default_network(opt, value): log.info('Using existing setting -- Setting: %s Value: %s', opt, value) def _parse_rh_config(path): rh_config = _read_file(path) cv_rh_config = {} if rh_config: for line in rh_config: line = line.strip() if not line or line.startswith('!') or line.startswith('#'): continue pair = [p.rstrip() for p in line.split('=', 1)] if len(pair) != 2: continue name, value = pair cv_rh_config[name.upper()] = value return cv_rh_config def _parse_ethtool_opts(opts, iface): ''' Filters given options and outputs valid settings for ETHTOOLS_OPTS If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' config = {} if 'autoneg' in opts: if opts['autoneg'] in _CONFIG_TRUE: config.update({'autoneg': 'on'}) elif opts['autoneg'] in _CONFIG_FALSE: config.update({'autoneg': 'off'}) else: _raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE) if 'duplex' in opts: valid = ['full', 'half'] if opts['duplex'] in valid: config.update({'duplex': opts['duplex']}) else: _raise_error_iface(iface, 'duplex', valid) if 'speed' in opts: valid = ['10', '100', '1000', '10000'] if six.text_type(opts['speed']) in valid: config.update({'speed': opts['speed']}) else: _raise_error_iface(iface, opts['speed'], valid) if 'advertise' in opts: valid = [ '0x001', '0x002', '0x004', '0x008', '0x010', '0x020', '0x20000', '0x8000', '0x1000', '0x40000', '0x80000', '0x200000', '0x400000', '0x800000', '0x1000000', '0x2000000', '0x4000000' ] if six.text_type(opts['advertise']) in valid: config.update({'advertise': opts['advertise']}) else: _raise_error_iface(iface, 'advertise', valid) valid = _CONFIG_TRUE + _CONFIG_FALSE for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'): if option in opts: if opts[option] in _CONFIG_TRUE: config.update({option: 'on'}) elif opts[option] in _CONFIG_FALSE: config.update({option: 'off'}) else: _raise_error_iface(iface, option, valid) return config def _parse_settings_bond(opts, iface): ''' Filters given options and outputs valid settings for requested operation. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond_def = { # 803.ad aggregation selection logic # 0 for stable (default) # 1 for bandwidth # 2 for count 'ad_select': '0', # Max number of transmit queues (default = 16) 'tx_queues': '16', # Link monitoring in milliseconds. Most NICs support this 'miimon': '100', # ARP interval in milliseconds 'arp_interval': '250', # Delay before considering link down in milliseconds (miimon * 2) 'downdelay': '200', # lacp_rate 0: Slow - every 30 seconds # lacp_rate 1: Fast - every 1 second 'lacp_rate': '0', # Max bonds for this driver 'max_bonds': '1', # Specifies the time, in milliseconds, to wait before # enabling a slave after a link recovery has been # detected. Only used with miimon. 'updelay': '0', # Used with miimon. # On: driver sends mii # Off: ethtool sends mii 'use_carrier': '0', # Default. Don't change unless you know what you are doing. 'xmit_hash_policy': 'layer2', } if opts['mode'] in ['balance-rr', '0']: log.info( 'Device: %s Bonding Mode: load balancing (round-robin)', iface ) return _parse_settings_bond_0(opts, iface, bond_def) elif opts['mode'] in ['active-backup', '1']: log.info( 'Device: %s Bonding Mode: fault-tolerance (active-backup)', iface ) return _parse_settings_bond_1(opts, iface, bond_def) elif opts['mode'] in ['balance-xor', '2']: log.info( 'Device: %s Bonding Mode: load balancing (xor)', iface ) return _parse_settings_bond_2(opts, iface, bond_def) elif opts['mode'] in ['broadcast', '3']: log.info( 'Device: %s Bonding Mode: fault-tolerance (broadcast)', iface ) return _parse_settings_bond_3(opts, iface, bond_def) elif opts['mode'] in ['802.3ad', '4']: log.info( 'Device: %s Bonding Mode: IEEE 802.3ad Dynamic link ' 'aggregation', iface ) return _parse_settings_bond_4(opts, iface, bond_def) elif opts['mode'] in ['balance-tlb', '5']: log.info( 'Device: %s Bonding Mode: transmit load balancing', iface ) return _parse_settings_bond_5(opts, iface, bond_def) elif opts['mode'] in ['balance-alb', '6']: log.info( 'Device: %s Bonding Mode: adaptive load balancing', iface ) return _parse_settings_bond_6(opts, iface, bond_def) else: valid = [ '0', '1', '2', '3', '4', '5', '6', 'balance-rr', 'active-backup', 'balance-xor', 'broadcast', '802.3ad', 'balance-tlb', 'balance-alb' ] _raise_error_iface(iface, 'mode', valid) def _parse_settings_bond_0(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond0. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' # balance-rr shares miimon settings with balance-xor bond = _parse_settings_bond_1(opts, iface, bond_def) bond.update({'mode': '0'}) # ARP targets in n.n.n.n form valid = ['list of ips (up to 16)'] if 'arp_ip_target' in opts: if isinstance(opts['arp_ip_target'], list): if 1 <= len(opts['arp_ip_target']) <= 16: bond.update({'arp_ip_target': ''}) for ip in opts['arp_ip_target']: # pylint: disable=C0103 if bond['arp_ip_target']: bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip else: bond['arp_ip_target'] = ip else: _raise_error_iface(iface, 'arp_ip_target', valid) else: _raise_error_iface(iface, 'arp_ip_target', valid) elif 'miimon' not in opts: _raise_error_iface(iface, 'arp_ip_target', valid) if 'arp_interval' in opts: try: int(opts['arp_interval']) bond.update({'arp_interval': opts['arp_interval']}) except Exception: _raise_error_iface(iface, 'arp_interval', ['integer']) else: _log_default_iface(iface, 'arp_interval', bond_def['arp_interval']) bond.update({'arp_interval': bond_def['arp_interval']}) return bond def _parse_settings_bond_1(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond1. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '1'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'primary' in opts: bond.update({'primary': opts['primary']}) return bond def _parse_settings_bond_2(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond2. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '2'} valid = ['list of ips (up to 16)'] if 'arp_ip_target' in opts: if isinstance(opts['arp_ip_target'], list): if 1 <= len(opts['arp_ip_target']) <= 16: bond.update({'arp_ip_target': ''}) for ip in opts['arp_ip_target']: # pylint: disable=C0103 if bond['arp_ip_target']: bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip else: bond['arp_ip_target'] = ip else: _raise_error_iface(iface, 'arp_ip_target', valid) else: _raise_error_iface(iface, 'arp_ip_target', valid) else: _raise_error_iface(iface, 'arp_ip_target', valid) if 'arp_interval' in opts: try: int(opts['arp_interval']) bond.update({'arp_interval': opts['arp_interval']}) except Exception: _raise_error_iface(iface, 'arp_interval', ['integer']) else: _log_default_iface(iface, 'arp_interval', bond_def['arp_interval']) bond.update({'arp_interval': bond_def['arp_interval']}) if 'hashing-algorithm' in opts: valid = ['layer2', 'layer2+3', 'layer3+4'] if opts['hashing-algorithm'] in valid: bond.update({'xmit_hash_policy': opts['hashing-algorithm']}) else: _raise_error_iface(iface, 'hashing-algorithm', valid) return bond def _parse_settings_bond_3(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond3. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '3'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) return bond def _parse_settings_bond_4(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond4. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '4'} for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']: if binding in opts: if binding == 'lacp_rate': if opts[binding] == 'fast': opts.update({binding: '1'}) if opts[binding] == 'slow': opts.update({binding: '0'}) valid = ['fast', '1', 'slow', '0'] else: valid = ['integer'] try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, valid) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'hashing-algorithm' in opts: valid = ['layer2', 'layer2+3', 'layer3+4'] if opts['hashing-algorithm'] in valid: bond.update({'xmit_hash_policy': opts['hashing-algorithm']}) else: _raise_error_iface(iface, 'hashing-algorithm', valid) return bond def _parse_settings_bond_5(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond5. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '5'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'primary' in opts: bond.update({'primary': opts['primary']}) return bond def _parse_settings_bond_6(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond6. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '6'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'primary' in opts: bond.update({'primary': opts['primary']}) return bond def _parse_settings_vlan(opts, iface): ''' Filters given options and outputs valid settings for a vlan ''' vlan = {} if 'reorder_hdr' in opts: if opts['reorder_hdr'] in _CONFIG_TRUE + _CONFIG_FALSE: vlan.update({'reorder_hdr': opts['reorder_hdr']}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'reorder_hdr', valid) if 'vlan_id' in opts: if opts['vlan_id'] > 0: vlan.update({'vlan_id': opts['vlan_id']}) else: _raise_error_iface(iface, 'vlan_id', 'Positive integer') if 'phys_dev' in opts: if opts['phys_dev']: vlan.update({'phys_dev': opts['phys_dev']}) else: _raise_error_iface(iface, 'phys_dev', 'Non-empty string') return vlan def _parse_routes(iface, opts): ''' Filters given options and outputs valid settings for the route settings file. ''' # Normalize keys opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts)) result = {} if 'routes' not in opts: _raise_error_routes(iface, 'routes', 'List of routes') for opt in opts: result[opt] = opts[opt] return result def _parse_network_settings(opts, current): ''' Filters given options and outputs valid settings for the global network settings file. ''' # Normalize keys opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts)) current = dict((k.lower(), v) for (k, v) in six.iteritems(current)) # Check for supported parameters retain_settings = opts.get('retain_settings', False) result = current if retain_settings else {} # Default quote type is an empty string, which will not quote values quote_type = '' valid = _CONFIG_TRUE + _CONFIG_FALSE if 'enabled' not in opts: try: opts['networking'] = current['networking'] # If networking option is quoted, use its quote type quote_type = salt.utils.stringutils.is_quoted(opts['networking']) _log_default_network('networking', current['networking']) except ValueError: _raise_error_network('networking', valid) else: opts['networking'] = opts['enabled'] true_val = '{0}yes{0}'.format(quote_type) false_val = '{0}no{0}'.format(quote_type) networking = salt.utils.stringutils.dequote(opts['networking']) if networking in valid: if networking in _CONFIG_TRUE: result['networking'] = true_val elif networking in _CONFIG_FALSE: result['networking'] = false_val else: _raise_error_network('networking', valid) if 'hostname' not in opts: try: opts['hostname'] = current['hostname'] _log_default_network('hostname', current['hostname']) except Exception: _raise_error_network('hostname', ['server1.example.com']) if opts['hostname']: result['hostname'] = '{1}{0}{1}'.format( salt.utils.stringutils.dequote(opts['hostname']), quote_type) else: _raise_error_network('hostname', ['server1.example.com']) if 'nozeroconf' in opts: nozeroconf = salt.utils.stringutils.dequote(opts['nozeroconf']) if nozeroconf in valid: if nozeroconf in _CONFIG_TRUE: result['nozeroconf'] = true_val elif nozeroconf in _CONFIG_FALSE: result['nozeroconf'] = false_val else: _raise_error_network('nozeroconf', valid) for opt in opts: if opt not in ['networking', 'hostname', 'nozeroconf']: result[opt] = '{1}{0}{1}'.format( salt.utils.stringutils.dequote(opts[opt]), quote_type) return result def _raise_error_iface(iface, option, expected): ''' Log and raise an error with a logical formatted message. ''' msg = _error_msg_iface(iface, option, expected) log.error(msg) raise AttributeError(msg) def _raise_error_network(option, expected): ''' Log and raise an error with a logical formatted message. ''' msg = _error_msg_network(option, expected) log.error(msg) raise AttributeError(msg) def _raise_error_routes(iface, option, expected): ''' Log and raise an error with a logical formatted message. ''' msg = _error_msg_routes(iface, option, expected) log.error(msg) raise AttributeError(msg) def _read_file(path): ''' Reads and returns the contents of a file ''' try: with salt.utils.files.fopen(path, 'rb') as rfh: lines = salt.utils.stringutils.to_unicode(rfh.read()).splitlines() try: lines.remove('') except ValueError: pass return lines except Exception: return [] # Return empty list for type consistency def _write_file_iface(iface, data, folder, pattern): ''' Writes a file to disk ''' filename = os.path.join(folder, pattern.format(iface)) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist' msg = msg.format(filename, folder) log.error(msg) raise AttributeError(msg) with salt.utils.files.fopen(filename, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) def _write_file_network(data, filename): ''' Writes a file to disk ''' with salt.utils.files.fopen(filename, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) def _read_temp(data): lines = data.splitlines() try: # Discard newlines if they exist lines.remove('') except ValueError: pass return lines def build_bond(iface, **settings): ''' Create a bond script in /etc/modprobe.d with the passed settings and load the bonding kernel module. CLI Example: .. code-block:: bash salt '*' ip.build_bond bond0 mode=balance-alb ''' rh_major = __grains__['osrelease'][:1] opts = _parse_settings_bond(settings, iface) try: template = JINJA.get_template('conf.jinja') except jinja2.exceptions.TemplateNotFound: log.error('Could not load template conf.jinja') return '' data = template.render({'name': iface, 'bonding': opts}) _write_file_iface(iface, data, _RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface)) path = os.path.join(_RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface)) if rh_major == '5': __salt__['cmd.run']( 'sed -i -e "/^alias\\s{0}.*/d" /etc/modprobe.conf'.format(iface), python_shell=False ) __salt__['cmd.run']( 'sed -i -e "/^options\\s{0}.*/d" /etc/modprobe.conf'.format(iface), python_shell=False ) __salt__['file.append']('/etc/modprobe.conf', path) __salt__['kmod.load']('bonding') if settings['test']: return _read_temp(data) return _read_file(path) def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['os'] == 'Fedora': if __grains__['osmajorrelease'] >= 18: rh_major = '7' else: rh_major = '6' else: rh_major = __grains__['osrelease'][:1] iface_type = iface_type.lower() if iface_type not in _IFACE_TYPES: _raise_error_iface(iface, iface_type, _IFACE_TYPES) if iface_type == 'slave': settings['slave'] = 'yes' if 'master' not in settings: msg = 'master is a required setting for slave interfaces' log.error(msg) raise AttributeError(msg) if iface_type == 'vlan': settings['vlan'] = 'yes' if iface_type == 'bridge': __salt__['pkg.install']('bridge-utils') if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'ipip', 'ib', 'alias']: opts = _parse_settings_eth(settings, iface_type, enabled, iface) try: template = JINJA.get_template('rh{0}_eth.jinja'.format(rh_major)) except jinja2.exceptions.TemplateNotFound: log.error( 'Could not load template rh%s_eth.jinja', rh_major ) return '' ifcfg = template.render(opts) if 'test' in settings and settings['test']: return _read_temp(ifcfg) _write_file_iface(iface, ifcfg, _RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}') path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface)) return _read_file(path) def build_routes(iface, **settings): ''' Build a route script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_routes eth0 <settings> ''' template = 'rh6_route_eth.jinja' try: if int(__grains__['osrelease'][0]) < 6: template = 'route_eth.jinja' except ValueError: pass log.debug('Template name: %s', template) opts = _parse_routes(iface, settings) log.debug('Opts: \n %s', opts) try: template = JINJA.get_template(template) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', template) return '' opts6 = [] opts4 = [] for route in opts['routes']: ipaddr = route['ipaddr'] if salt.utils.validate.net.ipv6_addr(ipaddr): opts6.append(route) else: opts4.append(route) log.debug("IPv4 routes:\n%s", opts4) log.debug("IPv6 routes:\n%s", opts6) routecfg = template.render(routes=opts4, iface=iface) routecfg6 = template.render(routes=opts6, iface=iface) if settings['test']: routes = _read_temp(routecfg) routes.extend(_read_temp(routecfg6)) return routes _write_file_iface(iface, routecfg, _RH_NETWORK_SCRIPT_DIR, 'route-{0}') _write_file_iface(iface, routecfg6, _RH_NETWORK_SCRIPT_DIR, 'route6-{0}') path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route-{0}'.format(iface)) path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route6-{0}'.format(iface)) routes = _read_file(path) routes.extend(_read_file(path6)) return routes def down(iface, iface_type): ''' Shutdown a network interface CLI Example: .. code-block:: bash salt '*' ip.down eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ifdown {0}'.format(iface)) return None def get_bond(iface): ''' Return the content of a bond script CLI Example: .. code-block:: bash salt '*' ip.get_bond bond0 ''' path = os.path.join(_RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface)) return _read_file(path) def get_interface(iface): ''' Return the contents of an interface script CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface)) return _read_file(path) def up(iface, iface_type): # pylint: disable=C0103 ''' Start up a network interface CLI Example: .. code-block:: bash salt '*' ip.up eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ifup {0}'.format(iface)) return None def get_routes(iface): ''' Return the contents of the interface routes script. CLI Example: .. code-block:: bash salt '*' ip.get_routes eth0 ''' path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route-{0}'.format(iface)) path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route6-{0}'.format(iface)) routes = _read_file(path) routes.extend(_read_file(path6)) return routes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' return _read_file(_RH_NETWORK_FILE) def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: res = __salt__['service.restart']('network') return hostname_res and res def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' # Read current configuration and store default values current_network_settings = _parse_rh_config(_RH_NETWORK_FILE) # Build settings opts = _parse_network_settings(settings, current_network_settings) try: template = JINJA.get_template('network.jinja') except jinja2.exceptions.TemplateNotFound: log.error('Could not load template network.jinja') return '' network = template.render(opts) if settings['test']: return _read_temp(network) # Write settings _write_file_network(network, _RH_NETWORK_FILE) return _read_file(_RH_NETWORK_FILE)
saltstack/salt
salt/modules/rh_ip.py
_parse_network_settings
python
def _parse_network_settings(opts, current): ''' Filters given options and outputs valid settings for the global network settings file. ''' # Normalize keys opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts)) current = dict((k.lower(), v) for (k, v) in six.iteritems(current)) # Check for supported parameters retain_settings = opts.get('retain_settings', False) result = current if retain_settings else {} # Default quote type is an empty string, which will not quote values quote_type = '' valid = _CONFIG_TRUE + _CONFIG_FALSE if 'enabled' not in opts: try: opts['networking'] = current['networking'] # If networking option is quoted, use its quote type quote_type = salt.utils.stringutils.is_quoted(opts['networking']) _log_default_network('networking', current['networking']) except ValueError: _raise_error_network('networking', valid) else: opts['networking'] = opts['enabled'] true_val = '{0}yes{0}'.format(quote_type) false_val = '{0}no{0}'.format(quote_type) networking = salt.utils.stringutils.dequote(opts['networking']) if networking in valid: if networking in _CONFIG_TRUE: result['networking'] = true_val elif networking in _CONFIG_FALSE: result['networking'] = false_val else: _raise_error_network('networking', valid) if 'hostname' not in opts: try: opts['hostname'] = current['hostname'] _log_default_network('hostname', current['hostname']) except Exception: _raise_error_network('hostname', ['server1.example.com']) if opts['hostname']: result['hostname'] = '{1}{0}{1}'.format( salt.utils.stringutils.dequote(opts['hostname']), quote_type) else: _raise_error_network('hostname', ['server1.example.com']) if 'nozeroconf' in opts: nozeroconf = salt.utils.stringutils.dequote(opts['nozeroconf']) if nozeroconf in valid: if nozeroconf in _CONFIG_TRUE: result['nozeroconf'] = true_val elif nozeroconf in _CONFIG_FALSE: result['nozeroconf'] = false_val else: _raise_error_network('nozeroconf', valid) for opt in opts: if opt not in ['networking', 'hostname', 'nozeroconf']: result[opt] = '{1}{0}{1}'.format( salt.utils.stringutils.dequote(opts[opt]), quote_type) return result
Filters given options and outputs valid settings for the global network settings file.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L836-L903
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _log_default_network(opt, value):\n log.info('Using existing setting -- Setting: %s Value: %s',\n opt, value)\n", "def _raise_error_network(option, expected):\n '''\n Log and raise an error with a logical formatted message.\n '''\n msg = _error_msg_network(option, expected)\n log.error(msg)\n raise AttributeError(msg)\n", "def is_quoted(value):\n '''\n Return a single or double quote, if a string is wrapped in extra quotes.\n Otherwise return an empty string.\n '''\n ret = ''\n if isinstance(value, six.string_types) \\\n and value[0] == value[-1] \\\n and value.startswith(('\\'', '\"')):\n ret = value[0]\n return ret\n", "def dequote(value):\n '''\n Remove extra quotes around a string.\n '''\n if is_quoted(value):\n return value[1:-1]\n return value\n" ]
# -*- coding: utf-8 -*- ''' The networking module for RHEL/Fedora based distros ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import logging import os.path import os # Import third party libs import jinja2 import jinja2.exceptions # Import salt libs import salt.utils.files import salt.utils.stringutils import salt.utils.templates import salt.utils.validate.net from salt.exceptions import CommandExecutionError from salt.ext import six # Set up logging log = logging.getLogger(__name__) # Set up template environment JINJA = jinja2.Environment( loader=jinja2.FileSystemLoader( os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'rh_ip') ) ) # Define the module's virtual name __virtualname__ = 'ip' def __virtual__(): ''' Confine this module to RHEL/Fedora based distros ''' if __grains__['os_family'] == 'RedHat': return __virtualname__ return (False, 'The rh_ip execution module cannot be loaded: this module is only available on RHEL/Fedora based distributions.') # Setup networking attributes _ETHTOOL_CONFIG_OPTS = [ 'autoneg', 'speed', 'duplex', 'rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro', 'advertise' ] _RH_CONFIG_OPTS = [ 'domain', 'peerdns', 'peerntp', 'defroute', 'mtu', 'static-routes', 'gateway', 'zone' ] _RH_CONFIG_BONDING_OPTS = [ 'mode', 'miimon', 'arp_interval', 'arp_ip_target', 'downdelay', 'updelay', 'use_carrier', 'lacp_rate', 'hashing-algorithm', 'max_bonds', 'tx_queues', 'num_grat_arp', 'num_unsol_na', 'primary', 'primary_reselect', 'ad_select', 'xmit_hash_policy', 'arp_validate', 'fail_over_mac', 'all_slaves_active', 'resend_igmp' ] _RH_NETWORK_SCRIPT_DIR = '/etc/sysconfig/network-scripts' _RH_NETWORK_FILE = '/etc/sysconfig/network' _RH_NETWORK_CONF_FILES = '/etc/modprobe.d' _CONFIG_TRUE = ['yes', 'on', 'true', '1', True] _CONFIG_FALSE = ['no', 'off', 'false', '0', False] _IFACE_TYPES = [ 'eth', 'bond', 'alias', 'clone', 'ipsec', 'dialup', 'bridge', 'slave', 'vlan', 'ipip', 'ib', ] def _error_msg_iface(iface, option, expected): ''' Build an appropriate error message from a given option and a list of expected values. ''' msg = 'Invalid option -- Interface: {0}, Option: {1}, Expected: [{2}]' return msg.format(iface, option, '|'.join(str(e) for e in expected)) def _error_msg_routes(iface, option, expected): ''' Build an appropriate error message from a given option and a list of expected values. ''' msg = 'Invalid option -- Route interface: {0}, Option: {1}, Expected: [{2}]' return msg.format(iface, option, expected) def _log_default_iface(iface, opt, value): log.info('Using default option -- Interface: %s Option: %s Value: %s', iface, opt, value) def _error_msg_network(option, expected): ''' Build an appropriate error message from a given option and a list of expected values. ''' msg = 'Invalid network setting -- Setting: {0}, Expected: [{1}]' return msg.format(option, '|'.join(str(e) for e in expected)) def _log_default_network(opt, value): log.info('Using existing setting -- Setting: %s Value: %s', opt, value) def _parse_rh_config(path): rh_config = _read_file(path) cv_rh_config = {} if rh_config: for line in rh_config: line = line.strip() if not line or line.startswith('!') or line.startswith('#'): continue pair = [p.rstrip() for p in line.split('=', 1)] if len(pair) != 2: continue name, value = pair cv_rh_config[name.upper()] = value return cv_rh_config def _parse_ethtool_opts(opts, iface): ''' Filters given options and outputs valid settings for ETHTOOLS_OPTS If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' config = {} if 'autoneg' in opts: if opts['autoneg'] in _CONFIG_TRUE: config.update({'autoneg': 'on'}) elif opts['autoneg'] in _CONFIG_FALSE: config.update({'autoneg': 'off'}) else: _raise_error_iface(iface, 'autoneg', _CONFIG_TRUE + _CONFIG_FALSE) if 'duplex' in opts: valid = ['full', 'half'] if opts['duplex'] in valid: config.update({'duplex': opts['duplex']}) else: _raise_error_iface(iface, 'duplex', valid) if 'speed' in opts: valid = ['10', '100', '1000', '10000'] if six.text_type(opts['speed']) in valid: config.update({'speed': opts['speed']}) else: _raise_error_iface(iface, opts['speed'], valid) if 'advertise' in opts: valid = [ '0x001', '0x002', '0x004', '0x008', '0x010', '0x020', '0x20000', '0x8000', '0x1000', '0x40000', '0x80000', '0x200000', '0x400000', '0x800000', '0x1000000', '0x2000000', '0x4000000' ] if six.text_type(opts['advertise']) in valid: config.update({'advertise': opts['advertise']}) else: _raise_error_iface(iface, 'advertise', valid) valid = _CONFIG_TRUE + _CONFIG_FALSE for option in ('rx', 'tx', 'sg', 'tso', 'ufo', 'gso', 'gro', 'lro'): if option in opts: if opts[option] in _CONFIG_TRUE: config.update({option: 'on'}) elif opts[option] in _CONFIG_FALSE: config.update({option: 'off'}) else: _raise_error_iface(iface, option, valid) return config def _parse_settings_bond(opts, iface): ''' Filters given options and outputs valid settings for requested operation. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond_def = { # 803.ad aggregation selection logic # 0 for stable (default) # 1 for bandwidth # 2 for count 'ad_select': '0', # Max number of transmit queues (default = 16) 'tx_queues': '16', # Link monitoring in milliseconds. Most NICs support this 'miimon': '100', # ARP interval in milliseconds 'arp_interval': '250', # Delay before considering link down in milliseconds (miimon * 2) 'downdelay': '200', # lacp_rate 0: Slow - every 30 seconds # lacp_rate 1: Fast - every 1 second 'lacp_rate': '0', # Max bonds for this driver 'max_bonds': '1', # Specifies the time, in milliseconds, to wait before # enabling a slave after a link recovery has been # detected. Only used with miimon. 'updelay': '0', # Used with miimon. # On: driver sends mii # Off: ethtool sends mii 'use_carrier': '0', # Default. Don't change unless you know what you are doing. 'xmit_hash_policy': 'layer2', } if opts['mode'] in ['balance-rr', '0']: log.info( 'Device: %s Bonding Mode: load balancing (round-robin)', iface ) return _parse_settings_bond_0(opts, iface, bond_def) elif opts['mode'] in ['active-backup', '1']: log.info( 'Device: %s Bonding Mode: fault-tolerance (active-backup)', iface ) return _parse_settings_bond_1(opts, iface, bond_def) elif opts['mode'] in ['balance-xor', '2']: log.info( 'Device: %s Bonding Mode: load balancing (xor)', iface ) return _parse_settings_bond_2(opts, iface, bond_def) elif opts['mode'] in ['broadcast', '3']: log.info( 'Device: %s Bonding Mode: fault-tolerance (broadcast)', iface ) return _parse_settings_bond_3(opts, iface, bond_def) elif opts['mode'] in ['802.3ad', '4']: log.info( 'Device: %s Bonding Mode: IEEE 802.3ad Dynamic link ' 'aggregation', iface ) return _parse_settings_bond_4(opts, iface, bond_def) elif opts['mode'] in ['balance-tlb', '5']: log.info( 'Device: %s Bonding Mode: transmit load balancing', iface ) return _parse_settings_bond_5(opts, iface, bond_def) elif opts['mode'] in ['balance-alb', '6']: log.info( 'Device: %s Bonding Mode: adaptive load balancing', iface ) return _parse_settings_bond_6(opts, iface, bond_def) else: valid = [ '0', '1', '2', '3', '4', '5', '6', 'balance-rr', 'active-backup', 'balance-xor', 'broadcast', '802.3ad', 'balance-tlb', 'balance-alb' ] _raise_error_iface(iface, 'mode', valid) def _parse_settings_bond_0(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond0. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' # balance-rr shares miimon settings with balance-xor bond = _parse_settings_bond_1(opts, iface, bond_def) bond.update({'mode': '0'}) # ARP targets in n.n.n.n form valid = ['list of ips (up to 16)'] if 'arp_ip_target' in opts: if isinstance(opts['arp_ip_target'], list): if 1 <= len(opts['arp_ip_target']) <= 16: bond.update({'arp_ip_target': ''}) for ip in opts['arp_ip_target']: # pylint: disable=C0103 if bond['arp_ip_target']: bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip else: bond['arp_ip_target'] = ip else: _raise_error_iface(iface, 'arp_ip_target', valid) else: _raise_error_iface(iface, 'arp_ip_target', valid) elif 'miimon' not in opts: _raise_error_iface(iface, 'arp_ip_target', valid) if 'arp_interval' in opts: try: int(opts['arp_interval']) bond.update({'arp_interval': opts['arp_interval']}) except Exception: _raise_error_iface(iface, 'arp_interval', ['integer']) else: _log_default_iface(iface, 'arp_interval', bond_def['arp_interval']) bond.update({'arp_interval': bond_def['arp_interval']}) return bond def _parse_settings_bond_1(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond1. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '1'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'primary' in opts: bond.update({'primary': opts['primary']}) return bond def _parse_settings_bond_2(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond2. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '2'} valid = ['list of ips (up to 16)'] if 'arp_ip_target' in opts: if isinstance(opts['arp_ip_target'], list): if 1 <= len(opts['arp_ip_target']) <= 16: bond.update({'arp_ip_target': ''}) for ip in opts['arp_ip_target']: # pylint: disable=C0103 if bond['arp_ip_target']: bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip else: bond['arp_ip_target'] = ip else: _raise_error_iface(iface, 'arp_ip_target', valid) else: _raise_error_iface(iface, 'arp_ip_target', valid) else: _raise_error_iface(iface, 'arp_ip_target', valid) if 'arp_interval' in opts: try: int(opts['arp_interval']) bond.update({'arp_interval': opts['arp_interval']}) except Exception: _raise_error_iface(iface, 'arp_interval', ['integer']) else: _log_default_iface(iface, 'arp_interval', bond_def['arp_interval']) bond.update({'arp_interval': bond_def['arp_interval']}) if 'hashing-algorithm' in opts: valid = ['layer2', 'layer2+3', 'layer3+4'] if opts['hashing-algorithm'] in valid: bond.update({'xmit_hash_policy': opts['hashing-algorithm']}) else: _raise_error_iface(iface, 'hashing-algorithm', valid) return bond def _parse_settings_bond_3(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond3. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '3'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) return bond def _parse_settings_bond_4(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond4. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '4'} for binding in ['miimon', 'downdelay', 'updelay', 'lacp_rate', 'ad_select']: if binding in opts: if binding == 'lacp_rate': if opts[binding] == 'fast': opts.update({binding: '1'}) if opts[binding] == 'slow': opts.update({binding: '0'}) valid = ['fast', '1', 'slow', '0'] else: valid = ['integer'] try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, valid) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'hashing-algorithm' in opts: valid = ['layer2', 'layer2+3', 'layer3+4'] if opts['hashing-algorithm'] in valid: bond.update({'xmit_hash_policy': opts['hashing-algorithm']}) else: _raise_error_iface(iface, 'hashing-algorithm', valid) return bond def _parse_settings_bond_5(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond5. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '5'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'primary' in opts: bond.update({'primary': opts['primary']}) return bond def _parse_settings_bond_6(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond6. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '6'} for binding in ['miimon', 'downdelay', 'updelay']: if binding in opts: try: int(opts[binding]) bond.update({binding: opts[binding]}) except Exception: _raise_error_iface(iface, binding, ['integer']) else: _log_default_iface(iface, binding, bond_def[binding]) bond.update({binding: bond_def[binding]}) if 'use_carrier' in opts: if opts['use_carrier'] in _CONFIG_TRUE: bond.update({'use_carrier': '1'}) elif opts['use_carrier'] in _CONFIG_FALSE: bond.update({'use_carrier': '0'}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'use_carrier', valid) else: _log_default_iface(iface, 'use_carrier', bond_def['use_carrier']) bond.update({'use_carrier': bond_def['use_carrier']}) if 'primary' in opts: bond.update({'primary': opts['primary']}) return bond def _parse_settings_vlan(opts, iface): ''' Filters given options and outputs valid settings for a vlan ''' vlan = {} if 'reorder_hdr' in opts: if opts['reorder_hdr'] in _CONFIG_TRUE + _CONFIG_FALSE: vlan.update({'reorder_hdr': opts['reorder_hdr']}) else: valid = _CONFIG_TRUE + _CONFIG_FALSE _raise_error_iface(iface, 'reorder_hdr', valid) if 'vlan_id' in opts: if opts['vlan_id'] > 0: vlan.update({'vlan_id': opts['vlan_id']}) else: _raise_error_iface(iface, 'vlan_id', 'Positive integer') if 'phys_dev' in opts: if opts['phys_dev']: vlan.update({'phys_dev': opts['phys_dev']}) else: _raise_error_iface(iface, 'phys_dev', 'Non-empty string') return vlan def _parse_settings_eth(opts, iface_type, enabled, iface): ''' Filters given options and outputs valid settings for a network interface. ''' result = {'name': iface} if 'proto' in opts: valid = ['none', 'bootp', 'dhcp'] if opts['proto'] in valid: result['proto'] = opts['proto'] else: _raise_error_iface(iface, opts['proto'], valid) if 'dns' in opts: result['dns'] = opts['dns'] result['peerdns'] = 'yes' if 'mtu' in opts: try: result['mtu'] = int(opts['mtu']) except ValueError: _raise_error_iface(iface, 'mtu', ['integer']) if iface_type not in ['bridge']: ethtool = _parse_ethtool_opts(opts, iface) if ethtool: result['ethtool'] = ethtool if iface_type == 'slave': result['proto'] = 'none' if iface_type == 'bond': bonding = _parse_settings_bond(opts, iface) if bonding: result['bonding'] = bonding result['devtype'] = "Bond" if iface_type == 'vlan': vlan = _parse_settings_vlan(opts, iface) if vlan: result['devtype'] = "Vlan" for opt in vlan: result[opt] = opts[opt] if iface_type not in ['bond', 'vlan', 'bridge', 'ipip']: auto_addr = False if 'addr' in opts: if salt.utils.validate.net.mac(opts['addr']): result['addr'] = opts['addr'] elif opts['addr'] == 'auto': auto_addr = True elif opts['addr'] != 'none': _raise_error_iface(iface, opts['addr'], ['AA:BB:CC:DD:EE:FF', 'auto', 'none']) else: auto_addr = True if auto_addr: # If interface type is slave for bond, not setting hwaddr if iface_type != 'slave': ifaces = __salt__['network.interfaces']() if iface in ifaces and 'hwaddr' in ifaces[iface]: result['addr'] = ifaces[iface]['hwaddr'] if iface_type == 'eth': result['devtype'] = 'Ethernet' if iface_type == 'bridge': result['devtype'] = 'Bridge' bypassfirewall = True valid = _CONFIG_TRUE + _CONFIG_FALSE for opt in ['bypassfirewall']: if opt in opts: if opts[opt] in _CONFIG_TRUE: bypassfirewall = True elif opts[opt] in _CONFIG_FALSE: bypassfirewall = False else: _raise_error_iface(iface, opts[opt], valid) bridgectls = [ 'net.bridge.bridge-nf-call-ip6tables', 'net.bridge.bridge-nf-call-iptables', 'net.bridge.bridge-nf-call-arptables', ] if bypassfirewall: sysctl_value = 0 else: sysctl_value = 1 for sysctl in bridgectls: try: __salt__['sysctl.persist'](sysctl, sysctl_value) except CommandExecutionError: log.warning('Failed to set sysctl: %s', sysctl) else: if 'bridge' in opts: result['bridge'] = opts['bridge'] if iface_type == 'ipip': result['devtype'] = 'IPIP' for opt in ['my_inner_ipaddr', 'my_outer_ipaddr']: if opt not in opts: _raise_error_iface(iface, opts[opt], ['1.2.3.4']) else: result[opt] = opts[opt] if iface_type == 'ib': result['devtype'] = 'InfiniBand' if 'prefix' in opts: if 'netmask' in opts: msg = 'Cannot use prefix and netmask together' log.error(msg) raise AttributeError(msg) result['prefix'] = opts['prefix'] elif 'netmask' in opts: result['netmask'] = opts['netmask'] for opt in ['ipaddr', 'master', 'srcaddr', 'delay', 'domain', 'gateway', 'uuid', 'nickname', 'zone']: if opt in opts: result[opt] = opts[opt] for opt in ['ipv6addr', 'ipv6gateway']: if opt in opts: result[opt] = opts[opt] if 'ipaddrs' in opts: result['ipaddrs'] = [] for opt in opts['ipaddrs']: if salt.utils.validate.net.ipv4_addr(opt): ip, prefix = [i.strip() for i in opt.split('/')] result['ipaddrs'].append({'ipaddr': ip, 'prefix': prefix}) else: msg = 'ipv4 CIDR is invalid' log.error(msg) raise AttributeError(msg) if 'ipv6addrs' in opts: for opt in opts['ipv6addrs']: if not salt.utils.validate.net.ipv6_addr(opt): msg = 'ipv6 CIDR is invalid' log.error(msg) raise AttributeError(msg) result['ipv6addrs'] = opts['ipv6addrs'] if 'enable_ipv6' in opts: result['enable_ipv6'] = opts['enable_ipv6'] valid = _CONFIG_TRUE + _CONFIG_FALSE for opt in ['onparent', 'peerdns', 'peerroutes', 'slave', 'vlan', 'defroute', 'stp', 'ipv6_peerdns', 'ipv6_defroute', 'ipv6_peerroutes', 'ipv6_autoconf', 'ipv4_failure_fatal', 'dhcpv6c']: if opt in opts: if opts[opt] in _CONFIG_TRUE: result[opt] = 'yes' elif opts[opt] in _CONFIG_FALSE: result[opt] = 'no' else: _raise_error_iface(iface, opts[opt], valid) if 'onboot' in opts: log.warning( 'The \'onboot\' option is controlled by the \'enabled\' option. ' 'Interface: %s Enabled: %s', iface, enabled ) if enabled: result['onboot'] = 'yes' else: result['onboot'] = 'no' # If the interface is defined then we want to always take # control away from non-root users; unless the administrator # wants to allow non-root users to control the device. if 'userctl' in opts: if opts['userctl'] in _CONFIG_TRUE: result['userctl'] = 'yes' elif opts['userctl'] in _CONFIG_FALSE: result['userctl'] = 'no' else: _raise_error_iface(iface, opts['userctl'], valid) else: result['userctl'] = 'no' # This vlan is in opts, and should be only used in range interface # will affect jinja template for interface generating if 'vlan' in opts: if opts['vlan'] in _CONFIG_TRUE: result['vlan'] = 'yes' elif opts['vlan'] in _CONFIG_FALSE: result['vlan'] = 'no' else: _raise_error_iface(iface, opts['vlan'], valid) if 'arpcheck' in opts: if opts['arpcheck'] in _CONFIG_FALSE: result['arpcheck'] = 'no' if 'ipaddr_start' in opts: result['ipaddr_start'] = opts['ipaddr_start'] if 'ipaddr_end' in opts: result['ipaddr_end'] = opts['ipaddr_end'] if 'clonenum_start' in opts: result['clonenum_start'] = opts['clonenum_start'] # If NetworkManager is available, we can control whether we use # it or not if 'nm_controlled' in opts: if opts['nm_controlled'] in _CONFIG_TRUE: result['nm_controlled'] = 'yes' elif opts['nm_controlled'] in _CONFIG_FALSE: result['nm_controlled'] = 'no' else: _raise_error_iface(iface, opts['nm_controlled'], valid) else: result['nm_controlled'] = 'no' return result def _parse_routes(iface, opts): ''' Filters given options and outputs valid settings for the route settings file. ''' # Normalize keys opts = dict((k.lower(), v) for (k, v) in six.iteritems(opts)) result = {} if 'routes' not in opts: _raise_error_routes(iface, 'routes', 'List of routes') for opt in opts: result[opt] = opts[opt] return result def _raise_error_iface(iface, option, expected): ''' Log and raise an error with a logical formatted message. ''' msg = _error_msg_iface(iface, option, expected) log.error(msg) raise AttributeError(msg) def _raise_error_network(option, expected): ''' Log and raise an error with a logical formatted message. ''' msg = _error_msg_network(option, expected) log.error(msg) raise AttributeError(msg) def _raise_error_routes(iface, option, expected): ''' Log and raise an error with a logical formatted message. ''' msg = _error_msg_routes(iface, option, expected) log.error(msg) raise AttributeError(msg) def _read_file(path): ''' Reads and returns the contents of a file ''' try: with salt.utils.files.fopen(path, 'rb') as rfh: lines = salt.utils.stringutils.to_unicode(rfh.read()).splitlines() try: lines.remove('') except ValueError: pass return lines except Exception: return [] # Return empty list for type consistency def _write_file_iface(iface, data, folder, pattern): ''' Writes a file to disk ''' filename = os.path.join(folder, pattern.format(iface)) if not os.path.exists(folder): msg = '{0} cannot be written. {1} does not exist' msg = msg.format(filename, folder) log.error(msg) raise AttributeError(msg) with salt.utils.files.fopen(filename, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) def _write_file_network(data, filename): ''' Writes a file to disk ''' with salt.utils.files.fopen(filename, 'w') as fp_: fp_.write(salt.utils.stringutils.to_str(data)) def _read_temp(data): lines = data.splitlines() try: # Discard newlines if they exist lines.remove('') except ValueError: pass return lines def build_bond(iface, **settings): ''' Create a bond script in /etc/modprobe.d with the passed settings and load the bonding kernel module. CLI Example: .. code-block:: bash salt '*' ip.build_bond bond0 mode=balance-alb ''' rh_major = __grains__['osrelease'][:1] opts = _parse_settings_bond(settings, iface) try: template = JINJA.get_template('conf.jinja') except jinja2.exceptions.TemplateNotFound: log.error('Could not load template conf.jinja') return '' data = template.render({'name': iface, 'bonding': opts}) _write_file_iface(iface, data, _RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface)) path = os.path.join(_RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface)) if rh_major == '5': __salt__['cmd.run']( 'sed -i -e "/^alias\\s{0}.*/d" /etc/modprobe.conf'.format(iface), python_shell=False ) __salt__['cmd.run']( 'sed -i -e "/^options\\s{0}.*/d" /etc/modprobe.conf'.format(iface), python_shell=False ) __salt__['file.append']('/etc/modprobe.conf', path) __salt__['kmod.load']('bonding') if settings['test']: return _read_temp(data) return _read_file(path) def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['os'] == 'Fedora': if __grains__['osmajorrelease'] >= 18: rh_major = '7' else: rh_major = '6' else: rh_major = __grains__['osrelease'][:1] iface_type = iface_type.lower() if iface_type not in _IFACE_TYPES: _raise_error_iface(iface, iface_type, _IFACE_TYPES) if iface_type == 'slave': settings['slave'] = 'yes' if 'master' not in settings: msg = 'master is a required setting for slave interfaces' log.error(msg) raise AttributeError(msg) if iface_type == 'vlan': settings['vlan'] = 'yes' if iface_type == 'bridge': __salt__['pkg.install']('bridge-utils') if iface_type in ['eth', 'bond', 'bridge', 'slave', 'vlan', 'ipip', 'ib', 'alias']: opts = _parse_settings_eth(settings, iface_type, enabled, iface) try: template = JINJA.get_template('rh{0}_eth.jinja'.format(rh_major)) except jinja2.exceptions.TemplateNotFound: log.error( 'Could not load template rh%s_eth.jinja', rh_major ) return '' ifcfg = template.render(opts) if 'test' in settings and settings['test']: return _read_temp(ifcfg) _write_file_iface(iface, ifcfg, _RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}') path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface)) return _read_file(path) def build_routes(iface, **settings): ''' Build a route script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_routes eth0 <settings> ''' template = 'rh6_route_eth.jinja' try: if int(__grains__['osrelease'][0]) < 6: template = 'route_eth.jinja' except ValueError: pass log.debug('Template name: %s', template) opts = _parse_routes(iface, settings) log.debug('Opts: \n %s', opts) try: template = JINJA.get_template(template) except jinja2.exceptions.TemplateNotFound: log.error('Could not load template %s', template) return '' opts6 = [] opts4 = [] for route in opts['routes']: ipaddr = route['ipaddr'] if salt.utils.validate.net.ipv6_addr(ipaddr): opts6.append(route) else: opts4.append(route) log.debug("IPv4 routes:\n%s", opts4) log.debug("IPv6 routes:\n%s", opts6) routecfg = template.render(routes=opts4, iface=iface) routecfg6 = template.render(routes=opts6, iface=iface) if settings['test']: routes = _read_temp(routecfg) routes.extend(_read_temp(routecfg6)) return routes _write_file_iface(iface, routecfg, _RH_NETWORK_SCRIPT_DIR, 'route-{0}') _write_file_iface(iface, routecfg6, _RH_NETWORK_SCRIPT_DIR, 'route6-{0}') path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route-{0}'.format(iface)) path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route6-{0}'.format(iface)) routes = _read_file(path) routes.extend(_read_file(path6)) return routes def down(iface, iface_type): ''' Shutdown a network interface CLI Example: .. code-block:: bash salt '*' ip.down eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ifdown {0}'.format(iface)) return None def get_bond(iface): ''' Return the content of a bond script CLI Example: .. code-block:: bash salt '*' ip.get_bond bond0 ''' path = os.path.join(_RH_NETWORK_CONF_FILES, '{0}.conf'.format(iface)) return _read_file(path) def get_interface(iface): ''' Return the contents of an interface script CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'ifcfg-{0}'.format(iface)) return _read_file(path) def up(iface, iface_type): # pylint: disable=C0103 ''' Start up a network interface CLI Example: .. code-block:: bash salt '*' ip.up eth0 ''' # Slave devices are controlled by the master. if iface_type not in ['slave']: return __salt__['cmd.run']('ifup {0}'.format(iface)) return None def get_routes(iface): ''' Return the contents of the interface routes script. CLI Example: .. code-block:: bash salt '*' ip.get_routes eth0 ''' path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route-{0}'.format(iface)) path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route6-{0}'.format(iface)) routes = _read_file(path) routes.extend(_read_file(path6)) return routes def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' return _read_file(_RH_NETWORK_FILE) def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if 'require_reboot' not in settings: settings['require_reboot'] = False if 'apply_hostname' not in settings: settings['apply_hostname'] = False hostname_res = True if settings['apply_hostname'] in _CONFIG_TRUE: if 'hostname' in settings: hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning( 'The network state sls is trying to apply hostname ' 'changes but no hostname is defined.' ) hostname_res = False res = True if settings['require_reboot'] in _CONFIG_TRUE: log.warning( 'The network state sls is requiring a reboot of the system to ' 'properly apply network configuration.' ) res = True else: res = __salt__['service.restart']('network') return hostname_res and res def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' # Read current configuration and store default values current_network_settings = _parse_rh_config(_RH_NETWORK_FILE) # Build settings opts = _parse_network_settings(settings, current_network_settings) try: template = JINJA.get_template('network.jinja') except jinja2.exceptions.TemplateNotFound: log.error('Could not load template network.jinja') return '' network = template.render(opts) if settings['test']: return _read_temp(network) # Write settings _write_file_network(network, _RH_NETWORK_FILE) return _read_file(_RH_NETWORK_FILE)