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(path)):
if salt.utils.check_include_exclude(fn_, include_pat, exclude_pat):
fn_ = self.cache_file(salt.utils.url.create(fn_), saltenv, cachedir=cachedir)
if fn_:
ret.append(fn_)
if include_empty:
cachedir = self.get_cachedir(cachedir)
dest = salt.utils.path.join(cachedir, u'files', saltenv)
for fn_ in self.file_list_emptydirs(saltenv):
fn_ = sdecode(fn_)
if fn_.startswith(path):
minion_dir = u'{0}/{1}'.format(dest, fn_)
if (not os.path.isdir(minion_dir)):
os.makedirs(minion_dir)
ret.append(minion_dir)
return ret
|
'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(self.opts[u'cachedir'], u'files', saltenv, path.lstrip(u'|/'))
extrndest = self._extrn_path(path, saltenv, cachedir=cachedir)
if os.path.exists(filesdest):
return (salt.utils.url.escape(filesdest) if escaped else filesdest)
elif os.path.exists(localsfilesdest):
return (salt.utils.url.escape(localsfilesdest) if escaped else localsfilesdest)
elif os.path.exists(extrndest):
return extrndest
return u''
|
'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 found in the configured file roots", saltenv)
return states
for path in self.opts[u'file_roots'][saltenv]:
for (root, dirs, files) in os.walk(path, topdown=True):
log.debug(u'Searching for states in dirs %s and files %s', dirs, files)
if (not [filename.endswith(u'.sls') for filename in files]):
del dirs[:]
else:
for found_file in files:
stripped_root = os.path.relpath(root, path)
if salt.utils.platform.is_windows():
stripped_root = stripped_root.replace(u'\\', u'/')
stripped_root = stripped_root.replace(u'/', u'.')
if found_file.endswith(u'.sls'):
if found_file.endswith(u'init.sls'):
if stripped_root.endswith(u'.'):
stripped_root = stripped_root.rstrip(u'.')
states.append(stripped_root)
else:
if (not stripped_root.endswith(u'.')):
stripped_root += u'.'
if stripped_root.startswith(u'.'):
stripped_root = stripped_root.lstrip(u'.')
states.append((stripped_root + found_file[:(-4)]))
else:
for path in self.file_list(saltenv):
if salt.utils.platform.is_windows():
path = path.replace(u'\\', u'/')
if path.endswith(u'.sls'):
if path.endswith(u'/init.sls'):
states.append(path.replace(u'/', u'.')[:(-9)])
else:
states.append(path.replace(u'/', u'.')[:(-4)])
return states
|
'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': path, u'dest': dest}
return {}
|
'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
except IndexError:
continue
minion_relpath = fn_[len(prefix):].lstrip(u'/')
ret.append(self.get_file(salt.utils.url.create(fn_), u'{0}/{1}'.format(dest, minion_relpath), True, saltenv, gzip))
try:
for fn_ in self.file_list_emptydirs(saltenv, prefix=path):
try:
if (fn_[len(path)] != u'/'):
continue
except IndexError:
continue
minion_relpath = fn_[len(prefix):].lstrip(u'/')
minion_mkdir = u'{0}/{1}'.format(dest, minion_relpath)
if (not os.path.isdir(minion_mkdir)):
os.makedirs(minion_mkdir)
ret.append(minion_mkdir)
except TypeError:
pass
ret.sort()
return ret
|
'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'/')))):
strpath = url.split(u'/')[(-1)]
else:
strpath = u'index.html'
if salt.utils.platform.is_windows():
strpath = salt.utils.sanitize_win_path_string(strpath)
dest = os.path.join(dest, strpath)
if (url_scheme and (url_scheme.lower() in string.ascii_lowercase)):
url_path = u':'.join((url_scheme, url_path))
url_scheme = u'file'
if (url_scheme in (u'file', u'')):
if (not os.path.isabs(url_path)):
raise CommandExecutionError(u"Path '{0}' is not absolute".format(url_path))
if (dest is None):
with salt.utils.files.fopen(url_path, u'r') as fp_:
data = fp_.read()
return data
return url_path
if (url_scheme == u'salt'):
result = self.get_file(url, dest, makedirs, saltenv, cachedir=cachedir)
if (result and (dest is None)):
with salt.utils.files.fopen(result, u'r') as fp_:
data = fp_.read()
return data
return result
if dest:
destdir = os.path.dirname(dest)
if (not os.path.isdir(destdir)):
if makedirs:
os.makedirs(destdir)
else:
return u''
elif (not no_cache):
dest = self._extrn_path(url, saltenv, cachedir=cachedir)
destdir = os.path.dirname(dest)
if (not os.path.isdir(destdir)):
os.makedirs(destdir)
if (url_data.scheme == u's3'):
try:
def s3_opt(key, default=None):
u'Get value of s3.<key> from Minion config or from Pillar'
if ((u's3.' + key) in self.opts):
return self.opts[(u's3.' + key)]
try:
return self.opts[u'pillar'][u's3'][key]
except (KeyError, TypeError):
return default
self.utils[u's3.query'](method=u'GET', bucket=url_data.netloc, path=url_data.path[1:], return_bin=False, local_file=dest, action=None, key=s3_opt(u'key'), keyid=s3_opt(u'keyid'), service_url=s3_opt(u'service_url'), verify_ssl=s3_opt(u'verify_ssl', True), location=s3_opt(u'location'), path_style=s3_opt(u'path_style', False), https_enable=s3_opt(u'https_enable', True))
return dest
except Exception as exc:
raise MinionError(u'Could not fetch from {0}. Exception: {1}'.format(url, exc))
if (url_data.scheme == u'ftp'):
try:
ftp = ftplib.FTP()
ftp.connect(url_data.hostname, url_data.port)
ftp.login(url_data.username, url_data.password)
with salt.utils.files.fopen(dest, u'wb') as fp_:
ftp.retrbinary(u'RETR {0}'.format(url_data.path), fp_.write)
ftp.quit()
return dest
except Exception as exc:
raise MinionError(u'Could not retrieve {0} from FTP server. Exception: {1}'.format(url, exc))
if (url_data.scheme == u'swift'):
try:
def swift_opt(key, default):
'\n Get value of <key> from Minion config or from Pillar\n '
if (key in self.opts):
return self.opts[key]
try:
return self.opts[u'pillar'][key]
except (KeyError, TypeError):
return default
swift_conn = SaltSwift(swift_opt(u'keystone.user', None), swift_opt(u'keystone.tenant', None), swift_opt(u'keystone.auth_url', None), swift_opt(u'keystone.password', None))
swift_conn.get_object(url_data.netloc, url_data.path[1:], dest)
return dest
except Exception:
raise MinionError(u'Could not fetch from {0}'.format(url))
get_kwargs = {}
if ((url_data.username is not None) and (url_data.scheme in (u'http', u'https'))):
netloc = url_data.netloc
at_sign_pos = netloc.rfind(u'@')
if (at_sign_pos != (-1)):
netloc = netloc[(at_sign_pos + 1):]
fixed_url = urlunparse((url_data.scheme, netloc, url_data.path, url_data.params, url_data.query, url_data.fragment))
get_kwargs[u'auth'] = (url_data.username, url_data.password)
else:
fixed_url = url
destfp = None
try:
write_body = [None, False, None]
def on_header(hdr):
if ((write_body[1] is not False) and (write_body[2] is None)):
write_body[1].parse_line(hdr)
if (u'Content-Type' in write_body[1]):
content_type = write_body[1].get(u'Content-Type')
if (not content_type.startswith(u'text')):
write_body[1] = write_body[2] = False
else:
encoding = u'utf-8'
fields = content_type.split(u';')
for field in fields:
if (u'encoding' in field):
encoding = field.split(u'encoding=')[(-1)]
write_body[2] = encoding
write_body[1] = False
if (write_body[0] is write_body[1] is False):
write_body[0] = None
if (write_body[0] is None):
try:
hdr = parse_response_start_line(hdr)
except HTTPInputError:
return
write_body[0] = (hdr.code not in [301, 302, 303, 307])
write_body[1] = HTTPHeaders()
if no_cache:
result = []
def on_chunk(chunk):
if write_body[0]:
if write_body[2]:
chunk = chunk.decode(write_body[2])
result.append(chunk)
else:
dest_tmp = u'{0}.part'.format(dest)
destfp = salt.utils.files.fopen(dest_tmp, u'wb')
def on_chunk(chunk):
if write_body[0]:
destfp.write(chunk)
query = salt.utils.http.query(fixed_url, stream=True, streaming_callback=on_chunk, header_callback=on_header, username=url_data.username, password=url_data.password, opts=self.opts, **get_kwargs)
if (u'handle' not in query):
raise MinionError(u'Error: {0} reading {1}'.format(query[u'error'], url))
if no_cache:
if write_body[2]:
return u''.join(result)
return six.b(u'').join(result)
else:
destfp.close()
destfp = None
salt.utils.files.rename(dest_tmp, dest)
return dest
except HTTPError as exc:
raise MinionError(u'HTTP error {0} reading {1}: {3}'.format(exc.code, url, *BaseHTTPServer.BaseHTTPRequestHandler.responses[exc.code]))
except URLError as exc:
raise MinionError(u'Error reading {0}: {1}'.format(url, exc.reason))
finally:
if (destfp is not None):
destfp.close()
|
'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 will be removed in Salt Oxygen.")
kwargs.pop(u'env')
kwargs[u'saltenv'] = saltenv
url_data = urlparse(url)
sfn = self.cache_file(url, saltenv, cachedir=cachedir)
if (not os.path.exists(sfn)):
return u''
if (template in salt.utils.templates.TEMPLATE_REGISTRY):
data = salt.utils.templates.TEMPLATE_REGISTRY[template](sfn, **kwargs)
else:
log.error(u'Attempted to render template with unavailable engine %s', template)
return u''
if (not data[u'result']):
log.error(u'Failed to render template with error: %s', data[u'data'])
return u''
if (not dest):
dest = self._extrn_path(url, saltenv, cachedir=cachedir)
makedirs = True
destdir = os.path.dirname(dest)
if (not os.path.isdir(destdir)):
if makedirs:
os.makedirs(destdir)
else:
salt.utils.files.safe_rm(data[u'data'])
return u''
shutil.move(data[u'data'], dest)
return dest
|
'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(cachedir)):
cachedir = os.path.join(self.opts[u'cachedir'], cachedir)
if url_data.query:
file_name = u'-'.join([url_data.path, url_data.query])
else:
file_name = url_data.path
return salt.utils.path.join(cachedir, u'extrn_files', saltenv, netloc, file_name)
|
'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):
fnd[u'path'] = full
fnd[u'rel'] = path
return fnd
return fnd
|
'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_file_ignored(self.opts, d))]
for fname in files:
relpath = os.path.relpath(os.path.join(root, fname), path)
ret.append(sdecode(relpath))
return ret
|
'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_file_ignored(self.opts, d))]
if ((len(dirs) == 0) and (len(files) == 0)):
ret.append(sdecode(os.path.relpath(root, path)))
return ret
|
'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 ret
|
'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._find_file(path, saltenv)
|
'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_type'] = hash_type
return ret
|
'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:
fnd_stat = None
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_type'] = hash_type
return (ret, fnd_stat)
|
'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 environment yet. It\'s worth noting
that originally this fn started with
if \'external_nodes\' not in opts: return {}
So since external_nodes is gone now, we are just returning the
empty dict.'
| 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_server = None
else:
hash_server = self.hash_file(path, saltenv)
mode_server = None
if (hash_server == u''):
log.debug(u"Could not find file '%s' in saltenv '%s'", path, saltenv)
return False
if ((dest is not None) and (os.path.isdir(dest) or dest.endswith((u'/', u'\\')))):
dest = os.path.join(dest, os.path.basename(path))
log.debug(u"In saltenv '%s', '%s' is a directory. Changing dest to '%s'", saltenv, os.path.dirname(dest), dest)
dest2check = dest
if (not dest2check):
rel_path = self._check_proto(path)
log.debug(u"In saltenv '%s', looking at rel_path '%s' to resolve '%s'", saltenv, rel_path, path)
with self._cache_loc(rel_path, saltenv, cachedir=cachedir) as cache_dest:
dest2check = cache_dest
log.debug(u"In saltenv '%s', ** considering ** path '%s' to resolve '%s'", saltenv, dest2check, path)
if (dest2check and os.path.isfile(dest2check)):
if (not salt.utils.platform.is_windows()):
(hash_local, stat_local) = self.hash_and_stat_file(dest2check, saltenv)
try:
mode_local = stat_local[0]
except (IndexError, TypeError):
mode_local = None
else:
hash_local = self.hash_file(dest2check, saltenv)
mode_local = None
if (hash_local == hash_server):
return dest2check
log.debug(u"Fetching file from saltenv '%s', ** attempting ** '%s'", saltenv, path)
d_tries = 0
transport_tries = 0
path = self._check_proto(path)
load = {u'path': path, u'saltenv': saltenv, u'cmd': u'_serve_file'}
if gzip:
gzip = int(gzip)
load[u'gzip'] = gzip
fn_ = None
if dest:
destdir = os.path.dirname(dest)
if (not os.path.isdir(destdir)):
if makedirs:
os.makedirs(destdir)
else:
return False
fn_ = salt.utils.files.fopen(dest, u'wb+')
else:
log.debug(u'No dest file found')
while True:
if (not fn_):
load[u'loc'] = 0
else:
load[u'loc'] = fn_.tell()
data = self.channel.send(load, raw=True)
if six.PY3:
data = decode_dict_keys_to_str(data)
try:
if (not data[u'data']):
if ((not fn_) and data[u'dest']):
with self._cache_loc(data[u'dest'], saltenv, cachedir=cachedir) as cache_dest:
dest = cache_dest
with salt.utils.files.fopen(cache_dest, u'wb+') as ofile:
ofile.write(data[u'data'])
if ((u'hsum' in data) and (d_tries < 3)):
d_tries += 1
hsum = salt.utils.get_hash(dest, salt.utils.stringutils.to_str(data.get(u'hash_type', 'md5')))
if (hsum != data[u'hsum']):
log.warning(u'Bad download of file %s, attempt %d of 3', path, d_tries)
continue
break
if (not fn_):
with self._cache_loc(data[u'dest'], saltenv, cachedir=cachedir) as cache_dest:
dest = cache_dest
if os.path.isdir(dest):
salt.utils.files.rm_rf(dest)
fn_ = salt.utils.files.fopen(dest, u'wb+')
if data.get(u'gzip', None):
data = salt.utils.gzip_util.uncompress(data[u'data'])
else:
data = data[u'data']
if (six.PY3 and isinstance(data, str)):
data = data.encode()
fn_.write(data)
except (TypeError, KeyError) as exc:
try:
data_type = type(data).__name__
except AttributeError:
data_type = str(type(data))
transport_tries += 1
log.warning(u'Data transport is broken, got: %s, type: %s, exception: %s, attempt %d of 3', data, data_type, exc, transport_tries)
self._refresh_channel()
if (transport_tries > 3):
log.error(u'Data transport is broken, got: %s, type: %s, exception: %s, retry attempts exhausted', data, data_type, exc)
break
if fn_:
fn_.close()
log.info(u"Fetching file from saltenv '%s', ** done ** '%s'", saltenv, path)
else:
log.debug(u"In saltenv '%s', we are ** missing ** the file '%s'", saltenv, path)
return dest
|
'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 = self.opts.get(u'hash_type', u'md5')
ret[u'hsum'] = salt.utils.get_hash(path, form=hash_type)
ret[u'hash_type'] = hash_type
return (ret, list(os.stat(path)))
load = {u'path': path, u'saltenv': saltenv, u'cmd': u'_file_hash_and_stat'}
return self.channel.send(load)
|
'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' in low) or ('eauth' in low))) and (low['client'] != 'ssh')):
raise salt.exceptions.EauthAuthenticationError('No authentication credentials given')
l_fun = getattr(self, low['client'])
f_call = salt.utils.format_call(l_fun, low)
return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {}))
|
'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) and the given function,
``fun``, is called with those parameters.
:return: Returns the result from the execution module'
| 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 parallel senders.'
| 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']})
minion.update({'success': event_info['success']})
job_complete = all([minion['success'] for (mid, minion) in six.iteritems(job['minions'])])
if job_complete:
job['state'] = 'complete'
self.publish('jobs', self.jobs)
|
'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'], 'tgt_type': event_info['tgt_type'], 'state': 'running'}
self.jobs[event_info['jid']] = job
self.publish('jobs', self.jobs)
|
'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.pop(minion, None)
new_minions = (set(minions_detected) - set(curr_minions))
tgt = ','.join(new_minions)
if tgt:
changed = True
client = salt.netapi.NetapiClient(opts)
client.run({'fun': 'grains.items', 'tgt': tgt, 'expr_type': 'list', 'mode': 'client', 'client': 'local', 'async': 'local_async', 'token': token})
if changed:
self.publish_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'):
self.process_ret_job_event(salt_data)
if (salt_data['data']['fun'] == 'grains.items'):
self.process_minion_update(salt_data)
if (parts[1] == 'key'):
self.process_key_event(salt_data)
if (parts[1] == 'presence'):
self.process_presence_events(salt_data, token, opts)
|
'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:
chunk['token'] = token
if cherrypy.session.get('user'):
chunk['__current_eauth_user'] = cherrypy.session.get('user')
if cherrypy.session.get('groups'):
chunk['__current_eauth_groups'] = cherrypy.session.get('groups')
if client:
chunk['client'] = client
if (('arg' in chunk) and (not isinstance(chunk['arg'], list))):
chunk['arg'] = [chunk['arg']]
ret = self.api.run(chunk)
if isinstance(ret, collections.Iterator):
for i in ret:
(yield i)
else:
(yield ret)
|
'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 response:**
.. code-block:: http
HTTP/1.1 200 OK
Content-Type: application/json'
| @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 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:: http
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:: http
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'
| @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:: http
GET /minions/ms-3 HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: http
HTTP/1.1 200 OK
Content-Length: 129005
Content-Type: application/x-yaml
return:
- ms-3:
grains.items:'
| 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 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:: http
POST /minions HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
Content-Type: application/json
tgt=*&fun=status.diskusage
**Example response:**
.. code-block:: http
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'
| 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:**
.. code-block:: bash
curl -i localhost:8000/jobs
.. code-block:: http
GET /jobs HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: http
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:: http
GET /jobs/20121130104633606931 HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: http
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'
| 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:
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
|
'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:: http
GET /keys HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: http
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:: http
GET /keys/jerry HTTP/1.1
Host: localhost:8000
Accept: application/x-yaml
**Example response:**
.. code-block:: http
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'
| 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', {}).get('return', {})}
|
'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:: http
POST /keys HTTP/1.1
Host: localhost:8000
**Example response:**
.. code-block:: http
HTTP/1.1 200 OK
Content-Length: 10240
Content-Disposition: attachment; filename="saltkeys-jerry.tar"
Content-Type: application/x-tar
jerry.pub0000644000000000000000000000070300000000000010730 0ustar 00000000000000'
| @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', '')
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 = six.StringIO()
tarball = tarfile.open(fileobj=fileobj, mode='w')
tarball.addfile(pub_key_file, six.StringIO(pub_key))
tarball.addfile(priv_key_file, six.StringIO(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'] = fileobj.len
headers['Cache-Control'] = 'no-cache'
fileobj.seek(0)
return fileobj
|
'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-block:: http
HTTP/1.1 200 OK
Content-Type: text/html'
| 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|
: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:: http
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:: http
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.*"'
| 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
username = creds.get('username', None)
if (not salt_api_acl_tool(username, cherrypy.request)):
raise cherrypy.HTTPError(401)
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)
cherrypy.session['user'] = token['name']
if ('groups' in token):
cherrypy.session['groups'] = token['groups']
try:
eauth = self.opts.get('external_auth', {}).get(token['eauth'], {})
if ((token['eauth'] == 'django') and ('^model' in eauth)):
perms = token['auth_list']
else:
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 '{0}', and user '{1}'.".format(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 {})}]}
|
'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:**
.. code-block:: http
HTTP/1.1 200 OK
Content-Type: application/json
"start": 1494987445.528182,
"token": "e72ca1655d05...",
"expire": 1495030645.528183,
"name": "saltdev",
"eauth": "auto"'
| @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", "password", and "eauth" params')
return list(self.exec_lowstate())
|
'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: |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:: http
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:: http
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. Instad,
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:: http
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:: http
return:
- silver:
fun: test.ping
fun_args: []
id: silver
jid: \'20141203103525666185\'
retcode: 0
return: true
success: true'
| 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 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:: http
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:: http
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 appliction 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"}}'
| 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'] = 'text/event-stream'
cherrypy.response.headers['Cache-Control'] = 'no-cache'
cherrypy.response.headers['Connection'] = 'keep-alive'
def listen():
'\n An iterator to yield Salt events\n '
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 u'retry: {0}\n'.format(400))
while True:
data = next(stream)
(yield u'tag: {0}\n'.format(data.get('tag', '')))
(yield u'data: {0}\n\n'.format(json.dumps(data)))
return listen()
|
'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:: http
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:: http
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``.'
| 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.release_lock()
handler = cherrypy.request.ws_handler
def event_stream(handler, pipe):
'\n An iterator to return Salt events (and optionally format them)\n '
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:
if ('format_events' in kwargs):
SaltInfo.process(data, salt_token, self.opts)
else:
handler.send('data: {0}\n\n'.format(json.dumps(data)), False)
except UnicodeDecodeError:
logger.error('Error: Salt event has non UTF-8 data:\n{0}'.format(data))
(parent_pipe, child_pipe) = Pipe()
handler.pipe = parent_pipe
handler.opts = self.opts
proc = Process(target=event_stream, args=(handler, child_pipe))
proc.start()
|
'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:: http
POST /hook HTTP/1.1
Host: localhost:8000
Content-Length: 16
Content-Type: application/json
{"foo": "Foo!", "bar": "Bar!"}
**Example response**:
.. code-block:: http
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 %}'
| 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': data, 'headers': headers}, tag)
return {'success': ret}
|
'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 {}
return cpstats.extrapolate_statistics(logging.statistics)
return {}
|
'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_responses', True), '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.cpstats.on': self.apiopts.get('collect_stats', False), 'tools.html_override.on': True, 'tools.cors_tool.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'
if ('static' in self.apiopts):
conf[self.apiopts.get('static_path', '/static')] = {'tools.staticdir.on': True, 'tools.staticdir.dir': self.apiopts['static']}
cherrypy.config.update(conf['global'])
return conf
|
'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]
del self.request_map[request]
|
'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(handle_future)
self.tag_map[tag].append(future)
self.request_map[request].append((tag, future))
if timeout:
timeout_future = tornado.ioloop.IOLoop.current().call_later(timeout, self._timeout_future, tag, future)
self.timeout_map[future] = timeout_future
return future
|
'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': mtag})
self.tag_map[tag_prefix].remove(future)
if (future in self.timeout_map):
tornado.ioloop.IOLoop.current().remove_timeout(self.timeout_map[future])
del self.timeout_map[future]
|
'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:
if fnmatch.fnmatch(content_type, media_range):
return (content_type, dumper)
return (None, None)
(content_type, dumper) = find_acceptable_content_type(parsed_accept_header)
if (not content_type):
self.send_error(406)
self.content_type = content_type
self.dumper = dumper
self.start = time.time()
self.connected = True
self.lowstate = self._get_lowstate()
|
'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
return ct_in_map[value](tornado.escape.native_str(data))
except KeyError:
self.send_error(406)
except ValueError:
self.send_error(400)
|
'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:
lowstate = data
return lowstate
|
'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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.