INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Set the salt process environment variables. name The environment key to set. Must be a string. value Either a string or dict. When string, it will be the value set for the environment key of 'name' above. When a dict, each key/value pair represents an environment variab...
def setenv(name, value, false_unsets=False, clear_all=False, update_minion=False, permanent=False): ''' Set the salt process environment variables. name The environment key to set. Must be a string. value Either a string or dict. W...
Create a znc compatible hashed password
def _makepass(password, hasher='sha256'): ''' Create a znc compatible hashed password ''' # Setup the hasher if hasher == 'sha256': h = hashlib.sha256(password) elif hasher == 'md5': h = hashlib.md5(password) else: return NotImplemented c = "abcdefghijklmnopqrstu...
Build module using znc-buildmod CLI Example: .. code-block:: bash salt '*' znc.buildmod module.cpp [...]
def buildmod(*modules): ''' Build module using znc-buildmod CLI Example: .. code-block:: bash salt '*' znc.buildmod module.cpp [...] ''' # Check if module files are missing missing = [module for module in modules if not os.path.exists(module)] if missing: return 'Error...
Return server version from znc --version CLI Example: .. code-block:: bash salt '*' znc.version
def version(): ''' Return server version from znc --version CLI Example: .. code-block:: bash salt '*' znc.version ''' cmd = ['znc', '--version'] out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() ret = out[0].split(' - ') return ret[0]
Return a MSSQL connection.
def _get_conn(ret=None): ''' Return a MSSQL connection. ''' _options = _get_options(ret) dsn = _options.get('dsn') user = _options.get('user') passwd = _options.get('passwd') return pyodbc.connect('DSN={0};UID={1};PWD={2}'.format( dsn, user, passwd))
Return data to an odbc server
def returner(ret): ''' Return data to an odbc server ''' conn = _get_conn(ret) cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, retval, id, success, full_ret) VALUES (?, ?, ?, ?, ?, ?)''' cur.execute( sql, ( ret['fun'], ...
Return the information returned when the specified job id was executed
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT id, full_ret FROM salt_returns WHERE jid = ?''' cur.execute(sql, (jid,)) data = cur.fetchall() ret = {} if data: ...
Return a dict of the last function called for all minions
def get_fun(fun): ''' Return a dict of the last function called for all minions ''' conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT s.id,s.jid, s.full_ret FROM salt_returns s JOIN ( SELECT MAX(jid) AS jid FROM salt_returns GROUP BY fun, id) max ...
Return a list of all job ids
def get_jids(): ''' Return a list of all job ids ''' conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT distinct jid, load FROM jids''' cur.execute(sql) data = cur.fetchall() ret = {} for jid, load in data: ret[jid] = salt.utils.jid.format_jid_instance(jid, s...
Loads and parses /usbkey/config
def _load_config(): ''' Loads and parses /usbkey/config ''' config = {} if os.path.isfile('/usbkey/config'): with salt.utils.files.fopen('/usbkey/config', 'r') as config_file: for optval in config_file: optval = salt.utils.stringutils.to_unicode(optval) ...
writes /usbkey/config
def _write_config(config): ''' writes /usbkey/config ''' try: with salt.utils.atomicfile.atomic_open('/usbkey/config', 'w') as config_file: config_file.write("#\n# This file was generated by salt\n#\n") for prop in salt.utils.odict.OrderedDict(sorted(config.items())): ...
Parse vm_present vm config
def _parse_vmconfig(config, instances): ''' Parse vm_present vm config ''' vmconfig = None if isinstance(config, (salt.utils.odict.OrderedDict)): vmconfig = salt.utils.odict.OrderedDict() for prop in config: if prop not in instances: vmconfig[prop] = conf...
get modified properties
def _get_instance_changes(current, state): ''' get modified properties ''' # get keys current_keys = set(current.keys()) state_keys = set(state.keys()) # compare configs changed = salt.utils.data.compare_dicts(current, state) for change in salt.utils.data.compare_dicts(current, stat...
Ensure configuration property is set to value in /usbkey/config name : string name of property value : string value of property
def config_present(name, value): ''' Ensure configuration property is set to value in /usbkey/config name : string name of property value : string value of property ''' name = name.lower() ret = {'name': name, 'changes': {}, 'result': None, ...
Ensure configuration property is absent in /usbkey/config name : string name of property
def config_absent(name): ''' Ensure configuration property is absent in /usbkey/config name : string name of property ''' name = name.lower() ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} # load configuration config = _load...
Ensure an image source is present on the computenode name : string source url source_type : string source type (imgapi or docker)
def source_present(name, source_type='imgapi'): ''' Ensure an image source is present on the computenode name : string source url source_type : string source type (imgapi or docker) ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment...
Ensure an image source is absent on the computenode name : string source url
def source_absent(name): ''' Ensure an image source is absent on the computenode name : string source url ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if name not in __salt__['imgadm.sources'](): # source is absent ...
Ensure image is present on the computenode name : string uuid of image
def image_present(name): ''' Ensure image is present on the computenode name : string uuid of image ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if _is_docker_uuid(name) and __salt__['imgadm.docker_to_uuid'](name): # do...
Ensure image is absent on the computenode name : string uuid of image .. note:: computenode.image_absent will only remove the image if it is not used by a vm.
def image_absent(name): ''' Ensure image is absent on the computenode name : string uuid of image .. note:: computenode.image_absent will only remove the image if it is not used by a vm. ''' ret = {'name': name, 'changes': {}, 'result': None, ...
Delete images not in use or installed via image_present .. warning:: Only image_present states that are included via the top file will be detected.
def image_vacuum(name): ''' Delete images not in use or installed via image_present .. warning:: Only image_present states that are included via the top file will be detected. ''' name = name.lower() ret = {'name': name, 'changes': {}, 'result': None, ...
Ensure vm is absent on the computenode name : string hostname of vm archive : boolean toggle archiving of vm on removal .. note:: State ID is used as hostname. Hostnames must be unique.
def vm_absent(name, archive=False): ''' Ensure vm is absent on the computenode name : string hostname of vm archive : boolean toggle archiving of vm on removal .. note:: State ID is used as hostname. Hostnames must be unique. ''' name = name.lower() ret = {'na...
Ensure vm is in the running state on the computenode name : string hostname of vm .. note:: State ID is used as hostname. Hostnames must be unique.
def vm_running(name): ''' Ensure vm is in the running state on the computenode name : string hostname of vm .. note:: State ID is used as hostname. Hostnames must be unique. ''' name = name.lower() ret = {'name': name, 'changes': {}, 'result': None, ...
Repack the options data
def _repack_options(options): ''' Repack the options data ''' return dict( [ (six.text_type(x), _normalize(y)) for x, y in six.iteritems(salt.utils.data.repack_dictlist(options)) ] )
Returns the key/value pairs in the passed dict in a commaspace-delimited list in the format "key=value".
def _get_option_list(options): ''' Returns the key/value pairs in the passed dict in a commaspace-delimited list in the format "key=value". ''' return ', '.join(['{0}={1}'.format(x, y) for x, y in six.iteritems(options)])
Verify that the desired port is installed, and that it was compiled with the desired options. options Make sure that the desired non-default options are set .. warning:: Any build options not passed here assume the default values for the port, and are not just differen...
def installed(name, options=None): ''' Verify that the desired port is installed, and that it was compiled with the desired options. options Make sure that the desired non-default options are set .. warning:: Any build options not passed here assume the default values for ...
Ensure that the configuration passed is formatted correctly and contains valid IP addresses, etc.
def _validate(dns_proto, dns_servers, ip_proto, ip_addrs, gateway): ''' Ensure that the configuration passed is formatted correctly and contains valid IP addresses, etc. ''' errors = [] # Validate DNS configuration if dns_proto == 'dhcp': if dns_servers is not None: error...
Compares the current interface against the desired configuration and returns a dictionary describing the changes that need to be made.
def _changes(cur, dns_proto, dns_servers, ip_proto, ip_addrs, gateway): ''' Compares the current interface against the desired configuration and returns a dictionary describing the changes that need to be made. ''' changes = {} cur_dns_proto = ( 'static' if 'Statically Configured DNS Ser...
Ensure that the named interface is configured properly. Args: name (str): The name of the interface to manage dns_proto (str): None Set to ``static`` and use the ``dns_servers`` parameter to provide a list of DNS nameservers. set to ``dhcp`` to use DHCP to get ...
def managed(name, dns_proto=None, dns_servers=None, ip_proto=None, ip_addrs=None, gateway=None, enabled=True, **kwargs): ''' Ensure that the named interface is configured properly. Args: name (str): The...
Load OpenSSL libcrypto
def _load_libcrypto(): ''' Load OpenSSL libcrypto ''' if sys.platform.startswith('win'): # cdll.LoadLibrary on windows requires an 'str' argument return cdll.LoadLibrary(str('libeay32')) # future lint: disable=blacklisted-function elif getattr(sys, 'frozen', False) and salt.utils.pl...
Set up libcrypto argtypes and initialize the library
def _init_libcrypto(): ''' Set up libcrypto argtypes and initialize the library ''' libcrypto = _load_libcrypto() try: libcrypto.OPENSSL_init_crypto() except AttributeError: # Support for OpenSSL < 1.1 (OPENSSL_API_COMPAT < 0x10100000L) libcrypto.OPENSSL_no_config() ...
Sign a message (digest) using the private key :param str msg: The message (digest) to sign :rtype: str :return: The signature, or an empty string if the encryption failed
def sign(self, msg): ''' Sign a message (digest) using the private key :param str msg: The message (digest) to sign :rtype: str :return: The signature, or an empty string if the encryption failed ''' # Allocate a buffer large enough for the signature. Freed by ct...
Install a cabal package. pkg A package name in format accepted by cabal-install. See: https://wiki.haskell.org/Cabal-Install pkgs A list of packages names in same format as ``pkg`` user The user to run cabal install with install_global Install package globally...
def install(pkg=None, pkgs=None, user=None, install_global=False, env=None): ''' Install a cabal package. pkg A package name in format accepted by cabal-install. See: https://wiki.haskell.org/Cabal-Install pkgs A list of packages ...
List packages matching a search string. pkg Search string for matching package names user The user to run cabal list with installed If True, only return installed packages. env Environment variables to set when invoking cabal. Uses the same ``env`` format as the ...
def list_( pkg=None, user=None, installed=False, env=None): ''' List packages matching a search string. pkg Search string for matching package names user The user to run cabal list with installed If True, only return installed packages. en...
Recover the message (digest) from the signature using the public key :param str signed: The signature created with the private key :rtype: str :return: The message (digest) recovered from the signature, or an empty string if the decryption failed
def verify(self, signed): ''' Recover the message (digest) from the signature using the public key :param str signed: The signature created with the private key :rtype: str :return: The message (digest) recovered from the signature, or an empty string if the decrypti...
Uninstall a cabal package. pkg The package to uninstall user The user to run ghc-pkg unregister with env Environment variables to set when invoking cabal. Uses the same ``env`` format as the :py:func:`cmd.run <salt.modules.cmdmod.run>` execution function CLI Exa...
def uninstall(pkg, user=None, env=None): ''' Uninstall a cabal package. pkg The package to uninstall user The user to run ghc-pkg unregister with env Environment variables to set when invoking cabal. Uses the same ``env`` format as the :py...
Accepts YAML_EX as a string or as a file object and runs it through the YAML_EX parser. :rtype: A Python data structure
def render(sls_data, saltenv='base', sls='', **kws): ''' Accepts YAML_EX as a string or as a file object and runs it through the YAML_EX parser. :rtype: A Python data structure ''' with warnings.catch_warnings(record=True) as warn_list: data = deserialize(sls_data) or {} for it...
Signal a Django server that a return is available
def returner(ret): ''' Signal a Django server that a return is available ''' signaled = dispatch.Signal(providing_args=['ret']).send(sender='returner', ret=ret) for signal in signaled: log.debug( 'Django returner function \'returner\' signaled %s ' 'which responded w...
Save the load to the specified jid
def save_load(jid, load, minions=None): ''' Save the load to the specified jid ''' signaled = dispatch.Signal( providing_args=['jid', 'load']).send( sender='save_load', jid=jid, load=load) for signal in signaled: log.debug( 'Django returner function \'save_lo...
Do any work necessary to prepare a JID, including sending a custom ID
def prep_jid(nocache=False, passed_jid=None): ''' Do any work necessary to prepare a JID, including sending a custom ID ''' return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
Load and start all available api modules
def run(self): ''' Load and start all available api modules ''' if not len(self.netapi): log.error("Did not find any netapi configurations, nothing to start") kwargs = {} if salt.utils.platform.is_windows(): kwargs['log_queue'] = salt.log.setup.ge...
Query |varstack| for the top data (states of the minions).
def top(**kwargs): ''' Query |varstack| for the top data (states of the minions). ''' conf = __opts__['master_tops']['varstack'] __grains__ = kwargs['grains'] vs_ = varstack.Varstack(config_filename=conf) ret = vs_.evaluate(__grains__) return {'base': ret['states']}
Try and authenticate
def auth(username, password): ''' Try and authenticate ''' try: keystone = client.Client(username=username, password=password, auth_url=get_auth_url()) return keystone.authenticate() except (AuthorizationFailure, Unauthorized): return False
Returns the value of the matched xpath element CLI Example: .. code-block:: bash salt '*' xml.get_value /tmp/test.xml ".//element"
def get_value(file, element): ''' Returns the value of the matched xpath element CLI Example: .. code-block:: bash salt '*' xml.get_value /tmp/test.xml ".//element" ''' try: root = ET.parse(file) element = root.find(element) return element.text except Attri...
Sets the value of the matched xpath element CLI Example: .. code-block:: bash salt '*' xml.set_value /tmp/test.xml ".//element" "new value"
def set_value(file, element, value): ''' Sets the value of the matched xpath element CLI Example: .. code-block:: bash salt '*' xml.set_value /tmp/test.xml ".//element" "new value" ''' try: root = ET.parse(file) relement = root.find(element) except AttributeError: ...
Return the attributes of the matched xpath element. CLI Example: .. code-block:: bash salt '*' xml.get_attribute /tmp/test.xml ".//element[@id='3']"
def get_attribute(file, element): ''' Return the attributes of the matched xpath element. CLI Example: .. code-block:: bash salt '*' xml.get_attribute /tmp/test.xml ".//element[@id='3']" ''' try: root = ET.parse(file) element = root.find(element) return element...
Set the requested attribute key and value for matched xpath element. CLI Example: .. code-block:: bash salt '*' xml.set_attribute /tmp/test.xml ".//element[@id='3']" editedby "gal"
def set_attribute(file, element, key, value): ''' Set the requested attribute key and value for matched xpath element. CLI Example: .. code-block:: bash salt '*' xml.set_attribute /tmp/test.xml ".//element[@id='3']" editedby "gal" ''' try: root = ET.parse(file) element...
List Swift containers
def get_account(self): ''' List Swift containers ''' try: listing = self.conn.get_account() return listing except Exception as exc: log.error('There was an error::') if hasattr(exc, 'code') and hasattr(exc, 'msg'): l...
Retrieve a file from Swift
def get_object(self, cont, obj, local_file=None, return_bin=False): ''' Retrieve a file from Swift ''' try: if local_file is None and return_bin is False: return False headers, body = self.conn.get_object(cont, obj, resp_chunk_size=65536) ...
Upload a file to Swift
def put_object(self, cont, obj, local_file): ''' Upload a file to Swift ''' try: with salt.utils.files.fopen(local_file, 'rb') as fp_: self.conn.put_object(cont, obj, fp_) return True except Exception as exc: log.error('There wa...
Delete a file from Swift
def delete_object(self, cont, obj): ''' Delete a file from Swift ''' try: self.conn.delete_object(cont, obj) return True except Exception as exc: log.error('There was an error::') if hasattr(exc, 'code') and hasattr(exc, 'msg'): ...
Parse one line of the XFS info output.
def _xfs_info_get_kv(serialized): ''' Parse one line of the XFS info output. ''' # No need to know sub-elements here if serialized.startswith("="): serialized = serialized[1:].strip() serialized = serialized.replace(" = ", "=*** ").replace(" =", "=") # Keywords has no spaces, value...
Parse output from "xfs_info" or "xfs_growfs -n".
def _parse_xfs_info(data): ''' Parse output from "xfs_info" or "xfs_growfs -n". ''' ret = {} spr = re.compile(r'\s+') entry = None for line in [spr.sub(" ", l).strip().replace(", ", " ") for l in data.split("\n")]: if not line: continue nfo = _xfs_info_get_kv(line...
Get filesystem geometry information. CLI Example: .. code-block:: bash salt '*' xfs.info /dev/sda1
def info(device): ''' Get filesystem geometry information. CLI Example: .. code-block:: bash salt '*' xfs.info /dev/sda1 ''' out = __salt__['cmd.run_all']("xfs_info {0}".format(device)) if out.get('stderr'): raise CommandExecutionError(out['stderr'].replace("xfs_info:", ""...
Parse CLI output of the xfsdump utility.
def _xfsdump_output(data): ''' Parse CLI output of the xfsdump utility. ''' out = {} summary = [] summary_block = False for line in [l.strip() for l in data.split("\n") if l.strip()]: line = re.sub("^xfsdump: ", "", line) if line.startswith("session id:"): out['S...
Dump filesystem device to the media (file, tape etc). Required parameters: * **device**: XFS device, content of which to be dumped. * **destination**: Specifies a dump destination. Valid options are: * **label**: Label of the dump. Otherwise automatically generated label is used. * **level**...
def dump(device, destination, level=0, label=None, noerase=None): ''' Dump filesystem device to the media (file, tape etc). Required parameters: * **device**: XFS device, content of which to be dumped. * **destination**: Specifies a dump destination. Valid options are: * **label**: Label...
Parse xfsrestore output keyset elements.
def _xr_to_keyset(line): ''' Parse xfsrestore output keyset elements. ''' tkns = [elm for elm in line.strip().split(":", 1) if elm] if len(tkns) == 1: return "'{0}': ".format(tkns[0]) else: key, val = tkns return "'{0}': '{1}',".format(key.strip(), val.strip())
Transform xfsrestore inventory data output to a Python dict source and evaluate it.
def _xfs_inventory_output(out): ''' Transform xfsrestore inventory data output to a Python dict source and evaluate it. ''' data = [] out = [line for line in out.split("\n") if line.strip()] # No inventory yet if len(out) == 1 and 'restore status' in out[0].lower(): return {'restore...
Parse prune output.
def _xfs_prune_output(out, uuid): ''' Parse prune output. ''' data = {} cnt = [] cutpoint = False for line in [l.strip() for l in out.split("\n") if l]: if line.startswith("-"): if cutpoint: break else: cutpoint = True ...
Prunes the dump session identified by the given session id. CLI Example: .. code-block:: bash salt '*' xfs.prune_dump b74a3586-e52e-4a4a-8775-c3334fa8ea2c
def prune_dump(sessionid): ''' Prunes the dump session identified by the given session id. CLI Example: .. code-block:: bash salt '*' xfs.prune_dump b74a3586-e52e-4a4a-8775-c3334fa8ea2c ''' out = __salt__['cmd.run_all']("xfsinvutil -s {0} -F".format(sessionid)) _verify_run(out) ...
Parse xfs_estimate output.
def _xfs_estimate_output(out): ''' Parse xfs_estimate output. ''' spc = re.compile(r"\s+") data = {} for line in [l for l in out.split("\n") if l.strip()][1:]: directory, bsize, blocks, megabytes, logsize = spc.sub(" ", line).split(" ") data[directory] = { 'block _siz...
Estimate the space that an XFS filesystem will take. For each directory estimate the space that directory would take if it were copied to an XFS filesystem. Estimation does not cross mount points. CLI Example: .. code-block:: bash salt '*' xfs.estimate /path/to/file salt '*' xfs.e...
def estimate(path): ''' Estimate the space that an XFS filesystem will take. For each directory estimate the space that directory would take if it were copied to an XFS filesystem. Estimation does not cross mount points. CLI Example: .. code-block:: bash salt '*' xfs.estimate /pat...
Create a file system on the specified device. By default wipes out with force. General options: * **label**: Specify volume label. * **ssize**: Specify the fundamental sector size of the filesystem. * **noforce**: Do not force create filesystem, if disk is already formatted. Filesystem geometry o...
def mkfs(device, label=None, ssize=None, noforce=None, bso=None, gmo=None, ino=None, lso=None, rso=None, nmo=None, dso=None): ''' Create a file system on the specified device. By default wipes out with force. General options: * **label**: Specify volume label. * **ssize**: Specify the fun...
Modify parameters of an XFS filesystem. CLI Example: .. code-block:: bash salt '*' xfs.modify /dev/sda1 label='My backup' lazy_counting=False salt '*' xfs.modify /dev/sda1 uuid=False salt '*' xfs.modify /dev/sda1 uuid=True
def modify(device, label=None, lazy_counting=None, uuid=None): ''' Modify parameters of an XFS filesystem. CLI Example: .. code-block:: bash salt '*' xfs.modify /dev/sda1 label='My backup' lazy_counting=False salt '*' xfs.modify /dev/sda1 uuid=False salt '*' xfs.modify /dev/sd...
List mounted filesystems.
def _get_mounts(): ''' List mounted filesystems. ''' mounts = {} with salt.utils.files.fopen("/proc/mounts") as fhr: for line in salt.utils.data.decode(fhr.readlines()): device, mntpnt, fstype, options, fs_freq, fs_passno = line.strip().split(" ") if fstype != 'xfs': ...
Defragment mounted XFS filesystem. In order to mount a filesystem, device should be properly mounted and writable. CLI Example: .. code-block:: bash salt '*' xfs.defragment /dev/sda1
def defragment(device): ''' Defragment mounted XFS filesystem. In order to mount a filesystem, device should be properly mounted and writable. CLI Example: .. code-block:: bash salt '*' xfs.defragment /dev/sda1 ''' if device == '/': raise CommandExecutionError("Root is not...
Return a checksum digest for a string instr A string checksum : ``md5`` The hashing algorithm to use to generate checksums. Valid options: md5, sha256, sha512. CLI Example: .. code-block:: bash salt '*' hashutil.digest 'get salted'
def digest(instr, checksum='md5'): ''' Return a checksum digest for a string instr A string checksum : ``md5`` The hashing algorithm to use to generate checksums. Valid options: md5, sha256, sha512. CLI Example: .. code-block:: bash salt '*' hashutil.digest 'g...
Return a checksum digest for a file infile A file path checksum : ``md5`` The hashing algorithm to use to generate checksums. Wraps the :py:func:`hashutil.digest <salt.modules.hashutil.digest>` execution function. CLI Example: .. code-block:: bash salt '*' has...
def digest_file(infile, checksum='md5'): ''' Return a checksum digest for a file infile A file path checksum : ``md5`` The hashing algorithm to use to generate checksums. Wraps the :py:func:`hashutil.digest <salt.modules.hashutil.digest>` execution function. CLI Exa...
Read a file from the file system and return as a base64 encoded string .. versionadded:: 2016.3.0 Pillar example: .. code-block:: yaml path: to: data: | {{ salt.hashutil.base64_encodefile('/path/to/binary_file') | indent(6) }} The :py:func:`file.decode <s...
def base64_encodefile(fname): ''' Read a file from the file system and return as a base64 encoded string .. versionadded:: 2016.3.0 Pillar example: .. code-block:: yaml path: to: data: | {{ salt.hashutil.base64_encodefile('/path/to/binary_file') | inde...
r''' Decode a base64-encoded string and write the result to a file .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' hashutil.base64_decodefile instr='Z2V0IHNhbHRlZAo=' outfile='/path/to/binary_file'
def base64_decodefile(instr, outfile): r''' Decode a base64-encoded string and write the result to a file .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' hashutil.base64_decodefile instr='Z2V0IHNhbHRlZAo=' outfile='/path/to/binary_file' ''' encoded_f = Strin...
Verify a challenging hmac signature against a string / shared-secret .. versionadded:: 2014.7.0 Returns a boolean if the verification succeeded or failed. CLI Example: .. code-block:: bash salt '*' hashutil.hmac_signature 'get salted' 'shared secret' 'eBWf9bstXg+NiP5AOwppB5HMvZiYMPzEM9W5YMm...
def hmac_signature(string, shared_secret, challenge_hmac): ''' Verify a challenging hmac signature against a string / shared-secret .. versionadded:: 2014.7.0 Returns a boolean if the verification succeeded or failed. CLI Example: .. code-block:: bash salt '*' hashutil.hmac_signatur...
Verify a challenging hmac signature against a string / shared-secret for github webhooks. .. versionadded:: 2017.7.0 Returns a boolean if the verification succeeded or failed. CLI Example: .. code-block:: bash salt '*' hashutil.github_signature '{"ref":....} ' 'shared secret' 'sha1=bc65...
def github_signature(string, shared_secret, challenge_hmac): ''' Verify a challenging hmac signature against a string / shared-secret for github webhooks. .. versionadded:: 2017.7.0 Returns a boolean if the verification succeeded or failed. CLI Example: .. code-block:: bash salt...
Execute a runner asynchronous: USAGE: .. code-block:: yaml run_cloud: wheel.cmd: - fun: key.delete - match: minion_id
def cmd( name, fun=None, arg=(), **kwargs): ''' Execute a runner asynchronous: USAGE: .. code-block:: yaml run_cloud: wheel.cmd: - fun: key.delete - match: minion_id ''' ret = {'name': name, 'changes': {}, ...
Get inspectlib module for the lazy loader. :param module: :return:
def _(module): ''' Get inspectlib module for the lazy loader. :param module: :return: ''' mod = None # pylint: disable=E0598 try: # importlib is in Python 2.7+ and 3+ import importlib mod = importlib.import_module("salt.modules.inspectlib.{0}".format(module)) ...
Start node inspection and save the data to the database for further query. Parameters: * **mode**: Clarify inspection mode: configuration, payload, all (default) payload * **filter**: Comma-separated directories to track payload. * **priority**: (advanced) Set priority of the inspection. D...
def inspect(mode='all', priority=19, **kwargs): ''' Start node inspection and save the data to the database for further query. Parameters: * **mode**: Clarify inspection mode: configuration, payload, all (default) payload * **filter**: Comma-separated directories to track payload. ...
Query the node for specific information. Parameters: * **scope**: Specify scope of the query. * **System**: Return system data. * **Software**: Return software information. * **Services**: Return known services. * **Identity**: Return user accounts information for this system. ...
def query(*args, **kwargs): ''' Query the node for specific information. Parameters: * **scope**: Specify scope of the query. * **System**: Return system data. * **Software**: Return software information. * **Services**: Return known services. * **Identity**: Return use...
Build an image from a current system description. The image is a system image can be output in bootable ISO or QCOW2 formats. Node uses the image building library Kiwi to perform the actual build. Parameters: * **format**: Specifies output format: "qcow2" or "iso. Default: `qcow2`. * **path**: Sp...
def build(format='qcow2', path='/tmp/'): ''' Build an image from a current system description. The image is a system image can be output in bootable ISO or QCOW2 formats. Node uses the image building library Kiwi to perform the actual build. Parameters: * **format**: Specifies output format: ...
Export an image description for Kiwi. Parameters: * **local**: Specifies True or False if the export has to be in the local file. Default: False. * **path**: If `local=True`, then specifies the path where file with the Kiwi description is written. Default: `/tmp`. CLI Example: .....
def export(local=False, path="/tmp", format='qcow2'): ''' Export an image description for Kiwi. Parameters: * **local**: Specifies True or False if the export has to be in the local file. Default: False. * **path**: If `local=True`, then specifies the path where file with the Kiwi description is w...
List current description snapshots. CLI Example: .. code-block:: bash salt myminion inspector.snapshots
def snapshots(): ''' List current description snapshots. CLI Example: .. code-block:: bash salt myminion inspector.snapshots ''' try: return _("collector").Inspector(cachedir=__opts__['cachedir'], piddir=os.path.dirname(__opts__['pidfile...
Remove description snapshots from the system. ::parameter: all. Default: False. Remove all snapshots, if set to True. CLI example: .. code-block:: bash salt myminion inspector.delete <ID> <ID1> <ID2>.. salt myminion inspector.delete all=True
def delete(all=False, *databases): ''' Remove description snapshots from the system. ::parameter: all. Default: False. Remove all snapshots, if set to True. CLI example: .. code-block:: bash salt myminion inspector.delete <ID> <ID1> <ID2>.. salt myminion inspector.delete all=True...
Create the salt proxy file and start the proxy process if required Parameters: name: The name of this state proxyname: Name to be used for this proxy (should match entries in pillar) start: Boolean indicating if the process should be started Exam...
def configure_proxy(name, proxyname='p8000', start=True): ''' Create the salt proxy file and start the proxy process if required Parameters: name: The name of this state proxyname: Name to be used for this proxy (should match entries in pillar) start: ...
Hadoop/hdfs command wrapper As Hadoop command has been deprecated this module will default to use hdfs command and fall back to hadoop if it is not found In order to prevent random execution the module name is checked Follows hadoop command template: hadoop module -command args ...
def _hadoop_cmd(module, command, *args): ''' Hadoop/hdfs command wrapper As Hadoop command has been deprecated this module will default to use hdfs command and fall back to hadoop if it is not found In order to prevent random execution the module name is checked Follows hadoop ...
Check if a file or directory is present on the distributed FS. CLI Example: .. code-block:: bash salt '*' hadoop.dfs_present /some_random_file Returns True if the file is present
def dfs_present(path): ''' Check if a file or directory is present on the distributed FS. CLI Example: .. code-block:: bash salt '*' hadoop.dfs_present /some_random_file Returns True if the file is present ''' cmd_return = _hadoop_cmd('dfs', 'stat', path) match = 'No such fil...
Check if a file or directory is absent on the distributed FS. CLI Example: .. code-block:: bash salt '*' hadoop.dfs_absent /some_random_file Returns True if the file is absent
def dfs_absent(path): ''' Check if a file or directory is absent on the distributed FS. CLI Example: .. code-block:: bash salt '*' hadoop.dfs_absent /some_random_file Returns True if the file is absent ''' cmd_return = _hadoop_cmd('dfs', 'stat', path) match = 'No such file or...
wait for subprocess to terminate and return subprocess' return code. If timeout is reached, throw TimedProcTimeoutError
def run(self): ''' wait for subprocess to terminate and return subprocess' return code. If timeout is reached, throw TimedProcTimeoutError ''' def receive(): if self.with_communicate: self.stdout, self.stderr = self.process.communicate(input=self.stdin...
Get complete stream info from AWS, via describe_stream, including all shards. CLI example:: salt myminion boto_kinesis._get_full_stream my_stream region=us-east-1
def _get_full_stream(stream_name, region=None, key=None, keyid=None, profile=None): ''' Get complete stream info from AWS, via describe_stream, including all shards. CLI example:: salt myminion boto_kinesis._get_full_stream my_stream region=us-east-1 ''' conn = _get_conn(region=region, key...
Get complete stream info from AWS, returning only when the stream is in the ACTIVE state. Continues to retry when stream is updating or creating. If the stream is deleted during retries, the loop will catch the error and break. CLI example:: salt myminion boto_kinesis.get_stream_when_active my_str...
def get_stream_when_active(stream_name, region=None, key=None, keyid=None, profile=None): ''' Get complete stream info from AWS, returning only when the stream is in the ACTIVE state. Continues to retry when stream is updating or creating. If the stream is deleted during retries, the loop will catch the...
Check if the stream exists. Returns False and the error if it does not. CLI example:: salt myminion boto_kinesis.exists my_stream region=us-east-1
def exists(stream_name, region=None, key=None, keyid=None, profile=None): ''' Check if the stream exists. Returns False and the error if it does not. CLI example:: salt myminion boto_kinesis.exists my_stream region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile...
Create a stream with name stream_name and initial number of shards num_shards. CLI example:: salt myminion boto_kinesis.create_stream my_stream N region=us-east-1
def create_stream(stream_name, num_shards, region=None, key=None, keyid=None, profile=None): ''' Create a stream with name stream_name and initial number of shards num_shards. CLI example:: salt myminion boto_kinesis.create_stream my_stream N region=us-east-1 ''' conn = _get_conn(region=re...
Delete the stream with name stream_name. This cannot be undone! All data will be lost!! CLI example:: salt myminion boto_kinesis.delete_stream my_stream region=us-east-1
def delete_stream(stream_name, region=None, key=None, keyid=None, profile=None): ''' Delete the stream with name stream_name. This cannot be undone! All data will be lost!! CLI example:: salt myminion boto_kinesis.delete_stream my_stream region=us-east-1 ''' conn = _get_conn(region=region,...
Increase stream retention period to retention_hours CLI example:: salt myminion boto_kinesis.increase_stream_retention_period my_stream N region=us-east-1
def increase_stream_retention_period(stream_name, retention_hours, region=None, key=None, keyid=None, profile=None): ''' Increase stream retention period to retention_hours CLI example:: salt myminion boto_kinesis.increase_stream_retention_period my_stream N re...
Enable enhanced monitoring for the specified shard-level metrics on stream stream_name CLI example:: salt myminion boto_kinesis.enable_enhanced_monitoring my_stream ["metrics", "to", "enable"] region=us-east-1
def enable_enhanced_monitoring(stream_name, metrics, region=None, key=None, keyid=None, profile=None): ''' Enable enhanced monitoring for the specified shard-level metrics on stream stream_name CLI example:: salt myminion boto_kinesis.enable_enhanced_monitoring my_st...
Collect some data: number of open shards, key range, etc. Modifies stream_details to add a sorted list of OpenShards. Returns (min_hash_key, max_hash_key, stream_details) CLI example:: salt myminion boto_kinesis.get_info_for_reshard existing_stream_details
def get_info_for_reshard(stream_details): """ Collect some data: number of open shards, key range, etc. Modifies stream_details to add a sorted list of OpenShards. Returns (min_hash_key, max_hash_key, stream_details) CLI example:: salt myminion boto_kinesis.get_info_for_reshard existing_st...
Reshard a kinesis stream. Each call to this function will wait until the stream is ACTIVE, then make a single split or merge operation. This function decides where to split or merge with the assumption that the ultimate goal is a balanced partition space. For safety, user must past in force=True; otherwis...
def reshard(stream_name, desired_size, force=False, region=None, key=None, keyid=None, profile=None): """ Reshard a kinesis stream. Each call to this function will wait until the stream is ACTIVE, then make a single split or merge operation. This function decides where to split or merge wit...
Return a list of all streams visible to the current account CLI example: .. code-block:: bash salt myminion boto_kinesis.list_streams
def list_streams(region=None, key=None, keyid=None, profile=None): ''' Return a list of all streams visible to the current account CLI example: .. code-block:: bash salt myminion boto_kinesis.list_streams ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) s...
Return the next open shard after shard_id CLI example:: salt myminion boto_kinesis._get_next_open_shard existing_stream_details shard_id
def _get_next_open_shard(stream_details, shard_id): ''' Return the next open shard after shard_id CLI example:: salt myminion boto_kinesis._get_next_open_shard existing_stream_details shard_id ''' found = False for shard in stream_details["OpenShards"]: current_shard_id = shard...
Retry if we're rate limited by AWS or blocked by another call. Give up and return error message if resource not found or argument is invalid. conn The connection established by the calling method via _get_conn() function The function to call on conn. i.e. create_stream **kwargs ...
def _execute_with_retries(conn, function, **kwargs): ''' Retry if we're rate limited by AWS or blocked by another call. Give up and return error message if resource not found or argument is invalid. conn The connection established by the calling method via _get_conn() function The ...
Set a single key .. note:: This will strip comments from your config file
def apply(key, value): ''' Set a single key .. note:: This will strip comments from your config file ''' path = __opts__['conf_file'] if os.path.isdir(path): path = os.path.join(path, 'master') data = values() data[key] = value with salt.utils.files.fopen(path, 'w+'...
Update master config with ``yaml_contents``. Writes ``yaml_contents`` to a file named ``file_name.conf`` under the folder specified by ``default_include``. This folder is named ``master.d`` by default. Please look at :conf_master:`include-configuration` for more information. Exampl...
def update_config(file_name, yaml_contents): ''' Update master config with ``yaml_contents``. Writes ``yaml_contents`` to a file named ``file_name.conf`` under the folder specified by ``default_include``. This folder is named ``master.d`` by default. Please look at :conf_master:`inc...
Idea from softwareproperties.ppa. Uses urllib2 which sacrifices server cert verification. This is used as fall-back code or for secure PPAs :param owner_name: :param ppa_name: :return:
def _get_ppa_info_from_launchpad(owner_name, ppa_name): ''' Idea from softwareproperties.ppa. Uses urllib2 which sacrifices server cert verification. This is used as fall-back code or for secure PPAs :param owner_name: :param ppa_name: :return: ''' lp_url = 'https://launchpad.net/...
Call apt* utilities.
def _call_apt(args, scope=True, **kwargs): ''' Call apt* utilities. ''' cmd = [] if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True): cmd.extend(['systemd-run', '--scope']) cmd.extend(args) params = {'output_loglevel': 'trace', ...