desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Download a list of files stored on the master and put them in the minion file cache'
def cache_files(self, paths, saltenv=u'base', cachedir=None):
ret = [] if isinstance(paths, six.string_types): paths = paths.split(u',') for path in paths: ret.append(self.cache_file(path, saltenv, cachedir=cachedir)) return ret
'Download and cache all files on a master in a specified environment'
def cache_master(self, saltenv=u'base', cachedir=None):
ret = [] for path in self.file_list(saltenv): ret.append(self.cache_file(salt.utils.url.create(path), saltenv, cachedir=cachedir)) return ret
'Download all of the files in a subdir of the master'
def cache_dir(self, path, saltenv=u'base', include_empty=False, include_pat=None, exclude_pat=None, cachedir=None):
ret = [] path = self._check_proto(sdecode(path)) if (not path.endswith(u'/')): path = (path + u'/') log.info(u"Caching directory '%s' for environment '%s'", path, saltenv) for fn_ in self.file_list(saltenv): fn_ = sdecode(fn_) if (fn_.strip() and fn_.startswith...
'Cache a local file on the minion in the localfiles cache'
def cache_local_file(self, path, **kwargs):
dest = os.path.join(self.opts[u'cachedir'], u'localfiles', path.lstrip(u'/')) destdir = os.path.dirname(dest) if (not os.path.isdir(destdir)): os.makedirs(destdir) shutil.copyfile(path, dest) return dest
'List files in the local minion files and localfiles caches'
def file_local_list(self, saltenv=u'base'):
filesdest = os.path.join(self.opts[u'cachedir'], u'files', saltenv) localfilesdest = os.path.join(self.opts[u'cachedir'], u'localfiles') fdest = self._file_local_list(filesdest) ldest = self._file_local_list(localfilesdest) return sorted(fdest.union(ldest))
'This function must be overwritten'
def file_list(self, saltenv=u'base', prefix=u''):
return []
'This function must be overwritten'
def dir_list(self, saltenv=u'base', prefix=u''):
return []
'This function must be overwritten'
def symlink_list(self, saltenv=u'base', prefix=u''):
return {}
'Returns the full path to a file if it is cached locally on the minion otherwise returns a blank string'
def is_cached(self, path, saltenv=u'base', cachedir=None):
if path.startswith(u'salt://'): (path, senv) = salt.utils.url.parse(path) if senv: saltenv = senv escaped = (True if salt.utils.url.is_escaped(path) else False) localsfilesdest = os.path.join(self.opts[u'cachedir'], u'localfiles', path.lstrip(u'|/')) filesdest = os.path.join(...
'Return a list of all available sls modules on the master for a given environment'
def list_states(self, saltenv):
limit_traversal = self.opts.get(u'fileserver_limit_traversal', False) states = [] if limit_traversal: if (saltenv not in self.opts[u'file_roots']): log.warning(u"During an attempt to list states for saltenv '%s', the environment could not be foun...
'Get a state file from the master and store it in the local minion cache; return the location of the file'
def get_state(self, sls, saltenv, cachedir=None):
if (u'.' in sls): sls = sls.replace(u'.', u'/') sls_url = salt.utils.url.create((sls + u'.sls')) init_url = salt.utils.url.create((sls + u'/init.sls')) for path in [sls_url, init_url]: dest = self.cache_file(path, saltenv, cachedir=cachedir) if dest: return {u'source'...
'Get a directory recursively from the salt-master'
def get_dir(self, path, dest=u'', saltenv=u'base', gzip=None, cachedir=None):
ret = [] path = self._check_proto(path).rstrip(u'/') separated = path.rsplit(u'/', 1) if (len(separated) != 2): prefix = u'' else: prefix = separated[0] for fn_ in self.file_list(saltenv, prefix=path): try: if (fn_[len(path)] != u'/'): continue...
'Get a single file from a URL.'
def get_url(self, url, dest, makedirs=False, saltenv=u'base', no_cache=False, cachedir=None):
url_data = urlparse(url) url_scheme = url_data.scheme url_path = os.path.join(url_data.netloc, url_data.path).rstrip(os.sep) if ((dest is not None) and (os.path.isdir(dest) or dest.endswith((u'/', u'\\')))): if (url_data.query or ((len(url_data.path) > 1) and (not url_data.path.endswith(u'/'))))...
'Cache a file then process it as a template'
def get_template(self, url, dest, template=u'jinja', makedirs=False, saltenv=u'base', cachedir=None, **kwargs):
if (u'env' in kwargs): salt.utils.warn_until(u'Oxygen', u"Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning wi...
'Return the extn_filepath for a given url'
def _extrn_path(self, url, saltenv, cachedir=None):
url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.sanitize_win_path_string(url_data.netloc) else: netloc = url_data.netloc netloc = netloc.split(u'@')[(-1)] if (cachedir is None): cachedir = self.opts[u'cachedir'] elif (not os.path.isabs(ca...
'Locate the file path'
def _find_file(self, path, saltenv=u'base'):
fnd = {u'path': u'', u'rel': u''} if (saltenv not in self.opts[u'file_roots']): return fnd if salt.utils.url.is_escaped(path): path = salt.utils.url.unescape(path) for root in self.opts[u'file_roots'][saltenv]: full = os.path.join(root, path) if os.path.isfile(full): ...
'Copies a file from the local files directory into :param:`dest` gzip compression settings are ignored for local files'
def get_file(self, path, dest=u'', makedirs=False, saltenv=u'base', gzip=None, cachedir=None):
path = self._check_proto(path) fnd = self._find_file(path, saltenv) fnd_path = fnd.get(u'path') if (not fnd_path): return u'' return fnd_path
'Return a list of files in the given environment with optional relative prefix path to limit directory traversal'
def file_list(self, saltenv=u'base', prefix=u''):
ret = [] if (saltenv not in self.opts[u'file_roots']): return ret prefix = prefix.strip(u'/') for path in self.opts[u'file_roots'][saltenv]: for (root, dirs, files) in os.walk(os.path.join(path, prefix), followlinks=True): dirs[:] = [d for d in dirs if (not salt.fileserver.is...
'List the empty dirs in the file_roots with optional relative prefix path to limit directory traversal'
def file_list_emptydirs(self, saltenv=u'base', prefix=u''):
ret = [] prefix = prefix.strip(u'/') if (saltenv not in self.opts[u'file_roots']): return ret for path in self.opts[u'file_roots'][saltenv]: for (root, dirs, files) in os.walk(os.path.join(path, prefix), followlinks=True): dirs[:] = [d for d in dirs if (not salt.fileserver.is...
'List the dirs in the file_roots with optional relative prefix path to limit directory traversal'
def dir_list(self, saltenv=u'base', prefix=u''):
ret = [] if (saltenv not in self.opts[u'file_roots']): return ret prefix = prefix.strip(u'/') for path in self.opts[u'file_roots'][saltenv]: for (root, dirs, files) in os.walk(os.path.join(path, prefix), followlinks=True): ret.append(sdecode(os.path.relpath(root, path))) ...
'Return either a file path or the result of a remote find_file call.'
def __get_file_path(self, path, saltenv=u'base'):
try: path = self._check_proto(path) except MinionError as err: if (not os.path.isfile(path)): log.warning(u'specified file %s is not present to generate hash: %s', path, err) return None else: return path return self._fin...
'Return the hash of a file, to get the hash of a file in the file_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file.'
def hash_file(self, path, saltenv=u'base'):
ret = {} fnd = self.__get_file_path(path, saltenv) if (fnd is None): return ret try: fnd_path = fnd[u'path'] except TypeError: fnd_path = fnd hash_type = self.opts.get(u'hash_type', u'md5') ret[u'hsum'] = salt.utils.get_hash(fnd_path, form=hash_type) ret[u'hash_ty...
'Return the hash of a file, to get the hash of a file in the file_roots prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. Additionally, return the stat result of the file, or None if no stat results were found.'
def hash_and_stat_file(self, path, saltenv=u'base'):
ret = {} fnd = self.__get_file_path(path, saltenv) if (fnd is None): return (ret, None) try: fnd_path = fnd[u'path'] fnd_stat = fnd.get(u'stat') except TypeError: fnd_path = fnd try: fnd_stat = list(os.stat(fnd_path)) except Exception: ...
'Return a list of the files in the file server\'s specified environment'
def list_env(self, saltenv=u'base'):
return self.file_list(saltenv)
'Return the master opts data'
def master_opts(self):
return self.opts
'Return the available environments'
def envs(self):
ret = [] for saltenv in self.opts[u'file_roots']: ret.append(saltenv) return ret
'Originally returned information via the external_nodes subsystem. External_nodes was deprecated and removed in 2014.1.6 in favor of master_tops (which had been around since pre-0.17). salt-call --local state.show_top ends up here, but master_tops has not been extended to support show_top in a completely local environm...
def master_tops(self):
return {}
'Reset the channel, in the event of an interruption'
def _refresh_channel(self):
self.channel = salt.transport.Channel.factory(self.opts) return self.channel
'Get a single file from the salt-master path must be a salt server location, aka, salt://path/to/file, if dest is omitted, then the downloaded file will be placed in the minion cache'
def get_file(self, path, dest=u'', makedirs=False, saltenv=u'base', gzip=None, cachedir=None):
(path, senv) = salt.utils.url.split_env(path) if senv: saltenv = senv if (not salt.utils.platform.is_windows()): (hash_server, stat_server) = self.hash_and_stat_file(path, saltenv) try: mode_server = stat_server[0] except (IndexError, TypeError): mode_...
'List the files on the master'
def file_list(self, saltenv=u'base', prefix=u''):
load = {u'saltenv': saltenv, u'prefix': prefix, u'cmd': u'_file_list'} return [sdecode(fn_) for fn_ in self.channel.send(load)]
'List the empty dirs on the master'
def file_list_emptydirs(self, saltenv=u'base', prefix=u''):
load = {u'saltenv': saltenv, u'prefix': prefix, u'cmd': u'_file_list_emptydirs'} self.channel.send(load)
'List the dirs on the master'
def dir_list(self, saltenv=u'base', prefix=u''):
load = {u'saltenv': saltenv, u'prefix': prefix, u'cmd': u'_dir_list'} return self.channel.send(load)
'List symlinked files and dirs on the master'
def symlink_list(self, saltenv=u'base', prefix=u''):
load = {u'saltenv': saltenv, u'prefix': prefix, u'cmd': u'_symlink_list'} return self.channel.send(load)
'Common code for hashing and stating files'
def __hash_and_stat_file(self, path, saltenv=u'base'):
try: path = self._check_proto(path) except MinionError as err: if (not os.path.isfile(path)): log.warning(u'specified file %s is not present to generate hash: %s', path, err) return {} else: ret = {} hash_type = s...
'Return the hash of a file, to get the hash of a file on the salt master file server prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file.'
def hash_file(self, path, saltenv=u'base'):
return self.__hash_and_stat_file(path, saltenv)[0]
'The same as hash_file, but also return the file\'s mode, or None if no mode data is present.'
def hash_and_stat_file(self, path, saltenv=u'base'):
return self.__hash_and_stat_file(path, saltenv)
'Return a list of the files in the file server\'s specified environment'
def list_env(self, saltenv=u'base'):
load = {u'saltenv': saltenv, u'cmd': u'_file_list'} return self.channel.send(load)
'Return a list of available environments'
def envs(self):
load = {u'cmd': u'_file_envs'} return self.channel.send(load)
'Return the master opts data'
def master_opts(self):
load = {u'cmd': u'_master_opts'} return self.channel.send(load)
'Return the metadata derived from the master_tops system'
def master_tops(self):
load = {u'cmd': u'_master_tops', u'id': self.opts[u'id'], u'opts': self.opts} if self.auth: load[u'tok'] = self.auth.gen_token(u'salt') return self.channel.send(load)
'Perform a lightweight check to see if the master daemon is running Note, this will return an invalid success if the master crashed or was not shut down cleanly.'
def _is_master_running(self):
if (self.opts['transport'] == 'tcp'): ipc_file = 'publish_pull.ipc' else: ipc_file = 'workers.ipc' return os.path.exists(os.path.join(self.opts['sock_dir'], ipc_file))
'Execute the specified function in the specified client by passing the lowstate'
def run(self, low):
if (not self._is_master_running()): raise salt.exceptions.SaltDaemonNotRunning('Salt Master is not available.') if (low.get('client') not in CLIENTS): raise salt.exceptions.SaltInvocationError("Invalid client specified: '{0}'".format(low.get('client'))) if ((not (('token...
'Run :ref:`execution modules <all-salt.modules>` asynchronously Wraps :py:meth:`salt.client.LocalClient.run_job`. :return: job ID'
def local_async(self, *args, **kwargs):
local = salt.client.get_local_client(mopts=self.opts) return local.run_job(*args, **kwargs)
'Run :ref:`execution modules <all-salt.modules>` synchronously See :py:meth:`salt.client.LocalClient.cmd` for all available parameters. Sends a command from the master to the targeted minions. This is the same interface that Salt\'s own CLI uses. Note the ``arg`` and ``kwarg`` parameters are sent down to the minion(s) ...
def local(self, *args, **kwargs):
local = salt.client.get_local_client(mopts=self.opts) return local.cmd(*args, **kwargs)
'Run :ref:`execution modules <all-salt.modules>` against subsets of minions .. versionadded:: 2016.3.0 Wraps :py:meth:`salt.client.LocalClient.cmd_subset`'
def local_subset(self, *args, **kwargs):
local = salt.client.get_local_client(mopts=self.opts) return local.cmd_subset(*args, **kwargs)
'Run :ref:`execution modules <all-salt.modules>` against batches of minions .. versionadded:: 0.8.4 Wraps :py:meth:`salt.client.LocalClient.cmd_batch` :return: Returns the result from the exeuction module for each batch of returns'
def local_batch(self, *args, **kwargs):
local = salt.client.get_local_client(mopts=self.opts) return local.cmd_batch(*args, **kwargs)
'Run salt-ssh commands synchronously Wraps :py:meth:`salt.client.ssh.client.SSHClient.cmd_sync`. :return: Returns the result from the salt-ssh command'
def ssh(self, *args, **kwargs):
ssh_client = salt.client.ssh.client.SSHClient(mopts=self.opts, disable_custom_roster=True) return ssh_client.cmd_sync(kwargs)
'Run `runner modules <all-salt.runners>` synchronously Wraps :py:meth:`salt.runner.RunnerClient.cmd_sync`. Note that runner functions must be called using keyword arguments. Positional arguments are not supported. :return: Returns the result from the runner module'
def runner(self, fun, timeout=None, full_return=False, **kwargs):
kwargs['fun'] = fun runner = salt.runner.RunnerClient(self.opts) return runner.cmd_sync(kwargs, timeout=timeout, full_return=full_return)
'Run `runner modules <all-salt.runners>` asynchronously Wraps :py:meth:`salt.runner.RunnerClient.cmd_async`. Note that runner functions must be called using keyword arguments. Positional arguments are not supported. :return: event data and a job ID for the executed function.'
def runner_async(self, fun, **kwargs):
kwargs['fun'] = fun runner = salt.runner.RunnerClient(self.opts) return runner.cmd_async(kwargs)
'Run :ref:`wheel modules <all-salt.wheel>` synchronously Wraps :py:meth:`salt.wheel.WheelClient.master_call`. Note that wheel functions must be called using keyword arguments. Positional arguments are not supported. :return: Returns the result from the wheel module'
def wheel(self, fun, **kwargs):
kwargs['fun'] = fun wheel = salt.wheel.WheelClient(self.opts) return wheel.cmd_sync(kwargs)
'Run :ref:`wheel modules <all-salt.wheel>` asynchronously Wraps :py:meth:`salt.wheel.WheelClient.master_call`. Note that wheel functions must be called using keyword arguments. Positional arguments are not supported. :return: Returns the result from the wheel module'
def wheel_async(self, fun, **kwargs):
kwargs['fun'] = fun wheel = salt.wheel.WheelClient(self.opts) return wheel.cmd_async(kwargs)
'Checks if the client has sent a ready message. A ready message causes ``send()`` to be called on the ``parent end`` of the pipe. Clients need to ensure that the pipe assigned to ``self.pipe`` is the ``parent end`` of a pipe. This ensures completion of the underlying websocket connection and can be used to synchronize ...
def received_message(self, message):
if (message.data == 'websocket client ready'): self.pipe.send(message) self.send('server received message', False)
'handler is expected to be the server side end of a websocket connection.'
def __init__(self, handler):
self.handler = handler self.jobs = {} self.minions = {}
'Publishes minions as a list of dicts.'
def publish_minions(self):
minions = [] for (minion, minion_info) in six.iteritems(self.minions): curr_minion = {} curr_minion.update(minion_info) curr_minion.update({'id': minion}) minions.append(curr_minion) ret = {'minions': minions} self.handler.send(json.dumps(ret), False)
'Publishes the data to the event stream.'
def publish(self, key, data):
publish_data = {key: data} self.handler.send(json.dumps(publish_data), False)
'Associate grains data with a minion and publish minion update'
def process_minion_update(self, event_data):
tag = event_data['tag'] event_info = event_data['data'] (_, _, _, _, mid) = tag.split('/') if (not self.minions.get(mid, None)): self.minions[mid] = {} minion = self.minions[mid] minion.update({'grains': event_info['return']}) self.publish_minions()
'Process a /ret event returned by Salt for a particular minion. These events contain the returned results from a particular execution.'
def process_ret_job_event(self, event_data):
tag = event_data['tag'] event_info = event_data['data'] (_, _, jid, _, mid) = tag.split('/') job = self.jobs.setdefault(jid, {}) minion = job.setdefault('minions', {}).setdefault(mid, {}) minion.update({'return': event_info['return']}) minion.update({'retcode': event_info['retcode']}) mi...
'Creates a new job with properties from the event data like jid, function, args, timestamp. Also sets the initial state to started. Minions that are participating in this job are also noted.'
def process_new_job_event(self, event_data):
job = None tag = event_data['tag'] event_info = event_data['data'] minions = {} for mid in event_info['minions']: minions[mid] = {'success': False} job = {'jid': event_info['jid'], 'start_time': event_info['_stamp'], 'minions': minions, 'fun': event_info['fun'], 'tgt': event_info['tgt'],...
'Tag: salt/key Data: {\'_stamp\': \'2014-05-20T22:45:04.345583\', \'act\': \'delete\', \'id\': \'compute.home\', \'result\': True}'
def process_key_event(self, event_data):
tag = event_data['tag'] event_info = event_data['data'] if (event_info['act'] == 'delete'): self.minions.pop(event_info['id'], None) elif (event_info['act'] == 'accept'): self.minions.setdefault(event_info['id'], {}) self.publish_minions()
'Check if any minions have connected or dropped. Send a message to the client if they have.'
def process_presence_events(self, event_data, token, opts):
tag = event_data['tag'] event_info = event_data['data'] minions_detected = event_info['present'] curr_minions = six.iterkeys(self.minions) changed = False dropped_minions = (set(curr_minions) - set(minions_detected)) for minion in dropped_minions: changed = True self.minions....
'Process events and publish data'
def process(self, salt_data, token, opts):
parts = salt_data['tag'].split('/') if (len(parts) < 2): return if (parts[1] == 'job'): if (parts[3] == 'new'): self.process_new_job_event(salt_data) if (salt_data['data']['fun'] == 'grains.items'): self.minions = {} elif (parts[3] == '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.'
def exec_lowstate(self, client=None, token=None):
lowstate = cherrypy.request.lowstate if cherrypy.request.config.get('tools.sessions.on', False): cherrypy.session.release_lock() if (not isinstance(lowstate, list)): raise cherrypy.HTTPError(400, 'Lowstates must be a list') for chunk in lowstate: if token: ...
'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:: http GET / HTTP/1.1 Host: localhost:8000 Accept: application/json **Example ...
@cherrypy.config(**{'tools.sessions.on': False}) def GET(self):
import inspect return {'return': 'Welcome', 'clients': salt.netapi.CLIENTS}
'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 ...
@cherrypy.tools.salt_token() @cherrypy.tools.salt_auth() def POST(self, **kwargs):
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...
def GET(self, mid=None):
cherrypy.request.lowstate = [{'client': 'local', 'tgt': (mid or '*'), 'fun': 'grains.items'}] return {'return': list(self.exec_lowstate(token=cherrypy.session.get('token')))}
'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| :term:`lowstate` data...
def POST(self, **kwargs):
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]}}
'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...
def GET(self, jid=None, timeout=''):
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: ...
'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...
def GET(self, mid=None):
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...
'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 bo...
@cherrypy.config(**{'tools.hypermedia_out.on': False, 'tools.sessions.on': False}) def POST(self, **kwargs):
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', '')...
'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:: http GET /login HTTP/1.1 Host: localhost:8000 Accept: text/html **Example response:** .. code...
def GET(self):
cherrypy.response.headers['WWW-Authenticate'] = 'Session' return {'status': cherrypy.response.status, 'return': 'Please log in'}
':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|...
def POST(self, **kwargs):
if (not self.api._is_master_running()): raise salt.exceptions.SaltDaemonNotRunning('Salt Master is not available.') if isinstance(cherrypy.serving.request.lowstate, list): creds = cherrypy.serving.request.lowstate[0] else: creds = cherrypy.serving.request.lowstate use...
'Destroy the currently active session and expire the session cookie'
def POST(self):
cherrypy.lib.sessions.expire() cherrypy.session.regenerate() return {'return': 'Your token has been cleared'}
'.. 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:*...
@cherrypy.config(**{'tools.sessions.on': False}) def POST(self, **kwargs):
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", ...
'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 :term:`lowstate` data describing Salt commands must be sent in the request body. :status 200: |200| :status 400: |40...
def POST(self, **kwargs):
return {'return': list(self.exec_lowstate())}
'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.'
def _is_valid_token(self, auth_token):
if (auth_token is None): return False (orig_session, _) = cherrypy.session.cache.get(auth_token, ({}, None)) salt_token = orig_session.get('token', auth_token) if (salt_token and self.resolver.get_token(salt_token)): return True return False
'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 ...
def GET(self, token=None, salt_token=None):
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) cherrypy.session.release_lock() cherrypy.response.headers['Content-Type'] = 't...
'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 <...sni...
def GET(self, token=None, **kwargs):
if token: (orig_session, _) = cherrypy.session.cache.get(token, ({}, None)) salt_token = orig_session.get('token') else: salt_token = cherrypy.session.get('token') if ((not salt_token) or (not self.auth.get_tok(salt_token))): raise cherrypy.HTTPError(401) cherrypy.session...
'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!"...
def POST(self, *args, **kwargs):
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': dat...
'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|'
def GET(self):
if hasattr(logging, 'statistics'): try: from cherrypy.lib import cpstats except ImportError: logger.error('Import of cherrypy.cpstats failed. Possible upstream bug here: https://github.com/cherrypy/cherrypy/issues/1444') return {} r...
'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|'
def GET(self, *args):
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))
'Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs.'
def _setattr_url_map(self):
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(...
'Assemble any dynamic or configurable URLs'
def _update_url_map(self):
if HAS_WEBSOCKETS: self.url_map.update({'ws': WebsocketEndpoint}) self.url_map.update({self.apiopts.get('webhook_url', 'hook').lstrip('/'): Webhook}) self.url_map.update({self.apiopts.get('app_path', 'app').lstrip('/'): App})
'Combine the CherryPy configuration with the rest_cherrypy config values pulled from the master config and return the CherryPy configuration'
def get_conf(self):
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), 'engine.timeout_monitor.on': self.apiopts.get('expire_respon...
'Remove all futures that were waiting for request `request` since it is done waiting'
def clean_timeout_futures(self, request):
if (request not in self.request_map): return for (tag, future) in self.request_map[request]: self._timeout_future(tag, future) if (future in self.timeout_map): tornado.ioloop.IOLoop.current().remove_timeout(self.timeout_map[future]) del self.timeout_map[future] ...
'Get an event (async of course) return a future that will get it later'
def get_event(self, request, tag='', callback=None, timeout=None):
if request._finished: future = Future() future.set_exception(TimeoutException()) return future future = Future() if (callback is not None): def handle_future(future): tornado.ioloop.IOLoop.current().add_callback(callback, future) future.add_done_callback(h...
'Timeout a specific future'
def _timeout_future(self, tag, future):
if (tag not in self.tag_map): return if (not future.done()): future.set_exception(TimeoutException()) self.tag_map[tag].remove(future) if (len(self.tag_map[tag]) == 0): del self.tag_map[tag]
'Callback for events on the event sub socket'
def _handle_event_socket_recv(self, raw):
(mtag, data) = self.event.unpack(raw, self.event.serial) for (tag_prefix, futures) in six.iteritems(self.tag_map): if mtag.startswith(tag_prefix): for future in futures: if future.done(): continue future.set_result({'data': data, 'tag': mta...
'Verify that the client is in fact one we have'
def _verify_client(self, low):
if (('client' not in low) or (low.get('client') not in self.saltclients)): self.set_status(400) self.write('400 Invalid Client: Client not found in salt clients') self.finish() return False return True
'Initialize the handler before requests are called'
def initialize(self):
if (not hasattr(self.application, 'event_listener')): logger.critical('init a listener') self.application.event_listener = EventListener(self.application.mod_opts, self.application.opts)
'The token used for the request'
@property def token(self):
if (AUTH_TOKEN_HEADER in self.request.headers): return self.request.headers[AUTH_TOKEN_HEADER] else: return self.get_cookie(AUTH_COOKIE_NAME)
'Boolean whether the request is auth\'d'
def _verify_auth(self):
return (self.token and bool(self.application.auth.get_tok(self.token)))
'Run before get/posts etc. Pre-flight checks: - verify that we can speak back to them (compatible accept header)'
def prepare(self):
accept_header = self.request.headers.get('Accept', '*/*') parsed_accept_header = [cgi.parse_header(h)[0] for h in accept_header.split(',')] def find_acceptable_content_type(parsed_accept_header): for media_range in parsed_accept_header: for (content_type, dumper) in self.ct_out_map: ...
'timeout a session'
def timeout_futures(self):
self.application.event_listener.clean_timeout_futures(self)
'When the job has been done, lets cleanup'
def on_finish(self):
self.timeout_futures()
'If the client disconnects, lets close out'
def on_connection_close(self):
self.finish()
'Serlialize the output based on the Accept header'
def serialize(self, data):
self.set_header('Content-Type', self.content_type) return self.dumper(data)
'function to get the data from the urlencoded forms ignore the data passed in and just get the args from wherever they are'
def _form_loader(self, _):
data = {} for key in self.request.arguments: val = self.get_arguments(key) if (len(val) == 1): data[key] = val[0] else: data[key] = val return data
'Deserialize the data based on request content type headers'
def deserialize(self, data):
ct_in_map = {'application/x-www-form-urlencoded': self._form_loader, 'application/json': json.loads, 'application/x-yaml': yaml.safe_load, 'text/yaml': yaml.safe_load, 'text/plain': json.loads} try: header = cgi.parse_header(self.request.headers['Content-Type']) (value, parameters) = header ...
'Format the incoming data into a lowstate object'
def _get_lowstate(self):
if (not self.request.body): return data = self.deserialize(self.request.body) self.raw_data = copy(data) if (data and ('arg' in data) and (not isinstance(data['arg'], list))): data['arg'] = [data['arg']] if (not isinstance(data, list)): lowstate = [data] else: low...
'Set default CORS headers'
def set_default_headers(self):
mod_opts = self.application.mod_opts if mod_opts.get('cors_origin'): origin = self.request.headers.get('Origin') allowed_origin = _check_cors_origin(origin, mod_opts['cors_origin']) if allowed_origin: self.set_header('Access-Control-Allow-Origin', allowed_origin)